text
stringlengths
2
1.04M
meta
dict
import Base.zero export AV_PERM_READ, AV_PERM_WRITE, AV_PERM_PRESERVE, AV_PERM_REUSE, AV_PERM_REUSE2, AV_PERM_NEG_LINESIZES, AV_PERM_ALIGN, AVFILTER_ALIGN, AVFILTER_FLAG_DYNAMIC_INPUTS, AVFILTER_FLAG_DYNAMIC_OUTPUTS, AVFILTER_FLAG_SLICE_THREADS, AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC, AVFILTER_FLAG_SUPPORT_TIMELINE_INTERNAL, AVFILTER_FLAG_SUPPORT_TIMELINE, AVFILTER_THREAD_SLICE, AVFILTER_CMD_FLAG_ONE, AVFILTER_CMD_FLAG_FAST, AVFilterContext, AVFilterLink, AVFilterPad, AVFilterFormats, Array_8_Ptr, Array_8_Cint, AVFilterBuffer, AVFilterBufferRefAudioProps, AVFilterBufferRefVideoProps, AVFilterBufferRef, AVFilter_, AVFilterInternal, AVFilterGraphInternal, AVFilterGraph, ANONYMOUS_1, AVFILTER_AUTO_CONVERT_ALL, AVFILTER_AUTO_CONVERT_NONE, AVFilterInOut, AV_BUFFERSINK_FLAG_PEEK, AV_BUFFERSINK_FLAG_NO_REQUEST, AVBufferSinkParams, AVABufferSinkParams, ANONYMOUS_2, AV_BUFFERSRC_FLAG_NO_CHECK_FORMAT, AV_BUFFERSRC_FLAG_NO_COPY, AV_BUFFERSRC_FLAG_PUSH, AV_BUFFERSRC_FLAG_KEEP_REF const AV_PERM_READ = 0x01 const AV_PERM_WRITE = 0x02 const AV_PERM_PRESERVE = 0x04 const AV_PERM_REUSE = 0x08 const AV_PERM_REUSE2 = 0x10 const AV_PERM_NEG_LINESIZES = 0x20 const AV_PERM_ALIGN = 0x40 const AVFILTER_ALIGN = 16 const AVFILTER_FLAG_DYNAMIC_INPUTS = 1 << 0 const AVFILTER_FLAG_DYNAMIC_OUTPUTS = 1 << 1 const AVFILTER_FLAG_SLICE_THREADS = 1 << 2 const AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC = 1 << 16 const AVFILTER_FLAG_SUPPORT_TIMELINE_INTERNAL = 1 << 17 const AVFILTER_FLAG_SUPPORT_TIMELINE = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC | AVFILTER_FLAG_SUPPORT_TIMELINE_INTERNAL const AVFILTER_THREAD_SLICE = 1 << 0 const AVFILTER_CMD_FLAG_ONE = 1 const AVFILTER_CMD_FLAG_FAST = 2 typealias AVFilterContext AVFilterContext typealias AVFilterLink AVFilterLink typealias AVFilterPad AVFilterPad typealias AVFilterFormats Void immutable Array_8_Ptr d1::Ptr{Uint8} d2::Ptr{Uint8} d3::Ptr{Uint8} d4::Ptr{Uint8} d5::Ptr{Uint8} d6::Ptr{Uint8} d7::Ptr{Uint8} d8::Ptr{Uint8} end zero(::Type{Array_8_Ptr}) = Array_8_Ptr(fill(C_NULL,8)...) immutable Array_8_Cint d1::Cint d2::Cint d3::Cint d4::Cint d5::Cint d6::Cint d7::Cint d8::Cint end zero(::Type{Array_8_Cint}) = Array_8_Cint(fill(zero(Cint),8)...) immutable AVFilterBuffer data::Array_8_Ptr extended_data::Ptr{Ptr{Uint8}} linesize::Array_8_Cint priv::Ptr{Void} free::Ptr{Void} format::Cint w::Cint h::Cint refcount::Uint32 end immutable AVFilterBufferRefAudioProps channel_layout::Uint64 nb_samples::Cint sample_rate::Cint channels::Cint end immutable AVFilterBufferRefVideoProps w::Cint h::Cint sample_aspect_ratio::AVRational interlaced::Cint top_field_first::Cint pict_type::AVPictureType key_frame::Cint qp_table_linesize::Cint qp_table_size::Cint qp_table::Ptr{Int8} end immutable AVFilterBufferRef buf::Ptr{AVFilterBuffer} data::Array_8_Ptr extended_data::Ptr{Ptr{Uint8}} linesize::Array_8_Cint video::Ptr{AVFilterBufferRefVideoProps} audio::Ptr{AVFilterBufferRefAudioProps} pts::Int64 pos::Int64 format::Cint perms::Cint _type::AVMediaType metadata::Ptr{AVDictionary} end immutable AVFilter_ name::Ptr{Uint8} description::Ptr{Uint8} inputs::Ptr{AVFilterPad} outputs::Ptr{AVFilterPad} priv_class::Ptr{AVClass} flags::Cint init::Ptr{Void} init_dict::Ptr{Void} uninit::Ptr{Void} query_formats::Ptr{Void} priv_size::Cint next::Ptr{AVFilter_} process_command::Ptr{Void} init_opaque::Ptr{Void} end typealias AVFilterInternal Void typealias AVFilterGraphInternal Void immutable AVFilterGraph av_class::Ptr{AVClass} filter_count_unused::Uint32 filters::Ptr{Ptr{AVFilterContext}} scale_sws_opts::Ptr{Uint8} resample_lavr_opts::Ptr{Uint8} nb_filters::Uint32 thread_type::Cint nb_threads::Cint internal::Ptr{AVFilterGraphInternal} opaque::Ptr{Void} execute::Ptr{avfilter_execute_func} aresample_swr_opts::Ptr{Uint8} sink_links::Ptr{Ptr{AVFilterLink}} sink_links_count::Cint disable_auto_convert::Uint32 end # begin enum ANONYMOUS_1 typealias ANONYMOUS_1 Cint const AVFILTER_AUTO_CONVERT_ALL = @compat Int32(0) const AVFILTER_AUTO_CONVERT_NONE = @compat Int32(-1) # end enum ANONYMOUS_1 immutable AVFilterInOut name::Ptr{Uint8} filter_ctx::Ptr{AVFilterContext} pad_idx::Cint next::Ptr{AVFilterInOut} end const AV_BUFFERSINK_FLAG_PEEK = 1 const AV_BUFFERSINK_FLAG_NO_REQUEST = 2 immutable AVBufferSinkParams pixel_fmts::Ptr{AVPixelFormat} end immutable AVABufferSinkParams sample_fmts::Ptr{AVSampleFormat} channel_layouts::Ptr{Int64} channel_counts::Ptr{Cint} all_channel_counts::Cint sample_rates::Ptr{Cint} end # begin enum ANONYMOUS_2 typealias ANONYMOUS_2 Uint32 const AV_BUFFERSRC_FLAG_NO_CHECK_FORMAT = @compat UInt32(1) const AV_BUFFERSRC_FLAG_NO_COPY = @compat UInt32(2) const AV_BUFFERSRC_FLAG_PUSH = @compat UInt32(4) const AV_BUFFERSRC_FLAG_KEEP_REF = @compat UInt32(8) # end enum ANONYMOUS_2
{ "content_hash": "14691dd355da1eddc5c9de983775e36e", "timestamp": "", "source": "github", "line_count": 219, "max_line_length": 119, "avg_line_length": 24.17351598173516, "alnum_prop": 0.7068379297317718, "repo_name": "SimonDanisch/VideoIO.jl", "id": "b4e7dd09d1831d67d21c7754c52ef926fad1fc32", "size": "5295", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/ffmpeg/AVFilters/v5/libavfilter_h.jl", "mode": "33188", "license": "mit", "language": [ { "name": "Julia", "bytes": "1681069" } ], "symlink_target": "" }
package discovery import ( "bytes" "code.google.com/p/google-api-go-client/googleapi" "encoding/json" "errors" "fmt" "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 _ = googleapi.Version var _ = errors.New var _ = strings.Replace const apiId = "discovery:v1" const apiName = "discovery" const apiVersion = "v1" const basePath = "https://www.googleapis.com/discovery/v1/" func New(client *http.Client) (*Service, error) { if client == nil { return nil, errors.New("client is nil") } s := &Service{client: client, BasePath: basePath} s.Apis = NewApisService(s) return s, nil } type Service struct { client *http.Client BasePath string // API endpoint base URL Apis *ApisService } func NewApisService(s *Service) *ApisService { rs := &ApisService{s: s} return rs } type ApisService struct { s *Service } type DirectoryList struct { // DiscoveryVersion: Indicate the version of the Discovery API used to // generate this doc. DiscoveryVersion string `json:"discoveryVersion,omitempty"` // Items: The individual directory entries. One entry per api/version // pair. Items []*DirectoryListItems `json:"items,omitempty"` // Kind: The kind for this response. Kind string `json:"kind,omitempty"` } type DirectoryListItems struct { // Description: The description of this API. Description string `json:"description,omitempty"` // DiscoveryLink: A link to the discovery document. DiscoveryLink string `json:"discoveryLink,omitempty"` // DiscoveryRestUrl: The URL for the discovery REST document. DiscoveryRestUrl string `json:"discoveryRestUrl,omitempty"` // DocumentationLink: A link to human readable documentation for the // API. DocumentationLink string `json:"documentationLink,omitempty"` // Icons: Links to 16x16 and 32x32 icons representing the API. Icons *DirectoryListItemsIcons `json:"icons,omitempty"` // Id: The id of this API. Id string `json:"id,omitempty"` // Kind: The kind for this response. Kind string `json:"kind,omitempty"` // Labels: Labels for the status of this API, such as labs or // deprecated. Labels []string `json:"labels,omitempty"` // Name: The name of the API. Name string `json:"name,omitempty"` // Preferred: True if this version is the preferred version to use. Preferred bool `json:"preferred,omitempty"` // Title: The title of this API. Title string `json:"title,omitempty"` // Version: The version of the API. Version string `json:"version,omitempty"` } type DirectoryListItemsIcons struct { // X16: The URL of the 16x16 icon. X16 string `json:"x16,omitempty"` // X32: The URL of the 32x32 icon. X32 string `json:"x32,omitempty"` } type JsonSchema struct { // Ref: A reference to another schema. The value of this property is the // "id" of another schema. Ref string `json:"$ref,omitempty"` // AdditionalProperties: If this is a schema for an object, this // property is the schema for any additional properties with dynamic // keys on this object. AdditionalProperties *JsonSchema `json:"additionalProperties,omitempty"` // Annotations: Additional information about this property. Annotations *JsonSchemaAnnotations `json:"annotations,omitempty"` // Default: The default value of this property (if one exists). Default string `json:"default,omitempty"` // Description: A description of this object. Description string `json:"description,omitempty"` // Enum: Values this parameter may take (if it is an enum). Enum []string `json:"enum,omitempty"` // EnumDescriptions: The descriptions for the enums. Each position maps // to the corresponding value in the "enum" array. EnumDescriptions []string `json:"enumDescriptions,omitempty"` // Format: An additional regular expression or key that helps constrain // the value. For more details see: // http://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.23 Format string `json:"format,omitempty"` // Id: Unique identifier for this schema. Id string `json:"id,omitempty"` // Items: If this is a schema for an array, this property is the schema // for each element in the array. Items *JsonSchema `json:"items,omitempty"` // Location: Whether this parameter goes in the query or the path for // REST requests. Location string `json:"location,omitempty"` // Maximum: The maximum value of this parameter. Maximum string `json:"maximum,omitempty"` // Minimum: The minimum value of this parameter. Minimum string `json:"minimum,omitempty"` // Pattern: The regular expression this parameter must conform to. Uses // Java 6 regex format: // http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html Pattern string `json:"pattern,omitempty"` // Properties: If this is a schema for an object, list the schema for // each property of this object. Properties map[string]JsonSchema `json:"properties,omitempty"` // ReadOnly: The value is read-only, generated by the service. The value // cannot be modified by the client. If the value is included in a POST, // PUT, or PATCH request, it is ignored by the service. ReadOnly bool `json:"readOnly,omitempty"` // Repeated: Whether this parameter may appear multiple times. Repeated bool `json:"repeated,omitempty"` // Required: Whether the parameter is required. Required bool `json:"required,omitempty"` // Type: The value type for this schema. A list of values can be found // here: http://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.1 Type string `json:"type,omitempty"` // Variant: In a variant data type, the value of one property is used to // determine how to interpret the entire entity. Its value must exist in // a map of descriminant values to schema names. Variant *JsonSchemaVariant `json:"variant,omitempty"` } type JsonSchemaAnnotations struct { // Required: A list of methods for which this property is required on // requests. Required []string `json:"required,omitempty"` } type JsonSchemaVariant struct { // Discriminant: The name of the type discriminant property. Discriminant string `json:"discriminant,omitempty"` // Map: The map of discriminant value to schema to use for parsing.. Map []*JsonSchemaVariantMap `json:"map,omitempty"` } type JsonSchemaVariantMap struct { Ref string `json:"$ref,omitempty"` Type_value string `json:"type_value,omitempty"` } type RestDescription struct { // Auth: Authentication information. Auth *RestDescriptionAuth `json:"auth,omitempty"` // BasePath: [DEPRECATED] The base path for REST requests. BasePath string `json:"basePath,omitempty"` // BaseUrl: [DEPRECATED] The base URL for REST requests. BaseUrl string `json:"baseUrl,omitempty"` // BatchPath: The path for REST batch requests. BatchPath string `json:"batchPath,omitempty"` // CanonicalName: Indicates how the API name should be capitalized and // split into various parts. Useful for generating pretty class names. CanonicalName string `json:"canonicalName,omitempty"` // Description: The description of this API. Description string `json:"description,omitempty"` // DiscoveryVersion: Indicate the version of the Discovery API used to // generate this doc. DiscoveryVersion string `json:"discoveryVersion,omitempty"` // DocumentationLink: A link to human readable documentation for the // API. DocumentationLink string `json:"documentationLink,omitempty"` // Etag: The ETag for this response. Etag string `json:"etag,omitempty"` // Features: A list of supported features for this API. Features []string `json:"features,omitempty"` // Icons: Links to 16x16 and 32x32 icons representing the API. Icons *RestDescriptionIcons `json:"icons,omitempty"` // Id: The ID of this API. Id string `json:"id,omitempty"` // Kind: The kind for this response. Kind string `json:"kind,omitempty"` // Labels: Labels for the status of this API, such as labs or // deprecated. Labels []string `json:"labels,omitempty"` // Methods: API-level methods for this API. Methods map[string]RestMethod `json:"methods,omitempty"` // Name: The name of this API. Name string `json:"name,omitempty"` // OwnerDomain: The domain of the owner of this API. Together with the // ownerName and a packagePath values, this can be used to generate a // library for this API which would have a unique fully qualified name. OwnerDomain string `json:"ownerDomain,omitempty"` // OwnerName: The name of the owner of this API. See ownerDomain. OwnerName string `json:"ownerName,omitempty"` // PackagePath: The package of the owner of this API. See ownerDomain. PackagePath string `json:"packagePath,omitempty"` // Parameters: Common parameters that apply across all apis. Parameters map[string]JsonSchema `json:"parameters,omitempty"` // Protocol: The protocol described by this document. Protocol string `json:"protocol,omitempty"` // Resources: The resources in this API. Resources map[string]RestResource `json:"resources,omitempty"` // Revision: The version of this API. Revision string `json:"revision,omitempty"` // RootUrl: The root URL under which all API services live. RootUrl string `json:"rootUrl,omitempty"` // Schemas: The schemas for this API. Schemas map[string]JsonSchema `json:"schemas,omitempty"` // ServicePath: The base path for all REST requests. ServicePath string `json:"servicePath,omitempty"` // Title: The title of this API. Title string `json:"title,omitempty"` // Version: The version of this API. Version string `json:"version,omitempty"` } type RestDescriptionAuth struct { // Oauth2: OAuth 2.0 authentication information. Oauth2 *RestDescriptionAuthOauth2 `json:"oauth2,omitempty"` } type RestDescriptionAuthOauth2 struct { // Scopes: Available OAuth 2.0 scopes. Scopes *RestDescriptionAuthOauth2Scopes `json:"scopes,omitempty"` } type RestDescriptionAuthOauth2Scopes struct { } type RestDescriptionIcons struct { // X16: The URL of the 16x16 icon. X16 string `json:"x16,omitempty"` // X32: The URL of the 32x32 icon. X32 string `json:"x32,omitempty"` } type RestMethod struct { // Description: Description of this method. Description string `json:"description,omitempty"` // EtagRequired: Whether this method requires an ETag to be specified. // The ETag is sent as an HTTP If-Match or If-None-Match header. EtagRequired bool `json:"etagRequired,omitempty"` // HttpMethod: HTTP method used by this method. HttpMethod string `json:"httpMethod,omitempty"` // Id: A unique ID for this method. This property can be used to match // methods between different versions of Discovery. Id string `json:"id,omitempty"` // MediaUpload: Media upload parameters. MediaUpload *RestMethodMediaUpload `json:"mediaUpload,omitempty"` // ParameterOrder: Ordered list of required parameters, serves as a hint // to clients on how to structure their method signatures. The array is // ordered such that the "most-significant" parameter appears first. ParameterOrder []string `json:"parameterOrder,omitempty"` // Parameters: Details for all parameters in this method. Parameters map[string]JsonSchema `json:"parameters,omitempty"` // Path: The URI path of this REST method. Should be used in conjunction // with the basePath property at the api-level. Path string `json:"path,omitempty"` // Request: The schema for the request. Request *RestMethodRequest `json:"request,omitempty"` // Response: The schema for the response. Response *RestMethodResponse `json:"response,omitempty"` // Scopes: OAuth 2.0 scopes applicable to this method. Scopes []string `json:"scopes,omitempty"` // SupportsMediaDownload: Whether this method supports media downloads. SupportsMediaDownload bool `json:"supportsMediaDownload,omitempty"` // SupportsMediaUpload: Whether this method supports media uploads. SupportsMediaUpload bool `json:"supportsMediaUpload,omitempty"` // SupportsSubscription: Whether this method supports subscriptions. SupportsSubscription bool `json:"supportsSubscription,omitempty"` } type RestMethodMediaUpload struct { // Accept: MIME Media Ranges for acceptable media uploads to this // method. Accept []string `json:"accept,omitempty"` // MaxSize: Maximum size of a media upload, such as "1MB", "2GB" or // "3TB". MaxSize string `json:"maxSize,omitempty"` // Protocols: Supported upload protocols. Protocols *RestMethodMediaUploadProtocols `json:"protocols,omitempty"` } type RestMethodMediaUploadProtocols struct { // Resumable: Supports the Resumable Media Upload protocol. Resumable *RestMethodMediaUploadProtocolsResumable `json:"resumable,omitempty"` // Simple: Supports uploading as a single HTTP request. Simple *RestMethodMediaUploadProtocolsSimple `json:"simple,omitempty"` } type RestMethodMediaUploadProtocolsResumable struct { // Multipart: True if this endpoint supports uploading multipart media. Multipart bool `json:"multipart,omitempty"` // Path: The URI path to be used for upload. Should be used in // conjunction with the basePath property at the api-level. Path string `json:"path,omitempty"` } type RestMethodMediaUploadProtocolsSimple struct { // Multipart: True if this endpoint supports upload multipart media. Multipart bool `json:"multipart,omitempty"` // Path: The URI path to be used for upload. Should be used in // conjunction with the basePath property at the api-level. Path string `json:"path,omitempty"` } type RestMethodRequest struct { // Ref: Schema ID for the request schema. Ref string `json:"$ref,omitempty"` // ParameterName: parameter name. ParameterName string `json:"parameterName,omitempty"` } type RestMethodResponse struct { // Ref: Schema ID for the response schema. Ref string `json:"$ref,omitempty"` } type RestResource struct { // Methods: Methods on this resource. Methods map[string]RestMethod `json:"methods,omitempty"` // Resources: Sub-resources on this resource. Resources map[string]RestResource `json:"resources,omitempty"` } // method id "discovery.apis.getRest": type ApisGetRestCall struct { s *Service api string version string opt_ map[string]interface{} } // GetRest: Retrieve the description of a particular version of an api. func (r *ApisService) GetRest(api string, version string) *ApisGetRestCall { c := &ApisGetRestCall{s: r.s, opt_: make(map[string]interface{})} c.api = api c.version = version return c } func (c *ApisGetRestCall) Do() (*RestDescription, error) { var body io.Reader = nil params := make(url.Values) params.Set("alt", "json") urls := googleapi.ResolveRelative(c.s.BasePath, "apis/{api}/{version}/rest") urls += "?" + params.Encode() req, _ := http.NewRequest("GET", urls, body) googleapi.Expand(req.URL, map[string]string{ "api": c.api, "version": c.version, }) req.Header.Set("User-Agent", "google-api-go-client/0.5") res, err := c.s.client.Do(req) if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } var ret *RestDescription if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { return nil, err } return ret, nil // { // "description": "Retrieve the description of a particular version of an api.", // "httpMethod": "GET", // "id": "discovery.apis.getRest", // "parameterOrder": [ // "api", // "version" // ], // "parameters": { // "api": { // "description": "The name of the API.", // "location": "path", // "required": true, // "type": "string" // }, // "version": { // "description": "The version of the API.", // "location": "path", // "required": true, // "type": "string" // } // }, // "path": "apis/{api}/{version}/rest", // "response": { // "$ref": "RestDescription" // } // } } // method id "discovery.apis.list": type ApisListCall struct { s *Service opt_ map[string]interface{} } // List: Retrieve the list of APIs supported at this endpoint. func (r *ApisService) List() *ApisListCall { c := &ApisListCall{s: r.s, opt_: make(map[string]interface{})} return c } // Name sets the optional parameter "name": Only include APIs with the // given name. func (c *ApisListCall) Name(name string) *ApisListCall { c.opt_["name"] = name return c } // Preferred sets the optional parameter "preferred": Return only the // preferred version of an API. func (c *ApisListCall) Preferred(preferred bool) *ApisListCall { c.opt_["preferred"] = preferred return c } func (c *ApisListCall) Do() (*DirectoryList, error) { var body io.Reader = nil params := make(url.Values) params.Set("alt", "json") if v, ok := c.opt_["name"]; ok { params.Set("name", fmt.Sprintf("%v", v)) } if v, ok := c.opt_["preferred"]; ok { params.Set("preferred", fmt.Sprintf("%v", v)) } urls := googleapi.ResolveRelative(c.s.BasePath, "apis") urls += "?" + params.Encode() req, _ := http.NewRequest("GET", urls, body) googleapi.SetOpaque(req.URL) req.Header.Set("User-Agent", "google-api-go-client/0.5") res, err := c.s.client.Do(req) if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } var ret *DirectoryList if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { return nil, err } return ret, nil // { // "description": "Retrieve the list of APIs supported at this endpoint.", // "httpMethod": "GET", // "id": "discovery.apis.list", // "parameters": { // "name": { // "description": "Only include APIs with the given name.", // "location": "query", // "type": "string" // }, // "preferred": { // "default": "false", // "description": "Return only the preferred version of an API.", // "location": "query", // "type": "boolean" // } // }, // "path": "apis", // "response": { // "$ref": "DirectoryList" // } // } }
{ "content_hash": "ca4ea18d1559174d6b2840f527ef7267", "timestamp": "", "source": "github", "line_count": 589, "max_line_length": 83, "avg_line_length": 30.743633276740237, "alnum_prop": 0.7162027833001988, "repo_name": "terminalv/google-api-go-client", "id": "ac8d3d47d87238a065dc5734c9c53f9ab147b95b", "size": "18387", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "discovery/v1/discovery-gen.go", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Go", "bytes": "6418560" }, { "name": "Shell", "bytes": "293" } ], "symlink_target": "" }
/** * Autogenerated by Thrift Compiler (0.9.0) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.sentry.hdfs.service.thrift; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TAuthzUpdateResponse implements org.apache.thrift.TBase<TAuthzUpdateResponse, TAuthzUpdateResponse._Fields>, java.io.Serializable, Cloneable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("TAuthzUpdateResponse"); private static final org.apache.thrift.protocol.TField AUTHZ_PATH_UPDATE_FIELD_DESC = new org.apache.thrift.protocol.TField("authzPathUpdate", org.apache.thrift.protocol.TType.LIST, (short)1); private static final org.apache.thrift.protocol.TField AUTHZ_PERM_UPDATE_FIELD_DESC = new org.apache.thrift.protocol.TField("authzPermUpdate", org.apache.thrift.protocol.TType.LIST, (short)2); private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>(); static { schemes.put(StandardScheme.class, new TAuthzUpdateResponseStandardSchemeFactory()); schemes.put(TupleScheme.class, new TAuthzUpdateResponseTupleSchemeFactory()); } private List<TPathsUpdate> authzPathUpdate; // optional private List<TPermissionsUpdate> authzPermUpdate; // optional /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { AUTHZ_PATH_UPDATE((short)1, "authzPathUpdate"), AUTHZ_PERM_UPDATE((short)2, "authzPermUpdate"); private static final Map<String, _Fields> byName = new HashMap<String, _Fields>(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // AUTHZ_PATH_UPDATE return AUTHZ_PATH_UPDATE; case 2: // AUTHZ_PERM_UPDATE return AUTHZ_PERM_UPDATE; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments private _Fields optionals[] = {_Fields.AUTHZ_PATH_UPDATE,_Fields.AUTHZ_PERM_UPDATE}; public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.AUTHZ_PATH_UPDATE, new org.apache.thrift.meta_data.FieldMetaData("authzPathUpdate", org.apache.thrift.TFieldRequirementType.OPTIONAL, new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, TPathsUpdate.class)))); tmpMap.put(_Fields.AUTHZ_PERM_UPDATE, new org.apache.thrift.meta_data.FieldMetaData("authzPermUpdate", org.apache.thrift.TFieldRequirementType.OPTIONAL, new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, TPermissionsUpdate.class)))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(TAuthzUpdateResponse.class, metaDataMap); } public TAuthzUpdateResponse() { } /** * Performs a deep copy on <i>other</i>. */ public TAuthzUpdateResponse(TAuthzUpdateResponse other) { if (other.isSetAuthzPathUpdate()) { List<TPathsUpdate> __this__authzPathUpdate = new ArrayList<TPathsUpdate>(); for (TPathsUpdate other_element : other.authzPathUpdate) { __this__authzPathUpdate.add(new TPathsUpdate(other_element)); } this.authzPathUpdate = __this__authzPathUpdate; } if (other.isSetAuthzPermUpdate()) { List<TPermissionsUpdate> __this__authzPermUpdate = new ArrayList<TPermissionsUpdate>(); for (TPermissionsUpdate other_element : other.authzPermUpdate) { __this__authzPermUpdate.add(new TPermissionsUpdate(other_element)); } this.authzPermUpdate = __this__authzPermUpdate; } } public TAuthzUpdateResponse deepCopy() { return new TAuthzUpdateResponse(this); } @Override public void clear() { this.authzPathUpdate = null; this.authzPermUpdate = null; } public int getAuthzPathUpdateSize() { return (this.authzPathUpdate == null) ? 0 : this.authzPathUpdate.size(); } public java.util.Iterator<TPathsUpdate> getAuthzPathUpdateIterator() { return (this.authzPathUpdate == null) ? null : this.authzPathUpdate.iterator(); } public void addToAuthzPathUpdate(TPathsUpdate elem) { if (this.authzPathUpdate == null) { this.authzPathUpdate = new ArrayList<TPathsUpdate>(); } this.authzPathUpdate.add(elem); } public List<TPathsUpdate> getAuthzPathUpdate() { return this.authzPathUpdate; } public void setAuthzPathUpdate(List<TPathsUpdate> authzPathUpdate) { this.authzPathUpdate = authzPathUpdate; } public void unsetAuthzPathUpdate() { this.authzPathUpdate = null; } /** Returns true if field authzPathUpdate is set (has been assigned a value) and false otherwise */ public boolean isSetAuthzPathUpdate() { return this.authzPathUpdate != null; } public void setAuthzPathUpdateIsSet(boolean value) { if (!value) { this.authzPathUpdate = null; } } public int getAuthzPermUpdateSize() { return (this.authzPermUpdate == null) ? 0 : this.authzPermUpdate.size(); } public java.util.Iterator<TPermissionsUpdate> getAuthzPermUpdateIterator() { return (this.authzPermUpdate == null) ? null : this.authzPermUpdate.iterator(); } public void addToAuthzPermUpdate(TPermissionsUpdate elem) { if (this.authzPermUpdate == null) { this.authzPermUpdate = new ArrayList<TPermissionsUpdate>(); } this.authzPermUpdate.add(elem); } public List<TPermissionsUpdate> getAuthzPermUpdate() { return this.authzPermUpdate; } public void setAuthzPermUpdate(List<TPermissionsUpdate> authzPermUpdate) { this.authzPermUpdate = authzPermUpdate; } public void unsetAuthzPermUpdate() { this.authzPermUpdate = null; } /** Returns true if field authzPermUpdate is set (has been assigned a value) and false otherwise */ public boolean isSetAuthzPermUpdate() { return this.authzPermUpdate != null; } public void setAuthzPermUpdateIsSet(boolean value) { if (!value) { this.authzPermUpdate = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case AUTHZ_PATH_UPDATE: if (value == null) { unsetAuthzPathUpdate(); } else { setAuthzPathUpdate((List<TPathsUpdate>)value); } break; case AUTHZ_PERM_UPDATE: if (value == null) { unsetAuthzPermUpdate(); } else { setAuthzPermUpdate((List<TPermissionsUpdate>)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case AUTHZ_PATH_UPDATE: return getAuthzPathUpdate(); case AUTHZ_PERM_UPDATE: return getAuthzPermUpdate(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case AUTHZ_PATH_UPDATE: return isSetAuthzPathUpdate(); case AUTHZ_PERM_UPDATE: return isSetAuthzPermUpdate(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof TAuthzUpdateResponse) return this.equals((TAuthzUpdateResponse)that); return false; } public boolean equals(TAuthzUpdateResponse that) { if (that == null) return false; boolean this_present_authzPathUpdate = true && this.isSetAuthzPathUpdate(); boolean that_present_authzPathUpdate = true && that.isSetAuthzPathUpdate(); if (this_present_authzPathUpdate || that_present_authzPathUpdate) { if (!(this_present_authzPathUpdate && that_present_authzPathUpdate)) return false; if (!this.authzPathUpdate.equals(that.authzPathUpdate)) return false; } boolean this_present_authzPermUpdate = true && this.isSetAuthzPermUpdate(); boolean that_present_authzPermUpdate = true && that.isSetAuthzPermUpdate(); if (this_present_authzPermUpdate || that_present_authzPermUpdate) { if (!(this_present_authzPermUpdate && that_present_authzPermUpdate)) return false; if (!this.authzPermUpdate.equals(that.authzPermUpdate)) return false; } return true; } @Override public int hashCode() { HashCodeBuilder builder = new HashCodeBuilder(); boolean present_authzPathUpdate = true && (isSetAuthzPathUpdate()); builder.append(present_authzPathUpdate); if (present_authzPathUpdate) builder.append(authzPathUpdate); boolean present_authzPermUpdate = true && (isSetAuthzPermUpdate()); builder.append(present_authzPermUpdate); if (present_authzPermUpdate) builder.append(authzPermUpdate); return builder.toHashCode(); } public int compareTo(TAuthzUpdateResponse other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; TAuthzUpdateResponse typedOther = (TAuthzUpdateResponse)other; lastComparison = Boolean.valueOf(isSetAuthzPathUpdate()).compareTo(typedOther.isSetAuthzPathUpdate()); if (lastComparison != 0) { return lastComparison; } if (isSetAuthzPathUpdate()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.authzPathUpdate, typedOther.authzPathUpdate); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetAuthzPermUpdate()).compareTo(typedOther.isSetAuthzPermUpdate()); if (lastComparison != 0) { return lastComparison; } if (isSetAuthzPermUpdate()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.authzPermUpdate, typedOther.authzPermUpdate); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("TAuthzUpdateResponse("); boolean first = true; if (isSetAuthzPathUpdate()) { sb.append("authzPathUpdate:"); if (this.authzPathUpdate == null) { sb.append("null"); } else { sb.append(this.authzPathUpdate); } first = false; } if (isSetAuthzPermUpdate()) { if (!first) sb.append(", "); sb.append("authzPermUpdate:"); if (this.authzPermUpdate == null) { sb.append("null"); } else { sb.append(this.authzPermUpdate); } first = false; } sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class TAuthzUpdateResponseStandardSchemeFactory implements SchemeFactory { public TAuthzUpdateResponseStandardScheme getScheme() { return new TAuthzUpdateResponseStandardScheme(); } } private static class TAuthzUpdateResponseStandardScheme extends StandardScheme<TAuthzUpdateResponse> { public void read(org.apache.thrift.protocol.TProtocol iprot, TAuthzUpdateResponse struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // AUTHZ_PATH_UPDATE if (schemeField.type == org.apache.thrift.protocol.TType.LIST) { { org.apache.thrift.protocol.TList _list122 = iprot.readListBegin(); struct.authzPathUpdate = new ArrayList<TPathsUpdate>(_list122.size); for (int _i123 = 0; _i123 < _list122.size; ++_i123) { TPathsUpdate _elem124; // required _elem124 = new TPathsUpdate(); _elem124.read(iprot); struct.authzPathUpdate.add(_elem124); } iprot.readListEnd(); } struct.setAuthzPathUpdateIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // AUTHZ_PERM_UPDATE if (schemeField.type == org.apache.thrift.protocol.TType.LIST) { { org.apache.thrift.protocol.TList _list125 = iprot.readListBegin(); struct.authzPermUpdate = new ArrayList<TPermissionsUpdate>(_list125.size); for (int _i126 = 0; _i126 < _list125.size; ++_i126) { TPermissionsUpdate _elem127; // required _elem127 = new TPermissionsUpdate(); _elem127.read(iprot); struct.authzPermUpdate.add(_elem127); } iprot.readListEnd(); } struct.setAuthzPermUpdateIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, TAuthzUpdateResponse struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.authzPathUpdate != null) { if (struct.isSetAuthzPathUpdate()) { oprot.writeFieldBegin(AUTHZ_PATH_UPDATE_FIELD_DESC); { oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, struct.authzPathUpdate.size())); for (TPathsUpdate _iter128 : struct.authzPathUpdate) { _iter128.write(oprot); } oprot.writeListEnd(); } oprot.writeFieldEnd(); } } if (struct.authzPermUpdate != null) { if (struct.isSetAuthzPermUpdate()) { oprot.writeFieldBegin(AUTHZ_PERM_UPDATE_FIELD_DESC); { oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, struct.authzPermUpdate.size())); for (TPermissionsUpdate _iter129 : struct.authzPermUpdate) { _iter129.write(oprot); } oprot.writeListEnd(); } oprot.writeFieldEnd(); } } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class TAuthzUpdateResponseTupleSchemeFactory implements SchemeFactory { public TAuthzUpdateResponseTupleScheme getScheme() { return new TAuthzUpdateResponseTupleScheme(); } } private static class TAuthzUpdateResponseTupleScheme extends TupleScheme<TAuthzUpdateResponse> { @Override public void write(org.apache.thrift.protocol.TProtocol prot, TAuthzUpdateResponse struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetAuthzPathUpdate()) { optionals.set(0); } if (struct.isSetAuthzPermUpdate()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetAuthzPathUpdate()) { { oprot.writeI32(struct.authzPathUpdate.size()); for (TPathsUpdate _iter130 : struct.authzPathUpdate) { _iter130.write(oprot); } } } if (struct.isSetAuthzPermUpdate()) { { oprot.writeI32(struct.authzPermUpdate.size()); for (TPermissionsUpdate _iter131 : struct.authzPermUpdate) { _iter131.write(oprot); } } } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, TAuthzUpdateResponse struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { { org.apache.thrift.protocol.TList _list132 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, iprot.readI32()); struct.authzPathUpdate = new ArrayList<TPathsUpdate>(_list132.size); for (int _i133 = 0; _i133 < _list132.size; ++_i133) { TPathsUpdate _elem134; // required _elem134 = new TPathsUpdate(); _elem134.read(iprot); struct.authzPathUpdate.add(_elem134); } } struct.setAuthzPathUpdateIsSet(true); } if (incoming.get(1)) { { org.apache.thrift.protocol.TList _list135 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, iprot.readI32()); struct.authzPermUpdate = new ArrayList<TPermissionsUpdate>(_list135.size); for (int _i136 = 0; _i136 < _list135.size; ++_i136) { TPermissionsUpdate _elem137; // required _elem137 = new TPermissionsUpdate(); _elem137.read(iprot); struct.authzPermUpdate.add(_elem137); } } struct.setAuthzPermUpdateIsSet(true); } } } }
{ "content_hash": "468816c5b21fa3d8700c804c2168bf7b", "timestamp": "", "source": "github", "line_count": 603, "max_line_length": 194, "avg_line_length": 34.698175787728026, "alnum_prop": 0.6678774554318214, "repo_name": "apache/incubator-sentry", "id": "ec1d2af36ce9917fd59926737de286f4ecd8c826", "size": "20923", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "sentry-hdfs/sentry-hdfs-common/src/gen/thrift/gen-javabean/org/apache/sentry/hdfs/service/thrift/TAuthzUpdateResponse.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "4846" }, { "name": "HTML", "bytes": "5005" }, { "name": "Java", "bytes": "3922648" }, { "name": "JavaScript", "bytes": "22225" }, { "name": "PLpgSQL", "bytes": "410" }, { "name": "Python", "bytes": "11367" }, { "name": "SQLPL", "bytes": "30" }, { "name": "Shell", "bytes": "27225" }, { "name": "Thrift", "bytes": "27270" }, { "name": "XSLT", "bytes": "25595" } ], "symlink_target": "" }
package ru.fabrikant.api.multi_integration.easuz.uploadfile; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import ru.fabrikant.api.multi_integration.easuz.types.FileInstance; import ru.fabrikant.api.multi_integration.easuz.types.Header; /** * <p>Java class for uploadProcedureFile complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="uploadProcedureFile"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="Header" type="{http://api.fabrikant.ru/multi-integration/easuz/types/}header"/&gt; * &lt;element name="PurchaseId" type="{http://api.fabrikant.ru/multi-integration/easuz/types/}idString"/&gt; * &lt;element name="LotId" type="{http://api.fabrikant.ru/multi-integration/easuz/types/}idString" minOccurs="0"/&gt; * &lt;element name="FileId" type="{http://api.fabrikant.ru/multi-integration/easuz/types/}idString"/&gt; * &lt;element name="FileInstance" type="{http://api.fabrikant.ru/multi-integration/easuz/types/}fileInstance"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "uploadProcedureFile", propOrder = { "header", "purchaseId", "lotId", "fileId", "fileInstance" }) public class UploadProcedureFile { @XmlElement(name = "Header", required = true) protected Header header; @XmlElement(name = "PurchaseId", required = true) protected String purchaseId; @XmlElement(name = "LotId") protected String lotId; @XmlElement(name = "FileId", required = true) protected String fileId; @XmlElement(name = "FileInstance", required = true) protected FileInstance fileInstance; /** * Gets the value of the header property. * * @return * possible object is * {@link Header } * */ public Header getHeader() { return header; } /** * Sets the value of the header property. * * @param value * allowed object is * {@link Header } * */ public void setHeader(Header value) { this.header = value; } /** * Gets the value of the purchaseId property. * * @return * possible object is * {@link String } * */ public String getPurchaseId() { return purchaseId; } /** * Sets the value of the purchaseId property. * * @param value * allowed object is * {@link String } * */ public void setPurchaseId(String value) { this.purchaseId = value; } /** * Gets the value of the lotId property. * * @return * possible object is * {@link String } * */ public String getLotId() { return lotId; } /** * Sets the value of the lotId property. * * @param value * allowed object is * {@link String } * */ public void setLotId(String value) { this.lotId = value; } /** * Gets the value of the fileId property. * * @return * possible object is * {@link String } * */ public String getFileId() { return fileId; } /** * Sets the value of the fileId property. * * @param value * allowed object is * {@link String } * */ public void setFileId(String value) { this.fileId = value; } /** * Gets the value of the fileInstance property. * * @return * possible object is * {@link FileInstance } * */ public FileInstance getFileInstance() { return fileInstance; } /** * Sets the value of the fileInstance property. * * @param value * allowed object is * {@link FileInstance } * */ public void setFileInstance(FileInstance value) { this.fileInstance = value; } }
{ "content_hash": "1cdf1c3b4962b0fb532c6f1adeb69eaf", "timestamp": "", "source": "github", "line_count": 176, "max_line_length": 126, "avg_line_length": 25.045454545454547, "alnum_prop": 0.5812159709618875, "repo_name": "semyonova/java_test", "id": "4aee79b3d24f8575ae5b12eb68abc9ad40c52b65", "size": "4408", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "multy-integration/src/main/java/ru/fabrikant/api/multi_integration/easuz/uploadfile/UploadProcedureFile.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "308308" }, { "name": "PHP", "bytes": "516" } ], "symlink_target": "" }
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" lang="en"> <head> <meta charset="utf-8" /><link rel="canonical" href="http://mongoc.org/libbson/current/bson_iter_utf8.html"/> <title>bson_iter_utf8() &#8212; libbson 1.21.2</title> <link rel="stylesheet" href="_static/readable.css" type="text/css" /> <link rel="stylesheet" href="_static/pygments.css" type="text/css" /> <link rel="stylesheet" href="_static/pygments.css" type="text/css" /> <link rel="stylesheet" href="_static/readable.css" type="text/css" /> <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script> <script type="text/javascript" src="_static/documentation_options.js"></script> <script type="text/javascript" src="_static/jquery.js"></script> <script type="text/javascript" src="_static/underscore.js"></script> <script type="text/javascript" src="_static/doctools.js"></script> <link rel="search" title="Search" href="search.html" /> <link rel="next" title="bson_iter_value()" href="bson_iter_value.html" /> <link rel="prev" title="bson_iter_type()" href="bson_iter_type.html" /> <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9"> </head><body> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="bson_iter_value.html" title="bson_iter_value()" accesskey="N">next</a></li> <li class="right" > <a href="bson_iter_type.html" title="bson_iter_type()" accesskey="P">previous</a> |</li> <li class="nav-item nav-item-0"><a href="index.html">libbson 1.21.2</a> &#187;</li> <li class="nav-item nav-item-1"><a href="api.html" >API Reference</a> &#187;</li> <li class="nav-item nav-item-2"><a href="bson_iter_t.html" accesskey="U">bson_iter_t</a> &#187;</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <div class="section" id="bson-iter-utf8"> <h1>bson_iter_utf8()<a class="headerlink" href="#bson-iter-utf8" title="Permalink to this headline">¶</a></h1> <div class="section" id="synopsis"> <h2>Synopsis<a class="headerlink" href="#synopsis" title="Permalink to this headline">¶</a></h2> <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="cp">#define BSON_ITER_HOLDS_UTF8(iter) (bson_iter_type ((iter)) == BSON_TYPE_UTF8)</span> <span class="k">const</span> <span class="kt">char</span> <span class="o">*</span> <span class="nf">bson_iter_utf8</span> <span class="p">(</span><span class="k">const</span> <span class="n">bson_iter_t</span> <span class="o">*</span><span class="n">iter</span><span class="p">,</span> <span class="kt">uint32_t</span> <span class="o">*</span><span class="n">length</span><span class="p">);</span> </pre></div> </div> </div> <div class="section" id="parameters"> <h2>Parameters<a class="headerlink" href="#parameters" title="Permalink to this headline">¶</a></h2> <ul class="simple"> <li><p><code class="docutils literal notranslate"><span class="pre">iter</span></code>: A <a class="symbol reference internal" href="bson_iter_t.html"><span class="doc">bson_iter_t</span></a>.</p></li> <li><p><code class="docutils literal notranslate"><span class="pre">length</span></code>: An optional location for the length of the resulting UTF-8 encoded string.</p></li> </ul> </div> <div class="section" id="description"> <h2>Description<a class="headerlink" href="#description" title="Permalink to this headline">¶</a></h2> <p>The <a class="symbol reference internal" href="#"><span class="doc">bson_iter_utf8()</span></a> function shall retrieve the contents of a BSON_TYPE_UTF8 element currently observed by <code class="docutils literal notranslate"><span class="pre">iter</span></code>.</p> <p>It is invalid to call this function while observing an element other than BSON_TYPE_UTF8.</p> </div> <div class="section" id="returns"> <h2>Returns<a class="headerlink" href="#returns" title="Permalink to this headline">¶</a></h2> <p>A UTF-8 encoded string that has not been modified or freed.</p> <p>It is suggested that the caller validate the content is valid UTF-8 before using this in other places. That can be done by calling <a class="symbol reference internal" href="bson_utf8_validate.html"><span class="doc">bson_utf8_validate()</span></a> or validating the underlying <a class="symbol reference internal" href="bson_t.html"><span class="doc">bson_t</span></a> before iterating it.</p> <p>Note that not all drivers use multi-byte representation for <code class="docutils literal notranslate"><span class="pre">\0</span></code> in UTF-8 encodings (commonly referred to as modified-UTF8). You probably want to take a look at the length field when marshaling to other runtimes.</p> </div> </div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"> <h3><a href="index.html">Table Of Contents</a></h3> <ul> <li class="toctree-l1"><a class="reference internal" href="tutorial.html">Tutorial</a></li> </ul> <ul> <li class="toctree-l1"><a class="reference internal" href="guides.html">Guides</a></li> </ul> <ul> <li class="toctree-l1"><a class="reference internal" href="cross-platform-notes.html">Cross Platform Notes</a></li> </ul> <ul class="current"> <li class="toctree-l1 current"><a class="reference internal" href="api.html">API Reference</a><ul class="current"> <li class="toctree-l2"><a class="reference internal" href="bson_t.html">bson_t</a></li> <li class="toctree-l2"><a class="reference internal" href="bson_context_t.html">bson_context_t</a></li> <li class="toctree-l2"><a class="reference internal" href="bson_decimal128_t.html">bson_decimal128_t</a></li> <li class="toctree-l2"><a class="reference internal" href="bson_error_t.html">bson_error_t</a></li> <li class="toctree-l2 current"><a class="reference internal" href="bson_iter_t.html">bson_iter_t</a></li> <li class="toctree-l2"><a class="reference internal" href="bson_json_reader_t.html">bson_json_reader_t</a></li> <li class="toctree-l2"><a class="reference internal" href="bson_md5_t.html">bson_md5_t</a></li> <li class="toctree-l2"><a class="reference internal" href="bson_oid_t.html">bson_oid_t</a></li> <li class="toctree-l2"><a class="reference internal" href="bson_reader_t.html">bson_reader_t</a></li> <li class="toctree-l2"><a class="reference internal" href="character_and_string_routines.html">Character and String Routines</a></li> <li class="toctree-l2"><a class="reference internal" href="bson_string_t.html">bson_string_t</a></li> <li class="toctree-l2"><a class="reference internal" href="bson_subtype_t.html">bson_subtype_t</a></li> <li class="toctree-l2"><a class="reference internal" href="bson_type_t.html">bson_type_t</a></li> <li class="toctree-l2"><a class="reference internal" href="bson_unichar_t.html">bson_unichar_t</a></li> <li class="toctree-l2"><a class="reference internal" href="bson_value_t.html">bson_value_t</a></li> <li class="toctree-l2"><a class="reference internal" href="bson_visitor_t.html">bson_visitor_t</a></li> <li class="toctree-l2"><a class="reference internal" href="bson_writer_t.html">bson_writer_t</a></li> <li class="toctree-l2"><a class="reference internal" href="bson_get_monotonic_time.html">System Clock</a></li> <li class="toctree-l2"><a class="reference internal" href="bson_memory.html">Memory Management</a></li> <li class="toctree-l2"><a class="reference internal" href="version.html">Libbson Versioning</a></li> </ul> </li> </ul> <!-- Because full_index.rst includes everything that index.rst includes, we have to exclude index.rst from the table-of-contents. This page is simply a link forced into the sidebar (in conf.py) to avoid including full_index.rst in the ToC. --> <ul><li class='toctree-l1'><a href="full_index.html">Index</a></li></ul> <div id="searchbox" style="display: none" role="search"> <h3>Quick search</h3> <div class="searchformwrapper"> <form class="search" action="search.html" method="get"> <input type="text" name="q" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="footer"> &copy; Copyright 2017-present, MongoDB, Inc. Created using <a href="http://sphinx-doc.org/">Sphinx</a> 4.1.2. </div> </body> </html>
{ "content_hash": "dec259a1d7eb49f43eeac4e54f11f44b", "timestamp": "", "source": "github", "line_count": 142, "max_line_length": 397, "avg_line_length": 62.5, "alnum_prop": 0.6731267605633803, "repo_name": "treefrogframework/treefrog-framework", "id": "8da3117e1f04039c0e32899ef1258335a5fef562", "size": "8881", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "3rdparty/mongo-c-driver-1.21.2/src/libbson/doc/html/bson_iter_utf8.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "19207" }, { "name": "C", "bytes": "14971" }, { "name": "C++", "bytes": "1717761" }, { "name": "CMake", "bytes": "14155" }, { "name": "HTML", "bytes": "9485" }, { "name": "JavaScript", "bytes": "1140610" }, { "name": "QMake", "bytes": "36422" }, { "name": "Shell", "bytes": "4387" } ], "symlink_target": "" }
using CSUnit; using System; using System.Xml; #if !ECMA_COMPAT public class TestXmlWhitespace : TestCase { // Internal state. private XmlDocument doc; // Constructor. public TestXmlWhitespace(String name) : base(name) { // Nothing to do here. } // Set up for the tests. protected override void Setup() { doc = new XmlDocument(); } // Clean up after the tests. protected override void Cleanup() { // Nothing to do here. } // Check the properties on a newly constructed whitespace node. private void CheckProperties(String msg, XmlWhitespace white, String value, bool failXml) { String temp; AssertEquals(msg + " [1]", "#whitespace", white.LocalName); AssertEquals(msg + " [2]", "#whitespace", white.Name); AssertEquals(msg + " [3]", String.Empty, white.Prefix); AssertEquals(msg + " [4]", String.Empty, white.NamespaceURI); AssertEquals(msg + " [5]", XmlNodeType.Whitespace, white.NodeType); AssertEquals(msg + " [6]", value, white.Data); AssertEquals(msg + " [7]", value, white.Value); AssertEquals(msg + " [8]", value, white.InnerText); AssertEquals(msg + " [9]", value.Length, white.Length); AssertEquals(msg + " [10]", String.Empty, white.InnerXml); if(failXml) { try { temp = white.OuterXml; Fail(msg + " [11]"); } catch(ArgumentException) { // Success } } else { AssertEquals(msg + " [12]", value, white.OuterXml); } } // Test the construction of whitespace nodes. public void TestXmlWhitespaceConstruct() { // Valid whitespace strings. Note: we can construct // empty whitespace nodes, but we cannot write them. CheckProperties("Construct (1)", doc.CreateWhitespace(null), String.Empty, true); CheckProperties("Construct (2)", doc.CreateWhitespace(String.Empty), String.Empty, true); CheckProperties("Construct (3)", doc.CreateWhitespace(" \f\t\r\n\v"), " \f\t\r\n\v", false); // Invalid whitespace strings. try { doc.CreateWhitespace("abc"); Fail("Construct (4)"); } catch(ArgumentException) { // Success } } // Test the setting of whitespace values. public void TestXmlWhitespaceSetValue() { XmlWhitespace white = doc.CreateWhitespace(null); white.Value = String.Empty; white.Value = " \f\t\r\n\v"; white.Value = null; try { white.Value = "abc"; Fail("SetValue (1)"); } catch(ArgumentException) { // Success } } }; // class TestXmlWhitespace #endif // !ECMA_COMPAT
{ "content_hash": "94dd4a2a6d8bf40c5a9dea0ee21c9fbd", "timestamp": "", "source": "github", "line_count": 114, "max_line_length": 65, "avg_line_length": 23.29824561403509, "alnum_prop": 0.6099397590361446, "repo_name": "jjenki11/blaze-chem-rendering", "id": "ca6d1859f3ab67dae1749f35e5b29a6ea3651c79", "size": "3516", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "qca_designer/lib/pnetlib-0.8.0/tests/System.Xml/TestXmlWhitespace.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Shell", "bytes": "2476" } ], "symlink_target": "" }
namespace omaha { const char kMagicBytes[] = "Gact"; const uint32 kPEHeaderOffset = 60; ApplyTag::ApplyTag() : prev_tag_string_length_(0), prev_cert_length_(0), append_(0) {} bool ApplyTag::IsValidTagString(const char* tag_string) { ASSERT1(tag_string); CAtlRegExp<CAtlRECharTraitsA> regex; REParseError error = regex.Parse(kValidTagStringRegEx); if (error != REPARSE_ERROR_OK) { return false; } CAtlREMatchContext<CAtlRECharTraitsA> context; return !!regex.Match(tag_string, &context); } HRESULT ApplyTag::Init(const TCHAR* signed_exe_file, const char* tag_string, int tag_string_length, const TCHAR* tagged_file, bool append) { ASSERT1(signed_exe_file); ASSERT1(tag_string); ASSERT1(tagged_file); signed_exe_file_ = signed_exe_file; tagged_file_ = tagged_file; append_ = append; // Check the tag_string for invalid characters. if (!IsValidTagString(tag_string)) { return E_INVALIDARG; } for (int i = 0; i < tag_string_length; ++i) { tag_string_.push_back(tag_string[i]); } return S_OK; } HRESULT ApplyTag::EmbedTagString() { std::vector<byte> input_file_buffer; HRESULT hr = ReadEntireFile(signed_exe_file_, 0, &input_file_buffer); if (FAILED(hr)) { return hr; } ASSERT1(!input_file_buffer.empty()); VERIFY1(ReadExistingTag(&input_file_buffer)); if (!append_ && prev_tag_string_length_) { // If there is a previous tag and the append flag is not set, then // we should error out. return APPLYTAG_E_ALREADY_TAGGED; } if (!CreateBufferToWrite()) { return E_FAIL; } // The input_file_buffer might contain the previously read tag, in which // case the buffer_data_ is larger than the actual output buffer length. // The real output buffer length is returned by the ApplyTagToBuffer // method. buffer_data_.resize(input_file_buffer.size() + tag_buffer_.size()); copy(input_file_buffer.begin(), input_file_buffer.end(), buffer_data_.begin()); int output_length = 0; if (!ApplyTagToBuffer(&output_length)) return E_FAIL; std::vector<byte> output_buffer(output_length); ASSERT1(static_cast<size_t>(output_length) <= buffer_data_.size()); copy(buffer_data_.begin(), buffer_data_.begin() + output_length, output_buffer.begin()); return WriteEntireFile(tagged_file_, output_buffer); } uint32 ApplyTag::GetUint32(const void* p) { ASSERT1(p); const uint32* pu = reinterpret_cast<const uint32*>(p); return *pu; } void ApplyTag::PutUint32(uint32 i, void* p) { ASSERT1(p); uint32* pu = reinterpret_cast<uint32*>(p); *pu = i; } bool ApplyTag::ReadExistingTag(std::vector<byte>* binary) { ASSERT1(binary); int len = 0; TagExtractor tag; char* bin = reinterpret_cast<char*>(&binary->front()); ASSERT1(bin); if (tag.ExtractTag(bin, binary->size(), NULL, &len)) { prev_tag_string_.resize(len); if (tag.ExtractTag(bin, binary->size(), &prev_tag_string_.front(), &len)) { // The extractor returns the actual length // of the string + 1 for the terminating null. prev_tag_string_length_ = len - 1; } } // Set the existing certificate length even if previous // tag does not exist. prev_cert_length_ = tag.cert_length(); return true; } bool ApplyTag::CreateBufferToWrite() { ASSERT1(!append_ && !prev_tag_string_length_ || append_); ASSERT1(!tag_string_.empty()); ASSERT1(!prev_tag_string_.size() || prev_tag_string_.size() == static_cast<size_t>(prev_tag_string_length_ + 1)); // Build the tag buffer. // The format of the tag buffer is: // 000000-000003: 4-byte magic (big-endian) // 000004-000005: unsigned 16-bit int string length (big-endian) // 000006-??????: ASCII string int tag_string_len = tag_string_.size() + prev_tag_string_length_; int kMagicBytesLen = ::lstrlenA(kMagicBytes); int tag_header_len = kMagicBytesLen + 2; int unpadded_tag_buffer_len = tag_string_len + tag_header_len; // The tag buffer should be padded to multiples of 8, otherwise it will // break the signature of the executable file. int padded_tag_buffer_length = (unpadded_tag_buffer_len + 15) & (-8); tag_buffer_.clear(); tag_buffer_.resize(padded_tag_buffer_length, 0); memcpy(&tag_buffer_.front(), kMagicBytes, kMagicBytesLen); tag_buffer_[kMagicBytesLen] = static_cast<char>((tag_string_len & 0xff00) >> 8); tag_buffer_[kMagicBytesLen+1] = static_cast<char>(tag_string_len & 0xff); if (prev_tag_string_length_ > 0) { copy(prev_tag_string_.begin(), prev_tag_string_.end(), tag_buffer_.begin() + tag_header_len); } copy(tag_string_.begin(), tag_string_.end(), tag_buffer_.begin() + tag_header_len + prev_tag_string_length_); ASSERT1(static_cast<int>(tag_buffer_.size()) == padded_tag_buffer_length); return true; } bool ApplyTag::ApplyTagToBuffer(int* output_len) { ASSERT1(output_len); uint32 original_data_len = buffer_data_.size() - tag_buffer_.size(); uint32 peheader = GetUint32(&buffer_data_.front() + kPEHeaderOffset); uint32 kCertDirAddressOffset = 152; uint32 kCertDirInfoSize = 4 + 4; ASSERT1(peheader + kCertDirAddressOffset + kCertDirInfoSize <= original_data_len); // Read certificate directory info. uint32 cert_dir_offset = GetUint32(&buffer_data_.front() + peheader + kCertDirAddressOffset); if (cert_dir_offset == 0) return false; uint32 cert_dir_len = GetUint32(&buffer_data_.front() + peheader + kCertDirAddressOffset + 4); ASSERT1(cert_dir_offset + cert_dir_len <= original_data_len); // Calculate the new output length. int prev_pad_length = cert_dir_len - prev_cert_length_ - prev_tag_string_length_; ASSERT1(prev_pad_length >= 0); int orig_dir_len = cert_dir_len - prev_tag_string_length_ - prev_pad_length; ASSERT1(orig_dir_len == prev_cert_length_); int output_length = original_data_len - prev_tag_string_length_ - prev_pad_length + tag_buffer_.size(); *output_len = output_length; ASSERT1(static_cast<size_t>(output_length) <= buffer_data_.size()); ASSERT1(output_length >= orig_dir_len); // Increase the size of certificate directory. int new_cert_len = prev_cert_length_ + tag_buffer_.size(); PutUint32(new_cert_len, &buffer_data_.front() + peheader + kCertDirAddressOffset + 4); // Read certificate struct info. uint32 cert_struct_len = GetUint32(&buffer_data_.front() + cert_dir_offset); ASSERT1(!(cert_struct_len > cert_dir_len || cert_struct_len < cert_dir_len - 8)); // Increase the certificate struct size. PutUint32(new_cert_len, &buffer_data_.front() + cert_dir_offset); // Copy the tag buffer. copy(tag_buffer_.begin(), tag_buffer_.end(), buffer_data_.begin() + cert_dir_offset + prev_cert_length_); return true; } } // namespace omaha.
{ "content_hash": "80502a8be968ebf17bee95160d3cea8f", "timestamp": "", "source": "github", "line_count": 220, "max_line_length": 79, "avg_line_length": 32.06363636363636, "alnum_prop": 0.648426424723561, "repo_name": "Crystalnix/bitpop-omaha", "id": "48d13e2bf91ef9e3195b812850f84390b5f7b675", "size": "7934", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "common/apply_tag.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "3914" }, { "name": "C", "bytes": "2176252" }, { "name": "C#", "bytes": "123756" }, { "name": "C++", "bytes": "11921521" }, { "name": "Java", "bytes": "92279" }, { "name": "Objective-C", "bytes": "37794" }, { "name": "Python", "bytes": "237192" } ], "symlink_target": "" }
layout: post title: Recent submissions --- ![Publications](/public/pics/Publications.jpg) The last couple of weeks were very rich in terms of preprints submissions. No particular increase in productivity. It just happened that a certain number of research projects were finalized by this time. I don't have any other explanation. In any case, here is the list of fresh manuscripts: * M. Chhay, **D. Dutykh**, M. Gisclon & Ch. Ruyer-Quil. [Asymptotic heat transfer model in thin liquid films](https://hal.archives-ouvertes.fr/hal-01224182/), Submitted, 2015 * G. Khakimzyanov & **D. Dutykh**. [On supraconvergence phenomenon for second order centered finite differences on non-uniform grids](https://hal.archives-ouvertes.fr/hal-01223522/), Submitted, 2015 * G. Khakimzyanov, **D. Dutykh**, D. Mitsotakis & N. Shokina. [Numerical solution of conservation laws on moving grids](https://hal.archives-ouvertes.fr/hal-01223510/), Submitted, 2015 * M. Chhay, **D. Dutykh** & D. Clamond. [On the multi-symplectic structure of the Serre-Green-Naghdi equations](https://hal.archives-ouvertes.fr/hal-01221356/), Submitted, 2015 I am looking forward to read any comments from Referees! ---
{ "content_hash": "18d39d46bc50b70ac284692d1efa5edd", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 291, "avg_line_length": 62.421052631578945, "alnum_prop": 0.7571669477234402, "repo_name": "dutykh/dutykh.github.io", "id": "0dbc30ce5e109d4c3c7c4a2c4ac3ce8bfc62500c", "size": "1190", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/2015-11-07-Submissions.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "20352" }, { "name": "HTML", "bytes": "5703" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- 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. --> <BooleanQuery> <Clause occurs="must"> <UserQuery>"Bank of England"</UserQuery> </Clause> <Clause occurs="filter"> <RangeQuery fieldName="date" lowerTerm="19870409" upperTerm="19870412"/> </Clause> </BooleanQuery>
{ "content_hash": "500fcdd43f96dff26c3a755ba9fcc7d4", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 76, "avg_line_length": 41.76, "alnum_prop": 0.7557471264367817, "repo_name": "PATRIC3/p3_solr", "id": "f7b6cae8282efc47ccf6cb739fb5f69e24ee85ac", "size": "1044", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lucene/queryparser/src/test/org/apache/lucene/queryparser/xml/UserInputQuery.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AMPL", "bytes": "291" }, { "name": "ANTLR", "bytes": "2863" }, { "name": "Batchfile", "bytes": "48067" }, { "name": "C++", "bytes": "13377" }, { "name": "CSS", "bytes": "239934" }, { "name": "Gnuplot", "bytes": "2444" }, { "name": "Groovy", "bytes": "3681" }, { "name": "HTML", "bytes": "800790" }, { "name": "Java", "bytes": "49075301" }, { "name": "JavaScript", "bytes": "1250337" }, { "name": "Lex", "bytes": "108342" }, { "name": "Perl", "bytes": "86525" }, { "name": "Python", "bytes": "237962" }, { "name": "Shell", "bytes": "160384" }, { "name": "XSLT", "bytes": "160778" } ], "symlink_target": "" }
// Copyright 2013 Cultural Heritage Agency of the Netherlands, Dutch National Military Museum and Trezorix bv // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Web.Mvc; namespace Trezorix.Checkers.DocumentCheckerApp.Helpers { public class XmlResult : ActionResult { public object Data { get; set; } public XmlResult(object objectToXmlify) { Data = objectToXmlify; ContentType = "text/xml"; } public string ContentType { get; set; } public override void ExecuteResult(ControllerContext context) { if (Data != null) { var xs = new System.Xml.Serialization.XmlSerializer(Data.GetType()); context.HttpContext.Response.ContentType = ContentType; xs.Serialize(context.HttpContext.Response.Output, Data); } } } }
{ "content_hash": "7061263e0ccff018617b6c2b7e7438a3", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 110, "avg_line_length": 31.975609756097562, "alnum_prop": 0.7185354691075515, "repo_name": "Joppe-A/rce-checkers2", "id": "92fd535aaac3ddee4bc1ee22dd372b355f0b4a93", "size": "1313", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "DocumentCheckerApp/Helpers/XmlResult.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "246" }, { "name": "ApacheConf", "bytes": "40" }, { "name": "Batchfile", "bytes": "292" }, { "name": "C#", "bytes": "485872" }, { "name": "CSS", "bytes": "284048" }, { "name": "HTML", "bytes": "323072" }, { "name": "JavaScript", "bytes": "22259129" }, { "name": "Ruby", "bytes": "4713" }, { "name": "Shell", "bytes": "2738" }, { "name": "XSLT", "bytes": "18116" } ], "symlink_target": "" }
class NetConnection; class NetStringHandle; extern U32 GameAddTaggedString(const char *string); class NetStringTable { friend class NetStringHandle; friend U32 GameAddTaggedString(const char *string); #ifdef TORQUE_DEBUG_NET friend class RemoteCommandEvent; #endif enum Constants { InitialSize = 16, InvalidEntry = 0xFFFFFFFF, HashTableSize = 2128, DataChunkerSize = 65536 }; struct Entry { char *string; U32 refCount; U32 scriptRefCount; U32 next; U32 link; U32 prevLink; U32 seq; }; U32 size; U32 firstFree; U32 firstValid; U32 sequenceCount; Entry *table; U32 hashTable[HashTableSize]; DataChunker *allocator; NetStringTable(); ~NetStringTable(); U32 addString(const char *string); // XA: Moved this ones to public to avoid using the friend_ConsoleMethod hack. public: const char *lookupString(U32 id); void removeString(U32 id, bool script = false); void incStringRefScript(U32 id); private: void incStringRef(U32 id); void repack(); public: static void create(); static void destroy(); static void expandString(NetStringHandle &string, char *buf, U32 bufSize, U32 argc, const char **argv); #if defined(TORQUE_DEBUG) void dumpToConsole(); #endif // DEBUG }; extern NetStringTable *gNetStringTable; // This class represents what is known as a "tagged string" in script. // It is essentially a networked version of the string table. The full string // is only transmitted once; then future references only need to transmit // the id. class NetStringHandle { U32 index; public: NetStringHandle() { index = 0; } NetStringHandle(const NetStringHandle &string) { index = string.index; if(index) gNetStringTable->incStringRef(index); } NetStringHandle(const char *string) { index = gNetStringTable->addString(string); } NetStringHandle(U32 initIndex) { index = initIndex; if(index) gNetStringTable->incStringRef(index); } ~NetStringHandle() { if(index) gNetStringTable->removeString(index); } void setFromIndex(U32 newIndex) { if(index) gNetStringTable->removeString(index); index = newIndex; } bool operator==(const NetStringHandle &s) const { return index == s.index; } bool operator!=(const NetStringHandle &s) const { return index != s.index; } NetStringHandle &operator=(const NetStringHandle &s) { if(index) gNetStringTable->removeString(index); index = s.index; if(index) gNetStringTable->incStringRef(index); return *this; } const char *getString() const { if(index) return gNetStringTable->lookupString(index); else return NULL; } bool isNull() const { return index == 0; } bool isValidString() const { return index != 0; } U32 getIndex() const { return index; } }; #endif
{ "content_hash": "9bc2e3c75086820f1ffb694c260de04a", "timestamp": "", "source": "github", "line_count": 129, "max_line_length": 106, "avg_line_length": 23.31782945736434, "alnum_prop": 0.6565824468085106, "repo_name": "John3/T3D_GMK_BULLET", "id": "629d691bbed58333608682ac5ff49f7f906dac87", "size": "4456", "binary": false, "copies": "2", "ref": "refs/heads/development", "path": "Engine/source/sim/netStringTable.h", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "32222" }, { "name": "Batchfile", "bytes": "12923" }, { "name": "C", "bytes": "11950387" }, { "name": "C#", "bytes": "5902839" }, { "name": "C++", "bytes": "33125127" }, { "name": "CMake", "bytes": "59253" }, { "name": "CSS", "bytes": "30290" }, { "name": "DIGITAL Command Language", "bytes": "9957" }, { "name": "GLSL", "bytes": "373616" }, { "name": "Groff", "bytes": "254284" }, { "name": "HLSL", "bytes": "753010" }, { "name": "HTML", "bytes": "1070573" }, { "name": "Lex", "bytes": "18736" }, { "name": "M4", "bytes": "151411" }, { "name": "Makefile", "bytes": "70241" }, { "name": "Module Management System", "bytes": "14415" }, { "name": "NSIS", "bytes": "1193756" }, { "name": "Objective-C", "bytes": "116279" }, { "name": "Objective-C++", "bytes": "137570" }, { "name": "OpenEdge ABL", "bytes": "4768" }, { "name": "PHP", "bytes": "586772" }, { "name": "Pascal", "bytes": "258402" }, { "name": "SAS", "bytes": "13756" }, { "name": "Shell", "bytes": "181035" }, { "name": "Smalltalk", "bytes": "1353" }, { "name": "Smarty", "bytes": "254142" }, { "name": "Yacc", "bytes": "19012" } ], "symlink_target": "" }
# Copyright (c) 2006-2012 Regents of the University of Minnesota. # For licensing terms, see the file LICENSE. from decimal import Decimal import os import sys import conf import g from item import geofeature from item import item_base from item import item_helper from item.util.item_type import Item_Type from util_ import geometry from util_ import gml from util_ import misc log = g.log.getLogger('node_byway') # MAYBE: Is node_byway Big Data? It stores all byways' linestrings' vertices at # the Current revision. We only use it for network connectivity. So # maybe only build the table for import/export/conflate and branch # merging? (This, along with making node_endpoint_xy table, will # probably help with database size -- at least it's easy to test the # difference: keep implementing without addressing this issue, make the # tables, make the branches, dump the database; then do again with this # bug addressed, dump again, and compare dump sizes (there might be a # command-line way to see database size, or maybe just peek in the pgsql # data directory). class One(item_helper.One): item_type = Item_Type.NODE_BYWAY item_type_table = 'node_byway' item_gwis_abbrev = 'nb' child_item_types = None local_defns = [ # py/psql name, deft, send?, pkey?, pytyp, reqv, abbrev ('branch_id', None, False, True, int, None), ('node_stack_id', None, False, True, int, None), ('byway_stack_id', None, False, True, int, None), # NOTE: Usually, we load the WKT, i.e., node_vertex_wkt, but we don't # manipulate this geometry in pyserver, so no biggee, raw is okay. ('node_vertex_xy', None, False, False, str, None), ] attr_defns = item_helper.One.attr_defns + local_defns psql_defns = item_helper.One.psql_defns + local_defns gwis_defns = item_base.One.attr_defns_reduce_for_gwis(psql_defns) __slots__ = [ ] + [attr_defn[0] for attr_defn in local_defns] # *** Constructor def __init__(self, qb=None, row=None, req=None, copy_from=None): g.assurt(copy_from is None) # Not supported for this class. item_helper.One.__init__(self, qb, row, req, copy_from) # *** Built-ins # def __str__(self): s = ('node_byway: br: %s / nd: %s / by: %s' % (self.branch_id, self.node_stack_id, self.byway_stack_id,)) return s # *** GML/XML Processing # def append_gml(self, elem): g.assurt(False) # Doesn't get sent to client. return item_helper.One.append_gml(self, elem) # *** # def is_internal(self): # If the node_byway doesn't reference a node_endpoint, the byway is not # using this x,y as an endpoint, but as an internal node of its # linestring. return not self.node_stack_id # FIXME: Audit: # - When two byways' node_vertex_xy are equal but # not node_stack_id (i.e. different nodes; or # one node is None, meaning x,y is internal for # one of the byways). # - When same byway has node_vertex_xy twice? But the # primary key will prevent that... # FIXME: Where is_internal is TRUE and FALSE for same # node_stack_id (i.e., a byway has a vertex at a place # where other places have a node_endpoint. # Is this part of import/export conny auditing (if z mismatches)? class Many(item_helper.Many): one_class = One __slots__ = () # *** SQL clauseses # Skipping sql_clauses: this class derives from item_helper. # *** Constructor def __init__(self): item_helper.Many.__init__(self) # *** # @staticmethod def get_where_is_internal(self, internals_ok=False, internals_only=False): # If this is not an endpoint node but an intermediate vertex. where_is_internal = "" if internals_only: where_is_internal = "AND (ndby.node_stack_id IS NULL)" elif not internals_ok: where_is_internal = "AND (ndby.node_stack_id IS NOT NULL)" return where_is_internal # def search_by_endpoint_xy(self, qb, pt_xy, internals_ok=False, limit_one=False): # NOTE: On SELECT, PostGIS calls ST_GeomFromEWKT if we don't (we can use # raw geometry or WKT geometry in the SQL). where_vertex_xy = geometry.xy_to_ewkt_point_restrict(pt_xy) radius = pow(0.1, conf.node_precision) * 2.1 # E.g., 0.21 #radius = conf.node_threshold # E.g., 0.11 where_is_internal = Many.get_where_is_internal(internals_ok) # The node_byway table stores lossy geometry. See node_endpoint if you # want the raw point geometry. # pt_xy = (Decimal(str(pt_xy[0])).quantize(conf.node_tolerance), # Decimal(str(pt_xy[1])).quantize(conf.node_tolerance),) pt_xy = (round(pt_xy[0], conf.node_precision), round(pt_xy[1], conf.node_precision),) if limit_one: limit_sql = "LIMIT 1" else: limit_sql = "" # NOTE: We don't use node_endpt_xy table, but rather the node_byway # table. The node_endpt_xy table sounds ideal, but the nodes # in that table may or may not correspond to any current- # versioned byways in the target branch. So use the node_byway # table and we should be able to find a node associated with # a live/current byway. # We used to "AND (ndby.node_vertex_xy = '%s')" # but now we ST_DWithin to allow a little wiggle # room. node_byway_sql = ( """ SELECT ndby.branch_id , ndby.node_stack_id , ndby.byway_stack_id , ndby.node_vertex_xy , ST_Distance(ndby.node_vertex_xy, '%s') AS pt_dist FROM node_byway AS ndby WHERE (ndby.branch_id = %d) AND ST_DWithin(ndby.node_vertex_xy, '%s', %s) %s ORDER BY --ndby.node_stack_id pt_dist ASC %s """ % (where_vertex_xy, qb.branch_hier[0][0], where_vertex_xy, radius, where_is_internal, limit_sql,)) rows = qb.db.sql(node_byway_sql) for row in rows: self.append(self.get_one(qb, row)) # def search_by_node_stack_id(self, qb, node_endpt_id, internals_ok=False): g.assurt(False) # Not currently used... maybe someday? # We don't need this where clause, e.g., ndby.node_stack_id IS NOT NULL # Nope: where_is_internal = Many.get_where_is_internal(internals_ok) rows = qb.db.sql( """ SELECT , ndby.branch_id , ndby.node_stack_id , ndby.byway_stack_id , ndby.node_vertex_xy FROM node_byway AS ndby WHERE ndby.branch_id = %d AND ndby.node_stack_id = %d """ % (qb.branch_hier[0][0], node_endpt_id,)) for row in rows: self.append(self.get_one(qb, row)) # @staticmethod def search_get_stats(qb, node_stack_id, internals_ok=False): # Nope: where_is_internal = Many.get_where_is_internal(internals_ok) # MAYBE: We could calculate referencers with a custom aggregate # that collapses byway_stack_id when we distinct(node_stack_id) # MAYBE: We could also check if node_vertex_xy doesn't match # node_endpoint.endpoint_xy. sql_count_from_node_byway = ( """ SELECT DISTINCT(ndby.node_stack_id) AS node_stack_id , COUNT(ndby.byway_stack_id) AS reference_n /* MAYBE: Coalesce ndby.node_vertex_xy ? */ FROM node_byway AS ndby WHERE ndby.branch_id = %d AND ndby.node_stack_id = %d GROUP BY ndby.node_stack_id """ % (qb.branch_hier[0][0], node_stack_id,)) rows_node_byway = qb.db.sql(sql_count_from_node_byway) if rows_node_byway: g.assurt(len(rows_node_byway) == 1) node_byway_ref_n = rows_node_byway[0]['reference_n'] else: # This happens when adding a byway from a parent branch to a child # branch: it's not there yet... node_byway_ref_n = -1 log.verbose( 'search_get_stats: node_byway: node_stack_id: %s / reference_n: %d' % (node_stack_id, node_byway_ref_n,)) sql_count_from_geofeature = ( """ SELECT COUNT(foo.stack_id) AS reference_n FROM ( SELECT DISTINCT(feat.stack_id) FROM geofeature AS feat JOIN item_versioned AS iv USING (system_id) WHERE ( (feat.beg_node_id = %d) OR (feat.fin_node_id = %d)) AND %s ) AS foo """ % (node_stack_id, node_stack_id, qb.branch_hier_where('iv'), )) rows_geofeature = qb.db.sql(sql_count_from_geofeature) if rows_geofeature: g.assurt(len(rows_geofeature) == 1) geofeature_ref_n = rows_geofeature[0]['reference_n'] log_fcn = log.verbose else: geofeature_ref_n = 0 log_fcn = log.warning log_fcn( 'search_get_stats: geofeature: node_stack_id: %s / reference_n: %d' % (node_stack_id, geofeature_ref_n,)) # This is only called when adding a byway to an intersection, right? # So what's in node_byway is one less than the new count? if (node_byway_ref_n != -1) and (node_byway_ref_n != geofeature_ref_n): log.verbose( 'search_get_stats: node_stack_id: %s / %s: %d != %s: %d' % (node_stack_id, 'node_byway_ref_n', node_byway_ref_n, 'geofeature_ref_n', geofeature_ref_n,)) # The number calculated the line segments' node IDs is accurate; # whatever is in node_byway might be stale... # No: reference_n = node_byway_ref_n reference_n = geofeature_ref_n return reference_n # *** # @staticmethod def reset_rows_for_byway(qb, for_byway, beg_node_id, fin_node_id): log.verbose('reset_rows_for_byway: node_byway: delete: for_byway: %s' % (for_byway,)) # Remove the byway's old entries from the table. rows = qb.db.sql( """ DELETE FROM node_byway WHERE (branch_id = %d) AND (byway_stack_id = %d) """ % (qb.branch_hier[0][0], for_byway.stack_id,)) # Insert the byway's vertices into the table. g.assurt(beg_node_id and fin_node_id) if not for_byway.deleted or for_byway.reverted: Many.insert_rows_for_byway(qb, for_byway, beg_node_id, fin_node_id) # @staticmethod def insert_rows_for_byway(qb, for_byway, beg_node_id, fin_node_id, bulk_list=None): # We don't expect deleted or reverted byways. The node_byway table is # another flattened-branch table, as opposed to a stacked-branch table: # rather than storing just changes in a branch, we store everything from # every branch. So if an item is really reverted in a branch, we won't # see that item but the parent item instead. And if an item is deleted in # a branch, it won't have been fetched for us, anyway (item_user_access # would have weeded it out). g.assurt((not for_byway.deleted) and (not for_byway.reverted)) g.assurt((beg_node_id > 0) and (fin_node_id > 0)) g.assurt(for_byway.geometry_wkt) xys_list = geometry.wkt_line_to_xy(for_byway.geometry_wkt, precision=conf.node_precision) insert_rows = [] last_pt_i = len(xys_list) - 1 for i in xrange(len(xys_list)): pt_xy = xys_list[i] # E.g., "SRID=%s;POINT(%.1f %.1f)" node_vertex_xy = geometry.xy_to_ewkt_point_restrict(pt_xy) if i == 0: g.assurt(beg_node_id > 0) node_id_str = str(beg_node_id) elif i == last_pt_i: g.assurt(fin_node_id > 0) node_id_str = str(fin_node_id) else: node_id_str = "NULL" g.assurt(node_id_str) # I.e., non-empty string. insert_vals = ("(%d, %s, %d, '%s')" % (qb.branch_hier[0][0], node_id_str, for_byway.stack_id, node_vertex_xy,)) insert_rows.append(insert_vals) if bulk_list is not None: bulk_list.extend(insert_rows) else: Many.insert_bulk_byways(qb, insert_rows) # @staticmethod def insert_bulk_byways(qb, bulk_list): # BUG nnnn: Branch Merge: When merging two branches, you have to # recalculate the whole node_byway table for the branch that's # merged to. I'm not sure there's an easier way: since we use stacked # branching, we don't want to record a parent branch byway in # node_byway unless we edit the byway, since we want the record # from the last_merge_rid; then when we merge, all the parent branch # byways that were not edited in the leafy branch have to be # recalculated (so maybe part of merge is to collect all the stack IDs # of things from last_merge_rid that we've updated to the # working_rid, and then we can just repair only those). # The node_byway table is always the latest revision, so no need for # revision_id. And we use the leafy branch ID and not the byway's. log.verbose('insert_bulk_byways: node_byway: insert: bulk_list: %s' % (bulk_list,)) insert_sql = ( """ INSERT INTO node_byway (branch_id , node_stack_id , byway_stack_id , node_vertex_xy) VALUES %s """ % (','.join(bulk_list),)) rows = qb.db.sql(insert_sql) g.assurt(rows is None) # *** Table management indexed_cols = ( 'byway_stack_id', 'node_stack_id', ) # @staticmethod def drop_indices(db): db.sql( """ SELECT cp_constraint_drop_safe('node_byway', 'enforce_valid_geometry') """) db.sql("DROP INDEX IF EXISTS node_byway_node_vertex_xy") # FIXME: This loop shared by the node_ classes. Put in some base class. for col_name in Many.indexed_cols: # E.g., "DROP INDEX IF EXISTS node_byway_branch_id" db.sql("DROP INDEX IF EXISTS node_byway_%s" % (col_name,)) # @staticmethod def make_indices(db): # Drop the indices first. Many.drop_indices(db) # sql_add_constraint = ( """ ALTER TABLE node_byway ADD CONSTRAINT enforce_valid_geometry CHECK (IsValid(node_vertex_xy)) """) db.sql(sql_add_constraint) # # This is the PostGIS 1.x way: USING GIST (... GIST_GEOMETRY_OPS) sql_add_index = ( """ CREATE INDEX node_byway_node_vertex_xy ON node_byway USING GIST (node_vertex_xy) """) db.sql(sql_add_index) # for col_name in Many.indexed_cols: # E.g., # "CREATE INDEX node_byway_branch_id ON node_byway(branch_id)" db.sql("CREATE INDEX node_byway_%s ON node_byway(%s)" % (col_name, col_name,)) # *** # ***
{ "content_hash": "367e8633a4e1bad4426fdf45d4a7027d", "timestamp": "", "source": "github", "line_count": 463, "max_line_length": 79, "avg_line_length": 34.131749460043196, "alnum_prop": 0.5640701132696323, "repo_name": "lbouma/Cyclopath", "id": "8b75af4db35916eeec445c283a11f748a038d97b", "size": "15803", "binary": false, "copies": "1", "ref": "refs/heads/release", "path": "pyserver/item/feat/node_byway.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ActionScript", "bytes": "3369673" }, { "name": "ApacheConf", "bytes": "46372" }, { "name": "C", "bytes": "281248" }, { "name": "CSS", "bytes": "36786" }, { "name": "Gnuplot", "bytes": "14865" }, { "name": "HTML", "bytes": "203213" }, { "name": "Java", "bytes": "688800" }, { "name": "JavaScript", "bytes": "60678" }, { "name": "M4", "bytes": "35700" }, { "name": "Makefile", "bytes": "8036" }, { "name": "PHP", "bytes": "18399" }, { "name": "PLSQL", "bytes": "451" }, { "name": "PLpgSQL", "bytes": "1407944" }, { "name": "Perl", "bytes": "669009" }, { "name": "Python", "bytes": "5830046" }, { "name": "Shell", "bytes": "639435" } ], "symlink_target": "" }
#include <vector> #include <Interval.h> #include <IntervalVector.h> #include <Functions.h> using std::vector; typedef struct _orderS{ vector<int> polyIndex; vector<int *> polyTuple; vector<INTERVAL> polyCoefficient; vector<INTERVAL> polyDerivative; vector<int> errorIndex; vector<int *> errorTuple; vector<int> errorEven; vector<INTERVAL> errorCoefficient; vector<INTERVAL> errorDerivative; } orderS; class Tensor { public: enum OP {CONS, VAR, ADD, SUB, PROD, DIV, POW, SIN, COS, PI, SQRT, SQR, TAN, COT, EXP, LOG, SINH, COSH, TANH, COTH, ARCTAN}; Tensor(int fN, int nV, vector<int*> fexp); virtual ~Tensor(); void setTuples(vector<pair<int *,INTERVAL> >* ti, int t[], int v, int n, INTERVAL c); void setTuples(int order); void computeTensor(INTERVAL_VECTOR & x, int n); INTERVAL integral(int t[], INTERVAL_VECTOR & r); INTERVAL polynomialEval(INTERVAL_VECTOR & x, INTERVAL_VECTOR & mid, INTERVAL_VECTOR & rad, int ord); INTERVAL functionPolynomialEval(INTERVAL_VECTOR & midX, int ord); INTERVAL error(int t[], INTERVAL_VECTOR & x); INTERVAL errorEval(INTERVAL_VECTOR & x, INTERVAL_VECTOR & mid, INTERVAL_VECTOR & rad, int ord); INTERVAL errorEval(INTERVAL_VECTOR & x, INTERVAL_VECTOR & mid, INTERVAL_VECTOR & rad, int ord, INTERVAL & P); INTERVAL functionErrorEval(INTERVAL_VECTOR & midX, int ord); INTERVAL errorDerivatives(int ord); INTERVAL quadratureDerivatives(INTERVAL_VECTOR & x, unsigned int ord); INTERVAL quadratureEval(INTERVAL_VECTOR & x); INTERVAL quadratureError(INTERVAL_VECTOR & x); INTERVAL quadratureError(INTERVAL_VECTOR & x, unsigned int ord); INTERVAL functionEval(INTERVAL_VECTOR & x); INTERVAL functionEval(INTERVAL_VECTOR & x, unsigned int ord); INTERVAL quadratureEval(INTERVAL_VECTOR & x, unsigned int ord); INTERVAL quadratureBestEval(INTERVAL_VECTOR & x, unsigned int & ord); INTERVAL quadratureError(INTERVAL_VECTOR & x, unsigned int ord, INTERVAL & P); INTERVAL quadraturePolynomial(INTERVAL_VECTOR & x, unsigned int ord); INTERVAL quadratureTaylor(INTERVAL_VECTOR & x, unsigned int ord, INTERVAL & P, INTERVAL & R); INTERVAL f(INTERVAL_VECTOR & x); void getT(INTERVAL_VECTOR & x, int nObs, int maxObs,int obsIndex[],INTERVAL fwr[]); INTERVAL getD(INTERVAL_VECTOR & x, INTERVAL df[]); void writeFunction(); void writeFunctionPaver(); int getFunctionDef(); void getFunctionDat(); void setFunction(); void setFunction(string functionName); bool setOrder(int order); void setCurrentSettings(); unsigned long int setOp(OP op); unsigned long int setOp(OP op, unsigned long int arg1); unsigned long int setOp(OP op, unsigned long int arg1, unsigned long int arg2); void setDerivative(); void getDerivative(); unsigned long int setDerivative(unsigned long int i, int t[], int v, int coef); unsigned long int setDerivative(unsigned long int i, int v); void showTuple(int* t); void showConstants(); void showDifferentiationVector(); void showTextVector(); void showIndexes(); bool isEven(int t[]); bool isCorrupted() { return maxOrder<0; } protected: vector<orderS> orderVec; bool changed; vector<int*> fDat; INTERVAL *x_init; vector<pair<OP,unsigned long int *> >* d; vector<int>* c; INTERVAL *t; int fNumber, nVars, nOrder, maxOrder, endIndex; vector<int> orderIndex; vector<int> taylorIndex; vector<INTERVAL> taylorCoefficient; vector<int *> taylorTuple; vector<bool> evenTuple; vector<vector<pair<int *,INTERVAL> >*>* ty; vector<int> polyIndex; vector<int> fIndex; vector<int *> polyTuple; vector<INTERVAL> polyCoefficient; vector<INTERVAL> polyDerivative; vector<INTERVAL> fInterval; vector<int> errorIndex; vector<int *> errorTuple; vector<int> errorEven; vector<INTERVAL> errorCoefficient; vector<INTERVAL> errorDerivative; private: }; #endif // TENSOR_H
{ "content_hash": "b710e4647c24e723304e120865072576", "timestamp": "", "source": "github", "line_count": 109, "max_line_length": 131, "avg_line_length": 40.84403669724771, "alnum_prop": 0.6309523809523809, "repo_name": "marcovc/procure", "id": "63f0746e2315d268c0c1234d2ea099d681e927ad", "size": "4488", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "old/QuadV2/Tensor.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "4688" }, { "name": "C++", "bytes": "327023" }, { "name": "Shell", "bytes": "338698" } ], "symlink_target": "" }
<?php return array( 0 => 'Your name (up to %s characters)', // FORM_COMMENT_INPUT_NAME (label of form input to add a comment expecting username to be entered) 1 => 'Vejs Blog', // LAYOUT_BANNER (text on banner image) 2 => 'Data Privacy', // LAYOUT_NAVI_DATAPRIVACY (text on navigation button to visit data privacy page) 3 => '', // LAYOUT_NAVI_FAQ (text on navigation button to visit 'Frequently Asked Questions' page) 4 => 'Home', // LAYOUT_NAVI_HOME (text on navigation button to go to startpage) 5 => 'Imprint', // LAYOUT_NAVI_IMPRINT (text on navigation button to visit imprint page) 6 => 'NO_LOC', // LAYOUT_SIDEBAR_ABOUTME_TEXT (full text with information about the author) 7 => 'About Me', // LAYOUT_SIDEBAR_ABOUTME_TITLE (caption of sidebar box with information about author) 8 => 'Articles by categorie', // LAYOUT_SIDEBAR_ARTICLES_BY_CATEGORY_TITLE (caption of sidebar box containing a list of the blog articles sorted alphabetically by category) 9 => 'Most viewed articles', // LAYOUT_SIDEBAR_ARTICLES_BY_VISITS_TITLE (caption of sidebar box containing a list of the blog articles with the most views) 10 => 'Crowdfunding Mexico', // LAYOUT_SIDEBAR_CROWDFUNDING_TITLE (caption of sidebar box containing the crowdfunding applet) 11 => 'Visitors since 11/09/2014', // LAYOUT_SIDEBAR_VISITORS_TITLE (caption of sidebar box containing a simple page hit counter) 12 => 'Vejs Blog', // LAYOUT_TITLE (text of page window/tab) );
{ "content_hash": "5cd28910b05d7e5a9b0683a8f317647f", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 176, "avg_line_length": 88.47058823529412, "alnum_prop": 0.706781914893617, "repo_name": "Siebeldorn/vejsblogplain", "id": "5c76fd10041e32a5beded7ec13796d4277d329dc", "size": "1506", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "code/website/include/loca/loca_en.inc.php", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "198" }, { "name": "C#", "bytes": "6831" }, { "name": "CSS", "bytes": "10992" }, { "name": "JavaScript", "bytes": "534" }, { "name": "PHP", "bytes": "60591" } ], "symlink_target": "" }
/*jslint nomen: false, plusplus: false, strict: false */ /*global require: false, define: false, window: false, document: false, setTimeout: false */ (function () { //Sadly necessary browser inference due to differences in the way //that browsers load and execute dynamically inserted javascript //and whether the script/cache method works. //Currently, Gecko and Opera do not load/fire onload for scripts with //type="script/cache" but they execute injected scripts in order //unless the 'async' flag is present. //However, this is all changing in latest browsers implementing HTML5 //spec. Firefox nightly supports using the .async true by default, and //if false, then it will execute in order. Favor that test first for forward //compatibility. However, it is unclear if webkit/IE will follow suit. //Latest webkit breaks the script/cache trick. //Test for document and window so that this file can be loaded in //a web worker/non-browser env. It will not make sense to use this //plugin in a non-browser env, but the file should not error out if included //in a file, then loaded in a non-browser env. var supportsInOrderExecution = typeof document !== "undefined" && typeof window !== "undefined" && (document.createElement("script").async || (window.opera && Object.prototype.toString.call(window.opera) === "[object Opera]") || //If Firefox 2 does not have to be supported, then //a better check may be: //('mozIsLocallyAvailable' in window.navigator) ("MozAppearance" in document.documentElement.style)), readyRegExp = /^(complete|loaded)$/, waiting = [], cached = {}; function loadResource(name, req, onLoad) { req([name], function (value) { //The value may be a real defined module. Wrap //it in a function call, because this function is used //as the factory function for this ordered dependency. onLoad(function () { return value; }); }); } //Callback used by the type="script/cache" callback that indicates a script //has finished downloading. function scriptCacheCallback(evt) { var node = evt.currentTarget || evt.srcElement, i, moduleName, resource; if (evt.type === "load" || readyRegExp.test(node.readyState)) { //Pull out the name of the module and the context. moduleName = node.getAttribute("data-requiremodule"); //Mark this cache request as loaded cached[moduleName] = true; //Find out how many ordered modules have loaded for (i = 0; (resource = waiting[i]); i++) { if (cached[resource.name]) { loadResource(resource.name, resource.req, resource.onLoad); } else { //Something in the ordered list is not loaded, //so wait. break; } } //If just loaded some items, remove them from waiting. if (i > 0) { waiting.splice(0, i); } //Remove this script tag from the DOM //Use a setTimeout for cleanup because some older IE versions vomit //if removing a script node while it is being evaluated. setTimeout(function () { node.parentNode.removeChild(node); }, 15); } } define({ version: '0.24.0', load: function (name, req, onLoad, config) { var url = req.nameToUrl(name, null); //If a build, just load the module as usual. if (config.isBuild) { loadResource(name, req, onLoad); return; } //Make sure the async attribute is not set for any pathway involving //this script. require.s.skipAsync[url] = true; if (supportsInOrderExecution) { //Just a normal script tag append, but without async attribute //on the script. req([name], function (value) { //The value may be a real defined module. Wrap //it in a function call, because this function is used //as the factory function for this ordered dependency. onLoad(function () { return value; }); }); } else { //Credit to LABjs author Kyle Simpson for finding that scripts //with type="script/cache" allow scripts to be downloaded into //browser cache but not executed. Use that //so that subsequent addition of a real type="text/javascript" //tag will cause the scripts to be executed immediately in the //correct order. if (req.isDefined(name)) { req([name], function (value) { //The value may be a real defined module. Wrap //it in a function call, because this function is used //as the factory function for this ordered dependency. onLoad(function () { return value; }); }); } else { waiting.push({ name: name, req: req, onLoad: onLoad }); require.attach(url, "", name, scriptCacheCallback, "script/cache"); } } } }); }());
{ "content_hash": "3897eb5eeaa8461fa5457f975284cabc", "timestamp": "", "source": "github", "line_count": 136, "max_line_length": 117, "avg_line_length": 43.73529411764706, "alnum_prop": 0.5309347679892401, "repo_name": "joshfire-platform-templates/event", "id": "8012803cc38f77d967da5381c4d5cb4935afa7d5", "size": "6157", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "app/joshfire/vendor/require.order.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "1205698" } ], "symlink_target": "" }
<?php namespace App\Http\Controllers; use App\SessionDevice; use App\SessionReferer; use Illuminate\Database\Eloquent\Builder; use Illuminate\Http\Request; use Illuminate\Support\Carbon; use Yajra\Datatables\Datatables; class VisitorController extends Controller { public function devices(Request $request) { return response()->view('visitors.devices', [ 'visitedFrom' => $request->input('visited_from', 'today - 30 days'), 'visitedTo' => $request->input('visited_to', 'now'), 'subscriber' => $request->input('subscriber', "1"), 'brands' => SessionDevice::distinct()->whereNotNull('brand')->pluck('brand', 'brand'), 'models' => SessionDevice::distinct()->whereNotNull('model')->pluck('model', 'model'), 'osNames' => SessionDevice::distinct()->whereNotNull('os_name')->pluck('os_name', 'os_name'), ]); } public function sources(Request $request) { return response()->view('visitors.sources', [ 'visitedFrom' => $request->input('visited_from', 'today - 30 days'), 'visitedTo' => $request->input('visited_to', 'now'), 'subscriber' => $request->input('subscriber', "1"), 'mediums' => SessionReferer::distinct()->whereNotNull('medium')->pluck('medium', 'medium'), 'sources' => SessionReferer::distinct()->whereNotNull('source')->pluck('source', 'source'), ]); } public function dtBrowsers(Request $request, Datatables $datatables) { $devices = SessionDevice::selectRaw(implode(',', [ 'client_name', 'client_type', 'SUM(count) as visits_count', ]))->groupBy('client_name', 'client_type'); if ($request->input('visited_from')) { $devices->where('time_from', '>=', Carbon::parse($request->input('visited_from'), $request->input('tz'))); } if ($request->input('visited_to')) { $devices->where('time_to', '<=', Carbon::parse($request->input('visited_to'), $request->input('tz'))); } if ($request->input('subscriber') !== null) { $devices->where(['subscriber' => $request->input('subscriber')]); } return $datatables->of($devices) ->filterColumn('model', function (Builder $query, $value) { $values = explode(",", $value); $query->whereIn('model', $values); }) ->filterColumn('brand', function (Builder $query, $value) { $values = explode(",", $value); $query->whereIn('brand', $values); }) ->filterColumn('os_name', function (Builder $query, $value) { $values = explode(",", $value); $query->whereIn('os_name', $values); }) ->make(true); } public function dtDevices(Request $request, Datatables $datatables) { $devices = SessionDevice::selectRaw(implode(',', [ 'model', 'brand', 'os_name', 'SUM(count) as visits_count', ]))->whereNotNull('model')->groupBy('model', 'brand', 'os_name'); if ($request->input('visited_from')) { $devices->where('time_from', '>=', Carbon::parse($request->input('visited_from'), $request->input('tz'))); } if ($request->input('visited_to')) { $devices->where('time_to', '<=', Carbon::parse($request->input('visited_to'), $request->input('tz'))); } if ($request->input('subscriber') !== null) { $devices->where(['subscriber' => $request->input('subscriber')]); } return $datatables->of($devices) ->filterColumn('model', function (Builder $query, $value) { $values = explode(",", $value); $query->whereIn('model', $values); }) ->filterColumn('brand', function (Builder $query, $value) { $values = explode(",", $value); $query->whereIn('brand', $values); }) ->filterColumn('os_name', function (Builder $query, $value) { $values = explode(",", $value); $query->whereIn('os_name', $values); }) ->make(true); } public function dtReferers(Request $request, Datatables $datatables) { $devices = SessionReferer::selectRaw(implode(',', [ 'medium', 'source', 'SUM(count) as visits_count', ]))->groupBy('medium', 'source'); if ($request->input('visited_from')) { $devices->where('time_from', '>=', Carbon::parse($request->input('visited_from'), $request->input('tz'))); } if ($request->input('visited_to')) { $devices->where('time_to', '<=', Carbon::parse($request->input('visited_to'), $request->input('tz'))); } if ($request->input('subscriber') !== null) { $devices->where(['subscriber' => $request->input('subscriber')]); } return $datatables->of($devices) ->filterColumn('source', function (Builder $query, $value) { $values = explode(",", $value); $query->whereIn('source', $values); }) ->filterColumn('medium', function (Builder $query, $value) { $values = explode(",", $value); $query->whereIn('medium', $values); }) ->make(true); } }
{ "content_hash": "c21dadb34dedb29a9116e4a411e515da", "timestamp": "", "source": "github", "line_count": 137, "max_line_length": 118, "avg_line_length": 40.262773722627735, "alnum_prop": 0.5248368382886149, "repo_name": "remp2020/remp", "id": "61ad3e26f6127ee44e972ee9b3207c02776f8401", "size": "5516", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Beam/app/Http/Controllers/VisitorController.php", "mode": "33188", "license": "mit", "language": [ { "name": "Blade", "bytes": "256438" }, { "name": "Dockerfile", "bytes": "4421" }, { "name": "Go", "bytes": "256155" }, { "name": "HTML", "bytes": "718" }, { "name": "JavaScript", "bytes": "190835" }, { "name": "Latte", "bytes": "206516" }, { "name": "Makefile", "bytes": "7623" }, { "name": "PHP", "bytes": "3150894" }, { "name": "SCSS", "bytes": "307946" }, { "name": "Shell", "bytes": "34385" }, { "name": "Vue", "bytes": "592721" } ], "symlink_target": "" }
/** * */ package controllers; import java.util.List; import models.NamedModel; import models.PSIMessage; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import play.Logger; import play.Play; import play.db.jpa.JPA; import play.mvc.Before; import play.mvc.Controller; import play.mvc.Http; import play.mvc.Http.Header; import play.mvc.results.Status; import util.ConfKeys; import util.GsonBinder; import util.Util; /** * Superclass for all PSI controllers that sets the HTTP header * {@code Access-Control-Allow-Origin} to {@code *} to allow JavaScript * clients. * <p> * Also centralises support for checking if a JSON request was badly * formed (since Play!'s mechanism for dealing with these is to fail * silently without telling my code), and for rendering simple responses * consisting of a non-200 (but successful) status code and a single * information-carrying header field. */ public abstract class CORSController extends Controller { /** A Gson instance which will escape characters in strings. */ private static final Gson GSON_W_ESCAPING = new Gson(); /** Header property name for location (of created or other resource). */ protected static final String LOCATION = "Location"; //Note that Play! converts any received request headers to lowercase, so ones we check for must also be lowercase private static final String ACRH = "access-control-request-headers"; private static final String ACAH = "Access-Control-Allow-Headers"; private static final String ACEH = "Access-Control-Expose-Headers"; private static final String ACRM = "access-control-request-method"; private static final String ACAM = "Access-Control-Allow-Methods"; /** * Generates NOT FOUND with a template message that indicates the system * thinks it knows what the user was looking for, and which points to the * URI where a list of existing items of that type can be found. * @param what name of the thing the client was looking for (must start * with a consonant for the message to make sense at the moment) * @param listAction the ControllerName.methodName action that would * generate the required resource list. */ protected static void notFoundSeeList(final String what, final String listAction, Object... actionArgs) { notFound("You appear to be looking for a " + what + " that does not exist. The list of available " + what + "s is at: " + Util.getReverseRoute(listAction, actionArgs)); } /** * Supports sending back details of why the request was bad, something that * the designers of Play didn't seem to think was important. */ protected static void badRequest(String message) { JPA.setRollbackOnly(); //Since Play DOES NOT do this automatically, as I previously believed (and, frankly, as it should on an error()) if (request.format.equals("json")) //since (1) Gson does not expose character escaping functions and (2) the 400.json file is just a text template message = GSON_W_ESCAPING.toJsonTree(message).toString().replaceAll("(^\\\"|\\\"$)", ""); error(Http.StatusCode.BAD_REQUEST, message); } /** * Subclasses that expect a non-null, valid JSON request should call this * with the GsonBinder-parsed request (which may be a specially-created * object with a single error property set) to check that the request was * syntactically valid JSON. If it isn't then this method will use * {@link #error(int, String)} to report a bad request to the client. */ protected static void failOnJSONSyntaxError(JsonObject req) { if (req.has(GsonBinder.ERROR_PROPERTY)) badRequest(req.get(GsonBinder.ERROR_PROPERTY).getAsString()); } /** * Subclasses should call this immediately after parsing a JSON request * into a specific subclass of {@link PSIRequest} to ensure that the * request appears to be valid (has the correct type field, etc.). */ protected static void failOnInvalidMessage(PSIMessage req) { if (! req.isValid()) badRequest(req.getValidationErrorMessage()); } /** * Subclasses can use this method to perform the following common sequence: * {@linkplain #failOnJSONSyntaxError(JsonObject) check the received JSON * request was free from errors}, extract the * specified POJO from the JSON request body, and {@linkplain * #failOnInvalidMessage(PSIRequest) perform basic validation on the * request message}. */ protected static <T extends PSIMessage> T parseAndCheckRequestBody(JsonObject body, Class<T> messageClass) { failOnJSONSyntaxError(body); T req = Util.GSON.fromJson(body, messageClass); failOnInvalidMessage(req); return req; } @Before public static void setCORS() { Logger.info("Received request: %s %s from %s", request.method, Util.requestPath(), request.remoteAddress); if (request.headers.containsKey("origin")) { Logger.trace("CORS request headers: %s", request.headers); Http.Response.current().accessControl("*"); if (Http.Request.current().headers.containsKey(ACRH)) { response.headers.put(ACAH, Http.Request.current().headers.get(ACRH)); } //Allow Location header field to be seen in CORS requests; may need to expand this list (Actually, it's on the whitelist, so this shouldn't be necessary) Http.Response.current().setHeader(ACEH, "Location"); Logger.trace("After setting CORS headers, Http.Response.current().headers == %s", Http.Response.current().headers); } } public static void basicOptions() { Logger.trace("Received an OPTIONS request: Request headers are %s", Http.Request.current().headers); //The CORS should be handled by the superclass's @Before handler response.status = Http.StatusCode.OK; //FIXME Should probably be more restrictive than this if (request.headers.containsKey(ACRH)) { response.headers.put(ACAH, request.headers.get(ACRH)); } if (request.headers.containsKey(ACRM)) { //Required to support responses to POSTs that redirect (to GET) when the request is preceded by a preflight OPTIONS request Header acrmHeader = request.headers.get(ACRM); response.headers.put(ACAM, acrmHeader); } Logger.trace("Response to OPTIONS request has these headers: %s", Http.Response.current().headers); } /** * Performs pretty printing using Gson before returning an * {@code application/json} response. Include {@code null}-valued fields, * since if they are still present in the given {@code JsonElement} then * whoever performed the original serialization clearly intended for them * to be kept. */ protected static void renderJSON(JsonElement json) { renderJSON( Util.PP_GSON_W_NULLS.toJson(json) ); } /** * Serializes the given object and then pretty prints it using Gson before * returning an {@code application/json} response. Null-valued fields are * not serialized. */ protected static void renderJSON(Object o) { renderJSON( Util.PP_GSON.toJson(o) ); } /** Convenience method to set the status, set a single header field and respond to the client. */ protected static void renderSimpleResponse(final int status, final String header, final String value, Http.Response responseToUse) { responseToUse = responseToUse == null ? Http.Response.current() : responseToUse; if (header != null) responseToUse.setHeader(header, value); responseToUse.headers.put(ACAM, new Header(ACAM, java.util.Arrays.asList(new String[]{"GET", "OPTIONS"}))); Logger.trace("Prior to sending, the status only response (%d) has these headers: %s", status, responseToUse.headers); throw new Status(status); } protected static void renderCreated(final String location, Http.Response responseToUse) { renderSimpleResponse(Http.StatusCode.CREATED, "Location", location, responseToUse); } protected static void renderDeleted() { renderSimpleResponse(Http.StatusCode.NO_RESPONSE, null, null, null); } /** * Renders a sorted URI list in JSON or HTML using the current request path * and names of all persistent models for the given {@code modelClass}. * @see #listAll(List, boolean) */ protected static void listAll(Class<? extends NamedModel> modelClass) { listAll(modelClass, null); } /** * Renders a URI list in JSON or HTML using the current request path and * names of all persistent models for the given {@code modelClass}. * @param kind An additional parameter that will be passed to the HTML * template renderer and thus will be available for use in the relevant * controller's template, if needed. * @see #listAll(Class, String) */ @SuppressWarnings("unchecked") //The 'name' property is of type string in every NamedModel in this system protected static void listAll(Class<? extends NamedModel> modelClass, String kind) { listAll((List<String>) JPA.em().createQuery("select name from " + modelClass.getSimpleName() + " order by name").getResultList(), kind); } /** * Renders a URI list in JSON or HTML using the current request path and * given resource names. If resources are database models then use * {@link #listAll(Class) or #listAll(Class, String)} instead. * @see #listAll(List, String) */ protected static void listAll(final List<String> resourceNames) { listAll(resourceNames, null); } /** * Renders a URI list in JSON or HTML using the current request path and * given resource names. If resources are database models then use * {@link #listAll(Class) or #listAll(Class, String)} instead. Resource * collections are all rendered the same way, only the content of the * collection changes. If rendering HTML, an appropriate {@code * listAll.html} template needs to be defined for the appropriate * controller though, in which the resource list must be called {@code * resources} (since Play does some automagical matching using the argument * variable's <em>name</em>). */ protected static void listAll(final List<String> resourceNames, String kind) { String representation = Application.generateResourceListAsJSON( Util.requestPath(), resourceNames); if (request.format == null || request.format.equals("json")) renderJSON( representation ); else if (request.format.equals("html")) render(resourceNames, kind, representation); renderText("Cannot represent request PSI Resource List in " + request.format); } }
{ "content_hash": "14a5bca76e83058ad86c8a1a30999078", "timestamp": "", "source": "github", "line_count": 237, "max_line_length": 170, "avg_line_length": 44.28270042194093, "alnum_prop": 0.7220581229156742, "repo_name": "psi-project/server", "id": "8da7b98f5a819c74c4e68f872cae6ab02c4a36c0", "size": "10495", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/controllers/CORSController.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "391" }, { "name": "Java", "bytes": "365543" }, { "name": "JavaScript", "bytes": "56304" } ], "symlink_target": "" }
package com.maimieng.bbs.mapper; import com.maimieng.bbs.po.User; import com.maimieng.bbs.po.UserVo; public interface UserMapperCustom { public User verifyUserName(String username) throws Exception; public User verifyLogin(UserVo userVo) throws Exception; }
{ "content_hash": "69c13960dff661848bcd368ea578cfb4", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 62, "avg_line_length": 29, "alnum_prop": 0.8160919540229885, "repo_name": "kingcos/CourseDesign", "id": "1558c3e60d5dfc8d7f4a0407e9d1f83b14f18abf", "size": "261", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "iBlog/BBS_with_SpringMVC_MyBatis/src/com/maimieng/bbs/mapper/UserMapperCustom.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "166" }, { "name": "CSS", "bytes": "49140" }, { "name": "HTML", "bytes": "7371" }, { "name": "Java", "bytes": "302939" }, { "name": "JavaScript", "bytes": "30952" }, { "name": "Objective-C", "bytes": "74061" } ], "symlink_target": "" }
<?php namespace NewsBundle\Model; use NewsBundle\Model\PostInterface; /** * * @author piro */ interface PostMediaItemInterface extends MediaItemAwareInterface { /** * * @return PostInterface */ public function getPost(); /** * * @param PostInterface $post */ public function setPost(PostInterface $post); }
{ "content_hash": "99f9878f138f82f984d8c4148cb09aa8", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 64, "avg_line_length": 14.4, "alnum_prop": 0.6361111111111111, "repo_name": "piron4o/tg_news", "id": "b645370c15281d43108ef3f5883ca279b53e4459", "size": "360", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/NewsBundle/Model/PostMediaItemInterface.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3605" }, { "name": "CSS", "bytes": "134" }, { "name": "HTML", "bytes": "14696" }, { "name": "PHP", "bytes": "159884" } ], "symlink_target": "" }
using NUnit.Framework; namespace Shouldly.Tests.TestHelpers { [TestFixture] public abstract class ShouldlyShouldFailureTestScenario { protected abstract void ShouldThrowAWobbly(); protected abstract string ChuckedAWobblyErrorMessage { get; } [Test] public void ShouldMethodShouldThrowAWobbly() { Should.Error(ShouldThrowAWobbly, ChuckedAWobblyErrorMessage); } } }
{ "content_hash": "206b02eaea605a9c2c9c66b0ca299449", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 73, "avg_line_length": 25.941176470588236, "alnum_prop": 0.691609977324263, "repo_name": "KennyBu/shouldly", "id": "7bb4f9d4713c233b614992a85a04fb100a7192ba", "size": "441", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "src/Shouldly.Tests/TestHelpers/ShouldlyShouldFailureTestScenario.cs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C#", "bytes": "683844" } ], "symlink_target": "" }
<html> <head> <title>চা Script - Coding Environment </title> <meta name="description" content="Cha Script Code Editor. Write your code in this editor."> <meta name="keywords" content="code,editor,code editor,bengali,programming language,programming,bangla,cha,script,cha script" /> <meta name="robots" content="index,follow"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="icon" type="image/png" href="images/favicon.png"> <script src="js/jquery.js"></script> <script src="js/bootstrap.js"></script> <script type="text/javascript" src="js/jquery.tooltipster.js"></script> <script src="js/jquery.a-tools-1.4.1.js"></script> <script src="js/jquery.asuggest.js"></script> <script src="js/base64.js"></script> <script src="js/text.js"></script> <script src="js/formState.js"></script> <script src="js/jquery-linedtextarea.js"></script> <link href="css/jquery-linedtextarea.css" type="text/css" rel="stylesheet" /> <link href="css/bootstrap.css" type="text/css" rel="stylesheet" /> <link rel="stylesheet" type="text/css" href="css/tooltipster.css" /> <link href="css/style.css" type="text/css" rel="stylesheet" /> <script> $(function() { $("#codee").linedtextarea( {selectedLine: 1} ); }); $(function(){ $('[rel="tooltip"]').tooltip(); }); $(document).ready(function() { $('.tooltip').tooltipster(); }); $(window).load(function() { $('#loading').hide(); }); </script> </head> <body> <!-- facebook like share plugin --> <div class="fb-like" data-href="https://www.facebook.com/chascript" data-width="100px" data-layout="button_count" data-action="like" data-show-faces="true" data-share="true" style="position: fixed; top: 47px; right: 80px;border: 1px solid;border-radius: 4px;"></div> <div id="fb-root"></div> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&appId=485258221589254&version=v2.0"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); </script> <div class="container-non-responsive"> <div class="head"> <nav class="cnav"> <img class="logo" src="images/logo2.png" alt="some_text"> <ul class="pull-right"> <li><a href="index.html"><span class="glyphicon glyphicon-home"></span> Home</a> </li> <li> <a href="code.html"><span class="glyphicon glyphicon-align-left"></span> কোড করুন</a></li> <li><a href="examples.html"><span class="glyphicon glyphicon-list-alt"></span> Examples</a> </li> <li><a href="tutorial.html"><span class="glyphicon glyphicon-edit"></span> Tutorial</a> </li> </ul> </nav> </div> <form style="display:inline" method="post" action="" id="formToSave _undoable_keystroke"> <div class="row first"> <div class="col-xs-7 first-left"> <div class="row navcode"> <nav class="enav"> <div class="col-xs-1 btitle">Code</div> <div class="col-xs-6 pull-right"> <ul class="pull-right"> <li rel="tooltip" data-placement="top" data-original-title="Undo" > <a href="#" onFocus="this.blur()" onClick="formState.undo(this)" name="Undo"><span class="glyphicon glyphicon-circle-arrow-left"></span>&nbsp;</a> </li> <li rel="tooltip" data-placement="top" data-original-title="Redo"> <a href="#" onFocus="this.blur()" onClick="formState.redo(this)" name="Redo"><span class="glyphicon glyphicon-circle-arrow-right"></span>&nbsp;</a> </li> <li rel="tooltip" data-placement="top" data-original-title="Delete"> <a href="#" id="cleare"><span style="font-size:0.86em" class=" glyphicon glyphicon-trash"></span>&nbsp;</a> </li> <a href="#" id = 'btn' class="run" ><span class="glyphicon glyphicon-cog"></span> Run</a> </ul> </div> </nav> </div> <div class="row"><textarea name = "code" style = "width:100%" rows = "24" id = "codee" class="editor"></textarea> </div> </form> </div> <!--end of col 6 --> <div class="col-xs-4 first-right"> <div class="row navcode"> <nav class="enav"> <div class="col-xs-1 btitle">Result</div> <div class="col-xs-6 pull-right"> <ul class="pull-right"> <li rel="tooltip" data-placement="top" data-original-title="Delete"> <a href="#" id="clearr"> &nbsp;<span style="font-size:0.86em" class=" glyphicon glyphicon-trash"></span></a></li> </ul> </div> </nav> </div> <div class="row result"><textarea id = 'hi' style = "width:100%" rows="12" class="result" ></textarea></div> <div class="row bottom" style=""> <div class="row keywords"> <div class="col-xs-3" onclick="insertAtCaret('codee', 'নাও()');return false;"> <a href="#" class="nao c"><span class="glyphicon glyphicon-log-in"></span>&nbsp;&nbsp;নাও</a> </div> <div class="col-xs-3" onclick="insertAtCaret('codee', 'দেখাও()');return false;"> <a href="#" class="dekhao b"><span class="glyphicon glyphicon-log-out"></span>&nbsp;&nbsp;দেখাও</a> </div> <div class="col-xs-3" onclick="insertAtCaret('codee', 'ফাংশন');return false;"> <a href="#" class="function a"><strong><span style="font-size:1.10em">f(x)</span></strong> ফাংশন</a> </div> <div class="col-xs-3" onclick="insertAtCaret('codee', 'উত্তর');return false;"> <a href="#" class="uttor d"><span class="glyphicon glyphicon-repeat"></span>&nbsp;&nbsp;উত্তর</a> </div> </div> <div class="row keywords"> <div class="col-xs-3"> <a href="#" class="shorto a" onclick="insertAtCaret('codee', 'যদি()\n{\n\n}\nনাহলে যদি()\n{\n\n}\nনাহলে\n{\n\n}');return false;"> <span style="font-size:0.86em" class="glyphicon glyphicon-random"></span>&nbsp;&nbsp;সর্ত</a> </div> <div class="col-xs-3" onclick="insertAtCaret('codee', 'যদি()');return false;"> <a href="#" class="jodi c"><span class=" glyphicon glyphicon-unchecked"></span>&nbsp;&nbsp;যদি</a> </div> <div class="col-xs-3" onclick="insertAtCaret('codee', 'নাহলে');return false;"> <a href="#" class="nahole d"><span class="glyphicon glyphicon-unchecked"></span>&nbsp;&nbsp;নাহলে</a> </div> <div class="col-xs-3" onclick="insertAtCaret('codee', 'সংখ্যা()');return false;"> <a href="#" class="songkha b"><span style="font-size:0.86em" class="glyphicon glyphicon-sort-by-order-alt"></span>&nbsp;&nbsp; সংখ্যা</a> </div> </div> <div class="row keywords"> <div class="col-xs-3"> <a href="#" class="cholbe d" onclick="insertAtCaret('codee', 'চলবে\n{\n যদি()\n {\n থামো\n }\n}');return false;"><span style="font-size:1.04em" class="glyphicon glyphicon-retweet"></span> &nbsp;&nbsp;চলবে</a> </div> <div class="col-xs-3" onclick="insertAtCaret('codee', 'থামো');return false;"> <a href="#" class="thamo a"><span style="font-size:0.86em" class="glyphicon glyphicon-off"></span> &nbsp;&nbsp;থামো</a> </div> <div class="col-xs-3" onclick="insertAtCaret('codee', 'বাদ');return false;"> <a href="#" class="baad b"><span style="font-size:0.86em" class="glyphicon glyphicon-remove"></span> &nbsp;&nbsp;বাদ</a> </div> <div class="col-xs-3" onclick="insertAtCaret('codee', 'ঃআছে()');return false;"> <a href="#" class="acche c"><span style="font-size:0.86em" class="glyphicon glyphicon-search"></span>&nbsp;&nbsp; আছে</a> </div> </div> <div class="row keywords"> <div class="col-xs-3" onclick="insertAtCaret('codee', 'সেট()');return false;"> <a href="#" class="set b"><span style="font-size:0.86em" class="glyphicon glyphicon-tasks"></span> &nbsp;&nbsp;সেট</a> </div> <div class="col-xs-3" onclick="insertAtCaret('codee', 'ঃআয়তন');return false;"> <a href="#" class="ayoton d"><span class=" glyphicon glyphicon-resize-vertical"></span>&nbsp;&nbsp; আয়তন</a> </div> <div class="col-xs-3" onclick="insertAtCaret('codee', 'ঃরাখো()');return false;"> <a href="#" class="rakho c"><span class="glyphicon glyphicon-arrow-down"></span> &nbsp;&nbsp;রাখো</a> </div> <div class="col-xs-3" onclick="insertAtCaret('codee', 'ঃসরাও()');return false;"> <a href="#" class="shorao a"><span class="glyphicon glyphicon-arrow-up"></span> &nbsp;&nbsp;সরাও</a> </div> </div> </div> </div> </div> <div class="row col-xs-7 second"> <nav class="enav"> <ul> <p style="display:inline;"><span class="glyphicon glyphicon-folder-open"></span> Load <input style="display:inline;" type="file" id="fileInput"></p> <a href="javascript://Save as TXT" id="submitLink" class="pull-right save"><span class="glyphicon glyphicon-floppy-disk"></span> Save</a> </ul> </nav> </div> </div> <script src="js/jScritp.js"></script> <script src="js/print.js"></script> <script src="js/toktrans.js"></script> </body> <div id="loading"> <img id="loading-image" src="images/loader.png" alt="Loading..." /> </div> </html>
{ "content_hash": "7b2f0b159ada20399a8dd931b8e0c114", "timestamp": "", "source": "github", "line_count": 183, "max_line_length": 270, "avg_line_length": 54.08743169398907, "alnum_prop": 0.5609213982622752, "repo_name": "ts270890/ts270890.github.io", "id": "291d936870bee853e90a2eb12810ee67a2b01f22", "size": "10222", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "chascript/code.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "126751" }, { "name": "HTML", "bytes": "31829" }, { "name": "JavaScript", "bytes": "43054" } ], "symlink_target": "" }
// This file was generated by Mendix Business Modeler. // // WARNING: Code you write here will be lost the next time you deploy the project. package system.proxies; import com.mendix.core.Core; import com.mendix.core.CoreException; import com.mendix.systemwideinterfaces.core.IContext; import com.mendix.systemwideinterfaces.core.IMendixIdentifier; import com.mendix.systemwideinterfaces.core.IMendixObject; /** * */ public class Session { private final IMendixObject sessionMendixObject; private final IContext context; /** * Internal name of this entity */ public static final String entityName = "System.Session"; /** * Enum describing members of this entity */ public enum MemberNames { SessionId("SessionId"), LastActive("LastActive"), Session_User("System.Session_User"); private String metaName; MemberNames(String s) { metaName = s; } @Override public String toString() { return metaName; } } public Session(IContext context) { this(context, Core.instantiate(context, "System.Session")); } protected Session(IContext context, IMendixObject sessionMendixObject) { if (sessionMendixObject == null) throw new IllegalArgumentException("The given object cannot be null."); if (!Core.isSubClassOf("System.Session", sessionMendixObject.getType())) throw new IllegalArgumentException("The given object is not a System.Session"); this.sessionMendixObject = sessionMendixObject; this.context = context; } /** * @deprecated Use 'Session.load(IContext, IMendixIdentifier)' instead. */ @Deprecated public static system.proxies.Session initialize(IContext context, IMendixIdentifier mendixIdentifier) throws CoreException { return system.proxies.Session.load(context, mendixIdentifier); } /** * Initialize a proxy using context (recommended). This context will be used for security checking when the get- and set-methods without context parameters are called. * The get- and set-methods with context parameter should be used when for instance sudo access is necessary (IContext.getSudoContext() can be used to obtain sudo access). */ public static system.proxies.Session initialize(IContext context, IMendixObject mendixObject) { return new system.proxies.Session(context, mendixObject); } public static system.proxies.Session load(IContext context, IMendixIdentifier mendixIdentifier) throws CoreException { IMendixObject mendixObject = Core.retrieveId(context, mendixIdentifier); return system.proxies.Session.initialize(context, mendixObject); } public static java.util.List<system.proxies.Session> load(IContext context, String xpathConstraint) throws CoreException { java.util.List<system.proxies.Session> result = new java.util.ArrayList<system.proxies.Session>(); for (IMendixObject obj : Core.retrieveXPathQuery(context, "//System.Session" + xpathConstraint)) result.add(system.proxies.Session.initialize(context, obj)); return result; } /** * Commit the changes made on this proxy object. */ public final void commit() throws CoreException { Core.commit(context, getMendixObject()); } /** * Commit the changes made on this proxy object using the specified context. */ public final void commit(IContext context) throws CoreException { Core.commit(context, getMendixObject()); } /** * Delete the object. */ public final void delete() { Core.delete(context, getMendixObject()); } /** * Delete the object using the specified context. */ public final void delete(IContext context) { Core.delete(context, getMendixObject()); } /** * @return value of SessionId */ public final String getSessionId() { return getSessionId(getContext()); } /** * @param context * @return value of SessionId */ public final String getSessionId(IContext context) { return (String) getMendixObject().getValue(context, MemberNames.SessionId.toString()); } /** * Set value of SessionId * @param sessionid */ public final void setSessionId(String sessionid) { setSessionId(getContext(), sessionid); } /** * Set value of SessionId * @param context * @param sessionid */ public final void setSessionId(IContext context, String sessionid) { getMendixObject().setValue(context, MemberNames.SessionId.toString(), sessionid); } /** * @return value of LastActive */ public final java.util.Date getLastActive() { return getLastActive(getContext()); } /** * @param context * @return value of LastActive */ public final java.util.Date getLastActive(IContext context) { return (java.util.Date) getMendixObject().getValue(context, MemberNames.LastActive.toString()); } /** * Set value of LastActive * @param lastactive */ public final void setLastActive(java.util.Date lastactive) { setLastActive(getContext(), lastactive); } /** * Set value of LastActive * @param context * @param lastactive */ public final void setLastActive(IContext context, java.util.Date lastactive) { getMendixObject().setValue(context, MemberNames.LastActive.toString(), lastactive); } /** * @return value of Session_User */ public final system.proxies.User getSession_User() throws CoreException { return getSession_User(getContext()); } /** * @param context * @return value of Session_User */ public final system.proxies.User getSession_User(IContext context) throws CoreException { system.proxies.User result = null; IMendixIdentifier identifier = getMendixObject().getValue(context, MemberNames.Session_User.toString()); if (identifier != null) result = system.proxies.User.load(context, identifier); return result; } /** * Set value of Session_User * @param session_user */ public final void setSession_User(system.proxies.User session_user) { setSession_User(getContext(), session_user); } /** * Set value of Session_User * @param context * @param session_user */ public final void setSession_User(IContext context, system.proxies.User session_user) { if (session_user == null) getMendixObject().setValue(context, MemberNames.Session_User.toString(), null); else getMendixObject().setValue(context, MemberNames.Session_User.toString(), session_user.getMendixObject().getId()); } /** * @return the IMendixObject instance of this proxy for use in the Core interface. */ public final IMendixObject getMendixObject() { return sessionMendixObject; } /** * @return the IContext instance of this proxy, or null if no IContext instance was specified at initialization. */ public final IContext getContext() { return context; } @Override public boolean equals(Object obj) { if (obj == this) return true; if (obj != null && getClass().equals(obj.getClass())) { final system.proxies.Session that = (system.proxies.Session) obj; return getMendixObject().equals(that.getMendixObject()); } return false; } @Override public int hashCode() { return getMendixObject().hashCode(); } /** * @return String name of this class */ public static String getType() { return "System.Session"; } /** * @return String GUID from this object, format: ID_0000000000 * @deprecated Use getMendixObject().getId().toLong() to get a unique identifier for this object. */ @Deprecated public String getGUID() { return "ID_" + getMendixObject().getId().toLong(); } }
{ "content_hash": "8e29270fa3d0216599886e0d3bf2f75c", "timestamp": "", "source": "github", "line_count": 297, "max_line_length": 172, "avg_line_length": 25.87878787878788, "alnum_prop": 0.698152485037731, "repo_name": "mendix/TooltipImage", "id": "979310bf0405df2e685540d3960d66f8ccbd7d48", "size": "7686", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/javasource/system/proxies/Session.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1223" }, { "name": "HTML", "bytes": "517" }, { "name": "Java", "bytes": "480967" }, { "name": "JavaScript", "bytes": "16553" } ], "symlink_target": "" }
using UnityEngine; using System.Collections; public class Inventory : MonoBehaviour { protected InventorySlot[] _slots; protected InventorySlot _selectedSlot = null; public InventorySlot selectedSlot { get { return _selectedSlot; } set { if (_selectedSlot != null && _selectedSlot != value) { _selectedSlot.selected = false; } _selectedSlot = value; if (_selectedSlot != null) _selectedSlot.selected = true; } } protected InventorySlot _hoveredSlot = null; public InventorySlot hoveredSlot { get { return _hoveredSlot; } set { _hoveredSlot = value; } } // Use this for initialization void Start () { _slots = new InventorySlot[transform.GetChildCount()]; for (int i = 0; i < transform.GetChildCount(); i++) { Transform child = transform.GetChild(i); InventorySlot slot = child.GetComponent<InventorySlot>(); _slots[i] = slot; } } public InventorySlot nextEmptySlot() { foreach (InventorySlot slot in _slots) { if (slot.isEmpty) return slot; } return null; } }
{ "content_hash": "309dbbffd22ed8de7734344b68ff2842", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 61, "avg_line_length": 22.06122448979592, "alnum_prop": 0.6558741905642923, "repo_name": "alect/Puzzledice", "id": "cdd612c890521e248cd73d1b385b058be7a9a565", "size": "1081", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Unity/Sandwitch/Assets/Scripts/gameobjects/gui/Inventory.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "279216" }, { "name": "Java", "bytes": "2576188" } ], "symlink_target": "" }
package jigg.pipeline /** A singleton managing the collection of `UnmanagedAnnotator`. * * See the document of `UnmanagedAnnotator` for its role. `list` is an essential object, * which preserves mapping from the annotator name to an `UnmanagedAnnotator`. If you * want to support a new annotator that depends on an unmanaged library, add it to the * `list`. */ object UnmanagedAnnotators { /** Information about the annotator that wraps a software, which is in JVM while not * included as a managed library via maven. * * When assembling, such external unmanaged jars are not included, so a user has to * explicitly add them to the class path. Each UnmanagedAnnotator object helps to * describe how to use it. For example, its default message, implemented in * `DefaultUnmanagedannotator` tells the url of the library jar file. */ trait UnmanagedAnnotator[A] { def name: String def clazz: Class[A] def msg: String } case class DefaultUnmanagedAnnotator[A]( val name: String, val clazz: Class[A], url: String) extends UnmanagedAnnotator[A] { def msg = s"""Failed to launch $name. Maybe the necessary jar file is not included in the current class path. This might be solved by adding jar/* into your class path, e.g., call the jigg like like: > java cp "jigg-xxx.jar:jar/*" jigg.pipeline.Pipeline ... If the error still remains, the necessary jar file is missing. You can download it from ${url}. Try e.g., > wget $url jar/ and do the above command. """ } val list = Map( "easyccg" -> DefaultUnmanagedAnnotator( "easyccg", classOf[EasyCCGAnnotator], "https://github.com/mikelewis0/easyccg/raw/master/easyccg.jar")) }
{ "content_hash": "de39e188df85b800e5a76cd2bd27689b", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 89, "avg_line_length": 34.38, "alnum_prop": 0.7108784176847004, "repo_name": "mynlp/jigg", "id": "7157b633470b4e9d9d7c325b3454531d0f7fe059", "size": "1719", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/scala/jigg/pipeline/UnmanagedAnnotators.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "1477" }, { "name": "Java", "bytes": "786" }, { "name": "Python", "bytes": "210085" }, { "name": "Scala", "bytes": "703798" }, { "name": "Shell", "bytes": "7990" } ], "symlink_target": "" }
package nz.co.testamation.core.mock.smtp; import com.dumbster.smtp.SmtpMessage; public interface SmtpMessageWrapperFactory { SmtpMessageWrapper create( SmtpMessage message ); }
{ "content_hash": "4b345dd3fdd1861b13cb9baf8cb7c6f6", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 53, "avg_line_length": 20.555555555555557, "alnum_prop": 0.8, "repo_name": "rlon008/testamation", "id": "37667c6d65d6a03ddf66faf5395fde6cac7fce60", "size": "778", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "testamation-core/src/main/java/nz/co/testamation/core/mock/smtp/SmtpMessageWrapperFactory.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "323845" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using SlickCMS.Data.Interfaces; namespace SlickCMS.Data.Entities { public partial class Post : IBaseEntity { public int PostId { get; set; } public int UserId { get; set; } public string Title { get; set; } public string Url { get; set; } public string Summary { get; set; } public string Content { get; set; } public string Search { get; set; } public DateTime DateCreated { get; set; } public DateTime DateModified { get; set; } public int Published { get; set; } public int Pageable { get; set; } } }
{ "content_hash": "a89f6d8db422aaf7cf170811d76a7af9", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 50, "avg_line_length": 31.142857142857142, "alnum_prop": 0.6100917431192661, "repo_name": "mattjuffs/slickcms", "id": "3d4c10cb060b465f2e0d7c2c00b31d02ef08f3eb", "size": "656", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SlickCMS.Data/Entities/Post.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "110" }, { "name": "C#", "bytes": "175283" }, { "name": "CSS", "bytes": "75598" }, { "name": "HTML", "bytes": "167300" }, { "name": "JavaScript", "bytes": "12844" } ], "symlink_target": "" }
<!-- HTML header for doxygen 1.8.10--> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta charset="utf-8"/> <title>File Members$</title> <link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.6.0/pure-min.css"> <link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.6.0/grids-responsive-min.css"> <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.css"> <link rel="stylesheet" href="/css/default.css"> <script src="//code.jquery.com/jquery-1.11.3.min.js"></script> <script> var isLanding = false; var menu = 'API Documentation'; </script> <title>Tell: File Members</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); $(window).load(resizeHeight); </script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> <link href="customdoxygen.css" rel="stylesheet" type="text/css"/> </head> <body id="tell"> <div class="header"> <div class="home-menu pure-menu pure-menu-horizontal pure-menu-fixed"> <ul id="menu" class="pure-menu-list"> </ul> <a class="pure-menu-heading"><img class="img-header" src="/images/tell-black.png"/></a> </div> </div> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">Tell &#160;<span id="projectnumber">0.1</span> </div> <div id="projectbrief">A shared-data database ecosystem</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.10 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&#160;List</span></a></li> <li class="current"><a href="globals.html"><span>File&#160;Members</span></a></li> </ul> </div> <div id="navrow3" class="tabs2"> <ul class="tablist"> <li class="current"><a href="globals.html"><span>All</span></a></li> <li><a href="globals_defs.html"><span>Macros</span></a></li> </ul> </div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('globals.html','');}); </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="contents"> <div class="textblock">Here is a list of all file members with links to the files they belong to:</div><ul> <li>LOG_ASSERT : <a class="el" href="logger_8hpp.html#abf862692bc90559dccc8f1c6edce1058">logger.hpp</a> </li> <li>LOG_DEBUG : <a class="el" href="logger_8hpp.html#a754b3d074e0af4ad3c7b918dd77ecb2d">logger.hpp</a> </li> <li>LOG_ERROR : <a class="el" href="logger_8hpp.html#ad4a9117ce894e3319e903142347a0f63">logger.hpp</a> </li> <li>LOG_FATAL : <a class="el" href="logger_8hpp.html#a89cecd05aeaafc715ebc091cf74d10fe">logger.hpp</a> </li> <li>LOG_INFO : <a class="el" href="logger_8hpp.html#a378e28bfcb78d17285210d6bbb70a083">logger.hpp</a> </li> <li>LOG_TRACE : <a class="el" href="logger_8hpp.html#a58c994180e09d2f6400133b19b1d7036">logger.hpp</a> </li> <li>LOG_WARN : <a class="el" href="logger_8hpp.html#add82efa459e0af380b68522c29b9fd44">logger.hpp</a> </li> </ul> </div><!-- contents --> </div><!-- doc-content --> <!-- HTML footer for doxygen 1.8.10--> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> </ul> </div> <script src="/js/load-menu.js"></script> </body> </html>
{ "content_hash": "555bc82cb8e84aa71b17cbe7d286385c", "timestamp": "", "source": "github", "line_count": 164, "max_line_length": 154, "avg_line_length": 38.76219512195122, "alnum_prop": 0.6380368098159509, "repo_name": "tellproject/homepage-generator", "id": "47289341181259e259cd31da3d54b840e54fdeeb", "size": "6357", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "api/globals.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "69785" }, { "name": "HTML", "bytes": "9402939" }, { "name": "Haskell", "bytes": "3049" }, { "name": "JavaScript", "bytes": "343390" } ], "symlink_target": "" }
require 'minitest/autorun' require_relative '../../lib/mani/tokenizer' describe Mani::Tokenizer do describe '.get_tokens' do describe 'when there are no tags' do it 'returns the correct tokens' do source = 'static' actual = Mani::Tokenizer.get_tokens source expected = [[:static, 'static']] actual.must_equal expected end end describe 'when there is an opening tag and no closing tag' do it 'returns the correct tokens' do source = 'static {{ static' actual = Mani::Tokenizer.get_tokens source expected = [ [:static, 'static {{ static'], ] actual.must_equal expected end end describe 'when there is a closing tag and no opening tag' do it 'returns the correct tokens' do source = 'static }} static' actual = Mani::Tokenizer.get_tokens source expected = [ [:static, 'static }} static'] ] actual.must_equal expected end end describe 'when there is a commented opening tag and no closing tag' do it 'returns the correct tokens' do source = 'static %{{ static' actual = Mani::Tokenizer.get_tokens source expected = [ [:static, 'static {{ static'] ] actual.must_equal expected end end describe 'when there is a commented closing tag and no opening tag' do it 'returns the correct tokens' do source = 'static %}} static' actual = Mani::Tokenizer.get_tokens source expected = [ [:static, 'static }} static'] ] actual.must_equal expected end end describe 'when there are commented opening and closing tags' do it 'returns the correct tokens' do source = 'static %{{seq%}} static' actual = Mani::Tokenizer.get_tokens source expected = [ [:static, 'static {{seq}} static'], ] actual.must_equal expected end end describe 'when there is a commented opening tag and a closing tag' do it 'returns the correct tokens' do source = 'static %{{seq}} static' actual = Mani::Tokenizer.get_tokens source expected = [ [:static, 'static {{seq}} static'], ] actual.must_equal expected end end describe 'when there is an opening tag and a commented closing tag' do it 'returns the correct tokens' do source = 'static {{seq%}} static' actual = Mani::Tokenizer.get_tokens source expected = [ [:static, 'static {{seq}} static'], ] actual.must_equal expected end end describe 'when there is an empty sequence' do it 'returns the correct tokens' do source = '{{}}' actual = Mani::Tokenizer.get_tokens source expected = [] actual.must_equal expected end end describe 'when there is one, unnested sequence' do it 'returns the correct tokens' do source = 'static {{seq}} static' actual = Mani::Tokenizer.get_tokens source expected = [ [:static, 'static '], [:sequence, 'seq'], [:static, ' static'] ] actual.must_equal expected end end describe 'when there is a sequence with a commented opening tag within' do it 'returns the correct tokens' do source = 'static {{seq %{{ }} static' actual = Mani::Tokenizer.get_tokens source expected = [ [:static, 'static '], [:sequence, 'seq {{ '], [:static, ' static'] ] actual.must_equal expected end end describe 'when there is a sequence with a commented closing tag within' do it 'returns the correct tokens' do source = 'static {{seq %}} }} static' actual = Mani::Tokenizer.get_tokens source expected = [ [:static, 'static '], [:sequence, 'seq }} '], [:static, ' static'] ] actual.must_equal expected end end describe 'when there are commented tags within a sequence' do it 'returns the correct tokens' do source = 'static {{seq %{{ nested %}} }} static' actual = Mani::Tokenizer.get_tokens source expected = [ [:static, 'static '], [:sequence, 'seq {{ nested }} '], [:static, ' static'] ] actual.must_equal expected end end describe 'when there is a sequence within commented tags' do it 'returns the correct tokens' do source = 'static %{{comment {{seq}} %}} static' actual = Mani::Tokenizer.get_tokens source expected = [ [:static, 'static {{comment '], [:sequence, 'seq'], [:static, ' }} static'] ] actual.must_equal expected end end describe 'when there is a sequence within a sequence' do it 'returns the correct tokens' do source = 'static {{nested {{seq}} }} static' actual = Mani::Tokenizer.get_tokens source expected = [ [:static, 'static '], [:sequence, 'nested {{seq'], [:static, ' }} static'] ] actual.must_equal expected end end describe 'when there are multiple, unnested sequence' do it 'returns the correct tokens' do source = '{{seq}} static {{second seq}} more static' actual = Mani::Tokenizer.get_tokens source expected = [ [:sequence, 'seq'], [:static, ' static '], [:sequence, 'second seq'], [:static, ' more static'] ] actual.must_equal expected end end describe 'when there are multiple empty sequence' do it 'returns the correct tokens' do source = '{{}} static {{}}' actual = Mani::Tokenizer.get_tokens source expected = [ [:static, ' static '], ] actual.must_equal expected end end describe 'when the tags are out of order' do it 'returns the correct tokens' do source = '}} static {{' actual = Mani::Tokenizer.get_tokens source expected = [ [:static, '}} static {{'], ] actual.must_equal expected end end describe 'when the commenting tags are out of order' do it 'returns the correct tokens' do source = '%}} static %{{' actual = Mani::Tokenizer.get_tokens source expected = [ [:static, '}} static {{'], ] actual.must_equal expected end end describe 'when literal commenting tags are used' do it 'returns the correct tokens' do source = '%%{{ static %%}} more static' actual = Mani::Tokenizer.get_tokens source expected = [ [:static, '%{{ static %}} more static'], ] actual.must_equal expected end end end end
{ "content_hash": "85b914bcf06e032fc3ed9bb3542fa02f", "timestamp": "", "source": "github", "line_count": 237, "max_line_length": 78, "avg_line_length": 29.476793248945146, "alnum_prop": 0.5565416547380475, "repo_name": "NSinopoli/mani", "id": "3695abec2e60fbc9bde21f18eed5b735cf1a9955", "size": "6986", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/lib/tokenizer_spec.rb", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Makefile", "bytes": "103" }, { "name": "Ruby", "bytes": "20336" } ], "symlink_target": "" }
FactoryGirl.define do factory :mdm_host_detail, :class => Mdm::HostDetail do # # Associations # association :host, :factory => :mdm_host end end
{ "content_hash": "5e4f8a17215aa147c80a27c47b2fb98d", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 56, "avg_line_length": 20.5, "alnum_prop": 0.6463414634146342, "repo_name": "bcook-r7/metasploit_data_models", "id": "438cb3d61b0500196d89f4f7a87735527e577ef8", "size": "164", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "spec/factories/mdm/host_details.rb", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "546" }, { "name": "HTML", "bytes": "2314" }, { "name": "JavaScript", "bytes": "641" }, { "name": "Ruby", "bytes": "699808" } ], "symlink_target": "" }
package kr.tinywind.springbootstreaming.model; import lombok.Data; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; /** * Created by tinywind on 2016-06-03. */ @Data public class MaterialDataList<T> extends ArrayList<T> { private Material material; public MaterialDataList(Material material) { this.material = material; } public boolean add(T data) { try { Method setMaterial = data.getClass().getDeclaredMethod("setMaterial", Material.class); setMaterial.invoke(data, material); } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { e.printStackTrace(); } return super.add(data); } }
{ "content_hash": "9df5ba7b4355eb40816c8c0982684040", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 98, "avg_line_length": 28.137931034482758, "alnum_prop": 0.6629901960784313, "repo_name": "tinywind/spring-boot-streaming", "id": "c5b548846178e69dd9fb65f0272ae2d648e7479b", "size": "816", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/kr/tinywind/springbootstreaming/model/MaterialDataList.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "39611" }, { "name": "JavaScript", "bytes": "24367" } ], "symlink_target": "" }
// 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; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Editor.Commands; using Microsoft.CodeAnalysis.Editor.CSharp.Formatting; using Microsoft.CodeAnalysis.Editor.CSharp.Formatting.Indentation; using Microsoft.CodeAnalysis.Editor.Implementation.Formatting; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Operations; using Moq; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting.Indentation { public class SmartTokenFormatterFormatRangeTests { [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task BeginningOfFile() { var code = @" using System;$$"; var expected = @" using System;"; Assert.NotNull(await Record.ExceptionAsync(async () => await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.None))); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Namespace1() { var code = @"using System; namespace NS { }$$"; var expected = @"using System; namespace NS { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Namespace2() { var code = @"using System; namespace NS { class Class { } }$$"; var expected = @"using System; namespace NS { class Class { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Namespace3() { var code = @"using System; namespace NS { }$$"; var expected = @"using System; namespace NS { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Namespace4() { var code = @"using System; namespace NS { }$$"; var expected = @"using System; namespace NS { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Namespace5() { var code = @"using System; namespace NS { class Class { } }$$"; var expected = @"using System; namespace NS { class Class { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Namespace6() { var code = @"using System; namespace NS { class Class { } }$$"; var expected = @"using System; namespace NS { class Class { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Namespace7() { var code = @"using System; namespace NS { class Class { } namespace NS2 {} }$$"; var expected = @"using System; namespace NS { class Class { } namespace NS2 { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Namespace8() { var code = @"using System; namespace NS { class Class { } namespace NS2 { } }$$"; var expected = @"using System; namespace NS { class Class { } namespace NS2 { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Class1() { var code = @"using System; class Class { }$$"; var expected = @"using System; class Class { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Class2() { var code = @"using System; class Class { void Method(int i) { } }$$"; var expected = @"using System; class Class { void Method(int i) { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Class3() { var code = @"using System; class Class { void Method(int i) { } }$$"; var expected = @"using System; class Class { void Method(int i) { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Class4() { var code = @"using System; class Class { delegate void Test(int i); }$$"; var expected = @"using System; class Class { delegate void Test(int i); }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Class5() { var code = @"using System; class Class { delegate void Test(int i); void Method() { } }$$"; var expected = @"using System; class Class { delegate void Test(int i); void Method() { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Interface1() { var code = @"using System; interface II { delegate void Test(int i); int Prop { get; set; } }$$"; var expected = @"using System; interface II { delegate void Test(int i); int Prop { get; set; } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Struct1() { var code = @"using System; struct Struct { Struct(int i) { } }$$"; var expected = @"using System; struct Struct { Struct(int i) { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Enum1() { var code = @"using System; enum Enum { A = 1, B = 2, C = 3 }$$"; var expected = @"using System; enum Enum { A = 1, B = 2, C = 3 }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task AccessorList1() { var code = @"using System; class Class { int Prop { get { return 1; }$$"; var expected = @"using System; class Class { int Prop { get { return 1; }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task AccessorList2() { var code = @"using System; class Class { int Prop { get { return 1; } }$$"; var expected = @"using System; class Class { int Prop { get { return 1; } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.IntKeyword); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task AccessorList3() { var code = @"using System; class Class { int Prop { get { return 1; } }$$"; var expected = @"using System; class Class { int Prop { get { return 1; } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.IntKeyword); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task AccessorList4() { var code = @"using System; class Class { int Prop { get { return 1; }$$"; var expected = @"using System; class Class { int Prop { get { return 1; }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.GetKeyword); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task AccessorList5() { var code = @"using System; class Class { int Prop { get { return 1; }$$"; var expected = @"using System; class Class { int Prop { get { return 1; }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.GetKeyword); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task AccessorList6() { var code = @"using System; class Class { int Prop { get { return 1; } }$$"; var expected = @"using System; class Class { int Prop { get { return 1; } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.IntKeyword); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task AccessorList7() { var code = @"using System; class Class { int Prop { get { return 1;$$ } }"; var expected = @"using System; class Class { int Prop { get { return 1; } }"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Block1() { var code = @"using System; class Class { public int Method() { }$$"; var expected = @"using System; class Class { public int Method() { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Block2() { var code = @"using System; class Class { public int Method() { }$$"; var expected = @"using System; class Class { public int Method() { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Block3() { var code = @"using System; class Class { public int Method() { }$$ }"; var expected = @"using System; class Class { public int Method() { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Block4() { var code = @"using System; class Class { public static Class operator +(Class c1, Class c2) { }$$ }"; var expected = @"using System; class Class { public static Class operator +(Class c1, Class c2) { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Block5() { var code = @"using System; class Class { void Method() { { }$$"; var expected = @"using System; class Class { void Method() { { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Block6() { var code = @"using System; class Class { void Method() { { }$$"; var expected = @"using System; class Class { void Method() { { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Block7() { var code = @"using System; class Class { void Method() { { { }$$"; var expected = @"using System; class Class { void Method() { { { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Block8() { var code = @"using System; class Class { void Method() { { { }$$ }"; var expected = @"using System; class Class { void Method() { { { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task SwitchStatement1() { var code = @"using System; class Class { void Method() { switch (a) { case 1: break; }$$ } }"; var expected = @"using System; class Class { void Method() { switch (a) { case 1: break; } } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task SwitchStatement2() { var code = @"using System; class Class { void Method() { switch (true) { }$$"; var expected = @"using System; class Class { void Method() { switch (true) { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task SwitchStatement3() { var code = @"using System; class Class { void Method() { switch (true) { case 1: { }$$"; var expected = @"using System; class Class { void Method() { switch (true) { case 1: { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.ColonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task SwitchStatement4() { var code = @"using System; class Class { void Method() { switch (true) { case 1: { }$$"; var expected = @"using System; class Class { void Method() { switch (true) { case 1: { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.ColonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Initializer1() { var code = @"using System; class Class { void Method() { var arr = new int[] { }$$"; var expected = @"using System; class Class { void Method() { var arr = new int[] { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.NewKeyword); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Initializer2() { var code = @"using System; class Class { void Method() { var arr = new int[] { }$$"; var expected = @"using System; class Class { void Method() { var arr = new int[] { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.NewKeyword); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Initializer3() { var code = @"using System; class Class { void Method() { var arr = new { A = 1, B = 2 }$$"; var expected = @"using System; class Class { void Method() { var arr = new { A = 1, B = 2 }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.NewKeyword); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Initializer4() { var code = @"using System; class Class { void Method() { var arr = new { A = 1, B = 2 }$$"; var expected = @"using System; class Class { void Method() { var arr = new { A = 1, B = 2 }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.NewKeyword); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Initializer5() { var code = @"using System; class Class { void Method() { var arr = new[] { 1, 2, 3, 4, 5 }$$"; var expected = @"using System; class Class { void Method() { var arr = new[] { 1, 2, 3, 4, 5 }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.NewKeyword); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Initializer6() { var code = @"using System; class Class { void Method() { var arr = new int[] { 1, 2, 3, 4, 5 }$$"; var expected = @"using System; class Class { void Method() { var arr = new int[] { 1, 2, 3, 4, 5 }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.NewKeyword); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement1() { var code = @"using System; class Class { void Method() { if (true) { }$$"; var expected = @"using System; class Class { void Method() { if (true) { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement2() { var code = @"using System; class Class { void Method() { if (true) { }$$ }"; var expected = @"using System; class Class { void Method() { if (true) { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement3() { var code = @"using System; class Class { void Method() { if (true) { }$$"; var expected = @"using System; class Class { void Method() { if (true) { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement4() { var code = @"using System; class Class { void Method() { while (true) { }$$ }"; var expected = @"using System; class Class { void Method() { while (true) { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [WorkItem(8413, "https://github.com/dotnet/roslyn/issues/8413")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatementDoBlockAlone() { var code = @"using System; class Class { void Method() { do { }$$ } }"; var expected = @"using System; class Class { void Method() { do { } } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement5() { var code = @"using System; class Class { void Method() { do { } while(true);$$ } }"; var expected = @"using System; class Class { void Method() { do { } while (true); } }"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement6() { var code = @"using System; class Class { void Method() { for (int i = 0; i < 10; i++) { }$$ }"; var expected = @"using System; class Class { void Method() { for (int i = 0; i < 10; i++) { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement7() { var code = @"using System; class Class { void Method() { foreach (var i in collection) { }$$ }"; var expected = @"using System; class Class { void Method() { foreach (var i in collection) { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement8() { var code = @"using System; class Class { void Method() { using (var resource = GetResource()) { }$$ }"; var expected = @"using System; class Class { void Method() { using (var resource = GetResource()) { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement9() { var code = @"using System; class Class { void Method() { if (true) int i = 10;$$"; var expected = @"using System; class Class { void Method() { if (true) int i = 10;"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task FieldlInitializer() { var code = @"using System; class Class { string str = Console.Title;$$ "; var expected = @"using System; class Class { string str = Console.Title; "; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task ArrayFieldlInitializer() { var code = @"using System; namespace NS { class Class { string[] strArr = { ""1"", ""2"" };$$ "; var expected = @"using System; namespace NS { class Class { string[] strArr = { ""1"", ""2"" }; "; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task ExpressionValuedPropertyInitializer() { var code = @"using System; class Class { public int Three => 1+2;$$ "; var expected = @"using System; class Class { public int Three => 1 + 2; "; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement10() { var code = @"using System; class Class { void Method() { if (true) int i = 10;$$ }"; var expected = @"using System; class Class { void Method() { if (true) int i = 10; }"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement11() { var code = @"using System; class Class { void Method() { using (var resource = GetResource()) resource.Do();$$"; var expected = @"using System; class Class { void Method() { using (var resource = GetResource()) resource.Do();"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement12() { var code = @"using System; class Class { void Method() { using (var resource = GetResource()) resource.Do();$$"; var expected = @"using System; class Class { void Method() { using (var resource = GetResource()) resource.Do();"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement13() { var code = @"using System; class Class { void Method() { using (var resource = GetResource()) resource.Do();$$ }"; var expected = @"using System; class Class { void Method() { using (var resource = GetResource()) resource.Do(); }"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement14() { var code = @"using System; class Class { void Method() { do i = 10;$$"; var expected = @"using System; class Class { void Method() { do i = 10;"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement15() { var code = @"using System; class Class { void Method() { do i = 10;$$"; var expected = @"using System; class Class { void Method() { do i = 10;"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement16() { var code = @"using System; class Class { void Method() { do i = 10;$$ }"; var expected = @"using System; class Class { void Method() { do i = 10; }"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement17() { var code = @"using System; class Class { void Method() { do i = 10; while (true);$$ }"; var expected = @"using System; class Class { void Method() { do i = 10; while (true); }"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task FollowPreviousElement1() { var code = @"using System; class Class { int i = 10; int i2 = 10;$$"; var expected = @"using System; class Class { int i = 10; int i2 = 10;"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task FollowPreviousElement2() { var code = @"using System; class Class { void Method(int i) { } void Method2() { }$$ }"; var expected = @"using System; class Class { void Method(int i) { } void Method2() { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.CloseBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task FollowPreviousElement3() { var code = @"using System; class Class { void Method(int i) { } A a = new A { Prop = 1, Prop2 = 2 };$$ }"; var expected = @"using System; class Class { void Method(int i) { } A a = new A { Prop = 1, Prop2 = 2 }; }"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.CloseBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task FollowPreviousElement4() { var code = @"using System; class Class { void Method(int i) { int i = 10; int i2 = 10;$$"; var expected = @"using System; class Class { void Method(int i) { int i = 10; int i2 = 10;"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task FollowPreviousElement5() { var code = @"using System; class Class { void Method(int i) { int i = 10; if (true) i = 50;$$"; var expected = @"using System; class Class { void Method(int i) { int i = 10; if (true) i = 50;"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task FollowPreviousElement6() { var code = @" using System; using System.Linq;$$"; var expected = @" using System; using System.Linq;"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task FollowPreviousElement7() { var code = @" using System; namespace NS { } namespace NS2 { }$$"; var expected = @" using System; namespace NS { } namespace NS2 { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.CloseBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task FollowPreviousElement8() { var code = @"using System; namespace NS { class Class { } class Class1 { }$$ }"; var expected = @"using System; namespace NS { class Class { } class Class1 { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.CloseBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task IfStatement1() { var code = @"using System; class Class { void Method() { if (true) { }$$"; var expected = @"using System; class Class { void Method() { if (true) { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task IfStatement2() { var code = @"using System; class Class { void Method() { if (true) { } else { }$$"; var expected = @"using System; class Class { void Method() { if (true) { } else { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task IfStatement3() { var code = @"using System; class Class { void Method() { if (true) { } else if (false) { }$$"; var expected = @"using System; class Class { void Method() { if (true) { } else if (false) { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task IfStatement4() { var code = @"using System; class Class { void Method() { if (true) return ; else if (false) return ;$$"; var expected = @"using System; class Class { void Method() { if (true) return; else if (false) return;"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task TryStatement1() { var code = @"using System; class Class { void Method() { try { }$$"; var expected = @"using System; class Class { void Method() { try { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task TryStatement2() { var code = @"using System; class Class { void Method() { try { } catch ( Exception ex) { }$$"; var expected = @"using System; class Class { void Method() { try { } catch (Exception ex) { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task TryStatement3() { var code = @"using System; class Class { void Method() { try { } catch ( Exception ex) { } catch (Exception ex2) { }$$"; var expected = @"using System; class Class { void Method() { try { } catch (Exception ex) { } catch (Exception ex2) { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task TryStatement4() { var code = @"using System; class Class { void Method() { try { } finally { }$$"; var expected = @"using System; class Class { void Method() { try { } finally { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [WorkItem(6645, "https://github.com/dotnet/roslyn/issues/6645")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task TryStatement5() { var code = @"using System; class Class { void Method() { try { }$$ } }"; var expected = @"using System; class Class { void Method() { try { } } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] [WorkItem(537555, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537555")] public async Task SingleLine() { var code = @"class C { void M() { C.M( );$$ } }"; var expected = @"class C { void M() { C.M(); } }"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task StringLiterals() { var code = @"class C { void M() { C.M(""Test {0}$$"; var expected = string.Empty; await AutoFormatOnMarkerAsync(code, expected, SyntaxKind.StringLiteralToken, SyntaxKind.None); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task CharLiterals() { var code = @"class C { void M() { C.M('}$$"; var expected = string.Empty; await AutoFormatOnMarkerAsync(code, expected, SyntaxKind.CharacterLiteralToken, SyntaxKind.None); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task CharLiterals1() { var code = @"''';$$"; var expected = string.Empty; await AutoFormatOnMarkerAsync(code, expected, SyntaxKind.EndOfFileToken, SyntaxKind.None); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Comments() { var code = @"class C { void M() { // { }$$"; var expected = string.Empty; await AutoFormatOnMarkerAsync(code, expected, SyntaxKind.OpenBraceToken, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task FirstLineInFile() { var code = @"using System;$$"; await AutoFormatOnSemicolonAsync(code, "using System;", SyntaxKind.UsingKeyword); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Label1() { var code = @"class C { void Method() { L : int i = 20;$$ } }"; var expected = @"class C { void Method() { L: int i = 20; } }"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Label2() { var code = @"class C { void Method() { L : int i = 20;$$ } }"; var expected = @"class C { void Method() { L: int i = 20; } }"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Label3() { var code = @"class C { void Method() { int base = 10; L : int i = 20;$$ } }"; var expected = @"class C { void Method() { int base = 10; L: int i = 20; } }"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Label4() { var code = @"class C { void Method() { int base = 10; L: int i = 20; int nextLine = 30 ;$$ } }"; var expected = @"class C { void Method() { int base = 10; L: int i = 20; int nextLine = 30; } }"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Label6() { var code = @"class C { void Method() { L: int i = 20; int nextLine = 30 ;$$ } }"; var expected = @"class C { void Method() { L: int i = 20; int nextLine = 30; } }"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WorkItem(537776, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537776")] [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task DisappearedTokens() { var code = @"class Class1 { int foo() return 0; }$$ }"; var expected = @"class Class1 { int foo() return 0; } }"; await AutoFormatOnCloseBraceAsync( code, expected, SyntaxKind.ClassKeyword); } [WorkItem(537779, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537779")] [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task DisappearedTokens2() { var code = @"class Class1 { void Foo() { Object o=new Object);$$ } }"; var expected = @"class Class1 { void Foo() { Object o=new Object); } }"; await AutoFormatOnSemicolonAsync( code, expected, SyntaxKind.SemicolonToken); } [WorkItem(537793, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537793")] [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Delegate1() { var code = @"delegate void MyDelegate(int a,int b);$$"; var expected = @"delegate void MyDelegate(int a, int b);"; await AutoFormatOnSemicolonAsync( code, expected, SyntaxKind.DelegateKeyword); } [WorkItem(537827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537827")] [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task DoubleInitializer() { var code = @"class C { void Method() { int[,] a ={{ 1 , 1 }$$ } }"; var expected = @"class C { void Method() { int[,] a ={{ 1 , 1 } } }"; await AutoFormatOnCloseBraceAsync( code, expected, SyntaxKind.OpenBraceToken); } [WorkItem(537825, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537825")] [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task MissingToken1() { var code = @"public class Class1 { int a = 1}$$; }"; var expected = @"public class Class1 { int a = 1}; }"; await AutoFormatOnCloseBraceAsync( code, expected, SyntaxKind.PublicKeyword); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task ArrayInitializer1() { var code = @"public class Class1 { var a = new [] { 1, 2, 3, 4 }$$ }"; var expected = @"public class Class1 { var a = new[] { 1, 2, 3, 4 } }"; await AutoFormatOnCloseBraceAsync( code, expected, SyntaxKind.NewKeyword); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task ArrayInitializer2() { var code = @"public class Class1 { var a = new [] { 1, 2, 3, 4 } ;$$ }"; var expected = @"public class Class1 { var a = new[] { 1, 2, 3, 4 }; }"; await AutoFormatOnSemicolonAsync( code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [WorkItem(537825, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537825")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task MalformedCode() { var code = @"namespace ClassLibrary1 { public class Class1 { int a}$$; } }"; var expected = @"namespace ClassLibrary1 { public class Class1 { int a}; } }"; await AutoFormatOnCloseBraceAsync( code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [WorkItem(537804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537804")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Colon_SwitchLabel() { var code = @"namespace ClassLibrary1 { public class Class1 { void Test() { switch(E.Type) { case 1 :$$ } } } }"; var expected = @"namespace ClassLibrary1 { public class Class1 { void Test() { switch(E.Type) { case 1: } } } }"; await AutoFormatOnColonAsync( code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [WorkItem(584599, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/584599")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Colon_SwitchLabel_Comment() { var code = @"namespace ClassLibrary1 { public class Class1 { void Test() { switch(E.Type) { // test case 1 :$$ } } } }"; var expected = @"namespace ClassLibrary1 { public class Class1 { void Test() { switch(E.Type) { // test case 1: } } } }"; await AutoFormatOnColonAsync( code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [WorkItem(584599, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/584599")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Colon_SwitchLabel_Comment2() { var code = @"namespace ClassLibrary1 { public class Class1 { void Test() { switch(E.Type) { case 2: // test case 1 :$$ } } } }"; var expected = @"namespace ClassLibrary1 { public class Class1 { void Test() { switch(E.Type) { case 2: // test case 1: } } } }"; await AutoFormatOnColonAsync( code, expected, SyntaxKind.ColonToken); } [Fact] [WorkItem(537804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537804")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Colon_Label() { var code = @"namespace ClassLibrary1 { public class Class1 { void Test() { label :$$ } } }"; var expected = @"namespace ClassLibrary1 { public class Class1 { void Test() { label : } } }"; await AutoFormatOnColonAsync( code, expected, SyntaxKind.None); } [WpfFact] [WorkItem(538793, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538793")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Colon_Label2() { var code = @"namespace ClassLibrary1 { public class Class1 { void Test() { label : Console.WriteLine(10) ;$$ } } }"; var expected = @"namespace ClassLibrary1 { public class Class1 { void Test() { label: Console.WriteLine(10); } } }"; await AutoFormatOnSemicolonAsync( code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [WorkItem(3186, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task SemicolonInElseIfStatement() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { int a = 0; if (a == 0) a = 1; else if (a == 1) a=2;$$ else a = 3; } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { int a = 0; if (a == 0) a = 1; else if (a == 1) a = 2; else a = 3; } }"; await AutoFormatOnSemicolonAsync( code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [WorkItem(538391, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538391")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task SemicolonInElseIfStatement2() { var code = @"public class Class1 { void Method() { int a = 1; if (a == 0) a = 8;$$ else a = 10; } }"; var expected = @"public class Class1 { void Method() { int a = 1; if (a == 0) a = 8; else a = 10; } }"; await AutoFormatOnSemicolonAsync( code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [WorkItem(8385, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task NullCoalescingOperator() { var code = @"class C { void M() { object o2 = null??null;$$ } }"; var expected = @"class C { void M() { object o2 = null ?? null; } }"; await AutoFormatOnSemicolonAsync( code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [WorkItem(541517, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541517")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task SwitchDefault() { var code = @"using System; class Program { static void Main() { switch (DayOfWeek.Monday) { case DayOfWeek.Monday: case DayOfWeek.Tuesday: break; case DayOfWeek.Wednesday: break; default:$$ } } }"; var expected = @"using System; class Program { static void Main() { switch (DayOfWeek.Monday) { case DayOfWeek.Monday: case DayOfWeek.Tuesday: break; case DayOfWeek.Wednesday: break; default: } } }"; await AutoFormatOnColonAsync( code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [WorkItem(542538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542538")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task MissingTokens1() { var code = @"class Program { static void Main(string[] args) { gl::$$ } }"; var expected = @"class Program { static void Main(string[] args) { gl:: } }"; await AutoFormatOnMarkerAsync( code, expected, SyntaxKind.ColonColonToken, SyntaxKind.OpenBraceToken); } [WpfFact] [WorkItem(542538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542538")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task MissingTokens2() { var code = @"class C { void M() { M(() => { }$$ } }"; var expected = @"class C { void M() { M(() => { } } }"; await AutoFormatOnCloseBraceAsync( code, expected, SyntaxKind.EqualsGreaterThanToken); } [WpfFact] [WorkItem(542953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542953")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task UsingAlias() { var code = @"using Alias=System;$$"; var expected = @"using Alias = System;"; await AutoFormatOnSemicolonAsync( code, expected, SyntaxKind.UsingKeyword); } [WpfFact] [WorkItem(542953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542953")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task NoLineChangeWithSyntaxError() { var code = @"struct Foo { public int member; } class Program{ void Main() { var f = new Foo { member;$$ } } }"; var expected = @"struct Foo { public int member; } class Program{ void Main() { var f = new Foo { member; } } }"; await AutoFormatOnSemicolonAsync( code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [WorkItem(620568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/620568")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task SkippedTokens1() { var code = @";$$*"; var expected = @";*"; await AutoFormatTokenAsync(code, expected); } [WpfFact] [WorkItem(530830, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530830")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task AutoPropertyAccessor() { var code = @"class C { int Prop { get ;$$ }"; var expected = @"class C { int Prop { get; }"; await AutoFormatTokenAsync(code, expected); } [WpfFact] [WorkItem(530830, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530830")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task AutoPropertyAccessor2() { var code = @"class C { int Prop { get; set ;$$ }"; var expected = @"class C { int Prop { get; set; }"; await AutoFormatTokenAsync(code, expected); } [WpfFact] [WorkItem(530830, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530830")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task AutoPropertyAccessor3() { var code = @"class C { int Prop { get; set ; }$$ }"; var expected = @"class C { int Prop { get; set; } }"; await AutoFormatTokenAsync(code, expected); } [WpfFact] [WorkItem(784674, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/784674")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task AutoPropertyAccessor4() { var code = @"class C { int Prop { get;$$ } }"; var expected = @"class C { int Prop { get; } }"; await AutoFormatTokenAsync(code, expected); } [WpfFact] [WorkItem(924469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/924469")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task AutoPropertyAccessor5() { var code = @"class C { int Prop { get; set ;$$ } }"; var expected = @"class C { int Prop { get; set; } }"; await AutoFormatTokenAsync(code, expected); } [WpfFact] [WorkItem(924469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/924469")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task AutoPropertyAccessor6() { var code = @"class C { int Prop { get;set;$$} }"; var expected = @"class C { int Prop { get; set; } }"; await AutoFormatTokenAsync(code, expected); } [WpfFact] [WorkItem(924469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/924469")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task AutoPropertyAccessor7() { var code = @"class C { int Prop { get;set;$$} }"; var expected = @"class C { int Prop { get; set; } }"; await AutoFormatTokenAsync(code, expected); } [WpfFact] [WorkItem(912965, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912965")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task NestedUsingStatement() { var code = @"class C { public void M() { using (null) using(null)$$ } }"; var expected = @"class C { public void M() { using (null) using (null) } }"; await AutoFormatTokenAsync(code, expected); } [WpfFact] [WorkItem(912965, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912965")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task NestedNotUsingStatement() { var code = @"class C { public void M() { using (null) for(;;)$$ } }"; var expected = @"class C { public void M() { using (null) for(;;) } }"; await AutoFormatTokenAsync(code, expected); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task UsingStatementWithNestedFixedStatement() { var code = @"class C { public void M() { using (null) fixed (void* ptr = &i) { }$$ } }"; var expected = @"class C { public void M() { using (null) fixed (void* ptr = &i) { } } }"; await AutoFormatTokenAsync(code, expected); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task FixedStatementWithNestedUsingStatement() { var code = @"class C { public void M() { fixed (void* ptr = &i) using (null)$$ } }"; var expected = @"class C { public void M() { fixed (void* ptr = &i) using (null) } }"; await AutoFormatTokenAsync(code, expected); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task FixedStatementWithNestedFixedStatement() { var code = @"class C { public void M() { fixed (void* ptr1 = &i) fixed (void* ptr2 = &i) { }$$ } }"; var expected = @"class C { public void M() { fixed (void* ptr1 = &i) fixed (void* ptr2 = &i) { } } }"; await AutoFormatTokenAsync(code, expected); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task FixedStatementWithNestedNotFixedStatement() { var code = @"class C { public void M() { fixed (void* ptr = &i) if (false) { }$$ } }"; var expected = @"class C { public void M() { fixed (void* ptr = &i) if (false) { } } }"; await AutoFormatTokenAsync(code, expected); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task NotFixedStatementWithNestedFixedStatement() { var code = @"class C { public void M() { if (false) fixed (void* ptr = &i) { }$$ } }"; var expected = @"class C { public void M() { if (false) fixed (void* ptr = &i) { } } }"; await AutoFormatTokenAsync(code, expected); } [WpfFact] [WorkItem(954386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954386")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task FormattingRangeForFirstStatementOfBlock() { var code = @"class C { public void M() {int s;$$ } }"; var expected = @"class C { public void M() { int s; } }"; await AutoFormatTokenAsync(code, expected); } [WpfFact] [WorkItem(954386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954386")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task FormattingRangeForFirstMemberofType() { var code = @"class C {int s;$$ public void M() { } }"; var expected = @"class C { int s; public void M() { } }"; await AutoFormatTokenAsync(code, expected); } [WpfFact] [WorkItem(954386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954386")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task FormattingRangeForFirstMethodMemberofType() { var code = @"interface C {void s();$$ }"; var expected = @"interface C { void s(); }"; await AutoFormatTokenAsync(code, expected); } [WpfFact] [WorkItem(954386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954386")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task FormattingRangeForFirstMemberOfNamespace() { var code = @"namespace C {delegate void s();$$ }"; var expected = @"namespace C { delegate void s(); }"; await AutoFormatTokenAsync(code, expected); } [WorkItem(981821, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981821")] [WpfFact] [Trait(Traits.Feature, Traits.Features.Formatting)] public async Task FormatDirectiveTriviaAlwaysToColumnZero() { var code = @"class Program { static void Main(string[] args) { #if #$$ } } "; var expected = @"class Program { static void Main(string[] args) { #if # } } "; await AutoFormatTokenAsync(code, expected); } [WorkItem(981821, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981821")] [WpfFact] [Trait(Traits.Feature, Traits.Features.Formatting)] public async Task FormatDirectiveTriviaAlwaysToColumnZeroWithCode() { var code = @"class Program { static void Main(string[] args) { #if int s = 10; #$$ } } "; var expected = @"class Program { static void Main(string[] args) { #if int s = 10; # } } "; await AutoFormatTokenAsync(code, expected); } [WorkItem(981821, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981821")] [WpfFact] [Trait(Traits.Feature, Traits.Features.Formatting)] public async Task FormatDirectiveTriviaAlwaysToColumnZeroWithBrokenElseDirective() { var code = @"class Program { static void Main(string[] args) { #else #$$ } } "; var expected = @"class Program { static void Main(string[] args) { #else # } } "; await AutoFormatTokenAsync(code, expected); } internal static async Task AutoFormatTokenAsync(string markup, string expected) { using (var workspace = await TestWorkspace.CreateCSharpAsync(markup)) { var subjectDocument = workspace.Documents.Single(); var textUndoHistory = new Mock<ITextUndoHistoryRegistry>(); var editorOperationsFactory = new Mock<IEditorOperationsFactoryService>(); var editorOperations = new Mock<IEditorOperations>(); editorOperationsFactory.Setup(x => x.GetEditorOperations(subjectDocument.GetTextView())).Returns(editorOperations.Object); var commandHandler = new FormatCommandHandler(TestWaitIndicator.Default, textUndoHistory.Object, editorOperationsFactory.Object); var typedChar = subjectDocument.GetTextBuffer().CurrentSnapshot.GetText(subjectDocument.CursorPosition.Value - 1, 1); commandHandler.ExecuteCommand(new TypeCharCommandArgs(subjectDocument.GetTextView(), subjectDocument.TextBuffer, typedChar[0]), () => { }); var newSnapshot = subjectDocument.TextBuffer.CurrentSnapshot; Assert.Equal(expected, newSnapshot.GetText()); } } private static Tuple<OptionSet, IEnumerable<IFormattingRule>> GetService( TestWorkspace workspace) { var options = workspace.Options; return Tuple.Create(options, Formatter.GetDefaultFormattingRules(workspace, LanguageNames.CSharp)); } private Task AutoFormatOnColonAsync(string codeWithMarker, string expected, SyntaxKind startTokenKind) { return AutoFormatOnMarkerAsync(codeWithMarker, expected, SyntaxKind.ColonToken, startTokenKind); } private Task AutoFormatOnSemicolonAsync(string codeWithMarker, string expected, SyntaxKind startTokenKind) { return AutoFormatOnMarkerAsync(codeWithMarker, expected, SyntaxKind.SemicolonToken, startTokenKind); } private Task AutoFormatOnCloseBraceAsync(string codeWithMarker, string expected, SyntaxKind startTokenKind) { return AutoFormatOnMarkerAsync(codeWithMarker, expected, SyntaxKind.CloseBraceToken, startTokenKind); } private async Task AutoFormatOnMarkerAsync(string initialMarkup, string expected, SyntaxKind tokenKind, SyntaxKind startTokenKind) { using (var workspace = await TestWorkspace.CreateCSharpAsync(initialMarkup)) { var tuple = GetService(workspace); var testDocument = workspace.Documents.Single(); var buffer = testDocument.GetTextBuffer(); var position = testDocument.CursorPosition.Value; var document = workspace.CurrentSolution.GetDocument(testDocument.Id); var root = (CompilationUnitSyntax)await document.GetSyntaxRootAsync(); var endToken = root.FindToken(position); if (position == endToken.SpanStart && !endToken.GetPreviousToken().IsKind(SyntaxKind.None)) { endToken = endToken.GetPreviousToken(); } Assert.Equal(tokenKind, endToken.Kind()); var formatter = new SmartTokenFormatter(tuple.Item1, tuple.Item2, root); var tokenRange = FormattingRangeHelper.FindAppropriateRange(endToken); if (tokenRange == null) { Assert.Equal(startTokenKind, SyntaxKind.None); return; } Assert.Equal(startTokenKind, tokenRange.Value.Item1.Kind()); if (tokenRange.Value.Item1.Equals(tokenRange.Value.Item2)) { return; } var changes = formatter.FormatRange(workspace, tokenRange.Value.Item1, tokenRange.Value.Item2, CancellationToken.None); var actual = GetFormattedText(buffer, changes); Assert.Equal(expected, actual); } } private static string GetFormattedText(ITextBuffer buffer, IList<TextChange> changes) { using (var edit = buffer.CreateEdit()) { foreach (var change in changes) { edit.Replace(change.Span.ToSpan(), change.NewText); } edit.Apply(); } return buffer.CurrentSnapshot.GetText(); } } }
{ "content_hash": "beccd20246c6862c3238939c427905e5", "timestamp": "", "source": "github", "line_count": 3329, "max_line_length": 161, "avg_line_length": 22.504355662361068, "alnum_prop": 0.5282646128382076, "repo_name": "jaredpar/roslyn", "id": "28ef39b01b20f0f1823b74b658e8dfe803b010db", "size": "74919", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartTokenFormatterFormatRangeTests.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "15099" }, { "name": "C#", "bytes": "80732271" }, { "name": "C++", "bytes": "6311" }, { "name": "F#", "bytes": "421" }, { "name": "Groovy", "bytes": "7036" }, { "name": "Makefile", "bytes": "3606" }, { "name": "PowerShell", "bytes": "25894" }, { "name": "Shell", "bytes": "7453" }, { "name": "Visual Basic", "bytes": "61232818" } ], "symlink_target": "" }
require_relative 'boot' require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module SkipTestUnit class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. config.load_defaults 5.1 # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. end end
{ "content_hash": "fe2507c0a2a95629a1fda39ae47023ad", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 82, "avg_line_length": 33.27777777777778, "alnum_prop": 0.7646076794657763, "repo_name": "himajin315/high-five", "id": "9679ed3cdc3d5264192dce854af3662fde6b2123", "size": "599", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "config/application.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "8361" }, { "name": "Gherkin", "bytes": "3294" }, { "name": "HTML", "bytes": "17227" }, { "name": "JavaScript", "bytes": "3263" }, { "name": "Ruby", "bytes": "67852" } ], "symlink_target": "" }
package org.example.shelf.config; import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; @Configuration @EnableWebSocketMessageBroker public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(MessageBrokerRegistry config) { // prefixes for all subscriptions config.enableSimpleBroker("/queue", "/topic"); config.setUserDestinationPrefix("/user"); // /app for normal calls, /topic for subscription events config.setApplicationDestinationPrefixes("/app", "/topic"); } @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/sample-ws-endpoint") .setAllowedOrigins("http://localhost:3000") // to allow frontend server proxy requests in dev mode .withSockJS(); } }
{ "content_hash": "4f960eabcdd44388fff10ca323e08d7f", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 114, "avg_line_length": 42.206896551724135, "alnum_prop": 0.7671568627450981, "repo_name": "joffrey-bion/livedoc", "id": "8d954e32dd04c99b892a05b7f9163ee7f0607c63", "size": "1224", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sample-app/src/main/java/org/example/shelf/config/WebSocketConfig.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1755" }, { "name": "Dockerfile", "bytes": "649" }, { "name": "FreeMarker", "bytes": "972" }, { "name": "HTML", "bytes": "2442" }, { "name": "Java", "bytes": "531425" }, { "name": "JavaScript", "bytes": "84372" }, { "name": "Kotlin", "bytes": "6030" }, { "name": "Shell", "bytes": "127" } ], "symlink_target": "" }
using System; namespace ModMaker.Lua { /// <summary> /// Defines that a method returns more than one value. The method must return a compatible type to /// IEnumerable. /// </summary> [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] public sealed class MultipleReturnAttribute : Attribute { } }
{ "content_hash": "e65d33924816257c4a61ed18af2f9866", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 100, "avg_line_length": 34.3, "alnum_prop": 0.7288629737609329, "repo_name": "TheModMaker/ModMaker.Lua", "id": "e943f7af07797ea5522d394300582152753590c6", "size": "934", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ModMaker.Lua/MultipleReturnAttribute.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "699980" }, { "name": "Lua", "bytes": "52553" }, { "name": "Python", "bytes": "1890" } ], "symlink_target": "" }
namespace food_therapist.Areas.HelpPage.ModelDescriptions { public class KeyValuePairModelDescription : ModelDescription { public ModelDescription KeyModelDescription { get; set; } public ModelDescription ValueModelDescription { get; set; } } }
{ "content_hash": "7dd5000aa27c6d9e9fb0ff2898e5a517", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 67, "avg_line_length": 30.333333333333332, "alnum_prop": 0.7435897435897436, "repo_name": "raduaron26/food-therapist", "id": "bd8468ed4e1eb23cb1cc9a1677ae83b0d13e10dd", "size": "273", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "food-therapist/Areas/HelpPage/ModelDescriptions/KeyValuePairModelDescription.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "108" }, { "name": "C#", "bytes": "196196" }, { "name": "CSS", "bytes": "2881" }, { "name": "HTML", "bytes": "5069" }, { "name": "JavaScript", "bytes": "20412" } ], "symlink_target": "" }
namespace Microsoft.Azure.Management.RecoveryServices.Models { using Newtonsoft.Json; using System.Linq; /// <summary> /// Metadata pertaining to creation and last modification of the resource. /// </summary> public partial class SystemData { /// <summary> /// Initializes a new instance of the SystemData class. /// </summary> public SystemData() { CustomInit(); } /// <summary> /// Initializes a new instance of the SystemData class. /// </summary> /// <param name="createdBy">The identity that created the /// resource.</param> /// <param name="createdByType">The type of identity that created the /// resource. Possible values include: 'User', 'Application', /// 'ManagedIdentity', 'Key'</param> /// <param name="createdAt">The timestamp of resource creation /// (UTC).</param> /// <param name="lastModifiedBy">The identity that last modified the /// resource.</param> /// <param name="lastModifiedByType">The type of identity that last /// modified the resource. Possible values include: 'User', /// 'Application', 'ManagedIdentity', 'Key'</param> /// <param name="lastModifiedAt">The type of identity that last /// modified the resource.</param> public SystemData(string createdBy = default(string), string createdByType = default(string), System.DateTime? createdAt = default(System.DateTime?), string lastModifiedBy = default(string), string lastModifiedByType = default(string), System.DateTime? lastModifiedAt = default(System.DateTime?)) { CreatedBy = createdBy; CreatedByType = createdByType; CreatedAt = createdAt; LastModifiedBy = lastModifiedBy; LastModifiedByType = lastModifiedByType; LastModifiedAt = lastModifiedAt; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets the identity that created the resource. /// </summary> [JsonProperty(PropertyName = "createdBy")] public string CreatedBy { get; set; } /// <summary> /// Gets or sets the type of identity that created the resource. /// Possible values include: 'User', 'Application', 'ManagedIdentity', /// 'Key' /// </summary> [JsonProperty(PropertyName = "createdByType")] public string CreatedByType { get; set; } /// <summary> /// Gets or sets the timestamp of resource creation (UTC). /// </summary> [JsonProperty(PropertyName = "createdAt")] public System.DateTime? CreatedAt { get; set; } /// <summary> /// Gets or sets the identity that last modified the resource. /// </summary> [JsonProperty(PropertyName = "lastModifiedBy")] public string LastModifiedBy { get; set; } /// <summary> /// Gets or sets the type of identity that last modified the resource. /// Possible values include: 'User', 'Application', 'ManagedIdentity', /// 'Key' /// </summary> [JsonProperty(PropertyName = "lastModifiedByType")] public string LastModifiedByType { get; set; } /// <summary> /// Gets or sets the type of identity that last modified the resource. /// </summary> [JsonProperty(PropertyName = "lastModifiedAt")] public System.DateTime? LastModifiedAt { get; set; } } }
{ "content_hash": "a1e6cb3f4bbc8ef2987b23a044f4583a", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 304, "avg_line_length": 39.97849462365591, "alnum_prop": 0.6032813340505648, "repo_name": "Azure/azure-sdk-for-net", "id": "a9cd2f2a86c76a53043961e6ba07ac9520a3e1f9", "size": "4071", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "sdk/recoveryservices/Microsoft.Azure.Management.RecoveryServices/src/Generated/Models/SystemData.cs", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<div class="padding"> <p>Angular directive for <a href="http://summernote.org/">Summernote</a></p> <h6>Basic</h6> <p>Super Simple WYSIWYG Editor on Bootstrap</p> <div class="box m-b-md"> <summernote height="300" ng-model="text"></summernote> </div> <h6>Air-mode</h6> <p>Air-mode gives clearer interface with hiddened toolbar. To reveal toolbar, select a text where you want to shape up. Simply turn on airMode and just focus on text.</p> <div class="box p-a m-b-md"> <summernote airMode ng-model="text"> </summernote> </div> <h6>Custom toolbar</h6> <p>Summernote allows you to make own custom toolbar.</p> <div class="box m-b-md"> <summernote config="options"></summernote> </div> </div>
{ "content_hash": "194c8e914fa54d211422442466025e03", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 172, "avg_line_length": 34.27272727272727, "alnum_prop": 0.6485411140583555, "repo_name": "twoh/leevee", "id": "bb801e5b5c70201ed20ddbfc212892e6fe98a4bd", "size": "754", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "templates/views/form/ng.editor.html", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "1223950" }, { "name": "HTML", "bytes": "6389346" }, { "name": "JavaScript", "bytes": "2380790" }, { "name": "PHP", "bytes": "434" }, { "name": "Python", "bytes": "45278" } ], "symlink_target": "" }
package org.apache.beam.sdk.io.gcp.pubsublite; import static com.google.cloud.pubsublite.internal.wire.ApiServiceUtils.blockingShutdown; import com.google.cloud.pubsublite.Offset; import com.google.cloud.pubsublite.internal.ExtractStatus; import com.google.cloud.pubsublite.internal.wire.Committer; import com.google.cloud.pubsublite.proto.SequencedMessage; import org.apache.beam.sdk.io.range.OffsetRange; import org.apache.beam.sdk.transforms.DoFn; import org.apache.beam.sdk.transforms.SerializableBiFunction; import org.apache.beam.sdk.transforms.SerializableFunction; import org.apache.beam.sdk.transforms.splittabledofn.RestrictionTracker; import org.apache.beam.sdk.transforms.splittabledofn.WatermarkEstimators.MonotonicallyIncreasing; import org.joda.time.Duration; import org.joda.time.Instant; class PerSubscriptionPartitionSdf extends DoFn<SubscriptionPartition, SequencedMessage> { private final Duration maxSleepTime; private final ManagedBacklogReaderFactory backlogReaderFactory; private final SubscriptionPartitionProcessorFactory processorFactory; private final SerializableFunction<SubscriptionPartition, InitialOffsetReader> offsetReaderFactory; private final SerializableBiFunction<TopicBacklogReader, OffsetByteRange, TrackerWithProgress> trackerFactory; private final SerializableFunction<SubscriptionPartition, Committer> committerFactory; PerSubscriptionPartitionSdf( Duration maxSleepTime, ManagedBacklogReaderFactory backlogReaderFactory, SerializableFunction<SubscriptionPartition, InitialOffsetReader> offsetReaderFactory, SerializableBiFunction<TopicBacklogReader, OffsetByteRange, TrackerWithProgress> trackerFactory, SubscriptionPartitionProcessorFactory processorFactory, SerializableFunction<SubscriptionPartition, Committer> committerFactory) { this.maxSleepTime = maxSleepTime; this.backlogReaderFactory = backlogReaderFactory; this.processorFactory = processorFactory; this.offsetReaderFactory = offsetReaderFactory; this.trackerFactory = trackerFactory; this.committerFactory = committerFactory; } @Teardown public void teardown() { backlogReaderFactory.close(); } @GetInitialWatermarkEstimatorState public Instant getInitialWatermarkState() { return Instant.EPOCH; } @NewWatermarkEstimator public MonotonicallyIncreasing newWatermarkEstimator(@WatermarkEstimatorState Instant state) { return new MonotonicallyIncreasing(state); } @ProcessElement public ProcessContinuation processElement( RestrictionTracker<OffsetByteRange, OffsetByteProgress> tracker, @Element SubscriptionPartition subscriptionPartition, OutputReceiver<SequencedMessage> receiver) throws Exception { try (SubscriptionPartitionProcessor processor = processorFactory.newProcessor(subscriptionPartition, tracker, receiver)) { processor.start(); ProcessContinuation result = processor.waitForCompletion(maxSleepTime); processor .lastClaimed() .ifPresent( lastClaimedOffset -> { Committer committer = committerFactory.apply(subscriptionPartition); committer.startAsync().awaitRunning(); // Commit the next-to-deliver offset. try { committer.commitOffset(Offset.of(lastClaimedOffset.value() + 1)).get(); } catch (Exception e) { throw ExtractStatus.toCanonical(e).underlying; } blockingShutdown(committer); }); return result; } } @GetInitialRestriction public OffsetByteRange getInitialRestriction( @Element SubscriptionPartition subscriptionPartition) { try (InitialOffsetReader reader = offsetReaderFactory.apply(subscriptionPartition)) { Offset offset = reader.read(); return OffsetByteRange.of( new OffsetRange(offset.value(), Long.MAX_VALUE /* open interval */)); } } @NewTracker public TrackerWithProgress newTracker( @Element SubscriptionPartition subscriptionPartition, @Restriction OffsetByteRange range) { return trackerFactory.apply(backlogReaderFactory.newReader(subscriptionPartition), range); } @GetSize public double getSize( @Element SubscriptionPartition subscriptionPartition, @Restriction OffsetByteRange restriction) { if (restriction.getRange().getTo() != Long.MAX_VALUE) { return restriction.getByteCount(); } return newTracker(subscriptionPartition, restriction).getProgress().getWorkRemaining(); } }
{ "content_hash": "f64a552906683e67dc949f59fd553953", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 97, "avg_line_length": 40.93805309734513, "alnum_prop": 0.7615650670125378, "repo_name": "axbaretto/beam", "id": "fdf79202986326784fd1df9957e0c0180af382bd", "size": "5431", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/pubsublite/PerSubscriptionPartitionSdf.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "1598" }, { "name": "Batchfile", "bytes": "3220" }, { "name": "C", "bytes": "1339873" }, { "name": "C++", "bytes": "1132901" }, { "name": "CSS", "bytes": "124283" }, { "name": "Dockerfile", "bytes": "23950" }, { "name": "FreeMarker", "bytes": "7428" }, { "name": "Go", "bytes": "2795906" }, { "name": "Groovy", "bytes": "187109" }, { "name": "HTML", "bytes": "238575" }, { "name": "Java", "bytes": "39085315" }, { "name": "JavaScript", "bytes": "1221326" }, { "name": "Jupyter Notebook", "bytes": "7396" }, { "name": "Makefile", "bytes": "354938" }, { "name": "Python", "bytes": "51449019" }, { "name": "Roff", "bytes": "70716" }, { "name": "Ruby", "bytes": "4159" }, { "name": "Shell", "bytes": "351541" }, { "name": "TeX", "bytes": "70920" }, { "name": "Thrift", "bytes": "1118" } ], "symlink_target": "" }
// daterangepicker.js // version : 0.0.9 // author : Chunlong Liu // last updated at: 2015-10-30 // license : MIT // www.jszen.com (function (factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['jquery', 'moment'], factory); } else if (typeof exports === 'object' && typeof module !== 'undefined') { // CommonJS. Register as a module module.exports = factory(require('jquery'), require('moment')); } else { // Browser globals factory(jQuery, moment); } }(function ($, moment) { $.dateRangePickerLanguages = { 'default': //default language: English { 'selected': 'Selected:', 'day':'Day', 'days': 'Days', 'apply': 'Close', 'week-1' : 'mo', 'week-2' : 'tu', 'week-3' : 'we', 'week-4' : 'th', 'week-5' : 'fr', 'week-6' : 'sa', 'week-7' : 'su', 'week-number': 'W', 'month-name': ['january','february','march','april','may','june','july','august','september','october','november','december'], 'shortcuts' : 'Shortcuts', 'custom-values': 'Custom Values', 'past': 'Past', 'following':'Following', 'previous' : 'Previous', 'prev-week' : 'Week', 'prev-month' : 'Month', 'prev-year' : 'Year', 'next':'Next', 'next-week':'Week', 'next-month':'Month', 'next-year':'Year', 'less-than' : 'Date range should not be more than %d days', 'more-than' : 'Date range should not be less than %d days', 'default-more' : 'Please select a date range longer than %d days', 'default-single' : 'Please select a date', 'default-less' : 'Please select a date range less than %d days', 'default-range' : 'Please select a date range between %d and %d days', 'default-default': 'Please select a date range', 'time':'Time', 'hour':'Hour', 'minute':'Minute' }, 'az': { 'selected': 'Seçildi:', 'day':' gün', 'days': ' gün', 'apply': 'tətbiq', 'week-1' : '1', 'week-2' : '2', 'week-3' : '3', 'week-4' : '4', 'week-5' : '5', 'week-6' : '6', 'week-7' : '7', 'month-name': ['yanvar','fevral','mart','aprel','may','iyun','iyul','avqust','sentyabr','oktyabr','noyabr','dekabr'], 'shortcuts' : 'Qısayollar', 'past': 'Keçmiş', 'following':'Növbəti', 'previous' : '&nbsp;&nbsp;&nbsp;', 'prev-week' : 'Öncəki həftə', 'prev-month' : 'Öncəki ay', 'prev-year' : 'Öncəki il', 'next': '&nbsp;&nbsp;&nbsp;', 'next-week':'Növbəti həftə', 'next-month':'Növbəti ay', 'next-year':'Növbəti il', 'less-than' : 'Tarix aralığı %d gündən çox olmamalıdır', 'more-than' : 'Tarix aralığı %d gündən az olmamalıdır', 'default-more' : '%d gündən çox bir tarix seçin', 'default-single' : 'Tarix seçin', 'default-less' : '%d gündən az bir tarix seçin', 'default-range' : '%d və %d gün aralığında tarixlər seçin', 'default-default': 'Tarix aralığı seçin' }, 'cn': //simplified chinese { 'selected': '已选择:', 'day':'天', 'days': '天', 'apply': '确定', 'week-1' : '一', 'week-2' : '二', 'week-3' : '三', 'week-4' : '四', 'week-5' : '五', 'week-6' : '六', 'week-7' : '日', 'week-number': '周', 'month-name': ['一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月'], 'shortcuts' : '快捷选择', 'past': '过去', 'following':'将来', 'previous' : '&nbsp;&nbsp;&nbsp;', 'prev-week' : '上周', 'prev-month' : '上个月', 'prev-year' : '去年', 'next': '&nbsp;&nbsp;&nbsp;', 'next-week':'下周', 'next-month':'下个月', 'next-year':'明年', 'less-than' : '所选日期范围不能大于%d天', 'more-than' : '所选日期范围不能小于%d天', 'default-more' : '请选择大于%d天的日期范围', 'default-less' : '请选择小于%d天的日期范围', 'default-range' : '请选择%d天到%d天的日期范围', 'default-single':'请选择一个日期', 'default-default': '请选择一个日期范围', 'time':'时间', 'hour':'小时', 'minute':'分钟' }, 'cz': { 'selected': 'Vybráno:', 'day':'Den', 'days': 'Dny', 'apply': 'Zavřít', 'week-1' : 'po', 'week-2' : 'út', 'week-3' : 'st', 'week-4' : 'čt', 'week-5' : 'pá', 'week-6' : 'so', 'week-7' : 'ne', 'month-name': ['leden','únor','březen','duben','květen','červen','červenec','srpen','září','říjen','listopad','prosinec'], 'shortcuts' : 'Zkratky', 'past': 'po', 'following':'následující', 'previous' : 'předchozí', 'prev-week' : 'týden', 'prev-month' : 'měsíc', 'prev-year' : 'rok', 'next':'další', 'next-week':'týden', 'next-month':'měsíc', 'next-year':'rok', 'less-than' : 'Rozsah data by neměl být větší než %d dnů', 'more-than' : 'Rozsah data by neměl být menší než %d dnů', 'default-more' : 'Prosím zvolte rozsah data větší než %d dnů', 'default-single' : 'Prosím zvolte datum', 'default-less' : 'Prosím zvolte rozsah data menší než %d dnů', 'default-range' : 'Prosím zvolte rozsah data mezi %d a %d dny', 'default-default': 'Prosím zvolte rozsah data' }, 'de': { 'selected': 'Auswahl:', 'day':'Tag', 'days': 'Tage', 'apply': 'Schließen', 'week-1' : 'mo', 'week-2' : 'di', 'week-3' : 'mi', 'week-4' : 'do', 'week-5' : 'fr', 'week-6' : 'sa', 'week-7' : 'so', 'month-name': ['januar','februar','märz','april','mai','juni','juli','august','september','oktober','november','dezember'], 'shortcuts' : 'Schnellwahl', 'past': 'Vorherige', 'following':'Folgende', 'previous' : 'Vorherige', 'prev-week' : 'Woche', 'prev-month' : 'Monat', 'prev-year' : 'Jahr', 'next':'Nächste', 'next-week':'Woche', 'next-month':'Monat', 'next-year':'Jahr', 'less-than' : 'Datumsbereich darf nicht größer sein als %d Tage', 'more-than' : 'Datumsbereich darf nicht kleiner sein als %d Tage', 'default-more' : 'Bitte mindestens %d Tage auswählen', 'default-single' : 'Bitte ein Datum auswählen', 'default-less' : 'Bitte weniger als %d Tage auswählen', 'default-range' : 'Bitte einen Datumsbereich zwischen %d und %d Tagen auswählen', 'default-default': 'Bitte ein Start- und Enddatum auswählen', 'Time': 'Zeit', 'hour': 'Stunde', 'minute': 'Minute', }, 'es': { 'selected': 'Seleccionado:', 'day':'Dia', 'days': 'Dias', 'apply': 'Cerrar', 'week-1' : 'lu', 'week-2' : 'ma', 'week-3' : 'mi', 'week-4' : 'ju', 'week-5' : 'vi', 'week-6' : 'sa', 'week-7' : 'do', 'month-name': ['enero','febrero','marzo','abril','mayo','junio','julio','agosto','septiembre','octubre','noviembre','diciembre'], 'shortcuts' : 'Accesos directos', 'past': 'Pasado', 'following':'Siguiente', 'previous' : 'Anterior', 'prev-week' : 'Semana', 'prev-month' : 'Mes', 'prev-year' : 'Año', 'next':'Siguiente', 'next-week':'Semana', 'next-month':'Mes', 'next-year':'Año', 'less-than' : 'El rango no deberia ser mayor de %d dias', 'more-than' : 'El rango no deberia ser menor de %d dias', 'default-more' : 'Por favor selecciona un rango mayor a %d dias', 'default-single' : 'Por favor selecciona un dia', 'default-less' : 'Por favor selecciona un rango menor a %d dias', 'default-range' : 'Por favor selecciona un rango entre %d y %d dias', 'default-default': 'Por favor selecciona un rango de fechas.' }, 'fr': { 'selected': 'Sélection:', 'day':'Jour', 'days': 'Jours', 'apply': 'Fermer', 'week-1' : 'lu', 'week-2' : 'ma', 'week-3' : 'me', 'week-4' : 'je', 'week-5' : 've', 'week-6' : 'sa', 'week-7' : 'di', 'month-name': ['janvier','février','mars','avril','mai','juin','juillet','août','septembre','octobre','novembre','décembre'], 'shortcuts' : 'Raccourcis', 'past': 'Passé', 'following':'Suivant', 'previous' : 'Précédent', 'prev-week' : 'Semaine', 'prev-month' : 'Mois', 'prev-year' : 'Année', 'next':'Suivant', 'next-week':'Semaine', 'next-month':'Mois', 'next-year':'Année', 'less-than' : 'L\'intervalle ne doit pas être supérieure à %d jours', 'more-than' : 'L\'intervalle ne doit pas être inférieure à %d jours', 'default-more' : 'Merci de choisir une intervalle supérieure à %d jours', 'default-single' : 'Merci de choisir une date', 'default-less' : 'Merci de choisir une intervalle inférieure %d jours', 'default-range' : 'Merci de choisir une intervalle comprise entre %d et %d jours', 'default-default': 'Merci de choisir une date' }, 'hu': { 'selected': 'Kiválasztva:', 'day':'Nap', 'days': 'Nap', 'apply': 'Ok', 'week-1' : 'h', 'week-2' : 'k', 'week-3' : 'sz', 'week-4' : 'cs', 'week-5' : 'p', 'week-6' : 'sz', 'week-7' : 'v', 'month-name': ['január','február','március','április','május','június','július','augusztus','szeptember','október','november','december'], 'shortcuts' : 'Gyorsválasztó', 'past': 'Múlt', 'following':'Következő', 'previous' : 'Előző', 'prev-week' : 'Hét', 'prev-month' : 'Hónap', 'prev-year' : 'Év', 'next':'Következő', 'next-week':'Hét', 'next-month':'Hónap', 'next-year':'Év', 'less-than' : 'A kiválasztás nem lehet több %d napnál', 'more-than' : 'A kiválasztás nem lehet több %d napnál', 'default-more' : 'Válassz ki egy időszakot ami hosszabb mint %d nap', 'default-single' : 'Válassz egy napot', 'default-less' : 'Válassz ki egy időszakot ami rövidebb mint %d nap', 'default-range' : 'Válassz ki egy %d - %d nap hosszú időszakot', 'default-default': 'Válassz ki egy időszakot' }, 'it': { 'selected': 'Selezionati:', 'day':'Giorno', 'days': 'Giorni', 'apply': 'Chiudi', 'week-1' : 'lu', 'week-2' : 'ma', 'week-3' : 'me', 'week-4' : 'gi', 'week-5' : 've', 'week-6' : 'sa', 'week-7' : 'do', 'month-name': ['gennaio','febbraio','marzo','aprile','maggio','giugno','luglio','agosto','settembre','ottobre','novembre','dicembre'], 'shortcuts' : 'Scorciatoie', 'past': 'Scorso', 'following':'Successivo', 'previous' : 'Precedente', 'prev-week' : 'Settimana', 'prev-month' : 'Mese', 'prev-year' : 'Anno', 'next':'Prossimo', 'next-week':'Settimana', 'next-month':'Mese', 'next-year':'Anno', 'less-than' : 'L\'intervallo non dev\'essere maggiore di %d giorni', 'more-than' : 'L\'intervallo non dev\'essere minore di %d giorni', 'default-more' : 'Seleziona un intervallo maggiore di %d giorni', 'default-single' : 'Seleziona una data', 'default-less' : 'Seleziona un intervallo minore di %d giorni', 'default-range' : 'Seleziona un intervallo compreso tra i %d e i %d giorni', 'default-default': 'Seleziona un intervallo di date' }, 'no': { 'selected': 'Valgt:', 'day':'Dag', 'days': 'Dager', 'apply': 'Lukk', 'week-1' : 'ma', 'week-2' : 'ti', 'week-3' : 'on', 'week-4' : 'to', 'week-5' : 'fr', 'week-6' : 'lø', 'week-7' : 'sø', 'month-name': ['januar','februar','mars','april','mai','juni','juli','august','september','oktober','november','desember'], 'shortcuts' : 'Snarveier', 'custom-values': 'Egendefinerte Verdier', 'past': 'Over', // Not quite sure about the context of this one 'following':'Følger', 'previous' : 'Forrige', 'prev-week' : 'Uke', 'prev-month' : 'Måned', 'prev-year' : 'År', 'next':'Neste', 'next-week':'Uke', 'next-month':'Måned', 'next-year':'År', 'less-than' : 'Datoperioden skal ikkje være lengre enn %d dager', 'more-than' : 'Datoperioden skal ikkje være kortere enn %d dager', 'default-more' : 'Vennligst velg ein datoperiode lengre enn %d dager', 'default-single' : 'Vennligst velg ein dato', 'default-less' : 'Vennligst velg ein datoperiode mindre enn %d dager', 'default-range' : 'Vennligst velg ein datoperiode mellom %d og %d dager', 'default-default': 'Vennligst velg ein datoperiode', 'time':'Tid', 'hour':'Time', 'minute':'Minutter' }, 'nl': { 'selected': 'Geselecteerd:', 'day':'Dag', 'days': 'Dagen', 'apply': 'Ok', 'week-1' : 'ma', 'week-2' : 'di', 'week-3' : 'wo', 'week-4' : 'do', 'week-5' : 'vr', 'week-6' : 'za', 'week-7' : 'zo', 'month-name': ['januari','februari','maart','april','mei','juni','juli','augustus','september','october','november','december'], 'shortcuts' : 'Snelkoppelingen', 'custom-values': 'Aangepaste waarden', 'past': 'Verleden', 'following':'Komend', 'previous' : 'Vorige', 'prev-week' : 'Week', 'prev-month' : 'Maand', 'prev-year' : 'Jaar', 'next':'Volgende', 'next-week':'Week', 'next-month':'Maand', 'next-year':'Jaar', 'less-than' : 'Interval moet langer dan %d dagen zijn', 'more-than' : 'Interval mag niet minder dan %d dagen zijn', 'default-more' : 'Selecteer een interval langer dan %dagen', 'default-single' : 'Selecteer een datum', 'default-less' : 'Selecteer een interval minder dan %d dagen', 'default-range' : 'Selecteer een interval tussen %d en %d dagen', 'default-default': 'Selecteer een interval', 'time':'Tijd', 'hour':'Uur', 'minute':'Minuut' }, 'ru': { 'selected': 'Выбрано:', 'day': 'День', 'days': 'Дней', 'apply': 'Закрыть', 'week-1': 'пн', 'week-2': 'вт', 'week-3': 'ср', 'week-4': 'чт', 'week-5': 'пт', 'week-6': 'сб', 'week-7': 'вс', 'month-name': ['январь','февраль','март','апрель','май','июнь','июль','август','сентябрь','октябрь','ноябрь','декабрь'], 'shortcuts': 'Быстрый выбор', 'past': 'Прошедшие', 'following': 'Следующие', 'previous': '&nbsp;&nbsp;&nbsp;', 'prev-week': 'Неделя', 'prev-month': 'Месяц', 'prev-year': 'Год', 'next': '&nbsp;&nbsp;&nbsp;', 'next-week': 'Неделя', 'next-month': 'Месяц', 'next-year': 'Год', 'less-than': 'Диапазон не может быть больше %d дней', 'more-than': 'Диапазон не может быть меньше %d дней', 'default-more': 'Пожалуйста выберите диапазон больше %d дней', 'default-single': 'Пожалуйста выберите дату', 'default-less': 'Пожалуйста выберите диапазон меньше %d дней', 'default-range': 'Пожалуйста выберите диапазон между %d и %d днями', 'default-default': 'Пожалуйста выберите диапазон' }, 'pl': { 'selected': 'Wybrany:', 'day':'Dzień', 'days': 'Dni', 'apply': 'Zamknij', 'week-1' : 'pon', 'week-2' : 'wt', 'week-3' : 'śr', 'week-4' : 'czw', 'week-5' : 'pt', 'week-6' : 'so', 'week-7' : 'nd', 'month-name': ['styczeń','luty','marzec','kwiecień','maj','czerwiec','lipiec','sierpień','wrzesień','październik','listopad','grudzień'], 'shortcuts' : 'Skróty', 'custom-values': 'Niestandardowe wartości', 'past': 'Przeszłe', 'following':'Następne', 'previous' : 'Poprzednie', 'prev-week' : 'tydzień', 'prev-month' : 'miesiąc', 'prev-year' : 'rok', 'next':'Następny', 'next-week':'tydzień', 'next-month':'miesiąc', 'next-year':'rok', 'less-than' : 'Okres nie powinien być dłuższy niż %d dni', 'more-than' : 'Okres nie powinien być krótszy niż %d ni', 'default-more' : 'Wybierz okres dłuższy niż %d dni', 'default-single' : 'Wybierz datę', 'default-less' : 'Wybierz okres krótszy niż %d dni', 'default-range' : 'Wybierz okres trwający od %d do %d dni', 'default-default': 'Wybierz okres', 'time':'Czas', 'hour':'Godzina', 'minute':'Minuta' }, 'se': { 'selected': 'Vald:', 'day':'dag', 'days': 'dagar', 'apply': 'godkänn', 'week-1' : 'ma', 'week-2' : 'ti', 'week-3' : 'on', 'week-4' : 'to', 'week-5' : 'fr', 'week-6' : 'lö', 'week-7' : 'sö', 'month-name': ['januari','februari','mars','april','maj','juni','juli','augusti','september','oktober','november','december'], 'shortcuts' : 'genvägar', 'custom-values': 'Anpassade värden', 'past': 'över', 'following':'följande', 'previous' : 'förra', 'prev-week' : 'vecka', 'prev-month' : 'månad', 'prev-year' : 'år', 'next':'nästa', 'next-week':'vecka', 'next-month':'måned', 'next-year':'år', 'less-than' : 'Datumintervall bör inte vara mindre än %d dagar', 'more-than' : 'Datumintervall bör inte vara mer än %d dagar', 'default-more' : 'Välj ett datumintervall längre än %d dagar', 'default-single' : 'Välj ett datum', 'default-less' : 'Välj ett datumintervall mindre än %d dagar', 'default-range' : 'Välj ett datumintervall mellan %d och %d dagar', 'default-default': 'Välj ett datumintervall', 'time':'tid', 'hour':'timme', 'minute':'minut' } }; $.fn.dateRangePicker = function(opt) { if (!opt) opt = {}; opt = $.extend(true, { autoClose: false, format: 'YYYY-MM-DD', separator: ' to ', language: 'auto', startOfWeek: 'sunday',// or monday getValue: function() { return $(this).val(); }, setValue: function(s) { if(!$(this).attr('readonly') && !$(this).is(':disabled') && s != $(this).val()) { $(this).val(s); } }, startDate: false, endDate: false, time: { enabled: false }, minDays: 0, maxDays: 0, showShortcuts: false, shortcuts: { //'prev-days': [1,3,5,7], // 'next-days': [3,5,7], //'prev' : ['week','month','year'], // 'next' : ['week','month','year'] }, customShortcuts : [], inline:false, container:'body', alwaysOpen:false, singleDate:false, lookBehind: false, batchMode: false, duration: 200, stickyMonths: false, dayDivAttrs: [], dayTdAttrs: [], selectForward: false, selectBackward: false, applyBtnClass: '', singleMonth: 'auto', hoveringTooltip: function(days, startTime, hoveringTime) { return days > 1 ? days + ' ' + lang('days') : ''; }, showTopbar: true, swapTime: false, showWeekNumbers: false, getWeekNumber: function(date) //date will be the first day of a week { return moment(date).format('w'); }, customOpenAnimation: null, customCloseAnimation: null },opt); opt.start = false; opt.end = false; opt.startWeek = false; //detect a touch device opt.isTouchDevice = 'ontouchstart' in window || navigator.msMaxTouchPoints; //if it is a touch device, hide hovering tooltip if (opt.isTouchDevice) opt.hoveringTooltip = false; //show one month on mobile devices if (opt.singleMonth == 'auto') opt.singleMonth = $(window).width() < 480; if (opt.singleMonth) opt.stickyMonths = false; if (opt.singleDate) opt.singleMonth = true; if (!opt.showTopbar) opt.autoClose = true; if (opt.startDate && typeof opt.startDate == 'string') opt.startDate = moment(opt.startDate,opt.format).toDate(); if (opt.endDate && typeof opt.endDate == 'string') opt.endDate = moment(opt.endDate,opt.format).toDate(); var langs = getLanguages(); var box; var initiated = false; var self = this; var selfDom = $(self).get(0); var domChangeTimer; $(this).unbind('.datepicker').bind('click.datepicker',function(evt) { var isOpen = box.is(':visible'); if(!isOpen) open(opt.duration); }).bind('change.datepicker', function(evt) { checkAndSetDefaultValue(); }).bind('keyup.datepicker',function() { try{ clearTimeout(domChangeTimer); }catch(e){} domChangeTimer = setTimeout(function() { checkAndSetDefaultValue(); },2000); }); init_datepicker.call(this); if (opt.alwaysOpen) { open(0); } // expose some api $(this).data('dateRangePicker', { setDateRange : function(d1,d2,silent) { if (typeof d1 == 'string' && typeof d2 == 'string') { d1 = moment(d1,opt.format).toDate(); d2 = moment(d2,opt.format).toDate(); } setDateRange(d1,d2,silent); }, clear: clearSelection, close: closeDatePicker, open: open, redraw: redrawDatePicker, getDatePicker: getDatePicker, destroy: function() { $(self).unbind('.datepicker'); $(self).data('dateRangePicker',''); $(self).data('date-picker-opened',null); box.remove(); $(window).unbind('resize.datepicker',calcPosition); $(document).unbind('click.datepicker',closeDatePicker); } }); $(window).bind('resize.datepicker',calcPosition); return this; function IsOwnDatePickerClicked(evt, selfObj) { return ( selfObj.contains(evt.target) || evt.target == selfObj || (selfObj.childNodes != undefined && $.inArray(evt.target, selfObj.childNodes)>=0)) } function init_datepicker() { var self = this; if ($(this).data('date-picker-opened')) { closeDatePicker(); return; } $(this).data('date-picker-opened',true); box = createDom().hide(); box.append('<div class="date-range-length-tip"></div>'); box.delegate('.day', 'mouseleave', function() { box.find('.date-range-length-tip').hide(); }); $(opt.container).append(box); if (!opt.inline) { calcPosition(); } else { box.addClass("inline-wrapper"); } if (opt.alwaysOpen) { box.find('.apply-btn').hide(); } var defaultTime = opt.defaultTime ? opt.defaultTime : new Date(); if (opt.lookBehind) { if (opt.startDate && compare_month(defaultTime, opt.startDate) < 0 ) defaultTime = nextMonth(moment(opt.startDate).toDate()); if (opt.endDate && compare_month(defaultTime,opt.endDate) > 0 ) defaultTime = moment(opt.endDate).toDate(); showMonth(prevMonth(defaultTime),'month1'); showMonth(defaultTime,'month2'); } else { if (opt.startDate && compare_month(defaultTime,opt.startDate) < 0 ) defaultTime = moment(opt.startDate).toDate(); if (opt.endDate && compare_month(nextMonth(defaultTime),opt.endDate) > 0 ) defaultTime = prevMonth(moment(opt.endDate).toDate()); showMonth(defaultTime,'month1'); showMonth(nextMonth(defaultTime),'month2'); } if (opt.singleDate) { if (opt.startDate && compare_month(defaultTime,opt.startDate) < 0 ) defaultTime = moment(opt.startDate).toDate(); if (opt.endDate && compare_month(defaultTime,opt.endDate) > 0 ) defaultTime = moment(opt.endDate).toDate(); showMonth(defaultTime,'month1'); } if (opt.time.enabled) { if ((opt.startDate && opt.endDate) || (opt.start && opt.end)) { showTime(moment(opt.start || opt.startDate).toDate(),'time1'); showTime(moment(opt.end || opt.endDate).toDate(),'time2'); } else { var defaultEndTime = opt.defaultEndTime ? opt.defaultEndTime : defaultTime; showTime(defaultTime,'time1'); showTime(defaultEndTime,'time2'); } } //showSelectedInfo(); var defaultTopText = ''; if (opt.singleDate) defaultTopText = lang('default-single'); else if (opt.minDays && opt.maxDays) defaultTopText = lang('default-range'); else if (opt.minDays) defaultTopText = lang('default-more'); else if (opt.maxDays) defaultTopText = lang('default-less'); else defaultTopText = lang('default-default'); box.find('.default-top').html( defaultTopText.replace(/\%d/,opt.minDays).replace(/\%d/,opt.maxDays)); if (opt.singleMonth) { box.addClass('single-month'); } else { box.addClass('two-months'); } setTimeout(function() { updateCalendarWidth(); initiated = true; },0); box.click(function(evt) { evt.stopPropagation(); }); //if user click other place of the webpage, close date range picker window $(document).bind('click.datepicker',function(evt) { if (!IsOwnDatePickerClicked(evt, self[0])) { if (box.is(':visible')) closeDatePicker(); } }); box.find('.next').click(function() { if(!opt.stickyMonths) gotoNextMonth(this); else gotoNextMonth_stickily(this); }); function gotoNextMonth(self) { var isMonth2 = $(self).parents('table').hasClass('month2'); var month = isMonth2 ? opt.month2 : opt.month1; month = nextMonth(month); if (!opt.singleMonth && !opt.singleDate && !isMonth2 && compare_month(month,opt.month2) >= 0 || isMonthOutOfBounds(month)) return; showMonth(month,isMonth2 ? 'month2' : 'month1'); showGap(); } function gotoNextMonth_stickily(self) { var nextMonth1 = nextMonth(opt.month1); var nextMonth2 = nextMonth(opt.month2); if(isMonthOutOfBounds(nextMonth2)) return; if (!opt.singleDate && compare_month(nextMonth1,nextMonth2) >= 0) return; showMonth(nextMonth1, 'month1'); showMonth(nextMonth2, 'month2'); showSelectedDays(); } box.find('.prev').click(function() { if(!opt.stickyMonths) gotoPrevMonth(this); else gotoPrevMonth_stickily(this); }); function gotoPrevMonth(self) { var isMonth2 = $(self).parents('table').hasClass('month2'); var month = isMonth2 ? opt.month2 : opt.month1; month = prevMonth(month); if (isMonth2 && compare_month(month,opt.month1) <= 0 || isMonthOutOfBounds(month)) return; showMonth(month,isMonth2 ? 'month2' : 'month1'); showGap(); } function gotoPrevMonth_stickily(self) { var prevMonth1 = prevMonth(opt.month1); var prevMonth2 = prevMonth(opt.month2); if(isMonthOutOfBounds(prevMonth1)) return; if(!opt.singleDate && compare_month(prevMonth2,prevMonth1) <= 0) return; showMonth(prevMonth2, 'month2'); showMonth(prevMonth1, 'month1'); showSelectedDays(); } box.delegate('.day','click', function(evt) { dayClicked($(this)); }); box.delegate('.day','mouseenter',function(evt) { dayHovering($(this)); }); box.delegate('.week-number', 'click', function(evt) { weekNumberClicked($(this)); }); box.attr('unselectable', 'on') .css('user-select', 'none') .bind('selectstart', function(e) { e.preventDefault(); return false; }); box.find('.apply-btn').click(function() { closeDatePicker(); var dateRange = getDateString(new Date(opt.start))+ opt.separator +getDateString(new Date(opt.end)); $(self).trigger('datepicker-apply', { 'value': dateRange, 'date1' : new Date(opt.start), 'date2' : new Date(opt.end) }); }); box.find('[custom]').click(function() { var valueName = $(this).attr('custom'); opt.start = false; opt.end = false; box.find('.day.checked').removeClass('checked'); opt.setValue.call(selfDom, valueName); checkSelectionValid(); showSelectedInfo(true); showSelectedDays(); if (opt.autoClose) closeDatePicker(); }); box.find('[shortcut]').click(function() { var shortcut = $(this).attr('shortcut'); var end = new Date(),start = false; if (shortcut.indexOf('day') != -1) { var day = parseInt(shortcut.split(',',2)[1],10); start = new Date(new Date().getTime() + 86400000*day); end = new Date(end.getTime() + 86400000*(day>0?1:-1) ); } else if (shortcut.indexOf('week')!= -1) { var dir = shortcut.indexOf('prev,') != -1 ? -1 : 1; if (dir == 1) var stopDay = opt.startOfWeek == 'monday' ? 1 : 0; else var stopDay = opt.startOfWeek == 'monday' ? 0 : 6; end = new Date(end.getTime() - 86400000); while(end.getDay() != stopDay) end = new Date(end.getTime() + dir*86400000); start = new Date(end.getTime() + dir*86400000*6); } else if (shortcut.indexOf('month') != -1) { var dir = shortcut.indexOf('prev,') != -1 ? -1 : 1; if (dir == 1) start = nextMonth(end); else start = prevMonth(end); start.setDate(1); end = nextMonth(start); end.setDate(1); end = new Date(end.getTime() - 86400000); } else if (shortcut.indexOf('year') != -1) { var dir = shortcut.indexOf('prev,') != -1 ? -1 : 1; start = new Date(); start.setFullYear(end.getFullYear() + dir); start.setMonth(0); start.setDate(1); end.setFullYear(end.getFullYear() + dir); end.setMonth(11); end.setDate(31); } else if (shortcut == 'custom') { var name = $(this).html(); if (opt.customShortcuts && opt.customShortcuts.length > 0) { for(var i=0;i<opt.customShortcuts.length;i++) { var sh = opt.customShortcuts[i]; if (sh.name == name) { var data = []; // try // { data = sh['dates'].call(); //}catch(e){} if (data && data.length == 2) { start = data[0]; end = data[1]; } // if only one date is specified then just move calendars there // move calendars to show this date's month and next months if (data && data.length == 1) { movetodate = data[0]; showMonth(movetodate,'month1'); showMonth(nextMonth(movetodate),'month2'); showGap(); } break; } } } } if (start && end) { setDateRange(start,end); checkSelectionValid(); } }); box.find(".time1 input[type=range]").bind("change touchmove mousemove", function (e) { var target = e.target, hour = target.name == "hour" ? $(target).val().replace(/^(\d{1})$/, "0$1") : undefined, min = target.name == "minute" ? $(target).val().replace(/^(\d{1})$/, "0$1") : undefined; setTime("time1", hour, min); }); box.find(".time2 input[type=range]").bind("change touchmove mousemove", function (e) { var target = e.target, hour = target.name == "hour" ? $(target).val().replace(/^(\d{1})$/, "0$1") : undefined, min = target.name == "minute" ? $(target).val().replace(/^(\d{1})$/, "0$1") : undefined; setTime("time2", hour, min); }); } function calcPosition() { if (!opt.inline) { var offset = $(self).offset(); if ($(opt.container).css("position") == "relative") { var containerOffset = $(opt.container).offset(); box.css( { top: offset.top - containerOffset.top + $(self).outerHeight() + 4, left: offset.left - containerOffset.left }); } else { if (offset.left < 460) //left to right { box.css( { top: offset.top+$(self).outerHeight() + parseInt($('body').css('border-top') || 0,10 ), left: offset.left }); } else { box.css( { top: offset.top+$(self).outerHeight() + parseInt($('body').css('border-top') || 0,10 ), left: offset.left + $(self).width() - box.width() - 16 }); } } } } // Return the date picker wrapper element function getDatePicker() { return box; } function open(animationTime) { calcPosition(); redrawDatePicker(); checkAndSetDefaultValue(); if (opt.customOpenAnimation) { opt.customOpenAnimation.call(box.get(0), function() { $(self).trigger('datepicker-opened', {relatedTarget: box}); }); } else { box.slideDown(animationTime, function(){ $(self).trigger('datepicker-opened', {relatedTarget: box}); }); } $(self).trigger('datepicker-open', {relatedTarget: box}); showGap(); updateCalendarWidth(); } function checkAndSetDefaultValue() { var __default_string = opt.getValue.call(selfDom); var defaults = __default_string ? __default_string.split( opt.separator ) : ''; if (defaults && ((defaults.length==1 && opt.singleDate) || defaults.length>=2)) { var ___format = opt.format; if (___format.match(/Do/)) { ___format = ___format.replace(/Do/,'D'); defaults[0] = defaults[0].replace(/(\d+)(th|nd|st)/,'$1'); if(defaults.length >= 2){ defaults[1] = defaults[1].replace(/(\d+)(th|nd|st)/,'$1'); } } // set initiated to avoid triggerring datepicker-change event initiated = false; if(defaults.length >= 2){ setDateRange(getValidValue(defaults[0], ___format, moment.locale(opt.language)),getValidValue(defaults[1], ___format, moment.locale(opt.language))); } else if(defaults.length==1 && opt.singleDate){ setSingleDate(getValidValue(defaults[0], ___format, moment.locale(opt.language))); } initiated = true; function getValidValue(date, format, locale) { if (moment(date, format, locale).isValid()) { return moment(date, format, locale).toDate(); } else { return moment().toDate() } } } } function updateCalendarWidth() { var gapMargin = box.find('.gap').css('margin-left'); if (gapMargin) gapMargin = parseInt(gapMargin); var w1 = box.find('.month1').width(); var w2 = box.find('.gap').width() + ( gapMargin ? gapMargin*2 : 0 ); var w3 = box.find('.month2').width(); box.find('.month-wrapper').width(w1 + w2 + w3); } function renderTime (name, date) { box.find("." + name + " input[type=range].hour-range").val(moment(date).hours()); box.find("." + name + " input[type=range].minute-range").val(moment(date).minutes()); setTime(name, moment(date).format("HH"), moment(date).format("mm")); } function changeTime (name, date) { opt[name] = parseInt( moment(parseInt(date)) .startOf('day') .add(moment(opt[name + "Time"]).format("HH"), 'h') .add(moment(opt[name + "Time"]).format("mm"), 'm').valueOf() ); } function swapTime () { renderTime("time1", opt.start); renderTime("time2", opt.end); } function setTime (name, hour, minute) { hour && (box.find("." + name + " .hour-val").text(hour)); minute && (box.find("." + name + " .minute-val").text(minute)); switch (name) { case "time1": if (opt.start) { setRange("start", moment(opt.start)); } setRange("startTime", moment(opt.startTime || moment().valueOf())); break; case "time2": if (opt.end) { setRange("end", moment(opt.end)); } setRange("endTime", moment(opt.endTime || moment().valueOf())); break; } function setRange(name, timePoint) { var h = timePoint.format("HH"), m = timePoint.format("mm"); opt[name] = timePoint .startOf('day') .add(hour || h, "h") .add(minute || m, "m") .valueOf(); } checkSelectionValid(); showSelectedInfo(); showSelectedDays(); } function clearSelection() { opt.start = false; opt.end = false; box.find('.day.checked').removeClass('checked'); box.find('.day.last-date-selected').removeClass('last-date-selected'); box.find('.day.first-date-selected').removeClass('first-date-selected'); opt.setValue.call(selfDom, ''); checkSelectionValid(); showSelectedInfo(); showSelectedDays(); } function handleStart(time) { var r = time; if (opt.batchMode === 'week-range') { if (opt.startOfWeek === 'monday') { r = moment(parseInt(time)).startOf('isoweek').valueOf(); } else { r = moment(parseInt(time)).startOf('week').valueOf(); } } else if (opt.batchMode === 'month-range') { r = moment(parseInt(time)).startOf('month').valueOf(); } return r; } function handleEnd(time) { var r = time; if (opt.batchMode === 'week-range') { if (opt.startOfWeek === 'monday') { r = moment(parseInt(time)).endOf('isoweek').valueOf(); } else { r = moment(parseInt(time)).endOf('week').valueOf(); } } else if (opt.batchMode === 'month-range') { r = moment(parseInt(time)).endOf('month').valueOf(); } return r; } function dayClicked(day) { if (day.hasClass('invalid')) return; var time = day.attr('time'); day.addClass('checked'); if ( opt.singleDate ) { opt.start = time; opt.end = false; } else if (opt.batchMode === 'week') { if (opt.startOfWeek === 'monday') { opt.start = moment(parseInt(time)).startOf('isoweek').valueOf(); opt.end = moment(parseInt(time)).endOf('isoweek').valueOf(); } else { opt.end = moment(parseInt(time)).endOf('week').valueOf(); opt.start = moment(parseInt(time)).startOf('week').valueOf(); } } else if (opt.batchMode === 'workweek') { opt.start = moment(parseInt(time)).day(1).valueOf(); opt.end = moment(parseInt(time)).day(5).valueOf(); } else if (opt.batchMode === 'weekend') { opt.start = moment(parseInt(time)).day(6).valueOf(); opt.end = moment(parseInt(time)).day(7).valueOf(); } else if (opt.batchMode === 'month') { opt.start = moment(parseInt(time)).startOf('month').valueOf(); opt.end = moment(parseInt(time)).endOf('month').valueOf(); } else if ((opt.start && opt.end) || (!opt.start && !opt.end) ) { opt.start = handleStart(time); opt.end = false; } else if (opt.start) { opt.end = handleEnd(time); if (opt.time.enabled) { changeTime("end", opt.end); } } //Update time in case it is enabled and timestamps are available if(opt.time.enabled) { if(opt.start) { changeTime("start", opt.start); } if(opt.end) { changeTime("end", opt.end); } } //In case the start is after the end, swap the timestamps if (!opt.singleDate && opt.start && opt.end && opt.start > opt.end) { var tmp = opt.end; opt.end = handleEnd(opt.start); opt.start = handleStart(tmp); if (opt.time.enabled && opt.swapTime) { swapTime(); } } opt.start = parseInt(opt.start); opt.end = parseInt(opt.end); clearHovering(); if (opt.start && !opt.end) { $(self).trigger('datepicker-first-date-selected', { 'date1' : new Date(opt.start) }); dayHovering(day); } updateSelectableRange(time); checkSelectionValid(); showSelectedInfo(); showSelectedDays(); autoclose(); } function weekNumberClicked(weekNumberDom) { var thisTime = parseInt(weekNumberDom.attr('data-start-time'),10); if (!opt.startWeek) { opt.startWeek = thisTime; weekNumberDom.addClass('week-number-selected'); var date1 = new Date(thisTime); opt.start = moment(date1).day(opt.startOfWeek == 'monday' ? 1 : 0).toDate(); opt.end = moment(date1).day(opt.startOfWeek == 'monday' ? 7 : 6).toDate(); } else { box.find('.week-number-selected').removeClass('week-number-selected'); var date1 = new Date(thisTime < opt.startWeek ? thisTime : opt.startWeek); var date2 = new Date(thisTime < opt.startWeek ? opt.startWeek : thisTime); opt.startWeek = false; opt.start = moment(date1).day(opt.startOfWeek == 'monday' ? 1 : 0).toDate(); opt.end = moment(date2).day(opt.startOfWeek == 'monday' ? 7 : 6).toDate(); } updateSelectableRange(); checkSelectionValid(); showSelectedInfo(); showSelectedDays(); autoclose(); } function isValidTime(time) { time = parseInt(time, 10); if (opt.startDate && compare_day(time, opt.startDate) < 0) return false; if (opt.endDate && compare_day(time, opt.endDate) > 0) return false; if (opt.start && !opt.end && !opt.singleDate) { //check maxDays and minDays setting if (opt.maxDays > 0 && countDays(time, opt.start) > opt.maxDays) return false; if (opt.minDays > 0 && countDays(time, opt.start) < opt.minDays) return false; //check selectForward and selectBackward if (opt.selectForward && time < opt.start ) return false; if (opt.selectBackward && time > opt.start) return false; //check disabled days if (opt.beforeShowDay && typeof opt.beforeShowDay == 'function') { var valid = true; var timeTmp = time; while( countDays(timeTmp, opt.start) > 1 ) { var arr = opt.beforeShowDay( new Date(timeTmp) ); if (!arr[0]) { valid = false; break; } if (Math.abs(timeTmp - opt.start) < 86400000) break; if (timeTmp > opt.start) timeTmp -= 86400000; if (timeTmp < opt.start) timeTmp += 86400000; } if (!valid) return false; } } return true; } function updateSelectableRange() { box.find('.day.invalid.tmp').removeClass('tmp invalid').addClass('valid'); if (opt.start && !opt.end) { box.find('.day.toMonth.valid').each(function() { var time = parseInt($(this).attr('time'), 10); if (!isValidTime(time)) $(this).addClass('invalid tmp').removeClass('valid'); else $(this).addClass('valid tmp').removeClass('invalid'); }); } return true; } function dayHovering(day) { var hoverTime = parseInt(day.attr('time')); var tooltip = ''; if (day.hasClass('has-tooltip') && day.attr('data-tooltip')) { tooltip = '<span style="white-space:nowrap">'+day.attr('data-tooltip')+'</span>'; } else if (!day.hasClass('invalid')) { if (opt.singleDate) { box.find('.day.hovering').removeClass('hovering'); day.addClass('hovering'); } else { box.find('.day').each(function() { var time = parseInt($(this).attr('time')), start = opt.start, end = opt.end; if ( time == hoverTime ) { $(this).addClass('hovering'); } else { $(this).removeClass('hovering'); } if ( ( opt.start && !opt.end ) && ( ( opt.start < time && hoverTime >= time ) || ( opt.start > time && hoverTime <= time ) ) ) { $(this).addClass('hovering'); } else { $(this).removeClass('hovering'); } }); if (opt.start && !opt.end) { var days = countDays(hoverTime, opt.start); if (opt.hoveringTooltip) { if (typeof opt.hoveringTooltip == 'function') { tooltip = opt.hoveringTooltip(days, opt.start, hoverTime); } else if (opt.hoveringTooltip === true && days > 1) { tooltip = days + ' ' + lang('days'); } } } } } if (tooltip) { var posDay = day.offset(); var posBox = box.offset(); var _left = posDay.left - posBox.left; var _top = posDay.top - posBox.top; _left += day.width()/2; var $tip = box.find('.date-range-length-tip'); var w = $tip.css({'visibility':'hidden', 'display':'none'}).html(tooltip).width(); var h = $tip.height(); _left -= w/2; _top -= h; setTimeout(function() { $tip.css({left:_left, top:_top, display:'block','visibility':'visible'}); },10); } else { box.find('.date-range-length-tip').hide(); } } function clearHovering() { box.find('.day.hovering').removeClass('hovering'); box.find('.date-range-length-tip').hide(); } function autoclose () { if (opt.singleDate === true) { if (initiated && opt.start ) { if (opt.autoClose) closeDatePicker(); } } else { if (initiated && opt.start && opt.end) { if (opt.autoClose) closeDatePicker(); } } } function checkSelectionValid() { var days = Math.ceil( (opt.end - opt.start) / 86400000 ) + 1; if (opt.singleDate) { // Validate if only start is there if (opt.start && !opt.end) box.find('.drp_top-bar').removeClass('error').addClass('normal'); else box.find('.drp_top-bar').removeClass('error').removeClass('normal'); } else if ( opt.maxDays && days > opt.maxDays) { opt.start = false; opt.end = false; box.find('.day').removeClass('checked'); box.find('.drp_top-bar').removeClass('normal').addClass('error').find('.error-top').html( lang('less-than').replace('%d',opt.maxDays) ); } else if ( opt.minDays && days < opt.minDays) { opt.start = false; opt.end = false; box.find('.day').removeClass('checked'); box.find('.drp_top-bar').removeClass('normal').addClass('error').find('.error-top').html( lang('more-than').replace('%d',opt.minDays) ); } else { if (opt.start || opt.end) box.find('.drp_top-bar').removeClass('error').addClass('normal'); else box.find('.drp_top-bar').removeClass('error').removeClass('normal'); } if ( (opt.singleDate && opt.start && !opt.end) || (!opt.singleDate && opt.start && opt.end) ) { box.find('.apply-btn').removeClass('disabled'); } else { box.find('.apply-btn').addClass('disabled'); } if (opt.batchMode) { if ( (opt.start && opt.startDate && compare_day(opt.start, opt.startDate) < 0) || (opt.end && opt.endDate && compare_day(opt.end, opt.endDate) > 0) ) { opt.start = false; opt.end = false; box.find('.day').removeClass('checked'); } } } function showSelectedInfo(forceValid,silent) { box.find('.start-day').html('...'); box.find('.end-day').html('...'); box.find('.selected-days').hide(); if (opt.start) { box.find('.start-day').html(getDateString(new Date(parseInt(opt.start)))); } if (opt.end) { box.find('.end-day').html(getDateString(new Date(parseInt(opt.end)))); } if (opt.start && opt.singleDate) { box.find('.apply-btn').removeClass('disabled'); var dateRange = getDateString(new Date(opt.start)); opt.setValue.call(selfDom, dateRange, getDateString(new Date(opt.start)), getDateString(new Date(opt.end))); if (initiated && !silent) { $(self).trigger('datepicker-change', { 'value': dateRange, 'date1' : new Date(opt.start) }); } } else if (opt.start && opt.end) { box.find('.selected-days').show().find('.selected-days-num').html(countDays(opt.end, opt.start)); box.find('.apply-btn').removeClass('disabled'); var dateRange = getDateString(new Date(opt.start))+ opt.separator +getDateString(new Date(opt.end)); opt.setValue.call(selfDom,dateRange, getDateString(new Date(opt.start)), getDateString(new Date(opt.end))); if (initiated && !silent) { $(self).trigger('datepicker-change', { 'value': dateRange, 'date1' : new Date(opt.start), 'date2' : new Date(opt.end) }); } } else if (forceValid) { box.find('.apply-btn').removeClass('disabled'); } else { box.find('.apply-btn').addClass('disabled'); } } function countDays(start,end) { return Math.abs( daysFrom1970(start) - daysFrom1970(end) ) + 1; } function setDateRange(date1,date2,silent) { if (date1.getTime() > date2.getTime()) { var tmp = date2; date2 = date1; date1 = tmp; tmp = null; } var valid = true; if (opt.startDate && compare_day(date1,opt.startDate) < 0) valid = false; if (opt.endDate && compare_day(date2,opt.endDate) > 0) valid = false; if (!valid) { showMonth(opt.startDate,'month1'); showMonth(nextMonth(opt.startDate),'month2'); showGap(); return; } opt.start = date1.getTime(); opt.end = date2.getTime(); if (opt.time.enabled) { renderTime("time1", date1); renderTime("time2", date2); } if (opt.stickyMonths || (compare_day(date1,date2) > 0 && compare_month(date1,date2) == 0)) { if (opt.lookBehind) { date1 = prevMonth(date2); } else { date2 = nextMonth(date1); } } if(opt.stickyMonths && compare_month(date2,opt.endDate) > 0) { date1 = prevMonth(date1); date2 = prevMonth(date2); } if (!opt.stickyMonths) { if (compare_month(date1,date2) == 0) { if (opt.lookBehind) { date1 = prevMonth(date2); } else { date2 = nextMonth(date1); } } } showMonth(date1,'month1'); showMonth(date2,'month2'); showGap(); checkSelectionValid(); showSelectedInfo(false,silent); autoclose(); } function setSingleDate(date1) { var valid = true; if (opt.startDate && compare_day(date1,opt.startDate) < 0) valid = false; if (opt.endDate && compare_day(date1,opt.endDate) > 0) valid = false; if (!valid) { showMonth(opt.startDate,'month1'); return; } opt.start = date1.getTime(); if (opt.time.enabled) { renderTime("time1", date1); } showMonth(date1,'month1'); //showMonth(date2,'month2'); showGap(); showSelectedInfo(); autoclose(); } function showSelectedDays() { if (!opt.start && !opt.end) return; box.find('.day').each(function() { var time = parseInt($(this).attr('time')), start = opt.start, end = opt.end; if (opt.time.enabled) { time = moment(time).startOf('day').valueOf(); start = moment(start || moment().valueOf()).startOf('day').valueOf(); end = moment(end || moment().valueOf()).startOf('day').valueOf(); } if ( (opt.start && opt.end && end >= time && start <= time ) || ( opt.start && !opt.end && moment(start).format('YYYY-MM-DD') == moment(time).format('YYYY-MM-DD') ) ) { $(this).addClass('checked'); } else { $(this).removeClass('checked'); } //add first-date-selected class name to the first date selected if ( opt.start && moment(start).format('YYYY-MM-DD') == moment(time).format('YYYY-MM-DD') ) { $(this).addClass('first-date-selected'); } else { $(this).removeClass('first-date-selected'); } //add last-date-selected if ( opt.end && moment(end).format('YYYY-MM-DD') == moment(time).format('YYYY-MM-DD') ) { $(this).addClass('last-date-selected'); } else { $(this).removeClass('last-date-selected'); } }); box.find('.week-number').each(function() { if ($(this).attr('data-start-time') == opt.startWeek) { $(this).addClass('week-number-selected'); } }); } function showMonth(date,month) { date = moment(date).toDate(); var monthName = nameMonth(date.getMonth()); box.find('.'+month+' .month-name').html(monthName+' '+date.getFullYear()); box.find('.'+month+' tbody').html(createMonthHTML(date)); opt[month] = date; updateSelectableRange(); } function showTime(date,name) { box.find('.' + name).append(getTimeHTML()); renderTime(name, date); } function nameMonth(m) { return lang('month-name')[m]; } function getDateString(d) { return moment(d).format(opt.format); } function showGap() { showSelectedDays(); var m1 = parseInt(moment(opt.month1).format('YYYYMM')); var m2 = parseInt(moment(opt.month2).format('YYYYMM')); var p = Math.abs(m1 - m2); var shouldShow = (p > 1 && p !=89); if (shouldShow) { box.addClass('has-gap').removeClass('no-gap').find('.gap').css('visibility','visible'); } else { box.removeClass('has-gap').addClass('no-gap').find('.gap').css('visibility','hidden'); } var h1 = box.find('table.month1').height(); var h2 = box.find('table.month2').height(); box.find('.gap').height(Math.max(h1,h2)+10); } function closeDatePicker() { if (opt.alwaysOpen) return; var afterAnim = function() { $(self).data('date-picker-opened',false); $(self).trigger('datepicker-closed', {relatedTarget: box}); }; if (opt.customCloseAnimation) { opt.customCloseAnimation.call(box.get(0), afterAnim); } else { $(box).slideUp(opt.duration, afterAnim); } $(self).trigger('datepicker-close', {relatedTarget: box}); } function redrawDatePicker() { showMonth(opt.month1, 'month1'); showMonth(opt.month2, 'month2'); } function compare_month(m1,m2) { var p = parseInt(moment(m1).format('YYYYMM')) - parseInt(moment(m2).format('YYYYMM')); if (p > 0 ) return 1; if (p == 0) return 0; return -1; } function compare_day(m1,m2) { var p = parseInt(moment(m1).format('YYYYMMDD')) - parseInt(moment(m2).format('YYYYMMDD')); if (p > 0 ) return 1; if (p == 0) return 0; return -1; } function nextMonth(month) { return moment(month).add(1, 'months').toDate(); } function prevMonth(month) { return moment(month).add(-1, 'months').toDate(); } function getTimeHTML() { return '<div>\ <span>'+lang('Time')+': <span class="hour-val">00</span>:<span class="minute-val">00</span></span>\ </div>\ <div class="hour">\ <label>'+lang('Hour')+': <input type="range" class="hour-range" name="hour" min="0" max="23"></label>\ </div>\ <div class="minute">\ <label>'+lang('Minute')+': <input type="range" class="minute-range" name="minute" min="0" max="59"></label>\ </div>'; } function createDom() { var html = '<div class="date-picker-wrapper'; if ( opt.extraClass ) html += ' '+opt.extraClass+' '; if ( opt.singleDate ) html += ' single-date '; if ( !opt.showShortcuts ) html += ' no-shortcuts '; if ( !opt.showTopbar ) html += ' no-topbar '; if ( opt.customTopBar) html += ' custom-topbar '; html += '">'; if (opt.showTopbar) { html += '<div class="drp_top-bar">'; if (opt.customTopBar) { if (typeof opt.customTopBar == 'function') opt.customTopBar = opt.customTopBar(); html += '<div class="custom-top">'+opt.customTopBar+'</div>'; } else { html += '<div class="normal-top">\ <span style="color:#333">'+lang('selected')+' </span> <b class="start-day">...</b>'; if ( ! opt.singleDate ) { html += ' <span class="separator-day">'+opt.separator+'</span> <b class="end-day">...</b> <i class="selected-days">(<span class="selected-days-num">3</span> '+lang('days')+')</i>' } html += '</div>'; html += '<div class="error-top">error</div>\ <div class="default-top">default</div>'; } html += '<input type="button" class="apply-btn disabled'+ getApplyBtnClass() +'" value="'+lang('apply')+'" />'; html += '</div>' } var _colspan = opt.showWeekNumbers ? 6 : 5; html += '<div class="month-wrapper">' +'<table class="month1" cellspacing="0" border="0" cellpadding="0"><thead><tr class="caption"><th style="width:27px;"><span class="prev">&lt;</span></th><th colspan="'+_colspan+'" class="month-name"></th><th style="width:27px;">' + (opt.singleDate || !opt.stickyMonths ? '<span class="next">&gt;</span>': '') + '</th></tr><tr class="week-name">'+getWeekHead()+'</thead><tbody></tbody></table>'; if ( hasMonth2() ) { html += '<div class="gap">'+getGapHTML()+'</div>' +'<table class="month2" cellspacing="0" border="0" cellpadding="0"><thead><tr class="caption"><th style="width:27px;">' + (!opt.stickyMonths ? '<span class="prev">&lt;</span>': '') + '</th><th colspan="'+_colspan+'" class="month-name"></th><th style="width:27px;"><span class="next">&gt;</span></th></tr><tr class="week-name">'+getWeekHead()+'</thead><tbody></tbody></table>' } //+'</div>' html += '<div style="clear:both;height:0;font-size:0;"></div>' +'<div class="time">' +'<div class="time1"></div>' if ( ! opt.singleDate ) { html += '<div class="time2"></div>' } html += '</div>' +'<div style="clear:both;height:0;font-size:0;"></div>' +'</div>'; html += '<div class="footer">'; if (opt.showShortcuts) { html += '<div class="shortcuts"><b>'+lang('shortcuts')+'</b>'; var data = opt.shortcuts; if (data) { if (data['prev-days'] && data['prev-days'].length > 0) { html += '&nbsp;<span class="prev-days">'+lang('past'); for(var i=0;i<data['prev-days'].length; i++) { var name = data['prev-days'][i]; name += (data['prev-days'][i] > 1) ? lang('days') : lang('day'); html += ' <a href="javascript:;" shortcut="day,-'+data['prev-days'][i]+'">'+name+'</a>'; } html+='</span>'; } if (data['next-days'] && data['next-days'].length > 0) { html += '&nbsp;<span class="next-days">'+lang('following'); for(var i=0;i<data['next-days'].length; i++) { var name = data['next-days'][i]; name += (data['next-days'][i] > 1) ? lang('days') : lang('day'); html += ' <a href="javascript:;" shortcut="day,'+data['next-days'][i]+'">'+name+'</a>'; } html+= '</span>'; } if (data['prev'] && data['prev'].length > 0) { html += '&nbsp;<span class="prev-buttons">'+lang('previous'); for(var i=0;i<data['prev'].length; i++) { var name = lang('prev-'+data['prev'][i]); html += ' <a href="javascript:;" shortcut="prev,'+data['prev'][i]+'">'+name+'</a>'; } html+='</span>'; } if (data['next'] && data['next'].length > 0) { html += '&nbsp;<span class="next-buttons">'+lang('next'); for(var i=0;i<data['next'].length; i++) { var name = lang('next-'+data['next'][i]); html += ' <a href="javascript:;" shortcut="next,'+data['next'][i]+'">'+name+'</a>'; } html+='</span>'; } } if (opt.customShortcuts) { for(var i=0;i<opt.customShortcuts.length; i++) { var sh = opt.customShortcuts[i]; html+= '&nbsp;<span class="custom-shortcut"><a href="javascript:;" shortcut="custom">'+sh.name+'</a></span>'; } } html += '</div>'; } // Add Custom Values Dom if (opt.showCustomValues) { html += '<div class="customValues"><b>'+(opt.customValueLabel || lang('custom-values'))+'</b>'; if (opt.customValues) { for(var i=0;i<opt.customValues.length;i++) { var val = opt.customValues[i]; html+= '&nbsp;<span class="custom-value"><a href="javascript:;" custom="'+ val.value+'">'+val.name+'</a></span>'; } } } html += '</div></div>'; return $(html); } function getApplyBtnClass() { var klass = '' if (opt.autoClose === true) { klass += ' hide'; } if (opt.applyBtnClass !== '') { klass += ' ' + opt.applyBtnClass; } return klass; } function getWeekHead() { var prepend = opt.showWeekNumbers ? '<th>'+lang('week-number')+'</th>' : ''; if (opt.startOfWeek == 'monday') { return prepend+'<th>'+lang('week-1')+'</th>\ <th>'+lang('week-2')+'</th>\ <th>'+lang('week-3')+'</th>\ <th>'+lang('week-4')+'</th>\ <th>'+lang('week-5')+'</th>\ <th>'+lang('week-6')+'</th>\ <th>'+lang('week-7')+'</th>'; } else { return prepend+'<th>'+lang('week-7')+'</th>\ <th>'+lang('week-1')+'</th>\ <th>'+lang('week-2')+'</th>\ <th>'+lang('week-3')+'</th>\ <th>'+lang('week-4')+'</th>\ <th>'+lang('week-5')+'</th>\ <th>'+lang('week-6')+'</th>'; } } function isMonthOutOfBounds(month) { var month = moment(month); if (opt.startDate && month.endOf('month').isBefore(opt.startDate)) { return true; } if (opt.endDate && month.startOf('month').isAfter(opt.endDate)) { return true; } return false; } function getGapHTML() { var html = ['<div class="gap-top-mask"></div><div class="gap-bottom-mask"></div><div class="gap-lines">']; for(var i=0;i<20;i++) { html.push('<div class="gap-line">\ <div class="gap-1"></div>\ <div class="gap-2"></div>\ <div class="gap-3"></div>\ </div>'); } html.push('</div>'); return html.join(''); } function hasMonth2() { return ( !opt.singleDate && !opt.singleMonth); } function attributesCallbacks(initialObject,callbacksArray,today) { var resultObject = jQuery.extend(true, {}, initialObject); jQuery.each(callbacksArray, function(cbAttrIndex, cbAttr){ var addAttributes = cbAttr(today); for(var attr in addAttributes){ if(resultObject.hasOwnProperty(attr)){ resultObject[attr] += addAttributes[attr]; }else{ resultObject[attr] = addAttributes[attr]; } } }); var attrString = ''; for(var attr in resultObject){ if(resultObject.hasOwnProperty(attr)){ attrString += attr + '="' + resultObject[attr] + '" '; } } return attrString; } function daysFrom1970(t) { return Math.floor(toLocalTimestamp(t) / 86400000); } function toLocalTimestamp(t) { if (moment.isMoment(t)) t = t.toDate().getTime(); if (typeof t == 'object' && t.getTime) t = t.getTime(); if (typeof t == 'string' && !t.match(/\d{13}/)) t = moment(t,opt.format).toDate().getTime(); t = parseInt(t, 10) - new Date().getTimezoneOffset()*60*1000; return t; } function createMonthHTML(d) { var days = []; d.setDate(1); var lastMonth = new Date(d.getTime() - 86400000); var now = new Date(); var dayOfWeek = d.getDay(); if((dayOfWeek == 0) && (opt.startOfWeek == 'monday')) { // add one week dayOfWeek = 7; } if (dayOfWeek > 0) { for (var i = dayOfWeek; i > 0; i--) { var day = new Date(d.getTime() - 86400000*i); var valid = isValidTime(day.getTime()); if (opt.startDate && compare_day(day,opt.startDate) < 0) valid = false; if (opt.endDate && compare_day(day,opt.endDate) > 0) valid = false; days.push( { date: day, type:'lastMonth', day: day.getDate(), time:day.getTime(), valid:valid }); } } var toMonth = d.getMonth(); for(var i=0; i<40; i++) { var today = moment(d).add(i, 'days').toDate(); var valid = isValidTime(today.getTime()); if (opt.startDate && compare_day(today,opt.startDate) < 0) valid = false; if (opt.endDate && compare_day(today,opt.endDate) > 0) valid = false; days.push( { date: today, type: today.getMonth() == toMonth ? 'toMonth' : 'nextMonth', day: today.getDate(), time:today.getTime(), valid:valid }); } var html = []; for(var week=0; week<6; week++) { if (days[week*7].type == 'nextMonth') break; html.push('<tr>'); for(var day = 0; day<7; day++) { var _day = (opt.startOfWeek == 'monday') ? day+1 : day; var today = days[week*7+_day]; var highlightToday = moment(today.time).format('L') == moment(now).format('L'); today.extraClass = ''; today.tooltip = ''; if(today.valid && opt.beforeShowDay && typeof opt.beforeShowDay == 'function') { var _r = opt.beforeShowDay(moment(today.time).toDate()); today.valid = _r[0]; today.extraClass = _r[1] || ''; today.tooltip = _r[2] || ''; if (today.tooltip != '') today.extraClass += ' has-tooltip '; } var todayDivAttr = { time: today.time, 'data-tooltip': today.tooltip, 'class': 'day '+today.type+' '+today.extraClass+' '+(today.valid ? 'valid' : 'invalid')+' '+(highlightToday?'real-today':'') }; if (day == 0 && opt.showWeekNumbers) { html.push('<td><div class="week-number" data-start-time="'+today.time+'">'+opt.getWeekNumber(today.date)+'</div></td>'); } html.push('<td ' + attributesCallbacks({},opt.dayTdAttrs,today) + '><div ' + attributesCallbacks(todayDivAttr,opt.dayDivAttrs,today) + '>'+showDayHTML(today.time, today.day)+'</div></td>'); } html.push('</tr>'); } return html.join(''); } function showDayHTML(time, date) { if (opt.showDateFilter && typeof opt.showDateFilter == 'function') return opt.showDateFilter(time, date); return date; } function getLanguages() { if (opt.language == 'auto') { var language = navigator.language ? navigator.language : navigator.browserLanguage; if (!language) return $.dateRangePickerLanguages['default']; var language = language.toLowerCase(); for(var key in $.dateRangePickerLanguages) { if (language.indexOf(key) != -1) { return $.dateRangePickerLanguages[key]; } } return $.dateRangePickerLanguages['default']; } else if ( opt.language && opt.language in $.dateRangePickerLanguages) { return $.dateRangePickerLanguages[opt.language]; } else { return $.dateRangePickerLanguages['default']; } } /** * translate language string */ function lang(t) { var _t = t.toLowerCase(); var re = (t in langs) ? langs[t] : ( _t in langs) ? langs[_t] : null; var defaultLanguage = $.dateRangePickerLanguages['default']; if (re == null) re = (t in defaultLanguage) ? defaultLanguage[t] : ( _t in defaultLanguage) ? defaultLanguage[_t] : ''; return re; } }; }));
{ "content_hash": "d738f4302577482721a7eb2fcf033aa9", "timestamp": "", "source": "github", "line_count": 2262, "max_line_length": 398, "avg_line_length": 29.082670203359857, "alnum_prop": 0.557741126396595, "repo_name": "leechuanrong/jquery-date-range-picker-master-lichr", "id": "e4e878b0ab903d38a02f047f0e451035bdf2def2", "size": "66695", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "jquery.daterangepicker.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "8032" }, { "name": "HTML", "bytes": "25759" }, { "name": "JavaScript", "bytes": "76411" } ], "symlink_target": "" }
<!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8"> <meta http-equiv="refresh" content="1;url=https://app.snapchat.com/web/deeplink/snapcode?username=dingwilson&type=SVG&bitmoji=enable"> <script type="text/javascript"> window.location.href = "https://app.snapchat.com/web/deeplink/snapcode?username=dingwilson&type=SVG&bitmoji=enable" </script> <title>Wilson Ding's SnapChat</title> </head> <body> <!-- Note: don't tell people to `click` the link, just tell them that it is a link. --> If you are not redirected automatically, click here to go to <a href='https://app.snapchat.com/web/deeplink/snapcode?username=dingwilson&type=SVG&bitmoji=enable'>Wilson Ding's SnapChat</a> </body> </html>
{ "content_hash": "81b503b40c31495c275cd916087bf330", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 196, "avg_line_length": 52.53333333333333, "alnum_prop": 0.666243654822335, "repo_name": "dingwilson/dingwilson.github.io", "id": "b490baf9a052ad0998de5c75559f166fa08c127a", "size": "788", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "snapchat.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "16243" }, { "name": "HTML", "bytes": "13225" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Perforaria epileiodes Vain. ### Remarks null
{ "content_hash": "fbd56af30ba69f8d6cf6893901c7c779", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 27, "avg_line_length": 10.153846153846153, "alnum_prop": 0.7121212121212122, "repo_name": "mdoering/backbone", "id": "f00a92f1ffedcfda89214c1314300e15a5d3c883", "size": "183", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Lecanoromycetes/Pertusariales/Coccotremataceae/Coccotrema/Perforaria epileiodes/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
(function() { function setupEvents() { var movementSocket = this.session.connectToChannel('/movement'), map = this; movementSocket.on('heroMoved', function(data) { if (typeof map.heroes[data.hero_id] !== 'undefined') { var hero = map.heroes[data.hero_id]; if (hero) { hero.moveToPosition(data.end.x, data.end.y); } } }); } function drawMap(mapConfig) { var stepsX = this.width / this.tileSize, stepsY = this.height / this.tileSize, mapLayer = new Kinetic.Layer(); for (var j = 0; j < stepsX; j++) { for (var i = 0; i < stepsY; i++) { var tile = new Kinetic.Line({ points: [0, 0, 0, this.tileSize, this.tileSize, this.tileSize, this.tileSize, 0], fillPatternImage: this.baseImage, strokeWidth: 0, fillPatternOffset: [0, 0], closed: true, }); tile.fillPatternOffsetX(this.tileSize * Math.floor(Math.random() * mapConfig.tilesConfig.stepsHorizontalAllowed + mapConfig.tilesConfig.imageX)); tile.fillPatternOffsetY(this.tileSize * Math.floor(Math.random() * mapConfig.tilesConfig.stepsVerticalAllowed + mapConfig.tilesConfig.imageY)); tile.setX(j * this.tileSize); tile.setY(i * this.tileSize); mapLayer.add(tile); } } this.layers['mapLayer'] = mapLayer; this.layers['heroLayer'] = new Kinetic.Layer(); this.layers['itemsLayer'] = new Kinetic.Layer(); this.layers['areasLayer'] = new Kinetic.Layer(); this.layers['obstaclesLayer'] = new Kinetic.Layer(); } function addObstaclesLayer(obstacles) { var map = this; $.each(obstacles, function(index, obstacle) { obstacle.session = map.session; obstacle.map = map; obstacle.layer = map.layers['obstaclesLayer']; var mapObstacle = new Nv.Obstacle(map, obstacle); }); } function addItemsLayer(mapItems) { var map = this; $.each(mapItems, function(index, item) { item.session = map.session; item.map = map; var mapItem = new Nv.MapItem(map, item); mapItem.layer = map.layers['itemsLayer']; map.layers['itemsLayer'].add(mapItem); }); } Nv.Map = function(mapConfig) { this.tileSize = mapConfig.tileSize; this.width = mapConfig.width; this.height = mapConfig.height; this.baseImage = mapConfig.baseImage; this.key = mapConfig.key; this.session = mapConfig.session; this.config = mapConfig; this.layers = {}; this.heroes = {}; this.collisions = []; drawMap.call(this, mapConfig); addItemsLayer.call(this, mapConfig.itemsOnMap); addObstaclesLayer.call(this, mapConfig.obstacles); // events setupEvents.call(this); }; Nv.Map.prototype = { heroEnter: function(hero, protagonist) { if (!protagonist) { this.heroes[hero.id] = hero; } this.layers['heroLayer'].add(hero); hero.animate(); }, heroLeave: function(hero_id) { if (typeof this.heroes[hero_id] !== 'undefined') { var hero = this.heroes[hero_id]; delete this.heroes[hero_id]; hero.leave(); Nv.Session.showGameMessage('Hero ' + hero.name + ' left area.'); } }, getLayers: function() { return this.layers; }, addToLayer: function(item, layer) { this.layers[layer].add(item); }, addLayersToStage: function(stage) { $.each(this.layers, function(layerKey, layer) { stage.add(layer); }); }, enableCollisionsFor: function(mapObject) { this.collisions.push(mapObject.getCollisionDimentions()); }, getHero: function(heroId) { if (Nv.sessionInstance().hero.id === heroId) { return Nv.sessionInstance().hero; } return this.heroes[heroId]; }, canMoveToPosition: function(x, y) { var collisionsLength = this.collisions.length; for (var i = 0; i < collisionsLength; i++) { var collision = this.collisions[i]; var xCollides = x >= collision.x && x <= collision.x + collision.width; var yCollides = y >= collision.y && y <= collision.y + collision.height; if (xCollides && yCollides) { return false; } }; return true; } }; })();
{ "content_hash": "976f7903270a0eed1922c67782ebbb3d", "timestamp": "", "source": "github", "line_count": 155, "max_line_length": 161, "avg_line_length": 32, "alnum_prop": 0.5219758064516129, "repo_name": "Nodeventures/Nodeventures", "id": "b75a3339f6f9cd1e26725a332081304e3a0b014b", "size": "4960", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clients/web/assets/js/ui/Map.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1207" }, { "name": "JavaScript", "bytes": "92147" } ], "symlink_target": "" }
package com.lyncode.reflection.model.java; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class JavaMethodArgumentTest { private final JavaMethod method = mock(JavaMethod.class); private final int position = 2; private JavaMethodArgument underTest = new JavaMethodArgument(method, position); @Test public void type() throws Exception { Class type = String.class; when(method.type(position)).thenReturn(type); Class result = underTest.type(); assertEquals(type, result); } @Test public void isVarArgMethod() throws Exception { when(method.numberOfArguments()).thenReturn(position + 1); when(method.isVarArgs()).thenReturn(true); boolean result = underTest.isVarArg(); assertThat(result, is(true)); } @Test public void isVarArgMethodWhenNotLastArgument() throws Exception { when(method.numberOfArguments()).thenReturn(position); when(method.isVarArgs()).thenReturn(true); boolean result = underTest.isVarArg(); assertThat(result, is(false)); } @Test public void isVarArgMethodWhenNotVarArgs() throws Exception { when(method.numberOfArguments()).thenReturn(position + 1); when(method.isVarArgs()).thenReturn(false); boolean result = underTest.isVarArg(); assertThat(result, is(false)); } }
{ "content_hash": "046438ae87f14074a288c43f7568e0b6", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 84, "avg_line_length": 28.70909090909091, "alnum_prop": 0.6903103229892337, "repo_name": "lyncode/reflection-invoke", "id": "be7cc4f8ce289352153aae61860e4306da824733", "size": "1579", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/com/lyncode/reflection/model/java/JavaMethodArgumentTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "60170" } ], "symlink_target": "" }
package com.github.games647.lagmonitor.listener; import com.github.games647.lagmonitor.graph.GraphRenderer; import com.github.games647.lagmonitor.util.LagUtils; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Item; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.MapMeta; import org.bukkit.map.MapView; public class GraphListener implements Listener { private final boolean mainHandSupported; public GraphListener() { boolean mainHandMethodEx = false; try { MethodType type = MethodType.methodType(ItemStack.class); MethodHandles.publicLookup().findVirtual(PlayerInventory.class, "getItemInMainHand", type); mainHandMethodEx = true; } catch (ReflectiveOperationException notFoundEx) { //default to false } this.mainHandSupported = mainHandMethodEx; } @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH) public void onInteract(PlayerInteractEvent clickEvent) { Player player = clickEvent.getPlayer(); PlayerInventory inventory = player.getInventory(); ItemStack mainHandItem; if (mainHandSupported) { mainHandItem = inventory.getItemInMainHand(); } else { mainHandItem = inventory.getItemInHand(); } if (isOurGraph(mainHandItem)) { inventory.setItemInMainHand(new ItemStack(Material.AIR)); } } @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH) public void onDrop(PlayerDropItemEvent dropItemEvent) { Item itemDrop = dropItemEvent.getItemDrop(); ItemStack mapItem = itemDrop.getItemStack(); if (isOurGraph(mapItem)) { mapItem.setAmount(0); } } private boolean isOurGraph(ItemStack item) { if (!LagUtils.isFilledMapSupported()) { return isOurGraphLegacy(item); } if (item.getType() != Material.FILLED_MAP) { return false; } ItemMeta meta = item.getItemMeta(); if (!(meta instanceof MapMeta)) { return false; } MapMeta mapMeta = (MapMeta) meta; MapView mapView = mapMeta.getMapView(); return mapView != null && isOurRenderer(mapView); } private boolean isOurGraphLegacy(ItemStack mapItem) { if (mapItem.getType() != Material.MAP) return false; short mapId = mapItem.getDurability(); MapView mapView = Bukkit.getMap(mapId); return mapView != null && isOurRenderer(mapView); } private boolean isOurRenderer(MapView mapView) { return mapView.getRenderers().stream() .anyMatch(GraphRenderer.class::isInstance); } }
{ "content_hash": "6afbdf59451625886e3c38ed9e14cbe7", "timestamp": "", "source": "github", "line_count": 99, "max_line_length": 103, "avg_line_length": 32.35353535353536, "alnum_prop": 0.6781142678738683, "repo_name": "games647/LagMonitor", "id": "fa57a5c2e26282d094c99b9cf2e082d53278849a", "size": "3203", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "src/main/java/com/github/games647/lagmonitor/listener/GraphListener.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "234335" } ], "symlink_target": "" }
// // 이 파일은 JAXB(JavaTM Architecture for XML Binding) 참조 구현 2.2.6 버전을 통해 생성되었습니다. // <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>를 참조하십시오. // 이 파일을 수정하면 소스 스키마를 재컴파일할 때 수정 사항이 손실됩니다. // 생성 날짜: 2012.09.05 시간 05:58:17 PM KST // package com.athena.chameleon.engine.entity.xml.webapp.v2_5; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * * * An injection target specifies a class and a name within * that class into which a resource should be injected. * * The injection target class specifies the fully qualified * class name that is the target of the injection. The * Java EE specifications describe which classes can be an * injection target. * * The injection target name specifies the target within * the specified class. The target is first looked for as a * JavaBeans property name. If not found, the target is * looked for as a field name. * * The specified resource will be injected into the target * during initialization of the class by either calling the * set method for the target property or by setting a value * into the named field. * * * * <p>injection-targetType complex type에 대한 Java 클래스입니다. * * <p>다음 스키마 단편이 이 클래스에 포함되는 필요한 콘텐츠를 지정합니다. * * <pre> * &lt;complexType name="injection-targetType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="injection-target-class" type="{http://java.sun.com/xml/ns/javaee}fully-qualified-classType"/> * &lt;element name="injection-target-name" type="{http://java.sun.com/xml/ns/javaee}java-identifierType"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "injection-targetType", propOrder = { "injectionTargetClass", "injectionTargetName" }) public class InjectionTargetType { @XmlElement(name = "injection-target-class", required = true) protected FullyQualifiedClassType injectionTargetClass; @XmlElement(name = "injection-target-name", required = true) protected JavaIdentifierType injectionTargetName; /** * injectionTargetClass 속성의 값을 가져옵니다. * * @return * possible object is * {@link FullyQualifiedClassType } * */ public FullyQualifiedClassType getInjectionTargetClass() { return injectionTargetClass; } /** * injectionTargetClass 속성의 값을 설정합니다. * * @param value * allowed object is * {@link FullyQualifiedClassType } * */ public void setInjectionTargetClass(FullyQualifiedClassType value) { this.injectionTargetClass = value; } /** * injectionTargetName 속성의 값을 가져옵니다. * * @return * possible object is * {@link JavaIdentifierType } * */ public JavaIdentifierType getInjectionTargetName() { return injectionTargetName; } /** * injectionTargetName 속성의 값을 설정합니다. * * @param value * allowed object is * {@link JavaIdentifierType } * */ public void setInjectionTargetName(JavaIdentifierType value) { this.injectionTargetName = value; } }
{ "content_hash": "80d63bddf1ae3c1b004ac16a00dec128", "timestamp": "", "source": "github", "line_count": 119, "max_line_length": 122, "avg_line_length": 30.176470588235293, "alnum_prop": 0.6393762183235867, "repo_name": "OpenSourceConsulting/athena-chameleon", "id": "9e5c03d13e0b419efa2fb28dccf9a70abcb0ca8b", "size": "3873", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/athena/chameleon/engine/entity/xml/webapp/v2_5/InjectionTargetType.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "937" }, { "name": "CSS", "bytes": "49541" }, { "name": "HTML", "bytes": "2705" }, { "name": "Java", "bytes": "7488807" }, { "name": "JavaScript", "bytes": "950966" }, { "name": "Shell", "bytes": "8902" } ], "symlink_target": "" }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/input_method/ibus_controller_impl.h" #include <algorithm> // for std::reverse. #include <cstdio> #include <cstring> // for std::strcmp. #include <set> #include <sstream> #include <stack> #include <utility> #include "ash/shell.h" #include "base/bind.h" #include "base/environment.h" #include "base/files/file_path_watcher.h" #include "base/memory/scoped_ptr.h" #include "base/message_loop.h" #include "base/rand_util.h" #include "base/string_split.h" #include "base/stringprintf.h" #include "chrome/browser/chromeos/input_method/input_method_config.h" #include "chrome/browser/chromeos/input_method/input_method_property.h" #include "chrome/browser/chromeos/input_method/input_method_util.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/ibus/ibus_client.h" #include "chromeos/dbus/ibus/ibus_config_client.h" #include "chromeos/dbus/ibus/ibus_constants.h" #include "chromeos/dbus/ibus/ibus_input_context_client.h" #include "chromeos/dbus/ibus/ibus_panel_service.h" #include "chromeos/dbus/ibus/ibus_property.h" #include "content/public/browser/browser_thread.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/root_window.h" #include "ui/base/ime/input_method_ibus.h" namespace { // Finds a property which has |new_prop.key| from |prop_list|, and replaces the // property with |new_prop|. Returns true if such a property is found. bool FindAndUpdateProperty( const chromeos::input_method::InputMethodProperty& new_prop, chromeos::input_method::InputMethodPropertyList* prop_list) { for (size_t i = 0; i < prop_list->size(); ++i) { chromeos::input_method::InputMethodProperty& prop = prop_list->at(i); if (prop.key == new_prop.key) { prop = new_prop; return true; } } return false; } void ConfigSetValueErrorCallback() { DVLOG(1) << "IBusConfig: SetValue is failed."; } } // namespace namespace chromeos { namespace input_method { namespace { // Returns true if |key| is blacklisted. bool PropertyKeyIsBlacklisted(const std::string& key) { // The list of input method property keys that we don't handle. static const char* kInputMethodPropertyKeysBlacklist[] = { "setup", // used in ibus-m17n. "status", // used in ibus-m17n. }; for (size_t i = 0; i < arraysize(kInputMethodPropertyKeysBlacklist); ++i) { if (key == kInputMethodPropertyKeysBlacklist[i]) return true; } return false; } // This function is called by and FlattenProperty() and converts IBus // representation of a property, |ibus_prop|, to our own and push_back the // result to |out_prop_list|. This function returns true on success, and // returns false if sanity checks for |ibus_prop| fail. bool ConvertProperty(const ibus::IBusProperty& ibus_prop, InputMethodPropertyList* out_prop_list) { DCHECK(out_prop_list); DCHECK(ibus_prop.key().empty()); ibus::IBusProperty::IBusPropertyType type = ibus_prop.type(); // Sanity checks. const bool has_sub_props = !ibus_prop.sub_properties().empty(); if (has_sub_props && (type != ibus::IBusProperty::IBUS_PROPERTY_TYPE_MENU)) { DVLOG(1) << "The property has sub properties, " << "but the type of the property is not PROP_TYPE_MENU"; return false; } if ((!has_sub_props) && (type == ibus::IBusProperty::IBUS_PROPERTY_TYPE_MENU)) { // This is usually not an error. ibus-daemon sometimes sends empty props. DVLOG(1) << "Property list is empty"; return false; } if (type == ibus::IBusProperty::IBUS_PROPERTY_TYPE_SEPARATOR || type == ibus::IBusProperty::IBUS_PROPERTY_TYPE_MENU) { // This is not an error, but we don't push an item for these types. return true; } // This label will be localized later. // See chrome/browser/chromeos/input_method/input_method_util.cc. std::string label_to_use; if (!ibus_prop.tooltip().empty()) label_to_use = ibus_prop.tooltip(); else if (!ibus_prop.label().empty()) label_to_use = ibus_prop.label(); else label_to_use = ibus_prop.key(); out_prop_list->push_back(InputMethodProperty( ibus_prop.key(), label_to_use, (type == ibus::IBusProperty::IBUS_PROPERTY_TYPE_RADIO), ibus_prop.checked())); return true; } // Converts |ibus_prop| to |out_prop_list|. Please note that |ibus_prop| // may or may not have children. See the comment for FlattenPropertyList // for details. Returns true if no error is found. bool FlattenProperty(const ibus::IBusProperty& ibus_prop, InputMethodPropertyList* out_prop_list) { DCHECK(out_prop_list); // Filter out unnecessary properties. if (PropertyKeyIsBlacklisted(ibus_prop.key())) return true; // Convert |prop| to InputMethodProperty and push it to |out_prop_list|. if (!ConvertProperty(ibus_prop, out_prop_list)) return false; // Process childrens iteratively (if any). Push all sub properties to the // stack. if (!ibus_prop.sub_properties().empty()) { const ibus::IBusPropertyList& sub_props = ibus_prop.sub_properties(); for (size_t i = 0; i < sub_props.size(); ++i) { if (!FlattenProperty(*sub_props[i], out_prop_list)) return false; } } return true; } // Converts IBus representation of a property list, |ibus_prop_list| to our // own. This function also flatten the original list (actually it's a tree). // Returns true if no error is found. The conversion to our own type is // necessary since our language switcher in Chrome tree don't (or can't) know // IBus types. Here is an example: // // ====================================================================== // Input: // // --- Item-1 // |- Item-2 // |- SubMenuRoot --- Item-3-1 // | |- Item-3-2 // | |- Item-3-3 // |- Item-4 // // (Note: Item-3-X is a selection item since they're on a sub menu.) // // Output: // // Item-1, Item-2, Item-3-1, Item-3-2, Item-3-3, Item-4 // (Note: SubMenuRoot does not appear in the output.) // ====================================================================== bool FlattenPropertyList(const ibus::IBusPropertyList& ibus_prop_list, InputMethodPropertyList* out_prop_list) { DCHECK(out_prop_list); bool result = true; for (size_t i = 0; i < ibus_prop_list.size(); ++i) { result &= FlattenProperty(*ibus_prop_list[i], out_prop_list); } return result; } class IBusAddressWatcher { public: class IBusAddressFileWatcherDelegate : public base::files::FilePathWatcher::Delegate { public: IBusAddressFileWatcherDelegate( const std::string& ibus_address, IBusControllerImpl* controller, IBusAddressWatcher* watcher) : ibus_address_(ibus_address), controller_(controller), watcher_(watcher) { DCHECK(watcher); DCHECK(!ibus_address.empty()); } virtual void OnFilePathChanged(const FilePath& file_path) OVERRIDE { if (!watcher_->IsWatching()) return; bool success = content::BrowserThread::PostTask( content::BrowserThread::UI, FROM_HERE, base::Bind( &IBusControllerImpl::IBusDaemonInitializationDone, controller_, ibus_address_)); DCHECK(success); watcher_->StopSoon(); } protected: virtual ~IBusAddressFileWatcherDelegate() {} private: // The ibus-daemon address. const std::string ibus_address_; IBusControllerImpl* controller_; IBusAddressWatcher* watcher_; DISALLOW_COPY_AND_ASSIGN(IBusAddressFileWatcherDelegate); }; static void Start(const std::string& ibus_address, IBusControllerImpl* controller) { IBusAddressWatcher* instance = IBusAddressWatcher::Get(); scoped_ptr<base::Environment> env(base::Environment::Create()); std::string address_file_path; // TODO(nona): move reading environment variables to UI thread. env->GetVar("IBUS_ADDRESS_FILE", &address_file_path); DCHECK(!address_file_path.empty()); if (instance->IsWatching()) instance->StopNow(); instance->watcher_ = new base::files::FilePathWatcher; // The |delegate| is owned by watcher. IBusAddressFileWatcherDelegate* delegate = new IBusAddressFileWatcherDelegate(ibus_address, controller, instance); bool result = instance->watcher_->Watch(FilePath(address_file_path), delegate); DCHECK(result); } void StopNow() { delete watcher_; watcher_ = NULL; } void StopSoon() { if (!watcher_) return; MessageLoop::current()->DeleteSoon(FROM_HERE, watcher_); watcher_ = NULL; } bool IsWatching() const { return watcher_ != NULL; } private: static IBusAddressWatcher* Get() { static IBusAddressWatcher* instance = new IBusAddressWatcher; DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::FILE)); return instance; } // Singleton IBusAddressWatcher() : watcher_(NULL) {} base::files::FilePathWatcher* watcher_; DISALLOW_COPY_AND_ASSIGN(IBusAddressWatcher); }; } // namespace IBusControllerImpl::IBusControllerImpl() : process_handle_(base::kNullProcessHandle), ibus_daemon_status_(IBUS_DAEMON_STOP), input_method_(NULL), ALLOW_THIS_IN_INITIALIZER_LIST(weak_ptr_factory_(this)) { } IBusControllerImpl::~IBusControllerImpl() { } bool IBusControllerImpl::Start() { if (IBusConnectionsAreAlive()) return true; if (ibus_daemon_status_ == IBUS_DAEMON_STOP || ibus_daemon_status_ == IBUS_DAEMON_SHUTTING_DOWN) { return StartIBusDaemon(); } return true; } void IBusControllerImpl::Reset() { if (!IBusConnectionsAreAlive()) return; IBusInputContextClient* client = DBusThreadManager::Get()->GetIBusInputContextClient(); if (client) client->Reset(); } bool IBusControllerImpl::Stop() { if (ibus_daemon_status_ == IBUS_DAEMON_SHUTTING_DOWN || ibus_daemon_status_ == IBUS_DAEMON_STOP) { return true; } ibus_daemon_status_ = IBUS_DAEMON_SHUTTING_DOWN; // TODO(nona): Shutdown ibus-bus connection. if (IBusConnectionsAreAlive()) { // Ask IBus to exit *asynchronously*. IBusClient* client = DBusThreadManager::Get()->GetIBusClient(); if (client) client->Exit(IBusClient::SHUT_DOWN_IBUS_DAEMON, base::Bind(&base::DoNothing)); } else { base::KillProcess(process_handle_, -1, false /* wait */); DVLOG(1) << "Killing ibus-daemon. PID=" << base::GetProcId(process_handle_); } process_handle_ = base::kNullProcessHandle; return true; } bool IBusControllerImpl::ChangeInputMethod(const std::string& id) { if (ibus_daemon_status_ == IBUS_DAEMON_SHUTTING_DOWN || ibus_daemon_status_ == IBUS_DAEMON_STOP) { return false; } // Sanity checks. DCHECK(!InputMethodUtil::IsKeyboardLayout(id)); if (!whitelist_.InputMethodIdIsWhitelisted(id) && !InputMethodUtil::IsExtensionInputMethod(id)) return false; // Clear input method properties unconditionally if |id| is not equal to // |current_input_method_id_|. // // When switching to another input method and no text area is focused, // RegisterProperties signal for the new input method will NOT be sent // until a text area is focused. Therefore, we have to clear the old input // method properties here to keep the input method switcher status // consistent. // // When |id| and |current_input_method_id_| are the same, the properties // shouldn't be cleared. If we do that, something wrong happens in step #4 // below: // 1. Enable "xkb:us::eng" and "mozc". Switch to "mozc". // 2. Focus Omnibox. IME properties for mozc are sent to Chrome. // 3. Switch to "xkb:us::eng". No function in this file is called. // 4. Switch back to "mozc". ChangeInputMethod("mozc") is called, but it's // basically NOP since ibus-daemon's current IME is already "mozc". // IME properties are not sent to Chrome for the same reason. if (id != current_input_method_id_) { const ibus::IBusPropertyList empty_list; RegisterProperties(empty_list); } current_input_method_id_ = id; if (!IBusConnectionsAreAlive()) { DVLOG(1) << "ChangeInputMethod: IBus connection is not alive (yet)."; // |id| will become usable shortly since Start() has already been called. // Just return true. } else { SendChangeInputMethodRequest(id); } return true; } bool IBusControllerImpl::ActivateInputMethodProperty(const std::string& key) { if (!IBusConnectionsAreAlive()) { DVLOG(1) << "ActivateInputMethodProperty: IBus connection is not alive"; return false; } // The third parameter of ibus_input_context_property_activate() has to be // true when the |key| points to a radio button. false otherwise. bool is_radio = true; size_t i; for (i = 0; i < current_property_list_.size(); ++i) { if (current_property_list_[i].key == key) { is_radio = current_property_list_[i].is_selection_item; break; } } if (i == current_property_list_.size()) { DVLOG(1) << "ActivateInputMethodProperty: unknown key: " << key; return false; } IBusInputContextClient* client = DBusThreadManager::Get()->GetIBusInputContextClient(); if (client) client->PropertyActivate(key, static_cast<ibus::IBusPropertyState>(is_radio)); return true; } bool IBusControllerImpl::IBusConnectionsAreAlive() { return ibus_daemon_status_ == IBUS_DAEMON_RUNNING; } void IBusControllerImpl::SendChangeInputMethodRequest(const std::string& id) { // Change the global engine *asynchronously*. IBusClient* client = DBusThreadManager::Get()->GetIBusClient(); if (client) client->SetGlobalEngine(id.c_str(), base::Bind(&base::DoNothing)); } bool IBusControllerImpl::SetInputMethodConfigInternal( const ConfigKeyType& key, const InputMethodConfigValue& value) { if (value.type != InputMethodConfigValue::kValueTypeString && value.type != InputMethodConfigValue::kValueTypeInt && value.type != InputMethodConfigValue::kValueTypeBool && value.type != InputMethodConfigValue::kValueTypeStringList) { DVLOG(1) << "SendInputMethodConfig: unknown value.type"; return false; } IBusConfigClient* client = DBusThreadManager::Get()->GetIBusConfigClient(); if (!client) { // Should return true if the ibus-memconf is not ready to use, otherwise IME // configuration will not be initialized. return true; } switch (value.type) { case InputMethodConfigValue::kValueTypeString: client->SetStringValue(key.first, key.second, value.string_value, base::Bind(&ConfigSetValueErrorCallback)); return true; case InputMethodConfigValue::kValueTypeInt: client->SetIntValue(key.first, key.second, value.int_value, base::Bind(&ConfigSetValueErrorCallback)); return true; case InputMethodConfigValue::kValueTypeBool: client->SetBoolValue(key.first, key.second, value.bool_value, base::Bind(&ConfigSetValueErrorCallback)); return true; case InputMethodConfigValue::kValueTypeStringList: client->SetStringListValue(key.first, key.second, value.string_list_value, base::Bind(&ConfigSetValueErrorCallback)); return true; default: NOTREACHED() << "SendInputMethodConfig: unknown value.type"; return false; } } void IBusControllerImpl::RegisterProperties( const ibus::IBusPropertyList& ibus_prop_list) { // Note: |panel| can be NULL. See ChangeInputMethod(). current_property_list_.clear(); if (!FlattenPropertyList(ibus_prop_list, &current_property_list_)) current_property_list_.clear(); // Clear properties on errors. FOR_EACH_OBSERVER(Observer, observers_, PropertyChanged()); } void IBusControllerImpl::UpdateProperty(const ibus::IBusProperty& ibus_prop) { InputMethodPropertyList prop_list; // our representation. if (!FlattenProperty(ibus_prop, &prop_list)) { // Don't update the UI on errors. DVLOG(1) << "Malformed properties are detected"; return; } // Notify the change. if (!prop_list.empty()) { for (size_t i = 0; i < prop_list.size(); ++i) { FindAndUpdateProperty(prop_list[i], &current_property_list_); } FOR_EACH_OBSERVER(Observer, observers_, PropertyChanged()); } } bool IBusControllerImpl::StartIBusDaemon() { if (ibus_daemon_status_ == IBUS_DAEMON_INITIALIZING || ibus_daemon_status_ == IBUS_DAEMON_RUNNING) { DVLOG(1) << "MaybeLaunchIBusDaemon: ibus-daemon is already running."; return false; } ibus_daemon_status_ = IBUS_DAEMON_INITIALIZING; ibus_daemon_address_ = base::StringPrintf( "unix:abstract=ibus-%d", base::RandInt(0, std::numeric_limits<int>::max())); // Set up ibus-daemon address file watcher before launching ibus-daemon, // because if watcher starts after ibus-daemon, we may miss the ibus // connection initialization. bool success = content::BrowserThread::PostTaskAndReply( content::BrowserThread::FILE, FROM_HERE, base::Bind(&IBusAddressWatcher::Start, ibus_daemon_address_, base::Unretained(this)), base::Bind(&IBusControllerImpl::LaunchIBusDaemon, weak_ptr_factory_.GetWeakPtr(), ibus_daemon_address_)); DCHECK(success); return true; } void IBusControllerImpl::LaunchIBusDaemon(const std::string& ibus_address) { DCHECK_EQ(base::kNullProcessHandle, process_handle_); static const char kIBusDaemonPath[] = "/usr/bin/ibus-daemon"; // TODO(zork): Send output to /var/log/ibus.log const std::string ibus_daemon_command_line = base::StringPrintf("%s --panel=disable --cache=none --restart --replace" " --address=%s", kIBusDaemonPath, ibus_address.c_str()); if (!LaunchProcess(ibus_daemon_command_line, &process_handle_, reinterpret_cast<GChildWatchFunc>(OnIBusDaemonExit))) { DVLOG(1) << "Failed to launch " << ibus_daemon_command_line; } } bool IBusControllerImpl::LaunchProcess(const std::string& command_line, base::ProcessHandle* process_handle, GChildWatchFunc watch_func) { std::vector<std::string> argv; base::ProcessHandle handle = base::kNullProcessHandle; base::SplitString(command_line, ' ', &argv); if (!base::LaunchProcess(argv, base::LaunchOptions(), &handle)) { DVLOG(1) << "Could not launch: " << command_line; return false; } // g_child_watch_add is necessary to prevent the process from becoming a // zombie. // TODO(yusukes): port g_child_watch_add to base/process_utils_posix.cc. const base::ProcessId pid = base::GetProcId(handle); g_child_watch_add(pid, watch_func, this); *process_handle = handle; DVLOG(1) << command_line << "is started. PID=" << pid; return true; } ui::InputMethodIBus* IBusControllerImpl::GetInputMethod() { return input_method_ ? input_method_ : static_cast<ui::InputMethodIBus*>( ash::Shell::GetPrimaryRootWindow()->GetProperty( aura::client::kRootWindowInputMethodKey)); } void IBusControllerImpl::set_input_method_for_testing( ui::InputMethodIBus* input_method) { input_method_ = input_method; } void IBusControllerImpl::OnIBusConfigClientInitialized() { InputMethodConfigRequests::const_iterator iter = current_config_values_.begin(); for (; iter != current_config_values_.end(); ++iter) { SetInputMethodConfigInternal(iter->first, iter->second); } } // static void IBusControllerImpl::IBusDaemonInitializationDone( IBusControllerImpl* controller, const std::string& ibus_address) { if (controller->ibus_daemon_address_ != ibus_address) return; if (controller->ibus_daemon_status_ != IBUS_DAEMON_INITIALIZING) { // Stop() or OnIBusDaemonExit() has already been called. return; } chromeos::DBusThreadManager::Get()->InitIBusBus(ibus_address); controller->ibus_daemon_status_ = IBUS_DAEMON_RUNNING; ui::InputMethodIBus* input_method_ibus = controller->GetInputMethod(); DCHECK(input_method_ibus); input_method_ibus->OnConnected(); DBusThreadManager::Get()->GetIBusPanelService()->SetUpPropertyHandler( controller); // Restore previous input method at the beggining of connection. if (!controller->current_input_method_id_.empty()) { controller->SendChangeInputMethodRequest( controller->current_input_method_id_); } DBusThreadManager::Get()->GetIBusConfigClient()->InitializeAsync( base::Bind(&IBusControllerImpl::OnIBusConfigClientInitialized, controller->weak_ptr_factory_.GetWeakPtr())); FOR_EACH_OBSERVER(Observer, controller->observers_, OnConnected()); VLOG(1) << "The ibus-daemon initialization is done."; } // static void IBusControllerImpl::OnIBusDaemonExit(GPid pid, gint status, IBusControllerImpl* controller) { if (controller->process_handle_ != base::kNullProcessHandle) { if (base::GetProcId(controller->process_handle_) == pid) { // ibus-daemon crashed. // TODO(nona): Shutdown ibus-bus connection. controller->process_handle_ = base::kNullProcessHandle; } else { // This condition is as follows. // 1. Called Stop (process_handle_ becomes null) // 2. Called LaunchProcess (process_handle_ becomes new instance) // 3. Callbacked OnIBusDaemonExit for old instance and reach here. // In this case, we should not reset process_handle_ as null, and do not // re-launch ibus-daemon. return; } } const IBusDaemonStatus on_exit_state = controller->ibus_daemon_status_; controller->ibus_daemon_status_ = IBUS_DAEMON_STOP; ui::InputMethodIBus* input_method_ibus = controller->GetInputMethod(); DCHECK(input_method_ibus); input_method_ibus->OnDisconnected(); FOR_EACH_OBSERVER(Observer, controller->observers_, OnDisconnected()); if (on_exit_state == IBUS_DAEMON_SHUTTING_DOWN) { // Normal exitting, so do nothing. return; } LOG(ERROR) << "The ibus-daemon crashed. Re-launching..."; controller->StartIBusDaemon(); } // static bool IBusControllerImpl::FindAndUpdatePropertyForTesting( const chromeos::input_method::InputMethodProperty& new_prop, chromeos::input_method::InputMethodPropertyList* prop_list) { return FindAndUpdateProperty(new_prop, prop_list); } } // namespace input_method } // namespace chromeos
{ "content_hash": "5f95fb64c3b5945353496834dbb735d7", "timestamp": "", "source": "github", "line_count": 669, "max_line_length": 80, "avg_line_length": 34.55605381165919, "alnum_prop": 0.6631196470282896, "repo_name": "leiferikb/bitpop-private", "id": "86f14c11cd18583e5b006fd45393e0572cea35a1", "size": "23118", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "chrome/browser/chromeos/input_method/ibus_controller_impl.cc", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "AppleScript", "bytes": "6973" }, { "name": "Arduino", "bytes": "464" }, { "name": "Assembly", "bytes": "1871" }, { "name": "C", "bytes": "1800028" }, { "name": "C++", "bytes": "76499582" }, { "name": "CSS", "bytes": "803682" }, { "name": "Java", "bytes": "1234788" }, { "name": "JavaScript", "bytes": "21793252" }, { "name": "Objective-C", "bytes": "5358744" }, { "name": "PHP", "bytes": "97817" }, { "name": "Perl", "bytes": "64410" }, { "name": "Python", "bytes": "3017857" }, { "name": "Ruby", "bytes": "650" }, { "name": "Shell", "bytes": "322362" }, { "name": "XSLT", "bytes": "418" }, { "name": "nesC", "bytes": "12138" } ], "symlink_target": "" }
""" This file contains classes and functionto interact with qcow images servers """ import copy import logging import os import paramiko from common import PromotionError, get_release_map class QcowConnectionClient(object): """ Proxy class for client connection """ _log = logging.getLogger("promoter") def __init__(self, server_conf): self._host = server_conf['host'] self._user = server_conf['user'] self._client_type = server_conf['client'] self._keypath = server_conf['keypath'] self._client = os if self._client_type == "sftp": client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) keypath = os.path.expanduser(self._keypath) self.key = paramiko.RSAKey.from_private_key_file(filename=keypath) self.kwargs = {} if self._user is not None: self.kwargs['username'] = self._user else: self.kwargs['username'] = os.environ.get("USER") self._log.debug("Connecting to %s as user %s", self._host, self._user) self.ssh_client = client def connect(self): if hasattr(self, 'ssh_client'): self.ssh_client.connect(self._host, pkey=self.key, **self.kwargs) self._client = self.ssh_client.open_sftp() def __getattr__(self, item): return getattr(self._client, item) def close(self): if self._client_type == "sftp": self._client.close() class QcowClient(object): """ This class interacts with qcow images servers """ log = logging.getLogger("promoter") def __init__(self, config): self.config = config self.release = config.release self.git_root = self.config.git_root self.distro_name = self.config.distro_name self.distro_version = self.config.distro_version self.rollback_links = {} server_conf = self.config.overcloud_images.get('qcow_servers') qcow_server = self.config.default_qcow_server self.user = server_conf[qcow_server]['user'] self.root = server_conf[qcow_server]['root'] self.host = server_conf[qcow_server]['host'] self.release = get_release_map(self.release) self.client = QcowConnectionClient(server_conf[qcow_server]) self.images_dir = os.path.join( os.path.join(config.stage_root, self.root), config.distro, self.release, "rdo_trunk") if self.config.release.startswith('osp'): self.images_dir = self.images_dir.rstrip("/rdo_trunk") def validate_qcows(self, dlrn_hash, name=None, assume_valid=False): """ Check we have the images dir in the server if name is specified, verify that name points to the hash - maybe qcow ran and failed Check at which point of qcow promotion we stopped 1) did we create a new symlink ? 2) did we create the previous symlink ? 3) are all the images uploaded correctly ? :param dlrn_hash: The hash to check :param name: The promotion name :param assume_valid: report everything worked unconditionally :return: A dict with result of the validation """ try: self.client.listdir(self.images_dir) self.client.chdir(self.images_dir) except EnvironmentError as ex: self.log.error("Qcow-client: Image root dir %s does not exist " "in the server, or is not accessible") self.log.exception(ex) raise results = { "hash_valid": False, "promotion_valid": False, "qcow_valid": False, "missing_qcows": copy.copy( self.config.overcloud_images['qcow_images']), "present_qcows": [], } stat = None images = None images_path = os.path.join(self.images_dir, dlrn_hash.full_hash) try: stat = self.client.stat(images_path) images = sorted(self.client.listdir(images_path)) except EnvironmentError: self.log.error("Images path for hash %s not present or " "accessible", dlrn_hash) if not images: self.log.error("No images found") if stat and images: results['hash_valid'] = True results['present_qcows'] = images results['missing_qcows'] = \ list(set(self.config.overcloud_images[ 'qcow_images']).difference( images)) if images == self.config.overcloud_images['qcow_images']: results['qcow_valid'] = True if name is not None: try: link = self.client.readlink(name) if link == dlrn_hash.full_hash: results['promotion_valid'] = True except EnvironmentError: self.log.error("%s was not promoted to %s", dlrn_hash.full_hash, name) return results def rollback(self): """ Rolls back the link to the initial status Rollback is guaranteed to work only for caught exceptions, and it may not be really useful. We have a rollback only if a remove or a symlink fails. - If a remove fails, it means that we don't need to rollback - If a symlink fails, then it will probably fail on rollback too. :return: None """ for name, target in self.rollback_links.items(): self.client.remove(name) self.client.symlink(target, name) self.rollback_links = {} def promote(self, candidate_hash, target_label, candidate_label=None, create_previous=True, validation=True): """ Effective promotion of the images. This method will handle symbolic links to the dir containing images from the candidate hash, optionally saving the current link as previous :param candidate_hash: The dlrn hash to promote :param target_label: The name of the link to create :param candidate_label: Currently unused :param create_previous: A bool to determine if previous link is created :param validation: A bool to determine if qcow validation should be done :return: None """ self.client.connect() if validation: self.validate_qcows(candidate_hash) self.client.chdir(self.images_dir) self.log.debug("Changing dir: {}".format(self.images_dir)) log_header = "Qcow promote '{}' to {}:".format(candidate_hash, target_label) self.log.info("%s Attempting promotion", log_header) # Check if candidate_hash dir is present try: self.client.stat(candidate_hash.full_hash) self.log.debug("Checking candidate hash dir: " "{}".format(candidate_hash.full_hash)) except EnvironmentError as ex: self.log.error("%s images dir for hash %s not present or not " "accessible", log_header, candidate_hash) self.log.exception(ex) self.client.close() raise PromotionError("{} No images dir for hash {}" "".format(log_header, candidate_hash)) # Check if the target label exists and points to a hash dir current_hash = None try: current_hash = self.client.readlink(target_label) self.log.debug("Checking target link: {}".format(current_hash)) except EnvironmentError: self.log.debug("%s No link named %s exists", log_header, target_label) # If this exists Check if we can remove the symlink if current_hash: self.rollback_links['target_label'] = current_hash try: self.client.remove(target_label) self.log.debug("Removing label: {}".format(target_label)) except EnvironmentError as ex: self.log.debug("Unable to remove the target_label: %s", target_label) self.log.exception(ex) self.client.close() raise # Check if a previous link exists and points to an hash-dir previous_label = "previous-{}".format(target_label) previous_hash = None try: previous_hash = self.client.readlink(previous_label) self.log.debug("Previous hash: {}".format(previous_hash)) except EnvironmentError: self.log.debug("%s No previous-link named %s exists", log_header, previous_label) self.log.debug("Previous hash %s", previous_hash) # If it exists and we are handling it, check if we can remove and # reassign it if current_hash and previous_hash and create_previous: self.rollback_links[previous_label] = previous_hash try: self.client.remove(previous_label) self.log.debug("Removing previous label: " "{}".format(previous_label)) except EnvironmentError as ex: self.log.debug("Unable to remove the target_label: %s", target_label) self.log.exception(ex) self.client.close() # Rollback is not tested, we enable it later, when tests are # easier to add # self.rollback() raise try: self.client.symlink(current_hash, previous_label) self.log.debug("Created symlink: " "{} -> {}".format(current_hash, previous_label)) except EnvironmentError as ex: self.log.error("%s failed to link %s to %s", log_header, previous_label, current_hash) self.log.exception(ex) # Rollback is not tested, we enable it later, when tests are # easier to add # self.rollback() self.client.close() raise # Finally the effective promotion try: self.client.symlink(os.path.join(self.images_dir, candidate_hash.full_hash), target_label) self.log.debug("Created symlink {} -> {}".format( candidate_hash.full_hash, target_label)) except EnvironmentError as ex: self.log.error("%s failed to link %s to %s", log_header, target_label, candidate_hash.full_hash) self.log.exception(ex) # Rollback is not tested, we enable it later, when tests are # easier to add # self.rollback() finally: self.client.close() self.log.info("%s Successful promotion", log_header)
{ "content_hash": "5dcc2965ce3136e0e64fbe2938594a49", "timestamp": "", "source": "github", "line_count": 284, "max_line_length": 80, "avg_line_length": 39.901408450704224, "alnum_prop": 0.558506883162725, "repo_name": "redhat-openstack/rdo-infra", "id": "5c3cd9c7336f5ae3afe0068b3b1f35cf73697473", "size": "11332", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ci-scripts/dlrnapi_promoter/qcow_client.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "261" }, { "name": "Dockerfile", "bytes": "2412" }, { "name": "Go", "bytes": "29397" }, { "name": "HTML", "bytes": "31437" }, { "name": "Jinja", "bytes": "12823" }, { "name": "Python", "bytes": "730685" }, { "name": "Shell", "bytes": "65445" } ], "symlink_target": "" }
describe("My Directive", function() { var el, scope; beforeEach(module('common')); beforeEach(module('templates-common')); beforeEach(inject(function($rootScope, $compile) { el = angular.element( '<div>' + '<my-directive label="Hello World"></sf-combo-button>' + '</div>' ); scope = $rootScope.$new(); $compile(el)(scope); scope.$digest(); })); it("should render the label", function() { expect(el.find('.my-directive').text().trim()).toBe('Hello World'); }); });
{ "content_hash": "6ac80935f1e45c4dd8de6679188d1737", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 69, "avg_line_length": 20.75, "alnum_prop": 0.6184738955823293, "repo_name": "blittle/angular-module-setup", "id": "aa2f44ee7fc24c6748fd7811f2f15e6db27c36bb", "size": "498", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/src/common/directives/my-directive/my-directive.spec.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "742" }, { "name": "JavaScript", "bytes": "15743" } ], "symlink_target": "" }
using Android.Util; namespace Com.Handmark.PullToRefresh.Library.Internal { public class Utils { static string LOG_TAG = "PullToRefresh"; public static void warnDeprecation(string depreacted, string replacement) { Log.Warn(LOG_TAG, "You're using the deprecated " + depreacted + " attr, please switch over to " + replacement); } } }
{ "content_hash": "d22d4c1b1f3c70dbbb877e05c232edb9", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 123, "avg_line_length": 24.4375, "alnum_prop": 0.649616368286445, "repo_name": "skywolf888/Android-PullToRefresh.Net", "id": "66b15bba28c5e7995111c4a3474b420afa0af2eb", "size": "475", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "PullToRefresh.Net/Library/Internal/Utils.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "256661" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>Uses of Class org.apache.commons.codec.language.bm.Lang (Apache Commons Codec 1.10 API)</title> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.commons.codec.language.bm.Lang (Apache Commons Codec 1.10 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../org/apache/commons/codec/language/bm/Lang.html" title="class in org.apache.commons.codec.language.bm">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/apache/commons/codec/language/bm/class-use/Lang.html" target="_top">Frames</a></li> <li><a href="Lang.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.apache.commons.codec.language.bm.Lang" class="title">Uses of Class<br>org.apache.commons.codec.language.bm.Lang</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../../org/apache/commons/codec/language/bm/Lang.html" title="class in org.apache.commons.codec.language.bm">Lang</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.apache.commons.codec.language.bm">org.apache.commons.codec.language.bm</a></td> <td class="colLast"> <div class="block">Implementation details of the Beider-Morse codec.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.apache.commons.codec.language.bm"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../org/apache/commons/codec/language/bm/Lang.html" title="class in org.apache.commons.codec.language.bm">Lang</a> in <a href="../../../../../../../org/apache/commons/codec/language/bm/package-summary.html">org.apache.commons.codec.language.bm</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../../org/apache/commons/codec/language/bm/package-summary.html">org.apache.commons.codec.language.bm</a> that return <a href="../../../../../../../org/apache/commons/codec/language/bm/Lang.html" title="class in org.apache.commons.codec.language.bm">Lang</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../../org/apache/commons/codec/language/bm/Lang.html" title="class in org.apache.commons.codec.language.bm">Lang</a></code></td> <td class="colLast"><span class="strong">PhoneticEngine.</span><code><strong><a href="../../../../../../../org/apache/commons/codec/language/bm/PhoneticEngine.html#getLang()">getLang</a></strong>()</code> <div class="block">Gets the Lang language guessing rules being used.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../../../../org/apache/commons/codec/language/bm/Lang.html" title="class in org.apache.commons.codec.language.bm">Lang</a></code></td> <td class="colLast"><span class="strong">Lang.</span><code><strong><a href="../../../../../../../org/apache/commons/codec/language/bm/Lang.html#instance(org.apache.commons.codec.language.bm.NameType)">instance</a></strong>(<a href="../../../../../../../org/apache/commons/codec/language/bm/NameType.html" title="enum in org.apache.commons.codec.language.bm">NameType</a>&nbsp;nameType)</code> <div class="block">Gets a Lang instance for one of the supported NameTypes.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../../../../org/apache/commons/codec/language/bm/Lang.html" title="class in org.apache.commons.codec.language.bm">Lang</a></code></td> <td class="colLast"><span class="strong">Lang.</span><code><strong><a href="../../../../../../../org/apache/commons/codec/language/bm/Lang.html#loadFromResource(java.lang.String,%20org.apache.commons.codec.language.bm.Languages)">loadFromResource</a></strong>(<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;languageRulesResourceName, <a href="../../../../../../../org/apache/commons/codec/language/bm/Languages.html" title="class in org.apache.commons.codec.language.bm">Languages</a>&nbsp;languages)</code> <div class="block">Loads language rules from a resource.</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../org/apache/commons/codec/language/bm/Lang.html" title="class in org.apache.commons.codec.language.bm">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/apache/commons/codec/language/bm/class-use/Lang.html" target="_top">Frames</a></li> <li><a href="Lang.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2002&#x2013;2014 <a href="http://www.apache.org/">The Apache Software Foundation</a>. All rights reserved.</small></p> </body> </html>
{ "content_hash": "628a640ffedf779f5e5d0e6ed3d7d093", "timestamp": "", "source": "github", "line_count": 172, "max_line_length": 432, "avg_line_length": 48.36046511627907, "alnum_prop": 0.6383746092810771, "repo_name": "angpulangpluma/ProjectCrypt", "id": "92a9e86dc65e1d041e55175c4108100288a66f8a", "size": "8318", "binary": false, "copies": "3", "ref": "refs/heads/restart", "path": "app/libs/commons-codec-1.10/apidocs/org/apache/commons/codec/language/bm/class-use/Lang.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "11139" }, { "name": "HTML", "bytes": "4517297" }, { "name": "Java", "bytes": "469051" }, { "name": "PHP", "bytes": "19820" } ], "symlink_target": "" }
package com.thoughtworks.deeplearning package plugins import com.thoughtworks.deeplearning.scalatest.ThoughtworksFutureToScalaFuture import com.thoughtworks.each.Monadic._ import com.thoughtworks.feature.{Factory, ImplicitApply} import com.thoughtworks.raii.asynchronous._ import org.nd4j.linalg.api.ndarray.INDArray import org.nd4j.linalg.api.ops.impl.transforms.IsMax import org.nd4j.linalg.convolution.Convolution import org.nd4j.linalg.factory.Nd4j import org.nd4j.linalg.ops.transforms.Transforms import org.nd4j.linalg.util.ArrayUtil import org.scalatest._ import org.nd4s.Implicits._ import com.thoughtworks.continuation._ import com.thoughtworks.future._ import scalaz.std.iterable._ object CumulativeINDArrayLayersSpec { trait CNNs extends INDArrayLayers with ImplicitsSingleton with Training with Operators { trait ImplicitsApi extends super[INDArrayLayers].ImplicitsApi with super[Training].ImplicitsApi with super[Operators].ImplicitsApi type Implicits <: ImplicitsApi private def toArray(tuple2: (Int, Int)): Array[Int] = { val (one, two) = tuple2 Array(one, two) } def im2col[Operand0, Out <: INDArrayLayer](operand0: Operand0, kernel: (Int, Int), stride: (Int, Int), padding: (Int, Int))( implicit deepLearning: DeepLearning.Aux[Operand0, INDArray, INDArray], layerImplicits: ImplicitApply.Aux[indArrayPartialApplyRawForward.Rest, Out]): Out = { INDArrayLayer.unary(operand0) { data0: INDArray => val shape0 = data0.shape val strideArray = toArray(stride) val paddingArray = toArray(padding) val outputData = Convolution.im2col(data0, toArray(kernel), strideArray, paddingArray) val delta0 = { outputDelta: INDArray => Convolution.col2im(outputDelta, strideArray, paddingArray, shape0(2), shape0(3)) } (outputData, delta0) } } @inline def conv2d[Input, Weight, Bias, Out <: INDArrayLayer](input: Input, weight: Weight, bias: Bias, kernel: (Int, Int), stride: (Int, Int), padding: (Int, Int))( implicit inputDeepLearning: DeepLearning.Aux[Input, INDArray, INDArray], weightDeepLearning: DeepLearning.Aux[Weight, INDArray, INDArray], biasDeepLearning: DeepLearning.Aux[Bias, INDArray, INDArray], layerImplicits: ImplicitApply.Aux[indArrayPartialApplyRawForward.Rest, Out]): Out = { import implicits._ INDArrayLayer(monadic[Do] { val inputShape = input.forward.each.data.shape val numberOfImages = inputShape(0) val depth = inputShape(1) val height = inputShape(2) val width = inputShape(3) val numberOfKernels = weight.forward.each.data.shape.head val col = im2col(input, kernel, stride, padding) val permutedCol = col.permute(0, 4, 5, 1, 2, 3) val depthKernelKernel = depth * kernel._1 * kernel._2 val operandCol2d = permutedCol.reshape(numberOfImages * height * width, depthKernelKernel) val reshapedWeight = weight.reshape(numberOfKernels, depthKernelKernel) val permutedWeight = reshapedWeight.permute(1, 0) val dotResult = operandCol2d dot permutedWeight val plusResult = dotResult + bias val reshapeResult = plusResult.reshape(numberOfImages, height, width, numberOfKernels) reshapeResult.permute(0, 3, 1, 2).forward.each }) } @inline def maxPool[Operand0, Out <: INDArrayLayer](operand0: Operand0, poolSize: (Int, Int))( implicit deepLearning: DeepLearning.Aux[Operand0, INDArray, INDArray], layerImplicits: ImplicitApply.Aux[indArrayPartialApplyRawForward.Rest, Out]): Out = { INDArrayLayer.unary(operand0) { data0: INDArray => val shape0 = data0.shape val kernelAndStrideSize: Array[Int] = toArray(poolSize) val preMaxPool: INDArray = Convolution .im2col(data0, kernelAndStrideSize, kernelAndStrideSize, Array(0, 0)) .permute(0, 1, 4, 5, 2, 3) val preShape: Seq[Int] = preMaxPool.shape().toSeq val lastDimensionSize: Int = preShape.takeRight(2).product val reshapedPreMaxPool: INDArray = preMaxPool .reshape(preShape.take(preShape.length - 2) :+ lastDimensionSize: _*) val outputData = reshapedPreMaxPool.max(4) val delta0 = { outputDelta: INDArray => val a = reshapedPreMaxPool val upStreamDup = a.dup() val rows = ArrayUtil.prod(a.length()) val isMax: INDArray = Nd4j.getExecutioner .execAndReturn(new IsMax(upStreamDup, 4)) .reshape(preShape.take(preShape.length - 2) :+ poolSize._2 :+ poolSize._1: _*) .permute(0, 1, 2, 4, 3, 5) .reshape('c', rows, 1) val outputDelta1d = { outputDelta .repeat(-1, poolSize._1) .permute(1, 0, 3, 2) .repeat(-1, poolSize._2) .permute(1, 0, 3, 2) .reshape('c', shape0.product, 1) } isMax .muliColumnVector(outputDelta1d) .reshape(shape0: _*) } (outputData, delta0) } } } trait FixedLearningRate extends LearningRate { val fixedLearningRate: scala.Double trait INDArrayOptimizerApi extends super.INDArrayOptimizerApi { this: INDArrayOptimizer => final def learningRate: scala.Double = fixedLearningRate } override type INDArrayOptimizer <: INDArrayOptimizerApi with Optimizer } trait LearningRate extends INDArrayWeights { trait INDArrayOptimizerApi extends super.INDArrayOptimizerApi { this: INDArrayOptimizer => def learningRate: scala.Double abstract override def delta: INDArray = super.delta mul learningRate } override type INDArrayOptimizer <: INDArrayOptimizerApi with Optimizer } trait L1Regularization extends INDArrayWeights { def l1Regularization: INDArray trait INDArrayOptimizerApi extends super.INDArrayOptimizerApi { this: INDArrayOptimizer => abstract override def delta: INDArray = super.delta + Transforms.sign(weight.data) * l1Regularization } override type INDArrayOptimizer <: INDArrayOptimizerApi with Optimizer } trait L2Regularization extends INDArrayWeights { def l2Regularization: INDArray trait INDArrayOptimizerApi extends super.INDArrayOptimizerApi { this: INDArrayOptimizer => abstract override def delta: INDArray = super.delta + weight.data * l2Regularization } override type INDArrayOptimizer <: INDArrayOptimizerApi with Optimizer } trait Momentum extends INDArrayWeights { trait INDArrayWeightApi extends super.INDArrayWeightApi { this: INDArrayWeight => def mu: scala.Double = 0.9 var v: INDArray = Nd4j.zeros(data.shape: _*) } override type INDArrayWeight <: INDArrayWeightApi with Weight trait INDArrayOptimizerApi extends super.INDArrayOptimizerApi { this: INDArrayOptimizer => private lazy val delta0: INDArray = { import weight._ v = super.delta + v * mu v } abstract override def delta: INDArray = delta0 } override type INDArrayOptimizer <: INDArrayOptimizerApi with Optimizer } trait NesterovMomentum extends Momentum { trait INDArrayOptimizerApi extends super.INDArrayOptimizerApi { this: INDArrayOptimizer => abstract override lazy val delta: INDArray = { import weight._ val vPrev = v vPrev * (-mu) + super.delta * (1 + mu) } } override type INDArrayOptimizer <: INDArrayOptimizerApi with Optimizer } /** * @note This [[Adagrad]] hyperparameter is usually used before global [[LearningRate]]. e.g. `Adagrad with FixedLearningRate`, not `FixedLearningRate with Adagrad` */ trait Adagrad extends INDArrayWeights { trait INDArrayWeightApi extends super.INDArrayWeightApi { this: INDArrayWeight => var cache: INDArray = Nd4j.zeros(data.shape: _*) } override type INDArrayWeight <: INDArrayWeightApi with Weight trait INDArrayOptimizerApi extends super.INDArrayOptimizerApi { this: INDArrayOptimizer => def eps: scala.Double = 1e-4 abstract override lazy val delta: INDArray = { import weight._ cache = cache + super.delta * super.delta super.delta / (Transforms.sqrt(cache) + eps) } } override type INDArrayOptimizer <: INDArrayOptimizerApi with Optimizer } /** * @note This [[RMSprop]] hyperparameter is usually used before global [[LearningRate]]. e.g. `RMSprop with FixedLearningRate`, not `FixedLearningRate with RMSprop` */ trait RMSprop extends INDArrayWeights { trait INDArrayWeightApi extends super.INDArrayWeightApi { this: INDArrayWeight => var cache: INDArray = Nd4j.zeros(data.shape: _*) } override type INDArrayWeight <: INDArrayWeightApi with Weight trait INDArrayOptimizerApi extends super.INDArrayOptimizerApi { this: INDArrayOptimizer => def eps: scala.Double = 1e-4 def decayRate: scala.Double = 0.99 abstract override lazy val delta: INDArray = { import weight._ cache = cache * decayRate + super.delta * super.delta * (1.0 - decayRate) super.delta / (Transforms.sqrt(cache) + eps) } } override type INDArrayOptimizer <: INDArrayOptimizerApi with Optimizer } trait Adam extends INDArrayWeights { trait INDArrayWeightApi extends super.INDArrayWeightApi { this: INDArrayWeight => var m: INDArray = Nd4j.zeros(data.shape: _*) var v: INDArray = Nd4j.zeros(data.shape: _*) } override type INDArrayWeight <: INDArrayWeightApi with Weight trait INDArrayOptimizerApi extends super.INDArrayOptimizerApi { this: INDArrayOptimizer => def beta1: scala.Double = 0.9 def beta2: scala.Double = 0.999 def eps: scala.Double = 1e-8 abstract override lazy val delta: INDArray = { import weight._ m = m * beta1 + super.delta * (1.0 - beta1) v = v * beta2 + (super.delta * super.delta) * (1.0 - beta2) m / (Transforms.sqrt(v) + eps) } } override type INDArrayOptimizer <: INDArrayOptimizerApi with Optimizer } } /** * @author 杨博 (Yang Bo) */ class CumulativeINDArrayLayersSpec extends AsyncFreeSpec with Matchers with Inside with ThoughtworksFutureToScalaFuture { import CumulativeINDArrayLayersSpec._ val hyperparameters = Factory[ Logging with ImplicitsSingleton with DoubleTraining with INDArrayTraining with INDArrayLiterals with DoubleLiterals with CumulativeDoubleLayers with Operators with CumulativeINDArrayLayers with FixedLearningRate] .newInstance(fixedLearningRate = 1.0) import hyperparameters.implicits._ def trainAndAssertLossAndWeight(myNetwork: INDArray => hyperparameters.INDArrayLayer, weight: hyperparameters.INDArrayWeight, trainTimes: Int = 2, expectedLoss: Int = 0, expectedWeightSum: Int = -16, input: INDArray = Nd4j.ones(4, 4)): Future[Assertion] = { @throwableMonadic[Future] val run: Future[Assertion] = { for (_ <- 1 to trainTimes) { myNetwork(input).train.each.sumT } val loss = myNetwork(input).predict.each loss.sumT should be(expectedLoss) weight.data.sumT should be(expectedWeightSum) } run } "INDArray + INDArray" in { val weight = hyperparameters.INDArrayWeight(Nd4j.ones(4, 4)) def myNetwork(input: INDArray): hyperparameters.INDArrayLayer = { weight + input } trainAndAssertLossAndWeight(myNetwork, weight) } "INDArray + Double" in { val weight = hyperparameters.INDArrayWeight(Nd4j.ones(4, 4)) def myNetwork(input: INDArray): hyperparameters.INDArrayLayer = { weight + 1.0 } trainAndAssertLossAndWeight(myNetwork, weight) } "Double + INDArray" in { val weight = hyperparameters.INDArrayWeight(Nd4j.ones(4, 4)) def myNetwork(input: INDArray): hyperparameters.INDArrayLayer = { 1.0 + weight } trainAndAssertLossAndWeight(myNetwork, weight) } "INDArray - INDArray" in { val weight = hyperparameters.INDArrayWeight(Nd4j.ones(4, 4)) def myNetwork(input: INDArray): hyperparameters.INDArrayLayer = { weight - (-input) } trainAndAssertLossAndWeight(myNetwork, weight) } "INDArray - Double" in { val weight = hyperparameters.INDArrayWeight(Nd4j.ones(4, 4)) def myNetwork(input: INDArray): hyperparameters.INDArrayLayer = { weight - (-1.0) } trainAndAssertLossAndWeight(myNetwork, weight) } "Double - INDArray" in { val weight = hyperparameters.INDArrayWeight((Nd4j.ones(4, 4).negi())) def myNetwork(input: INDArray): hyperparameters.INDArrayLayer = { 1.0 - weight } trainAndAssertLossAndWeight(myNetwork, weight, expectedWeightSum = 16) } "INDArray * INDArray" in { val weight = hyperparameters.INDArrayWeight((Nd4j.ones(4, 4) mul 2)) def myNetwork(input: INDArray): hyperparameters.INDArrayLayer = { weight * input } trainAndAssertLossAndWeight(myNetwork, weight, expectedWeightSum = 0) } "INDArray * Double" in { val weight = hyperparameters.INDArrayWeight((Nd4j.ones(4, 4) mul 2)) def myNetwork(input: INDArray): hyperparameters.INDArrayLayer = { weight * 1.0 } trainAndAssertLossAndWeight(myNetwork, weight, expectedWeightSum = 0) } "Double * INDArray" in { val weight = hyperparameters.INDArrayWeight((Nd4j.ones(4, 4) mul 2)) def myNetwork(input: INDArray): hyperparameters.INDArrayLayer = { 1.0 * weight } trainAndAssertLossAndWeight(myNetwork, weight, expectedWeightSum = 0) } "INDArray / INDArray" in { val weight = hyperparameters.INDArrayWeight((Nd4j.ones(4, 4) mul 2)) def myNetwork(input: INDArray): hyperparameters.INDArrayLayer = { weight / input } trainAndAssertLossAndWeight(myNetwork, weight, expectedWeightSum = 0) } "INDArray / Double" in { val weight = hyperparameters.INDArrayWeight((Nd4j.ones(4, 4) mul 2)) def myNetwork(input: INDArray): hyperparameters.INDArrayLayer = { weight / 1.0 } trainAndAssertLossAndWeight(myNetwork, weight, expectedWeightSum = 0) } "Double / INDArray" in { val weight = hyperparameters.INDArrayWeight(Nd4j.ones(4, 4)) def myNetwork(input: INDArray): hyperparameters.INDArrayLayer = { 1.0 / weight } @monadic[Future] val task: Future[Unit] = { for (_ <- 1 to 20000) { myNetwork(Nd4j.ones(4, 4)).train.each } } throwableMonadic[Future] { task.each val loss = myNetwork(Nd4j.ones(4, 4)).predict.each loss.sumT should be < 0.5 weight.data.sumT should be > 600.0 } } "max(INDArray,Double)" in { val weight = hyperparameters.INDArrayWeight((Nd4j.ones(4, 4) * 10)) def myNetwork(input: INDArray): hyperparameters.INDArrayLayer = { hyperparameters.max(weight, 0.0) } trainAndAssertLossAndWeight(myNetwork, weight, trainTimes = 10, expectedWeightSum = 0) } "min(INDArray,Double)" in { val weight = hyperparameters.INDArrayWeight((Nd4j.ones(4, 4) * 10)) def myNetwork(input: INDArray): hyperparameters.INDArrayLayer = { hyperparameters.min(weight, 100.0) } trainAndAssertLossAndWeight(myNetwork, weight, trainTimes = 10, expectedWeightSum = 0) } "exp(INDArray)" in { val weight = hyperparameters.INDArrayWeight((Nd4j.ones(4, 4) * 10)) def myNetwork(input: INDArray): hyperparameters.INDArrayLayer = { hyperparameters.exp(weight) } @monadic[Future] val task: Future[Unit] = { for (_ <- 1 to 50) { myNetwork(Nd4j.ones(4, 4)).train.each } } throwableMonadic[Future] { task.each val loss = myNetwork(Nd4j.ones(4, 4)).predict.each loss.sumT should be < 1.0 weight.data.sumT should be < 1.0 } } "log(INDArray)" in { val weight = hyperparameters.INDArrayWeight((Nd4j.ones(4, 4) * 10)) def myNetwork(input: INDArray): hyperparameters.INDArrayLayer = { hyperparameters.log(weight) } @monadic[Future] val task: Future[Unit] = { for (_ <- 1 to 50) { myNetwork(Nd4j.ones(4, 4)).train.each } } throwableMonadic[Future] { task.each val loss = myNetwork(Nd4j.ones(4, 4)).predict.each loss.sumT should be < 10.0 weight.data.sumT should be < 22.0 } } "abs(INDArray)" in { val weight = hyperparameters.INDArrayWeight((Nd4j.ones(4, 4) * 10)) def myNetwork(input: INDArray): hyperparameters.INDArrayLayer = { hyperparameters.abs(weight) } @monadic[Future] val task: Future[Unit] = { for (_ <- 1 to 10) { myNetwork(Nd4j.ones(4, 4)).train.each } } throwableMonadic[Future] { task.each val loss = myNetwork(Nd4j.ones(4, 4)).predict.each loss.sumT should be < 1.0 weight.data.sumT should be < 1.0 } } "INDArray dot INDArray" in { val weight = hyperparameters.INDArrayWeight((Nd4j.ones(4, 4) * 10)) def myNetwork(input: INDArray): hyperparameters.INDArrayLayer = { def RichINDArray = ??? // Disable org.nd4s.Implicits.RichINDArray input dot weight } @monadic[Future] val task: Future[Unit] = { for (_ <- 1 to 10) { myNetwork(Nd4j.ones(4, 4)).train.each } } throwableMonadic[Future] { task.each val loss = myNetwork(Nd4j.ones(4, 4)).predict.each loss.sumT should be(-1920.0) weight.data.sumT should be(-480.0) } } "INDArray im2col (kernel,stride,padding) --forward" in { val hyperparameters = Factory[ CNNs with Logging with ImplicitsSingleton with INDArrayTraining with INDArrayLiterals with DoubleLiterals with CumulativeDoubleLayers with Operators with CumulativeINDArrayLayers with FixedLearningRate] .newInstance(fixedLearningRate = 0.03) import hyperparameters.implicits._ val weight = hyperparameters.INDArrayWeight((-(1 to 54).toNDArray).reshape(2, 3, 3, 3)) def myNetwork(kernel: (Int, Int), stride: (Int, Int), padding: (Int, Int)): hyperparameters.INDArrayLayer = { hyperparameters.im2col(weight, kernel, stride, padding) } myNetwork((3, 3), (1, 1), (1, 1)).train.map { result => result.sumT should be(-8085.0) } } "INDArray im2col (kernel,stride,padding) --train" in { val hyperparameters = Factory[ CNNs with Logging with ImplicitsSingleton with INDArrayTraining with INDArrayLiterals with DoubleLiterals with CumulativeDoubleLayers with Operators with CumulativeINDArrayLayers with FixedLearningRate] .newInstance(fixedLearningRate = 0.01) import hyperparameters.implicits._ val weight = hyperparameters.INDArrayWeight((1 to 54).toNDArray.reshape(2, 3, 3, 3)) def myNetwork(kernel: (Int, Int), stride: (Int, Int), padding: (Int, Int)): hyperparameters.INDArrayLayer = { hyperparameters.im2col(weight, kernel, stride, padding) } @monadic[Future] val task: Future[Unit] = { for (_ <- 1 to 1000) { myNetwork((3, 3), (1, 1), (1, 1)).train.each } } throwableMonadic[Future] { task.each val loss = (myNetwork((3, 3), (1, 1), (1, 1))).predict.each loss.sumT should be < 1.0 } } "INDArray reshape shapes --forward" in { val weight = hyperparameters.INDArrayWeight((1 to 54).toNDArray.reshape(2, 3, 3, 3)) def myNetwork(dimensions: Int*): hyperparameters.INDArrayLayer = { weight.reshape(dimensions: _*) } myNetwork(2, 3, 3, 3).train.map { result => result.sumT should be(1431.0) } } "INDArray maxPool poolsize --forward" in { val hyperparameters = Factory[ CNNs with Logging with ImplicitsSingleton with INDArrayTraining with INDArrayLiterals with DoubleLiterals with CumulativeDoubleLayers with Operators with CumulativeINDArrayLayers with FixedLearningRate] .newInstance(fixedLearningRate = 1.0) import hyperparameters.implicits._ val weight = hyperparameters.INDArrayWeight((1 to 96).toNDArray.reshape(2, 3, 4, 4)) def myNetwork(poolSize: (Int, Int)): hyperparameters.INDArrayLayer = { hyperparameters.maxPool(weight, poolSize) } myNetwork((2, 2)).train.map { result => result.sumT should be(1224.0) } } "INDArray maxPool poolsize -- train" in { val hyperparameters = Factory[ CNNs with Logging with ImplicitsSingleton with INDArrayTraining with INDArrayLiterals with DoubleLiterals with CumulativeDoubleLayers with Operators with CumulativeINDArrayLayers with FixedLearningRate] .newInstance(fixedLearningRate = 1.0) import hyperparameters.implicits._ val weight = hyperparameters.INDArrayWeight((1 to 96).toNDArray.reshape(2, 3, 4, 4)) def myNetwork(poolSize: (Int, Int)): hyperparameters.INDArrayLayer = { hyperparameters.maxPool(weight, poolSize) } val poolSize = (2, 2) @monadic[Future] val task: Future[Unit] = { for (_ <- 1 to 700) { myNetwork(poolSize).train.each } } throwableMonadic[Future] { task.each val loss: INDArray = (myNetwork(poolSize)).predict.each loss.meanT should be < 10.0 } } "4D INDArray * 4D INDArray -- forward" in { val weight = hyperparameters.INDArrayWeight((0 until (1 * 2 * 3 * 4)).toNDArray.reshape(1, 2, 3, 4)) def myNetwork(input: INDArray): hyperparameters.INDArrayLayer = { weight * input } val input = (0 until (1 * 2 * 3 * 4)).toNDArray.reshape(1, 2, 3, 4) myNetwork(input).train.map { (result) => result.meanNumber.doubleValue should be(180.16666666666666667 +- 0.1) } } "4D INDArray * 4D INDArray -- train" in { val weight = hyperparameters.INDArrayWeight((0 until (1 * 2 * 3 * 4)).toNDArray.reshape(1, 2, 3, 4)) def myNetwork(input: INDArray): hyperparameters.INDArrayLayer = { weight * input } val input = (0 until (1 * 2 * 3 * 4)).toNDArray.reshape(1, 2, 3, 4) @monadic[Future] val task: Future[Unit] = { for (_ <- 1 to 100) { myNetwork(input).train.each } } throwableMonadic[Future] { task.each val loss: INDArray = (myNetwork(input)).predict.each loss.meanNumber.doubleValue should be < 1.0 } } "INDArray permute dimensions --forward" in { val weight = hyperparameters.INDArrayWeight((1 to 54).toNDArray.reshape(2, 3, 9)) def myNetwork(dimensions: Int*): hyperparameters.INDArrayLayer = { weight.permute(dimensions: _*) } myNetwork(0, 2, 1).train.map { (result) => result.sumT should be(1431.0) } } "conv2d(INDArray, INDArray, INDArray, kernel, stride, padding)" in { val hyperparameters = Factory[ CNNs with Logging with ImplicitsSingleton with INDArrayTraining with INDArrayLiterals with DoubleLiterals with CumulativeDoubleLayers with Operators with CumulativeINDArrayLayers with FixedLearningRate] .newInstance(fixedLearningRate = 0.01) import hyperparameters.implicits._ val weight: hyperparameters.INDArrayWeight = hyperparameters.INDArrayWeight(Nd4j.ones(1, 1, 3, 3)) val bias: hyperparameters.INDArrayWeight = hyperparameters.INDArrayWeight(Nd4j.zeros(1)) def convolution(input: INDArray): hyperparameters.INDArrayLayer = { hyperparameters.conv2d(input, weight, bias, (3, 3), (1, 1), (1, 1)) } val expectResult = Array(14.00, 24.00, 30.00, 22.00, 33.00, 54.00, 63.00, 45.00, 57.00, 90.00, 99.00, 69.00, 46.00, 72.00, 78.00, 54.00).toNDArray .reshape(1, 1, 4, 4) val input: INDArray = (1 to 16).toNDArray.reshape(1, 1, 4, 4) convolution(input).train.map { (result) => result.eq(expectResult).sumT should be(16) } } "sumT(INDArray)" in { val weight = hyperparameters.INDArrayWeight((1 to 54).toNDArray.reshape(2, 3, 3, 3)) def myNetwork(): hyperparameters.DoubleLayer = { weight.sum } @monadic[Future] val task: Future[Unit] = { for (_ <- 1 to 54) { myNetwork().train.each } } throwableMonadic[Future] { task.each val loss = myNetwork().predict.each loss should be < 1.0 } } "sum(INDArray,dimensions) --2 dimensions" in { val weight = hyperparameters.INDArrayWeight((1 to 54).toNDArray.reshape(6, 9)) def myNetwork(dimensions: Int*): hyperparameters.INDArrayLayer = { weight.sum(dimensions: _*) } @monadic[Future] val task: Future[Unit] = { for (_ <- 1 to 54) { myNetwork(0).train.each } } throwableMonadic[Future] { task.each val loss = myNetwork(0).predict.each loss.sumT should be < 1.0 } } // Failed due to nd4j bugs in broadcasting. TODO: Try to upgrade nd4j to a new version. "sum(INDArray,dimensions) --4 dimensions" in { val weight = hyperparameters.INDArrayWeight((1 to 54).toNDArray.reshape(2, 3, 3, 3)) def myNetwork(dimensions: Int*): hyperparameters.INDArrayLayer = { weight.sum(dimensions: _*) } @monadic[Future] val task: Future[Unit] = { for (_ <- 1 to 54) { myNetwork(0, 1).train.each } } throwableMonadic[Future] { task.each val loss = myNetwork(0, 1).predict.each loss.sumT should be < 1.0 } } "mean(INDArray)" in { val weight = hyperparameters.INDArrayWeight((1 to 54).toNDArray.reshape(2, 3, 3, 3)) def myNetwork(): hyperparameters.DoubleLayer = { weight.mean } @monadic[Future] val task: Future[Unit] = { for (_ <- 1 to 27) { myNetwork().train.each } } throwableMonadic[Future] { task.each val loss = myNetwork().predict.each loss should be < 27.5 } } "INDArray reshape shapes --train" in { val hyperparameters = Factory[Logging with ImplicitsSingleton with INDArrayTraining with INDArrayLiterals with DoubleLiterals with CumulativeDoubleLayers with Operators with CumulativeINDArrayLayers with FixedLearningRate] .newInstance(fixedLearningRate = 0.01) import hyperparameters.implicits._ val weight = hyperparameters.INDArrayWeight((1 to 54).toNDArray.reshape(2, 3, 3, 3)) def myNetwork(dimensions: Int*): hyperparameters.INDArrayLayer = { weight.reshape(dimensions: _*) } @monadic[Future] val task: Future[Unit] = { for (_ <- 1 to 10000) { myNetwork(2, 3, 3, 3).train.each } } throwableMonadic[Future] { task.each val loss = (myNetwork(2, 3, 3, 3)).predict.each loss.sumT should be < 1.0 } } "INDArray permute dimensions --train" in { val hyperparameters = Factory[Logging with ImplicitsSingleton with INDArrayTraining with INDArrayLiterals with DoubleLiterals with CumulativeDoubleLayers with Operators with CumulativeINDArrayLayers with FixedLearningRate] .newInstance(fixedLearningRate = 0.01) import hyperparameters.implicits._ val weight = hyperparameters.INDArrayWeight((1 to 54).toNDArray.reshape(2, 3, 9)) def myNetwork(dimensions: Int*): hyperparameters.INDArrayLayer = { weight.permute(dimensions: _*) } @monadic[Future] val task: Future[Unit] = { for (_ <- 1 to 10000) { myNetwork(0, 2, 1).train.each } } throwableMonadic[Future] { task.each val loss = myNetwork(0, 2, 1).predict.each loss.sumT should be < 1.0 } } }
{ "content_hash": "80741af3516d332b3b65c87a51463141", "timestamp": "", "source": "github", "line_count": 884, "max_line_length": 216, "avg_line_length": 31.83371040723982, "alnum_prop": 0.6524288404818592, "repo_name": "izhangzhihao/DeepLearning.scala", "id": "32b559d81149f06b4edd7e7daca5b8319c255b65", "size": "28145", "binary": false, "copies": "1", "ref": "refs/heads/2.0.x", "path": "plugins-CumulativeINDArrayLayers/src/test/scala-2.11/com/thoughtworks/deeplearning/plugins/CumulativeINDArrayLayersSpec.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Scala", "bytes": "139652" } ], "symlink_target": "" }
haloc::Hash::Params::Params() : bucket_rows(DEFAULT_BUCKET_ROWS), bucket_cols(DEFAULT_BUCKET_COLS), max_desc(DEFAULT_MAX_DESC), num_proj(DEFAULT_NUM_PROJ) {} haloc::Hash::Hash() : initialized_(false) {} std::vector<float> haloc::Hash::GetHash( const std::vector<cv::KeyPoint>& kp, const cv::Mat& desc, const cv::Size& img_size) { // Initialize first time if (!IsInitialized()) Init(img_size, kp.size(), desc.cols); state_.Clear(); // Initialize output std::vector<float> hash; // The maximum number of features per bucket int max_features_x_bucket = static_cast<int>( floor(params_.max_desc/(params_.bucket_cols*params_.bucket_rows))); // Bucket descriptors std::vector<cv::Mat> bucket_desc = BucketDescriptors(kp, desc); // Get a hash for every bucket const int min_feat = static_cast<int>(0.7 * max_features_x_bucket); for (uint i=0; i < bucket_desc.size(); ++i) { std::vector<float> bucketed_hash; if (bucket_desc[i].rows >= min_feat) { bucketed_hash = ProjectDescriptors(bucket_desc[i]); } else { for (uint i=0; i < desc.cols*params_.num_proj; ++i) bucketed_hash.push_back(0.0); } hash.insert(hash.end(), bucketed_hash.begin(), bucketed_hash.end()); } return hash; } int haloc::Hash::CalcDist(const std::vector<float>& hash_a, const std::vector<float>& hash_b, float eps) { // Init const int num_buckets = params_.bucket_cols*params_.bucket_rows; // const float eps = 0.6; int num_buckets_overlap = 0; // Compute the distance for (uint i=0; i < comb_.size(); ++i) { int comb_overlap = 0; for (uint j=0; j < num_buckets; ++j) { int idx_a = comb_[i][j].first * params_.num_proj * desc_length_; int idx_b = comb_[i][j].second * params_.num_proj * desc_length_; // Check if buckets are empty std::vector<float>::const_iterator a_first = hash_a.begin() + idx_a; std::vector<float>::const_iterator a_last = hash_a.begin() + idx_a + desc_length_*params_.num_proj; float sum_a = std::accumulate(a_first, a_last, 0.0); if (sum_a == 0.0) continue; std::vector<float>::const_iterator b_first = hash_b.begin() + idx_b; std::vector<float>::const_iterator b_last = hash_b.begin() + idx_b + desc_length_*params_.num_proj; float sum_b = std::accumulate(b_first, b_last, 0.0); if (sum_b == 0.0) continue; float proj_sum = 0.0; for (uint k=0; k < desc_length_*params_.num_proj; ++k) { proj_sum += fabs(hash_a[idx_a+k] - hash_b[idx_b+k]); } if (proj_sum <= eps) comb_overlap++; } if (comb_overlap > num_buckets_overlap) { num_buckets_overlap = comb_overlap; } } return num_buckets_overlap; } void haloc::Hash::PublishState(const cv::Mat& img) { // The bucketed image pub_.PublishBucketedImage(state_, img, params_.bucket_rows, params_.bucket_cols); // The bucketed info int max_features_x_bucket = static_cast<int>( floor(params_.max_desc/(params_.bucket_cols*params_.bucket_rows))); pub_.PublishBucketedInfo(state_, max_features_x_bucket); } void haloc::Hash::Init(const cv::Size& img_size, const int& num_feat, const int& desc_length) { InitProjections(params_.max_desc); InitCombinations(); img_size_ = img_size; desc_length_ = desc_length; // Sanity check if (params_.max_desc < num_feat * 0.7) { ROS_WARN_STREAM("[Haloc:] WARNING -> Please setup the maximum number " << "descriptors correctly. The current image has " << num_feat << " and " << "the max_desc param is " << params_.max_desc << ". The parameter for " << "the maximum number of descriptors must be smaller than the number" << "of real features in the images."); } initialized_ = true; } void haloc::Hash::InitCombinations() { comb_.clear(); int num_buckets = params_.bucket_cols*params_.bucket_rows; int second_idx_shift = 0; for (uint i=0; i < num_buckets; ++i) { std::vector< std::pair<int, int> > combinations_row; for (uint j=0; j < num_buckets; ++j) { int second_idx = j + second_idx_shift; if (second_idx > num_buckets-1) { second_idx = second_idx - num_buckets; } combinations_row.push_back(std::make_pair(j, second_idx)); } comb_.push_back(combinations_row); second_idx_shift++; } } void haloc::Hash::InitProjections(const int& desc_size) { // Initializations int seed = time(NULL); r_.clear(); // The maximum number of features per bucket int max_features_x_bucket = static_cast<int>( floor(params_.max_desc/(params_.bucket_cols*params_.bucket_rows))); // The size of the descriptors may vary... // But, we limit the number of descriptors per bucket. int v_size = max_features_x_bucket; // We will generate N-orthogonal vectors creating a linear system of type Ax=b // Generate a first random vector std::vector<float> r = ComputeRandomVector(v_size, seed); r_.push_back(UnitVector(r)); // Generate the set of orthogonal vectors for (uint i=1; i < params_.num_proj; i++) { // Generate a random vector of the correct size std::vector<float> new_v = ComputeRandomVector(v_size - i, seed + i); // Get the right terms (b) Eigen::VectorXf b(r_.size()); for (uint n=0; n < r_.size(); n++) { std::vector<float> cur_v = r_[n]; float sum = 0.0; for (uint m=0; m < new_v.size(); m++) sum += new_v[m]*cur_v[m]; b(n) = -sum; } // Get the matrix of equations (A) Eigen::MatrixXf A(i, i); for (uint n=0; n < r_.size(); n++) { uint k = 0; for (uint m=r_[n].size()-i; m < r_[n].size(); m++) { A(n, k) = r_[n][m]; k++; } } // Apply the solver Eigen::VectorXf x = A.colPivHouseholderQr().solve(b); // Add the solutions to the new vector for (uint n=0; n < r_.size(); n++) new_v.push_back(x(n)); new_v = UnitVector(new_v); // Push the new vector r_.push_back(new_v); } } std::vector<float> haloc::Hash::ComputeRandomVector(const int& size, int seed) { std::vector<float> h; for (int i=0; i < size; i++) h.push_back((float)rand()/RAND_MAX); return h; } std::vector<float> haloc::Hash::UnitVector(const std::vector<float>& x) { // Compute the norm float sum = 0.0; for (uint i=0; i < x.size(); i++) sum += pow(x[i], 2.0); float x_norm = sqrt(sum); // x^ = x/|x| std::vector<float> out; for (uint i=0; i < x.size(); i++) out.push_back(x[i] / x_norm); return out; } std::vector<cv::Mat> haloc::Hash::BucketDescriptors( const std::vector<cv::KeyPoint>& kp, const cv::Mat& desc) { // Find max values float u_max = 0; float v_max = 0; std::vector<cv::KeyPoint> kp_in = kp; for (std::vector<cv::KeyPoint>::iterator it = kp_in.begin(); it != kp_in.end(); it++) { if (it->pt.x > u_max) u_max = it->pt.x; if (it->pt.y > v_max) v_max = it->pt.y; } // Compute width and height of the buckets float bucket_width = img_size_.width / params_.bucket_cols; float bucket_height = img_size_.height / params_.bucket_rows; // Allocate number of buckets needed std::vector<cv::Mat> desc_buckets(params_.bucket_cols*params_.bucket_rows); std::vector< std::vector<cv::KeyPoint> > kp_buckets( params_.bucket_cols*params_.bucket_rows); // Assign descriptors to their buckets for (uint i=0; i < kp_in.size(); ++i) { int u = static_cast<int>(floor(kp_in[i].pt.x/bucket_width)); int v = static_cast<int>(floor(kp_in[i].pt.y/bucket_height)); desc_buckets[v*params_.bucket_cols+u].push_back(desc.row(i)); kp_buckets[v*params_.bucket_cols+u].push_back(kp_in[i]); } // The maximum number of features per bucket int max_features_x_bucket = static_cast<int>( floor(params_.max_desc/(params_.bucket_cols*params_.bucket_rows))); // Select the best keypoints for each bucket std::vector<cv::Mat> out_desc(params_.bucket_cols*params_.bucket_rows); for (int i=0; i < params_.bucket_cols*params_.bucket_rows; ++i) { // Sort keypoints by response std::vector<cv::KeyPoint> cur_kps = kp_buckets[i]; std::vector<int> index(cur_kps.size(), 0); for (uint j=0; j<index.size(); j++) { index[j] = j; } std::sort(index.begin(), index.end(), [&](const int& a, const int& b) { return (cur_kps[a].response > cur_kps[b].response); }); // Add up to max_features_x_bucket features from this bucket int k = 0; int num_kp = 0; for (uint j=0; j < cur_kps.size(); ++j) { if (k < max_features_x_bucket) { out_desc[i].push_back(desc_buckets[i].row(index[j])); state_.bucketed_kp.push_back(kp_buckets[i][index[j]]); num_kp++; } else { state_.unbucketed_kp.push_back(kp_buckets[i][index[j]]); } k++; } state_.num_kp_per_bucket.push_back(num_kp); } return out_desc; } std::vector<float> haloc::Hash::ProjectDescriptors(const cv::Mat& desc) { // Initialize first time if (!IsInitialized()) Init(cv::Size(0, 0), desc.rows, desc.cols); // Initialize output std::vector<float> hash; // Sanity checks if (desc.rows == 0) { ROS_ERROR("[Haloc:] ERROR -> Descriptor matrix is empty."); return hash; } if (desc.rows > r_[0].size()) { ROS_ERROR_STREAM("[Haloc:] ERROR -> The number of descriptors is " << "larger than the size of the projection vector. This should not happen."); return hash; } // Project the descriptors for (uint i=0; i < r_.size(); i++) { for (int n=0; n < desc.cols; n++) { float desc_sum = 0.0; for (uint m=0; m < desc.rows; m++) { float projected = r_[i][m]*desc.at<float>(m, n); float projected_normalized = (projected + 1.0) / 2.0; desc_sum += projected_normalized; } hash.push_back(desc_sum / static_cast<float>(desc.rows)); } } return hash; }
{ "content_hash": "04cec2f3e16343355e8a19080df968ad", "timestamp": "", "source": "github", "line_count": 304, "max_line_length": 80, "avg_line_length": 32.48026315789474, "alnum_prop": 0.6080615758557829, "repo_name": "srv/libhaloc", "id": "727b3c95f293ac4b7f8133863209ab80e25da7ad", "size": "10697", "binary": false, "copies": "1", "ref": "refs/heads/kinetic", "path": "src/hash.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C++", "bytes": "23604" }, { "name": "CMake", "bytes": "2003" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>mathcomp-fingroup: Not compatible</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.13.0 / mathcomp-fingroup - 1.6.4</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> mathcomp-fingroup <small> 1.6.4 <span class="label label-info">Not compatible</span> </small> </h1> <p><em><script>document.write(moment("2021-04-16 16:56:55 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2021-04-16 16:56:55 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-gmp 3 Virtual package relying on a GMP lib system installation coq 8.13.0 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.11.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.11.1 Official release 4.11.1 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.1 A library manager for OCaml zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers # opam file: opam-version: &quot;2.0&quot; name: &quot;coq-mathcomp-fingroup&quot; version: &quot;1.6.4&quot; maintainer: &quot;Mathematical Components &lt;mathcomp-dev@sympa.inria.fr&gt;&quot; homepage: &quot;http://math-comp.github.io/math-comp/&quot; bug-reports: &quot;Mathematical Components &lt;mathcomp-dev@sympa.inria.fr&gt;&quot; license: &quot;CeCILL-B&quot; build: [ make &quot;-C&quot; &quot;mathcomp/fingroup&quot; &quot;-j&quot; &quot;%{jobs}%&quot; ] install: [ make &quot;-C&quot; &quot;mathcomp/fingroup&quot; &quot;install&quot; ] remove: [ &quot;sh&quot; &quot;-c&quot; &quot;rm -rf &#39;%{lib}%/coq/user-contrib/mathcomp/fingroup&#39;&quot; ] depends: [ &quot;ocaml&quot; &quot;coq-mathcomp-ssreflect&quot; {= &quot;1.6.4&quot;} ] tags: [ &quot;keyword:finite groups&quot; &quot;keyword:small scale reflection&quot; &quot;keyword:mathematical components&quot; &quot;keyword:odd order theorem&quot; ] authors: [ &quot;Jeremy Avigad &lt;&gt;&quot; &quot;Andrea Asperti &lt;&gt;&quot; &quot;Stephane Le Roux &lt;&gt;&quot; &quot;Yves Bertot &lt;&gt;&quot; &quot;Laurence Rideau &lt;&gt;&quot; &quot;Enrico Tassi &lt;&gt;&quot; &quot;Ioana Pasca &lt;&gt;&quot; &quot;Georges Gonthier &lt;&gt;&quot; &quot;Sidi Ould Biha &lt;&gt;&quot; &quot;Cyril Cohen &lt;&gt;&quot; &quot;Francois Garillot &lt;&gt;&quot; &quot;Alexey Solovyev &lt;&gt;&quot; &quot;Russell O&#39;Connor &lt;&gt;&quot; &quot;Laurent Théry &lt;&gt;&quot; &quot;Assia Mahboubi &lt;&gt;&quot; ] synopsis: &quot;Mathematical Components Library on finite groups&quot; description: &quot;&quot;&quot; This library contains definitions and theorems about finite groups, group quotients, group morphisms, group presentation, group action...&quot;&quot;&quot; url { src: &quot;http://github.com/math-comp/math-comp/archive/mathcomp-1.6.4.tar.gz&quot; checksum: &quot;md5=29362a734d183301e2ce839b0ad14bd9&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-mathcomp-fingroup.1.6.4 coq.8.13.0</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.13.0). The following dependencies couldn&#39;t be met: - coq-mathcomp-fingroup -&gt; coq-mathcomp-ssreflect = 1.6.4 -&gt; coq &lt; 8.8~ -&gt; ocaml &lt; 4.10 base of this switch (use `--unlock-base&#39; to force) No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-mathcomp-fingroup.1.6.4</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> <small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small> </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "ce478c2e0569edc05248f32967f176b8", "timestamp": "", "source": "github", "line_count": 164, "max_line_length": 554, "avg_line_length": 46.96341463414634, "alnum_prop": 0.5614126200986757, "repo_name": "coq-bench/coq-bench.github.io", "id": "8ec8a5d6d072a06e4fa35b56795157460d6d0239", "size": "7705", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.11.1-2.0.7/released/8.13.0/mathcomp-fingroup/1.6.4.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "06a62842c469e6fe37f95b6f21bae2e1", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "7a784ff0bf8a83cbe1ef3b97b4512ca5218619c6", "size": "171", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Laurales/Lauraceae/Ocotea/Ocotea ovalifolia/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package org.elasticsearch.test.unit.index.cache.filter; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.TextField; import org.apache.lucene.index.*; import org.apache.lucene.search.ConstantScoreQuery; import org.apache.lucene.search.Filter; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.MatchAllDocsQuery; import org.apache.lucene.store.Directory; import org.apache.lucene.store.RAMDirectory; import org.elasticsearch.common.lucene.Lucene; import org.elasticsearch.common.lucene.search.TermFilter; import org.elasticsearch.common.lucene.search.XConstantScoreQuery; import org.elasticsearch.common.lucene.search.XFilteredQuery; import org.elasticsearch.index.Index; import org.elasticsearch.index.cache.filter.FilterCache; import org.elasticsearch.index.cache.filter.none.NoneFilterCache; import org.testng.annotations.Test; import java.io.IOException; import static org.elasticsearch.common.settings.ImmutableSettings.Builder.EMPTY_SETTINGS; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; /** * */ public class FilterCacheTests { @Test public void testNoCache() throws Exception { verifyCache(new NoneFilterCache(new Index("test"), EMPTY_SETTINGS)); } private void verifyCache(FilterCache filterCache) throws Exception { Directory dir = new RAMDirectory(); IndexWriter indexWriter = new IndexWriter(dir, new IndexWriterConfig(Lucene.VERSION, Lucene.STANDARD_ANALYZER)); DirectoryReader reader = IndexReader.open(indexWriter, true); for (int i = 0; i < 100; i++) { Document document = new Document(); document.add(new TextField("id", Integer.toString(i), Field.Store.YES)); indexWriter.addDocument(document); } reader = refreshReader(reader); IndexSearcher searcher = new IndexSearcher(reader); assertThat(Lucene.count(searcher, new ConstantScoreQuery(filterCache.cache(new TermFilter(new Term("id", "1"))))), equalTo(1l)); assertThat(Lucene.count(searcher, new XFilteredQuery(new MatchAllDocsQuery(), filterCache.cache(new TermFilter(new Term("id", "1"))))), equalTo(1l)); indexWriter.deleteDocuments(new Term("id", "1")); reader = refreshReader(reader); searcher = new IndexSearcher(reader); TermFilter filter = new TermFilter(new Term("id", "1")); Filter cachedFilter = filterCache.cache(filter); long constantScoreCount = filter == cachedFilter ? 0 : 1; // sadly, when caching based on cacheKey with NRT, this fails, that's why we have DeletionAware one assertThat(Lucene.count(searcher, new ConstantScoreQuery(cachedFilter)), equalTo(constantScoreCount)); assertThat(Lucene.count(searcher, new XConstantScoreQuery(cachedFilter)), equalTo(0l)); assertThat(Lucene.count(searcher, new XFilteredQuery(new MatchAllDocsQuery(), cachedFilter)), equalTo(0l)); indexWriter.close(); } private DirectoryReader refreshReader(DirectoryReader reader) throws IOException { IndexReader oldReader = reader; reader = DirectoryReader.openIfChanged(reader); if (reader != oldReader) { oldReader.close(); } return reader; } }
{ "content_hash": "462748537993a252d28f16d751816f4e", "timestamp": "", "source": "github", "line_count": 79, "max_line_length": 157, "avg_line_length": 42.58227848101266, "alnum_prop": 0.7321640903686087, "repo_name": "dongaihua/highlight-elasticsearch", "id": "921fbd4b49ee6c4f55b908e6ffdfb8355e27dfa9", "size": "4169", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/test/java/org/elasticsearch/test/unit/index/cache/filter/FilterCacheTests.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "15890580" }, { "name": "Shell", "bytes": "12355" } ], "symlink_target": "" }
<div class = 'dashboardView'> <div class = 'dashboardMenu'> <h3>{{username}}</h3> <ul id = 'navTools'> <li><p id = 'waiting' data-forElement = 'all'>all rides</p></li> <li><p id = 'confirmed' data-forElement = 'confirmed'>confirmed rides</p></li> <li><p id = 'pending' data-forElement = 'notConfirmed'>pending rides</p></li> <li><p id = "createRoute" data-forElement = 'routeForm'>Create Ride</p></li> </ul> </div> <div class = 'sideBuffer'></div> <div class = 'container'> <div class = 'routeForm' style="display: none;"> <form> <div class = 'location'> <label><input class = 'userInput' id = 'startAddress' placeholder = 'Start Address' type="text"></label> <label><input class = 'userInput'id = 'endAddress' placeholder = 'End Address' type="text"></label> </div> <div class = 'timeField'> <label for = 'fromTime'>Leaving between<input id="fromTime" type="text" class="userInput time ui-timepicker-input" autocomplete="off"></label> <label for = 'toTime'>and<input id="toTime" type="text" class="userInput time ui-timepicker-input" autocomplete="off"></label> </div> <div class = 'days'> <span class = 'dayToggle' id = 'sunday'>Su</span> <span class = 'dayToggle' id = 'monday'>M</span> <span class = 'dayToggle' id = 'tuesday'>Tu</span> <span class = 'dayToggle' id = 'wednesday'>W</span> <span class = 'dayToggle' id = 'thursday'>Th</span> <span class = 'dayToggle' id = 'friday'>F</span> <span class = 'dayToggle' id = 'saturday'>Sa</span> </div> <div class = 'driver'> <span class = 'driverToggle'>I am driving</span> <input class = 'isDriver' style="display: none;" id = 'seats' placeholder = 'Open seats' type="text"> <input class = 'isDriver' style="display: none;" id = 'fee' placeholder="Fee per ride" type="text"> </div> <div class = 'submit'> <span class = 'submitRoute' ng-click= "submitRoute()">Submit</span> </div> </form> </div> <div class = 'allRoutes' > <div class = 'noRouteMessage' ng-hide= "passengerRoutes[0]"><p> You have no routes created. Go make your first one!</p></div> <ul ng-repeat= 'route in passengerRoutes track by $index' ng-hide= "user.IsDriver"> <li> <div class='routeRender' ng-class="route.confirmedDriverRoute ? 'confirmed' : 'notConfirmed'"> <div class = 'rideInfo'> <p class = 'from'><b>{{route.startLabel}}</b> to <b>{{route.endLabel}}</b></p> <p class = 'timeWindow'> Leaving between <b>{{route.fromHour > 12 ? route.fromHour-12 : route.fromHour}}:{{route.fromHour > 11 ? route.fromMinutes + "PM" : route.fromMinutes + "AM"}}</b> and <b>{{route.toHour > 12 ? route.toHour-12 : route.toHour}}:{{route.toHour > 11 ? route.fromMinutes + "PM" : route.fromMinutes + "AM"}}</b></p> <p class = 'noDrivers' ng-hide= "route.confirmedDriverRoute"><i> No drivers have accepted the ride yet. </i></p> </div> <div class = 'selectedDays'> <ul><li ng-repeat= 'day in route.days' ><div class = 'singleDay'>{{day}}</div></li></ul> <div ng-show= "route.confirmedDriverRoute" class= 'driverInfo'> <p>{{route.confirmedDriverRoute.driverInformation.name}}</p> <p>{{route.confirmedDriverRoute.driverInformation.phoneNumber}}</p> <img ng-src= {{route.confirmedDriverRoute.driverInformation.picture}} /> </div> </div> </div> </div> </li> </ul> <div ng-repeat= 'route in driverRoutes track by $index' ng-show= "user.IsDriver"> <div class = 'singleRoute'> <div class='routeRender'> <p class = 'from'>From: {{route.startLabel}}</p> <p class = 'to'>To: {{route.endLabel}}</p> <p class = 'time'> Leaving between {{route.fromHour > 12 ? route.fromHour-12 : route.fromHour}}:{{route.fromHour > 11 ? route.fromMinutes + "PM" : route.fromMinutes + "AM"}} and {{route.toHour > 12 ? route.toHour-12 : route.toHour}}:{{route.toHour > 11 ? route.fromMinutes + "PM" : route.fromMinutes + "AM"}}</p> <p class = 'days'>{{route.days}}</p> </div> <span ng-show= "route.confirmedPassengerRoutes.length > 0">Confirmed Passengers:</span> <div ng-repeat='confirmedRoute in route.confirmedPassengerRoutes track by $index'> <div class = 'driverInfo confirmedPassenger'> <img ng-src= {{confirmedRoute.passengerInformation.picture}} /> <div class = 'nameDays'> <p>{{confirmedRoute.passengerInformation.name}}</p> <p> Driving: {{confirmedRoute.days}}</p> </div> <div class = 'startEnd'> <p> Leaving between {{route.fromHour > 12 ? route.fromHour-12 : route.fromHour}}:{{route.fromHour > 11 ? route.fromMinutes + "PM" : route.fromMinutes + "AM"}} and {{route.toHour > 12 ? route.toHour-12 : route.toHour}}:{{route.toHour > 11 ? route.fromMinutes + "PM" : route.fromMinutes + "AM"}}</p> <p>From: {{confirmedRoute.startLabel}}</p> <p>To: {{confirmedRoute.endLabel}}</p> </div> </div> </div> <span ng-show= "route.prospectivePassengerRoutes.length > 0">Prospective Passengers:</span> <span ng-show= "route.prospectivePassengerRoutes.length <= 0">No Prospective Passengers</span> <div ng-repeat='prospectiveRoute in route.prospectivePassengerRoutes track by $index'> <div class = 'driverInfo notConfirmed' ng-click="confirmPassenger(prospectiveRoute._id, route._id)"> <img ng-src= {{confirmedRoute.passengerInformation.picture}} /> <div class = 'nameDays'> <p>{{confirmedRoute.passengerInformation.name}}</p> <p> Driving: {{confirmedRoute.days}}</p> </div> <div class = 'startEnd'> <p>{{confirmedRoute.fromHour}}:{{confirmedRoute.fromMinutes}} and {{confirmedRoute.toHour}}:{{confirmedRoute.toMinutes}}</p> <p>From: {{confirmedRoute.startLabel}}</p> <p>To: {{confirmedRoute.endLabel}}</p> </div> </div> </div> </div> <br> <hr> </div> </div> </div> </div>
{ "content_hash": "6996387d7f613d619711e5ee4f9f13b9", "timestamp": "", "source": "github", "line_count": 114, "max_line_length": 339, "avg_line_length": 52.53508771929825, "alnum_prop": 0.6236433461345801, "repo_name": "OpenSeatApp/openseat", "id": "610610b8e42e5d665846109a4051729a41978046", "size": "5989", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "client/components/dashboard/dashboardView.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4211" }, { "name": "HTML", "bytes": "7118" }, { "name": "JavaScript", "bytes": "33419" } ], "symlink_target": "" }
import collections requirements = None db = None db_url = None db_opts = None file_config = None test_schema = None test_schema_2 = None _current = None _fixture_functions = None # installed by plugin_base def combinations(*comb, **kw): r"""Deliver multiple versions of a test based on positional combinations. This is a facade over pytest.mark.parametrize. :param \*comb: argument combinations. These are tuples that will be passed positionally to the decorated function. :param argnames: optional list of argument names. These are the names of the arguments in the test function that correspond to the entries in each argument tuple. pytest.mark.parametrize requires this, however the combinations function will derive it automatically if not present by using ``inspect.getfullargspec(fn).args[1:]``. Note this assumes the first argument is "self" which is discarded. :param id\_: optional id template. This is a string template that describes how the "id" for each parameter set should be defined, if any. The number of characters in the template should match the number of entries in each argument tuple. Each character describes how the corresponding entry in the argument tuple should be handled, as far as whether or not it is included in the arguments passed to the function, as well as if it is included in the tokens used to create the id of the parameter set. If omitted, the argument combinations are passed to parametrize as is. If passed, each argument combination is turned into a pytest.param() object, mapping the elements of the argument tuple to produce an id based on a character value in the same position within the string template using the following scheme:: i - the given argument is a string that is part of the id only, don't pass it as an argument n - the given argument should be passed and it should be added to the id by calling the .__name__ attribute r - the given argument should be passed and it should be added to the id by calling repr() s - the given argument should be passed and it should be added to the id by calling str() a - (argument) the given argument should be passed and it should not be used to generated the id e.g.:: @testing.combinations( (operator.eq, "eq"), (operator.ne, "ne"), (operator.gt, "gt"), (operator.lt, "lt"), id_="na" ) def test_operator(self, opfunc, name): pass The above combination will call ``.__name__`` on the first member of each tuple and use that as the "id" to pytest.param(). """ return _fixture_functions.combinations(*comb, **kw) def fixture(*arg, **kw): return _fixture_functions.fixture(*arg, **kw) def get_current_test_name(): return _fixture_functions.get_current_test_name() class Config(object): def __init__(self, db, db_opts, options, file_config): self._set_name(db) self.db = db self.db_opts = db_opts self.options = options self.file_config = file_config self.test_schema = "test_schema" self.test_schema_2 = "test_schema_2" _stack = collections.deque() _configs = set() def _set_name(self, db): if db.dialect.server_version_info: svi = ".".join(str(tok) for tok in db.dialect.server_version_info) self.name = "%s+%s_[%s]" % (db.name, db.driver, svi) else: self.name = "%s+%s" % (db.name, db.driver) @classmethod def register(cls, db, db_opts, options, file_config): """add a config as one of the global configs. If there are no configs set up yet, this config also gets set as the "_current". """ cfg = Config(db, db_opts, options, file_config) cls._configs.add(cfg) return cfg @classmethod def set_as_current(cls, config, namespace): global db, _current, db_url, test_schema, test_schema_2, db_opts _current = config db_url = config.db.url db_opts = config.db_opts test_schema = config.test_schema test_schema_2 = config.test_schema_2 namespace.db = db = config.db @classmethod def push_engine(cls, db, namespace): assert _current, "Can't push without a default Config set up" cls.push( Config( db, _current.db_opts, _current.options, _current.file_config ), namespace, ) @classmethod def push(cls, config, namespace): cls._stack.append(_current) cls.set_as_current(config, namespace) @classmethod def reset(cls, namespace): if cls._stack: cls.set_as_current(cls._stack[0], namespace) cls._stack.clear() @classmethod def all_configs(cls): return cls._configs @classmethod def all_dbs(cls): for cfg in cls.all_configs(): yield cfg.db def skip_test(self, msg): skip_test(msg) def skip_test(msg): raise _fixture_functions.skip_test_exception(msg)
{ "content_hash": "7c4174abcc0cb3c240cc3dd14a9a593f", "timestamp": "", "source": "github", "line_count": 165, "max_line_length": 79, "avg_line_length": 32.018181818181816, "alnum_prop": 0.6293772477758849, "repo_name": "kawamon/hue", "id": "140f5f782421e97024b9988bd13d28e6f25a3b20", "size": "5521", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "desktop/core/ext-py/SQLAlchemy-1.3.17/lib/sqlalchemy/testing/config.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ABAP", "bytes": "962" }, { "name": "ActionScript", "bytes": "1133" }, { "name": "Ada", "bytes": "99" }, { "name": "Assembly", "bytes": "5786" }, { "name": "AutoHotkey", "bytes": "720" }, { "name": "Batchfile", "bytes": "118907" }, { "name": "C", "bytes": "3196521" }, { "name": "C#", "bytes": "83" }, { "name": "C++", "bytes": "308860" }, { "name": "COBOL", "bytes": "4" }, { "name": "CSS", "bytes": "1050129" }, { "name": "Cirru", "bytes": "520" }, { "name": "Clojure", "bytes": "794" }, { "name": "CoffeeScript", "bytes": "403" }, { "name": "ColdFusion", "bytes": "86" }, { "name": "Common Lisp", "bytes": "632" }, { "name": "D", "bytes": "324" }, { "name": "Dart", "bytes": "489" }, { "name": "Dockerfile", "bytes": "10981" }, { "name": "Eiffel", "bytes": "375" }, { "name": "Elixir", "bytes": "692" }, { "name": "Elm", "bytes": "487" }, { "name": "Emacs Lisp", "bytes": "411907" }, { "name": "Erlang", "bytes": "487" }, { "name": "Forth", "bytes": "979" }, { "name": "FreeMarker", "bytes": "1017" }, { "name": "G-code", "bytes": "521" }, { "name": "GLSL", "bytes": "512" }, { "name": "Genshi", "bytes": "946" }, { "name": "Gherkin", "bytes": "699" }, { "name": "Go", "bytes": "7312" }, { "name": "Groovy", "bytes": "1080" }, { "name": "HTML", "bytes": "24999718" }, { "name": "Haskell", "bytes": "512" }, { "name": "Haxe", "bytes": "447" }, { "name": "HiveQL", "bytes": "43" }, { "name": "Io", "bytes": "140" }, { "name": "JSONiq", "bytes": "4" }, { "name": "Java", "bytes": "471854" }, { "name": "JavaScript", "bytes": "28075556" }, { "name": "Julia", "bytes": "210" }, { "name": "Jupyter Notebook", "bytes": "73168" }, { "name": "LSL", "bytes": "2080" }, { "name": "Lean", "bytes": "213" }, { "name": "Lex", "bytes": "264449" }, { "name": "Liquid", "bytes": "1883" }, { "name": "LiveScript", "bytes": "5747" }, { "name": "Lua", "bytes": "78382" }, { "name": "M4", "bytes": "1377" }, { "name": "MATLAB", "bytes": "203" }, { "name": "Makefile", "bytes": "269655" }, { "name": "Mako", "bytes": "3614942" }, { "name": "Mask", "bytes": "597" }, { "name": "Myghty", "bytes": "936" }, { "name": "Nix", "bytes": "2212" }, { "name": "OCaml", "bytes": "539" }, { "name": "Objective-C", "bytes": "2672" }, { "name": "OpenSCAD", "bytes": "333" }, { "name": "PHP", "bytes": "662" }, { "name": "PLSQL", "bytes": "31565" }, { "name": "PLpgSQL", "bytes": "6006" }, { "name": "Pascal", "bytes": "1412" }, { "name": "Perl", "bytes": "4327" }, { "name": "PigLatin", "bytes": "371" }, { "name": "PowerShell", "bytes": "3204" }, { "name": "Python", "bytes": "76440000" }, { "name": "R", "bytes": "2445" }, { "name": "Roff", "bytes": "95764" }, { "name": "Ruby", "bytes": "1098" }, { "name": "Rust", "bytes": "495" }, { "name": "Scala", "bytes": "1541" }, { "name": "Scheme", "bytes": "559" }, { "name": "Shell", "bytes": "190718" }, { "name": "Smarty", "bytes": "130" }, { "name": "TSQL", "bytes": "10013" }, { "name": "Tcl", "bytes": "899" }, { "name": "TeX", "bytes": "165743" }, { "name": "Thrift", "bytes": "317058" }, { "name": "TypeScript", "bytes": "1607" }, { "name": "VBA", "bytes": "2884" }, { "name": "VBScript", "bytes": "938" }, { "name": "VHDL", "bytes": "830" }, { "name": "Vala", "bytes": "485" }, { "name": "Verilog", "bytes": "274" }, { "name": "Vim Snippet", "bytes": "226931" }, { "name": "XQuery", "bytes": "114" }, { "name": "XSLT", "bytes": "521413" }, { "name": "Yacc", "bytes": "2133855" } ], "symlink_target": "" }
package com.laixl.coolweather.activity; import android.app.Activity; import android.app.ProgressDialog; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.laixl.coolweather.R; import com.laixl.coolweather.db.CoolWeatherDB; import com.laixl.coolweather.model.City; import com.laixl.coolweather.model.County; import com.laixl.coolweather.model.Province; import com.laixl.coolweather.util.HttpCallbackListener; import com.laixl.coolweather.util.HttpUtil; import com.laixl.coolweather.util.Utility; import java.util.ArrayList; import java.util.List; /** * Created by Administrator on 2015/7/1. */ public class ChooseAreaActivity extends Activity { public static final int LEVEL_PROVINCE = 0; public static final int LEVEL_CITY = 1; public static final int LEVEL_COUNTY = 2; private ProgressDialog progressDialog; private TextView titleText; private ListView listView; private ArrayAdapter<String> adapter; private CoolWeatherDB coolWeatherDB; private List<String> dataList = new ArrayList<String>(); /** * 省列表 */ private List<Province> provincesList; /** * 市列表 */ private List<City> cityList; /** * 省列表 */ private List<County> countyList; /** * 选中的省份 */ private Province selectedProvince; /** * 选中的城市 */ private City selectedCity; /** * 当前选中的级别 */ private int currentLevel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.choose_area); listView = (ListView) findViewById(R.id.list_view); titleText = (TextView) findViewById(R.id.title_text); adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dataList); listView.setAdapter(adapter); coolWeatherDB = CoolWeatherDB.getInstance(this); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (currentLevel == LEVEL_PROVINCE) { selectedProvince = provincesList.get(position); queryCities(); } else if (currentLevel == LEVEL_CITY) { selectedCity = cityList.get(position); queryCounties(); } } }); queryProvinces(); // 加载省级数据 } /** * 查询全国所有的省,优先从数据库查询,如果没有查询到再去服务器上查询 */ private void queryProvinces() { provincesList = coolWeatherDB.loadProvinces(); if (provincesList.size() > 0) { dataList.clear(); for (Province province : provincesList) { dataList.add(province.getProvinceName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); titleText.setText("中国"); currentLevel = LEVEL_PROVINCE; } else { queryFromService(null, "province"); } } /** * 查询全国所有的市,优先从数据库查询,如果没有查询到再去服务器上查询 */ private void queryCities() { cityList = coolWeatherDB.loadCities(selectedProvince.getId()); if (cityList.size() > 0) { dataList.clear(); for (City city : cityList) { dataList.add(city.getCityName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); titleText.setText(selectedProvince.getProvinceName()); currentLevel = LEVEL_CITY; } else { queryFromService(selectedProvince.getProvinceCode(), "city"); } } /** * 查询全国所有的县,优先从数据库查询,如果没有查询到再去服务器上查询 */ private void queryCounties() { countyList = coolWeatherDB.loadCounties(selectedCity.getId()); if (countyList.size() > 0) { dataList.clear(); for (County county : countyList) { dataList.add(county.getCountyName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); titleText.setText(selectedCity.getCityName()); currentLevel = LEVEL_COUNTY; } else { queryFromService(selectedCity.getCityCode(), "county"); } } /** * 根据传入的代号和类型从服务器上查询省市县数据 */ private void queryFromService(final String code, final String type) { String address; if ( !TextUtils.isEmpty(code) ) { address = "http://www.weather.com.cn/data/list3/city" + code + ".xml"; } else { address = "http://www.weather.com.cn/data/list3/city.xml"; } showProgressDialog(); HttpUtil.sendHttpRequest(address, new HttpCallbackListener() { @Override public void onFinish(String response) { boolean result = false; if ("province".equals(type)) { result = Utility.handleProvincesResponse(coolWeatherDB, response); } else if ("city".equals(type)) { result = Utility.handleCitiesResponse(coolWeatherDB, response, selectedProvince.getId()); } else if ("county".equals(type)) { result = Utility.handleCountiesResponse(coolWeatherDB, response, selectedCity.getId()); } if (result) { // 通过runOnUiThread()方法回到主线程处理逻辑 runOnUiThread(new Runnable() { @Override public void run() { closeProgressDialog(); if ("province".equals(type)) { queryProvinces(); } else if ("city".equals(type)) { queryCities(); } else if ("county".equals(type)) { queryCounties(); } } }); } } @Override public void onError(Exception e) { // 通过runOnUiThread()方法回到主线程处理逻辑 runOnUiThread(new Runnable() { @Override public void run() { closeProgressDialog(); Toast.makeText(ChooseAreaActivity.this, "加载失败", Toast.LENGTH_SHORT).show(); } }); } }); } /** * 显示进度对话框 */ private void showProgressDialog() { if (progressDialog == null) { progressDialog = new ProgressDialog(this); progressDialog.setMessage("正在加载中..."); progressDialog.setCanceledOnTouchOutside(false); } progressDialog.show(); } /** * 关闭进度对话框 */ private void closeProgressDialog() { if (progressDialog != null) { progressDialog.dismiss(); } } /** * 捕获Back按键,根据当前的级别赖判断,此时应该返回市列表、省列表、还是直接退出 */ @Override public void onBackPressed() { if (currentLevel == LEVEL_COUNTY) { queryCities(); } else if (currentLevel == LEVEL_CITY) { queryProvinces(); } else { finish(); } } }
{ "content_hash": "7387a234808563ab9090cf5db373e170", "timestamp": "", "source": "github", "line_count": 247, "max_line_length": 96, "avg_line_length": 31.356275303643724, "alnum_prop": 0.5535183989670756, "repo_name": "tincat85/coolweather", "id": "dc91e83361b9cff639365f58c604b723443a21eb", "size": "8225", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/laixl/coolweather/activity/ChooseAreaActivity.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "22380" } ], "symlink_target": "" }
function Test-DbaMigrationConstraint { <# .SYNOPSIS Show if you can migrate the database(s) between the servers. .DESCRIPTION When you want to migrate from a higher edition to a lower one there are some features that can't be used. This function will validate if you have any of this features in use and will report to you. The validation will be made ONLY on on SQL Server 2008 or higher using the 'sys.dm_db_persisted_sku_features' dmv. This function only validate SQL Server 2008 versions or higher. The editions supported by this function are: - Enterprise - Developer - Evaluation - Standard - Express Take into account the new features introduced on SQL Server 2016 SP1 for all versions. More information at https://blogs.msdn.microsoft.com/sqlreleaseservices/sql-server-2016-service-pack-1-sp1-released/ The -Database parameter is auto-populated for command-line completion. .PARAMETER Source Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher. .PARAMETER SourceSqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. .PARAMETER Destination Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher. .PARAMETER DestinationSqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. .PARAMETER Database The database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed. .PARAMETER ExcludeDatabase The database(s) to exclude. Options for this list are auto-populated from the server. .PARAMETER EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch. .NOTES Tags: Migration Author: Claudio Silva (@ClaudioESSilva) Website: https://dbatools.io Copyright: (c) 2018 by dbatools, licensed under MIT License: MIT https://opensource.org/licenses/MIT .LINK https://dbatools.io/Test-DbaMigrationConstraint .EXAMPLE PS C:\> Test-DbaMigrationConstraint -Source sqlserver2014a -Destination sqlcluster All databases on sqlserver2014a will be verified for features in use that can't be supported on sqlcluster. .EXAMPLE PS C:\> Test-DbaMigrationConstraint -Source sqlserver2014a -Destination sqlcluster -SourceSqlCredential $cred All databases will be verified for features in use that can't be supported on the destination server. SQL credentials are used to authenticate against sqlserver2014a and Windows Authentication is used for sqlcluster. .EXAMPLE PS C:\> Test-DbaMigrationConstraint -Source sqlserver2014a -Destination sqlcluster -Database db1 Only db1 database will be verified for features in use that can't be supported on the destination server. #> [CmdletBinding(DefaultParameterSetName = "DbMigration")] param ( [parameter(Mandatory, ValueFromPipeline)] [DbaInstance]$Source, [PSCredential]$SourceSqlCredential, [parameter(Mandatory)] [DbaInstance]$Destination, [PSCredential]$DestinationSqlCredential, [object[]]$Database, [object[]]$ExcludeDatabase, [switch]$EnableException ) begin { <# 1804890536 = Enterprise 1872460670 = Enterprise Edition: Core-based Licensing 610778273 = Enterprise Evaluation 284895786 = Business Intelligence -2117995310 = Developer -1592396055 = Express -133711905= Express with Advanced Services -1534726760 = Standard 1293598313 = Web 1674378470 = SQL Database #> $editions = @{ "Enterprise" = 10; "Developer" = 10; "Evaluation" = 10; "Standard" = 5; "Express" = 1 } $notesCanMigrate = "Database can be migrated." $notesCannotMigrate = "Database cannot be migrated." } process { try { $sourceServer = Connect-DbaInstance -SqlInstance $Source -SqlCredential $SourceSqlCredential } catch { Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $Source } try { $destServer = Connect-DbaInstance -SqlInstance $Destination -SqlCredential $DestinationSqlCredential } catch { Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $Destination } if (-Not $Database) { $Database = $sourceServer.Databases | Where-Object IsSystemObject -eq 0 | Select-Object Name, Status } if ($ExcludeDatabase) { $Database = $sourceServer.Databases | Where-Object Name -NotIn $ExcludeDatabase } if ($Database.Count -gt 0) { if ($Database -in @("master", "msdb", "tempdb")) { Stop-Function -Message "Migrating system databases is not currently supported." return } if ($sourceServer.VersionMajor -lt 9 -and $destServer.VersionMajor -gt 10) { Stop-Function -Message "Sql Server 2000 databases cannot be migrated to SQL Server version 2012 and above. Quitting." return } if ($sourceServer.Collation -ne $destServer.Collation) { Write-Message -Level Warning -Message "Collation on $Source, $($sourceServer.collation) differs from the $Destination, $($destServer.collation)." } if ($sourceServer.VersionMajor -gt $destServer.VersionMajor) { #indicate they must use 'Generate Scripts' and 'Export Data' options? Stop-Function -Message "You can't migrate databases from a higher version to a lower one. Quitting." return } if ($sourceServer.VersionMajor -lt 10) { Stop-Function -Message "This function does not support versions lower than SQL Server 2008 (v10)" return } #if editions differs, from higher to lower one, verify the sys.dm_db_persisted_sku_features - only available from SQL 2008 + if (($sourceServer.VersionMajor -ge 10 -and $destServer.VersionMajor -ge 10)) { foreach ($db in $Database) { if ([string]::IsNullOrEmpty($db.Status)) { $dbstatus = ($sourceServer.Databases | Where-Object Name -eq $db).Status.ToString() $dbName = $db } else { $dbstatus = $db.Status.ToString() $dbName = $db.Name } Write-Message -Level Verbose -Message "Checking database '$dbName'." if ($dbstatus.Contains("Offline") -eq $false -or $db.IsAccessible -eq $true) { [long]$destVersionNumber = $($destServer.VersionString).Replace(".", "") [string]$sourceVersion = "$($sourceServer.Edition) $($sourceServer.ProductLevel) ($($sourceServer.Version))" [string]$destVersion = "$($destServer.Edition) $($destServer.ProductLevel) ($($destServer.Version))" [string]$dbFeatures = "" #Check if database has any FILESTREAM filegroup Write-Message -Level Verbose -Message "Checking if FileStream is in use for database '$dbName'." if ($sourceServer.Databases[$dbName].FileGroups | Where-Object FileGroupType -eq 'FileStreamDataFileGroup') { Write-Message -Level Verbose -Message "Found FileStream filegroup and files." $fileStreamSource = Get-DbaSpConfigure -SqlInstance $sourceServer -ConfigName FilestreamAccessLevel $fileStreamDestination = Get-DbaSpConfigure -SqlInstance $destServer -ConfigName FilestreamAccessLevel if ($fileStreamSource.RunningValue -ne $fileStreamDestination.RunningValue) { [pscustomobject]@{ SourceInstance = $sourceServer.Name DestinationInstance = $destServer.Name SourceVersion = $sourceVersion DestinationVersion = $destVersion Database = $dbName FeaturesInUse = $dbFeatures IsMigratable = $false Notes = "$notesCannotMigrate. Destination server dones not have the 'FilestreamAccessLevel' configuration (RunningValue: $($fileStreamDestination.RunningValue)) equal to source server (RunningValue: $($fileStreamSource.RunningValue))." } Continue } } try { $sql = "SELECT feature_name FROM sys.dm_db_persisted_sku_features" $skuFeatures = $sourceServer.Query($sql, $dbName) Write-Message -Level Verbose -Message "Checking features in use..." if (@($skuFeatures).Count -gt 0) { foreach ($row in $skuFeatures) { $dbFeatures += ",$($row["feature_name"])" } $dbFeatures = $dbFeatures.TrimStart(",") } } catch { Stop-Function -Message "Issue collecting sku features." -ErrorRecord $_ -Target $sourceServer -Continue } #If SQL Server 2016 SP1 (13.0.4001.0) or higher if ($destVersionNumber -ge 13040010) { <# Need to verify if Edition = EXPRESS and database uses 'Change Data Capture' (CDC) This means that database cannot be migrated because Express edition doesn't have SQL Server Agent #> if ($editions.Item($destServer.Edition.ToString().Split(" ")[0]) -eq 1 -and $dbFeatures.Contains("ChangeCapture")) { [pscustomobject]@{ SourceInstance = $sourceServer.Name DestinationInstance = $destServer.Name SourceVersion = $sourceVersion DestinationVersion = $destVersion Database = $dbName FeaturesInUse = $dbFeatures IsMigratable = $false Notes = "$notesCannotMigrate. Destination server edition is EXPRESS which does not support 'ChangeCapture' feature that is in use." } } else { [pscustomobject]@{ SourceInstance = $sourceServer.Name DestinationInstance = $destServer.Name SourceVersion = $sourceVersion DestinationVersion = $destVersion Database = $dbName FeaturesInUse = $dbFeatures IsMigratable = $true Notes = $notesCanMigrate } } } #Version is lower than SQL Server 2016 SP1 else { Write-Message -Level Verbose -Message "Source Server Edition: $($sourceServer.Edition) (Weight: $($editions.Item($sourceServer.Edition.ToString().Split(" ")[0])))" Write-Message -Level Verbose -Message "Destination Server Edition: $($destServer.Edition) (Weight: $($editions.Item($destServer.Edition.ToString().Split(" ")[0])))" #Check for editions. If destination edition is lower than source edition and exists features in use if (($editions.Item($destServer.Edition.ToString().Split(" ")[0]) -lt $editions.Item($sourceServer.Edition.ToString().Split(" ")[0])) -and (!([string]::IsNullOrEmpty($dbFeatures)))) { [pscustomobject]@{ SourceInstance = $sourceServer.Name DestinationInstance = $destServer.Name SourceVersion = $sourceVersion DestinationVersion = $destVersion Database = $dbName FeaturesInUse = $dbFeatures IsMigratable = $false Notes = "$notesCannotMigrate There are features in use not available on destination instance." } } # else { [pscustomobject]@{ SourceInstance = $sourceServer.Name DestinationInstance = $destServer.Name SourceVersion = $sourceVersion DestinationVersion = $destVersion Database = $dbName FeaturesInUse = $dbFeatures IsMigratable = $true Notes = $notesCanMigrate } } } } else { Write-Message -Level Warning -Message "Database '$dbName' is offline or not accessible. Bring database online and re-run the command." } } } else { #SQL Server 2005 or under Write-Message -Level Warning -Message "This validation will not be made on versions lower than SQL Server 2008 (v10)." Write-Message -Level Verbose -Message "Source server version: $($sourceServer.VersionMajor)." Write-Message -Level Verbose -Message "Destination server version: $($destServer.VersionMajor)." } } else { Write-Message -Level Output -Message "There are no databases to validate." } } }
{ "content_hash": "99df873252a9111f71a61e45d833d2a0", "timestamp": "", "source": "github", "line_count": 301, "max_line_length": 285, "avg_line_length": 53.72093023255814, "alnum_prop": 0.5424242424242425, "repo_name": "alevyinroc/dbatools", "id": "88524343c107704a380b7ee1cda171c169919f6b", "size": "16170", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "functions/Test-DbaMigrationConstraint.ps1", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "481258" }, { "name": "PowerShell", "bytes": "10381925" }, { "name": "Rich Text Format", "bytes": "61846" }, { "name": "TSQL", "bytes": "1026352" } ], "symlink_target": "" }
Given(/^the domain objects are defined$/) do |code_sample| Object.module_eval(code_sample) end Given(/^a database connection is established$/) do |code_sample| example_eval(code_sample) end Given(/^the associations are defined in the configuration$/) do |code_sample| example_eval(code_sample) end Given(/^a object store is instantiated$/) do |code_sample| example_eval(code_sample) end Given(/^a conventionally similar database schema for table "(.*?)"$/) do |table_name, schema_table| create_table(table_name, parse_schema_table(schema_table)) end When(/^a new graph of objects are created$/) do |code_sample| @objects_to_be_saved_sample = code_sample end When(/^the new graph is saved$/) do |save_objects_code| example_eval( [@objects_to_be_saved_sample, save_objects_code].join("\n") ) end When(/^the following query is executed$/) do |code_sample| @query = code_sample @result = example_eval(code_sample) end Then(/^the persisted user object is returned with lazy associations$/) do |expected_inspection_string| expect(normalise_inspection_string(@result.inspect)) .to eq(normalise_inspection_string(expected_inspection_string)) end Then(/^the user's posts will be loaded once the association proxy receives an Enumerable message$/) do |expected_inspection_string| posts = @result.posts.to_a expect(normalise_inspection_string(posts.inspect)) .to eq(normalise_inspection_string(expected_inspection_string)) end
{ "content_hash": "a58926e2fcb6d93ef2b631f04e4e30c4", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 131, "avg_line_length": 31.82608695652174, "alnum_prop": 0.7404371584699454, "repo_name": "bestie/terrestrial", "id": "12ffcec3270c5944debb13935d0e6b36b43f411a", "size": "1464", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "features/step_definitions/example_steps.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Gherkin", "bytes": "4146" }, { "name": "Ruby", "bytes": "165321" } ], "symlink_target": "" }
<?php /** Zend_Search_Lucene_Storage_Directory */ require_once 'Zend/Search/Lucene/Storage/Directory.php'; /** Zend_Search_Lucene_Storage_File_Filesystem */ require_once 'Zend/Search/Lucene/Storage/File/Filesystem.php'; /** * FileSystem implementation of Directory abstraction. * * @package Zend_Search_Lucene * @subpackage Storage * @copyright Copyright (c) 2005-2006 Zend Technologies USA Inc. (http://www.zend.com) * @license http://www.zend.com/license/framework/1_0.txt Zend Framework License version 1.0 */ class Zend_Search_Lucene_Storage_Directory_Filesystem extends Zend_Search_Lucene_Storage_Directory { /** * Filesystem path to the directory * * @var string */ private $_dirPath = null; /** * Cache for Zend_Search_Lucene_Storage_File_Filesystem objects * Array: filename => Zend_Search_Lucene_Storage_File object * * @var array * @throws Zend_Search_Lucene_Exception */ private $_fileHandlers; /** * Utility function to recursive directory creation * * @param string $dir * @param integer $mode * @param boolean $recursive * @return boolean */ static public function mkdirs($dir, $mode = 0777, $recursive = true) { if (is_null($dir) || $dir === '') { return false; } if (is_dir($dir) || $dir === '/') { return true; } if (self::mkdirs(dirname($dir), $mode, $recursive)) { return mkdir($dir, $mode); } return false; } /** * Object constructor * Checks if $path is a directory or tries to create it. * * @param string $path * @throws Zend_Search_Lucene_Exception */ public function __construct($path) { if (!is_dir($path)) { if (file_exists($path)) { throw new Zend_Search_Lucene_Exception('Path exists, but it\'s not a directory'); } else { if (!self::mkdirs($path)) { throw new Zend_Search_Lucene_Exception("Can't create directory '$path'."); } } } $this->_dirPath = $path; $this->_fileHandlers = array(); } /** * Closes the store. * * @return void */ public function close() { foreach ($this->_fileHandlers as $fileObject) { $fileObject->close(); } unset($this->_fileHandlers); } /** * Returns an array of strings, one for each file in the directory. * * @return array */ public function fileList() { $result = array(); $dirContent = opendir( $this->_dirPath ); while ($file = readdir($dirContent)) { if (($file == '..')||($file == '.')) continue; $fullName = $this->_dirPath . '/' . $file; if( !is_dir($this->_dirPath . '/' . $file) ) { $result[] = $file; } } return $result; } /** * Creates a new, empty file in the directory with the given $filename. * * @param string $filename * @return Zend_Search_Lucene_Storage_File */ public function createFile($filename) { if (isset($this->_fileHandlers[$filename])) { $this->_fileHandlers[$filename]->close(); } unset($this->_fileHandlers[$filename]); $this->_fileHandlers[$filename] = new Zend_Search_Lucene_Storage_File_Filesystem($this->_dirPath . '/' . $filename, 'w+b'); return $this->_fileHandlers[$filename]; } /** * Removes an existing $filename in the directory. * * @param string $filename * @return void */ public function deleteFile($filename) { if (isset($this->_fileHandlers[$filename])) { $this->_fileHandlers[$filename]->close(); } unset($this->_fileHandlers[$filename]); unlink($this->_dirPath .'/'. $filename); } /** * Returns true if a file with the given $filename exists. * * @param string $filename * @return boolean */ public function fileExists($filename) { return file_exists($this->_dirPath .'/'. $filename); } /** * Returns the length of a $filename in the directory. * * @param string $filename * @return integer */ public function fileLength($filename) { if (isset( $this->_fileHandlers[$filename] )) { return $this->_fileHandlers[$filename]->size(); } return filesize($this->_dirPath .'/'. $filename); } /** * Returns the UNIX timestamp $filename was last modified. * * @param string $filename * @return integer */ public function fileModified($filename) { return filemtime($this->_dirPath .'/'. $filename); } /** * Renames an existing file in the directory. * * @param string $from * @param string $to * @return void */ public function renameFile($from, $to) { if ($this->_fileHandlers[$from] !== null) { $this->_fileHandlers[$from]->close(); } unset($this->_fileHandlers[$from]); if ($this->_fileHandlers[$to] !== null) { $this->_fileHandlers[$to]->close(); } unset($this->_fileHandlers[$to]); if (file_exists($this->_dirPath . '/' . $to)) { unlink($this->_dirPath . '/' . $to); } return @rename($this->_dirPath . '/' . $from, $this->_dirPath . '/' . $to); } /** * Sets the modified time of $filename to now. * * @param string $filename * @return void */ public function touchFile($filename) { return touch($this->_dirPath .'/'. $filename); } /** * Returns a Zend_Search_Lucene_Storage_File object for a given $filename in the directory. * * @param string $filename * @return Zend_Search_Lucene_Storage_File */ public function getFileObject($filename) { if (isset( $this->_fileHandlers[$filename] )) { $this->_fileHandlers[$filename]->seek(0); return $this->_fileHandlers[$filename]; } $this->_fileHandlers[$filename] = new Zend_Search_Lucene_Storage_File_Filesystem($this->_dirPath . '/' . $filename, 'rb'); return $this->_fileHandlers[$filename]; } }
{ "content_hash": "a753194aa02ae59c25664f188bdb2cfa", "timestamp": "", "source": "github", "line_count": 252, "max_line_length": 131, "avg_line_length": 25.61904761904762, "alnum_prop": 0.5427509293680297, "repo_name": "majuca/prado", "id": "73d10659e753dfa3fd2ed1e60469ed20f32e2168", "size": "7199", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "demos/quickstart/protected/index/Zend/Search/Lucene/Storage/Directory/Filesystem.php", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "837" }, { "name": "Batchfile", "bytes": "5993" }, { "name": "CSS", "bytes": "124203" }, { "name": "HTML", "bytes": "319333" }, { "name": "JavaScript", "bytes": "832716" }, { "name": "PHP", "bytes": "7010511" }, { "name": "Smarty", "bytes": "67099" }, { "name": "TeX", "bytes": "12999" }, { "name": "XSLT", "bytes": "252" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "568b724488651d6008517fc642e8828a", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "1ff5c5612c7322bff354382963b9977b31cb252c", "size": "180", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Oxalidales/Connaraceae/Santalodes/Santalodes stenopetalum/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package com.xiaoshangxing.utils.baseClass; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v7.app.AppCompatActivity; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.WindowManager; import com.xiaoshangxing.R; import com.xiaoshangxing.utils.AppContracts; import com.xiaoshangxing.utils.customView.dialog.LoadingDialog; import com.xiaoshangxing.utils.normalUtils.ScreenUtils; import com.xiaoshangxing.utils.normalUtils.ToastUtils; import io.realm.Realm; /** * Created by FengChaoQun * on 2016/6/11 */ public class BaseActivity extends AppCompatActivity implements BaseView { public static final String TAG = AppContracts.TAG + "-BaseActivity"; //手指上下滑动时的最小速度 private static final int YSPEED_MIN = 1000; private static final int XSPEED_MIN = 200; //手指向上滑或下滑时的最小距离 private static final int YDISTANCE_MIN = 100; //手指向右滑动时的最小距离 private static int XDISTANCE_MIN = 150; protected FragmentManager mFragmentManager; protected LoadingDialog loadingDialog; protected Realm realm; protected boolean isEnableRightSlide = true; protected RightSlide rightSlide; //记录手指按下时的横坐标。 private float xDown; //记录手指按下时的纵坐标。 private float yDown; //记录手指移动时的横坐标。 private float xMove; //记录手指移动时的纵坐标。 private float yMove; //用于计算手指滑动的速度。 private VelocityTracker mVelocityTracker; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); realm = Realm.getDefaultInstance(); mFragmentManager = getSupportFragmentManager(); loadingDialog = new LoadingDialog(this); hideTitle(true); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_right); setDefaultRightSlide(); XDISTANCE_MIN = ScreenUtils.getAdapterPx(R.dimen.x150, this); } @Override protected void onDestroy() { super.onDestroy(); realm.close(); if (loadingDialog != null) { loadingDialog.dismiss(); } } /** * *describe:默认隐藏标题栏 */ protected void hideTitle(boolean hideTitle) { if (!hideTitle) { getSupportActionBar().show(); } else { getSupportActionBar().hide(); } } /** * *describe:显示LoadingDialog */ public void showLoadingDialog(String text) { //防止偶尔出现的的WindowManager$BadTokenException异常 //先判断Activity是否被销毁 为确保 再加try catch if (this.isDestroyed()) { return; } try { loadingDialog.setLoadText(text); loadingDialog.show(); WindowManager.LayoutParams lp = loadingDialog.getWindow().getAttributes(); lp.width = getResources().getDimensionPixelSize(R.dimen.x360); //设置宽度 lp.height = getResources().getDimensionPixelSize(R.dimen.y360); //设置宽度 loadingDialog.getWindow().setAttributes(lp); } catch (Exception e) { e.printStackTrace(); } } /** * *describe:关闭LoadingDialog */ public void hideLoadingDialog() { loadingDialog.dismiss(); } /* **describe:设置关闭LoadingDialog时的回调 */ public void setOnLoadingDialogDiamiss(LoadingDialog.onDismiss on) { loadingDialog.setOnDismiss(on); } /** * *describe:Toast */ public void showToast(String toast) { ToastUtils.showShort(this, toast); } public Realm getRealm() { return realm; } @Override public boolean dispatchTouchEvent(MotionEvent event) { createVelocityTracker(event); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: xDown = event.getRawX(); yDown = event.getRawY(); break; case MotionEvent.ACTION_MOVE: xMove = event.getRawX(); yMove = event.getRawY(); break; case MotionEvent.ACTION_UP: //滑动的距离 int distanceX = (int) (xMove - xDown); int distanceY = (int) (yMove - yDown); //获取顺时速度 int ySpeed = getYScrollVelocity(); int xSpeed = getXScrollVelocity(); //关闭Activity需满足以下条件: //1.x轴滑动的距离>XDISTANCE_MIN //2.y轴滑动的距离在YDISTANCE_MIN范围内 //3.y轴上(即上下滑动的速度)<XSPEED_MIN,如果大于,则认为用户意图是在上下滑动而非左滑结束Activity if (distanceX > XDISTANCE_MIN && (distanceY < YDISTANCE_MIN && distanceY > -YDISTANCE_MIN) && ySpeed < YSPEED_MIN && xSpeed > XSPEED_MIN) { if (rightSlide != null) { return rightSlide.rightSlide(); } } recycleVelocityTracker(); break; default: break; } return super.dispatchTouchEvent(event); } /** * 创建VelocityTracker对象,并将触摸界面的滑动事件加入到VelocityTracker当中。 * * @param event */ private void createVelocityTracker(MotionEvent event) { if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } mVelocityTracker.addMovement(event); } /** * 回收VelocityTracker对象。 */ private void recycleVelocityTracker() { mVelocityTracker.recycle(); mVelocityTracker = null; } /** * @return 滑动速度,以每秒钟移动了多少像素值为单位。 */ private int getYScrollVelocity() { mVelocityTracker.computeCurrentVelocity(1000); int velocity = (int) mVelocityTracker.getYVelocity(); return Math.abs(velocity); } private int getXScrollVelocity() { mVelocityTracker.computeCurrentVelocity(1000); int velocity = (int) mVelocityTracker.getXVelocity(); return Math.abs(velocity); } public void setRightSlide(RightSlide rightSlide) { if (isEnableRightSlide) { this.rightSlide = rightSlide; } } /** * *describe:设置默认右滑关闭当前activity */ public void setDefaultRightSlide() { setRightSlide(new RightSlide() { @Override public boolean rightSlide() { finish(); return true; } }); } public void clearRightSlide() { this.rightSlide = null; } public boolean isEnableRightSlide() { return isEnableRightSlide; } public void setEnableRightSlide(boolean enableRightSlide) { clearRightSlide(); isEnableRightSlide = enableRightSlide; } @Override public Activity getActivity() { return this; } @Override public BaseView getBaseView() { return this; } public interface RightSlide { boolean rightSlide(); } }
{ "content_hash": "4fe60b8d7532eeb211d4a8e8d1d91847", "timestamp": "", "source": "github", "line_count": 250, "max_line_length": 106, "avg_line_length": 27.78, "alnum_prop": 0.6056155507559395, "repo_name": "JNDX25219/XiaoShangXing", "id": "b9a53f089456b47475c338c6c7efb6d5167c3c42", "size": "7505", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/xiaoshangxing/utils/baseClass/BaseActivity.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2955459" } ], "symlink_target": "" }
var _ = require('underscore'); var archinfo = require('./archinfo.js'); var buildmessage = require('./buildmessage.js'); var bundler = require('./bundler.js'); var isopack = require('./isopack.js'); var isopackets = require('./isopackets.js'); var linker = require('./linker.js'); var meteorNpm = require('./meteor-npm.js'); var watch = require('./watch.js'); var Console = require('./console.js').Console; var files = require('./files.js'); var colonConverter = require('./colon-converter.js'); var compiler = exports; // Whenever you change anything about the code that generates isopacks, bump // this version number. The idea is that the "format" field of the isopack // JSON file only changes when the actual specified structure of the // isopack/unibuild changes, but this version (which is build-tool-specific) // can change when the the contents (not structure) of the built output // changes. So eg, if we improve the linker's static analysis, this should be // bumped. // // You should also update this whenever you update any of the packages used // directly by the isopack creation process (eg js-analyze) since they do not // end up as watched dependencies. (At least for now, packages only used in // target creation (eg minifiers) don't require you to update BUILT_BY, though // you will need to quit and rerun "meteor run".) compiler.BUILT_BY = 'meteor/16'; // This is a list of all possible architectures that a build can target. (Client // is expanded into 'web.browser' and 'web.cordova') compiler.ALL_ARCHES = [ "os", "web.browser", "web.cordova" ]; compiler.compile = function (packageSource, options) { buildmessage.assertInCapture(); var packageMap = options.packageMap; var isopackCache = options.isopackCache; var includeCordovaUnibuild = options.includeCordovaUnibuild; var pluginWatchSet = packageSource.pluginWatchSet.clone(); var plugins = {}; var pluginProviderPackageNames = {}; // Build plugins _.each(packageSource.pluginInfo, function (info) { buildmessage.enterJob({ title: "building plugin `" + info.name + "` in package `" + packageSource.name + "`", rootPath: packageSource.sourceRoot }, function () { // XXX we should probably also pass options.noLineNumbers into // buildJsImage so it can pass it back to its call to // compiler.compile var buildResult = bundler.buildJsImage({ name: info.name, packageMap: packageMap, isopackCache: isopackCache, use: info.use, sourceRoot: packageSource.sourceRoot, sources: info.sources, npmDependencies: info.npmDependencies, // Plugins have their own npm dependencies separate from the // rest of the package, so they need their own separate npm // shrinkwrap and cache state. npmDir: files.pathResolve( files.pathJoin(packageSource.sourceRoot, '.npm', 'plugin', info.name)) }); if (buildmessage.jobHasMessages()) return; _.each(buildResult.usedPackageNames, function (packageName) { pluginProviderPackageNames[packageName] = true; }); // Add this plugin's dependencies to our "plugin dependency" // WatchSet. buildResult.watchSet will end up being the merged // watchSets of all of the unibuilds of the plugin -- plugins have // only one unibuild and this should end up essentially being just // the source files of the plugin. pluginWatchSet.merge(buildResult.watchSet); // Register the built plugin's code. if (!_.has(plugins, info.name)) plugins[info.name] = {}; plugins[info.name][buildResult.image.arch] = buildResult.image; }); }); // Grab any npm dependencies. Keep them in a cache in the package // source directory so we don't have to do this from scratch on // every build. // // Go through a specialized npm dependencies update process, // ensuring we don't get new versions of any (sub)dependencies. This // process also runs mostly safely multiple times in parallel (which // could happen if you have two apps running locally using the same // package). // // We run this even if we have no dependencies, because we might // need to delete dependencies we used to have. var isPortable = true; var nodeModulesPath = null; if (packageSource.npmCacheDirectory) { if (meteorNpm.updateDependencies(packageSource.name, packageSource.npmCacheDirectory, packageSource.npmDependencies)) { nodeModulesPath = files.pathJoin(packageSource.npmCacheDirectory, 'node_modules'); if (! meteorNpm.dependenciesArePortable(packageSource.npmCacheDirectory)) isPortable = false; } } var isopk = new isopack.Isopack; isopk.initFromOptions({ name: packageSource.name, metadata: packageSource.metadata, version: packageSource.version, isTest: packageSource.isTest, plugins: plugins, pluginWatchSet: pluginWatchSet, cordovaDependencies: packageSource.cordovaDependencies, npmDiscards: packageSource.npmDiscards, includeTool: packageSource.includeTool, debugOnly: packageSource.debugOnly }); _.each(packageSource.architectures, function (unibuild) { if (unibuild.arch === 'web.cordova' && ! includeCordovaUnibuild) return; var unibuildResult = compileUnibuild({ isopack: isopk, sourceArch: unibuild, isopackCache: isopackCache, nodeModulesPath: nodeModulesPath, isPortable: isPortable, noLineNumbers: options.noLineNumbers }); _.extend(pluginProviderPackageNames, unibuildResult.pluginProviderPackageNames); }); if (options.includePluginProviderPackageMap) { isopk.setPluginProviderPackageMap( packageMap.makeSubsetMap(_.keys(pluginProviderPackageNames))); } return isopk; }; // options.sourceArch is a SourceArch to compile. Process all source files // through the appropriate handlers and run the prelink phase on any resulting // JavaScript. Create a new Unibuild and add it to options.isopack. // // Returns a list of source files that were used in the compilation. var compileUnibuild = function (options) { buildmessage.assertInCapture(); var isopk = options.isopack; var inputSourceArch = options.sourceArch; var isopackCache = options.isopackCache; var nodeModulesPath = options.nodeModulesPath; var isPortable = options.isPortable; var noLineNumbers = options.noLineNumbers; var isApp = ! inputSourceArch.pkg.name; var resources = []; var js = []; var pluginProviderPackageNames = {}; // The current package always is a plugin provider. (This also means we no // longer need a buildOfPath entry in buildinfo.json.) pluginProviderPackageNames[isopk.name] = true; var watchSet = inputSourceArch.watchSet.clone(); // *** Determine and load active plugins // XXX we used to include our own extensions only if we were the // "use" role. now we include them everywhere because we don't have // a special "use" role anymore. it's not totally clear to me what // the correct behavior should be -- we need to resolve whether we // think about extensions as being global to a package or particular // to a unibuild. // (there's also some weirdness here with handling implies, because // the implies field is on the target unibuild, but we really only care // about packages.) var activePluginPackages = [isopk]; // We don't use plugins from weak dependencies, because the ability // to compile a certain type of file shouldn't depend on whether or // not some unrelated package in the target has a dependency. And we // skip unordered dependencies, because it's not going to work to // have circular build-time dependencies. // // eachUsedUnibuild takes care of pulling in implied dependencies for us (eg, // templating from standard-app-packages). // // We pass archinfo.host here, not self.arch, because it may be more specific, // and because plugins always have to run on the host architecture. compiler.eachUsedUnibuild({ dependencies: inputSourceArch.uses, arch: archinfo.host(), isopackCache: isopackCache, skipUnordered: true // implicitly skip weak deps by not specifying acceptableWeakPackages option }, function (unibuild) { if (unibuild.pkg.name === isopk.name) return; pluginProviderPackageNames[unibuild.pkg.name] = true; // If other package is built from source, then we need to rebuild this // package if any file in the other package that could define a plugin // changes. watchSet.merge(unibuild.pkg.pluginWatchSet); if (_.isEmpty(unibuild.pkg.plugins)) return; activePluginPackages.push(unibuild.pkg); }); activePluginPackages = _.uniq(activePluginPackages); // *** Assemble the list of source file handlers from the plugins var allHandlersWithPkgs = {}; var sourceExtensions = {}; // maps source extensions to isTemplate sourceExtensions['js'] = false; allHandlersWithPkgs['js'] = { pkgName: null /* native handler */, handler: function (compileStep) { // This is a hardcoded handler for *.js files. Since plugins // are written in JavaScript we have to start somewhere. var options = { data: compileStep.read().toString('utf8'), path: compileStep.inputPath, sourcePath: compileStep.inputPath, _hash: compileStep._hash }; if (compileStep.fileOptions.hasOwnProperty("bare")) { options.bare = compileStep.fileOptions.bare; } else if (compileStep.fileOptions.hasOwnProperty("raw")) { // XXX eventually get rid of backward-compatibility "raw" name // XXX COMPAT WITH 0.6.4 options.bare = compileStep.fileOptions.raw; } compileStep.addJavaScript(options); } }; _.each(activePluginPackages, function (otherPkg) { _.each(otherPkg.getSourceHandlers(), function (sourceHandler, ext) { // XXX comparing function text here seems wrong. if (_.has(allHandlersWithPkgs, ext) && allHandlersWithPkgs[ext].handler.toString() !== sourceHandler.handler.toString()) { buildmessage.error( "conflict: two packages included in " + (inputSourceArch.pkg.name || "the app") + ", " + (allHandlersWithPkgs[ext].pkgName || "the app") + " and " + (otherPkg.name || "the app") + ", " + "are both trying to handle ." + ext); // Recover by just going with the first handler we saw return; } // Is this handler only registered for, say, "web", and we're building, // say, "os"? if (sourceHandler.archMatching && !archinfo.matches(inputSourceArch.arch, sourceHandler.archMatching)) { return; } allHandlersWithPkgs[ext] = { pkgName: otherPkg.name, handler: sourceHandler.handler }; sourceExtensions[ext] = !!sourceHandler.isTemplate; }); }); // *** Determine source files // Note: sourceExtensions does not include leading dots // Note: the getSourcesFunc function isn't expected to add its // source files to watchSet; rather, the watchSet is for other // things that the getSourcesFunc consulted (such as directory // listings or, in some hypothetical universe, control files) to // determine its source files. var sourceItems = inputSourceArch.getSourcesFunc(sourceExtensions, watchSet); if (nodeModulesPath) { // If this slice has node modules, we should consider the shrinkwrap file // to be part of its inputs. (This is a little racy because there's no // guarantee that what we read here is precisely the version that's used, // but it's better than nothing at all.) // // Note that this also means that npm modules used by plugins will get // this npm-shrinkwrap.json in their pluginDependencies (including for all // packages that depend on us)! This is good: this means that a tweak to // an indirect dependency of the coffee-script npm module used by the // coffeescript package will correctly cause packages with *.coffee files // to be rebuilt. var shrinkwrapPath = nodeModulesPath.replace( /node_modules$/, 'npm-shrinkwrap.json'); watch.readAndWatchFile(watchSet, shrinkwrapPath); } // *** Process each source file var addAsset = function (contents, relPath, hash) { // XXX hack if (! inputSourceArch.pkg.name) relPath = relPath.replace(/^(private|public)\//, ''); resources.push({ type: "asset", data: contents, path: relPath, servePath: colonConverter.convert( files.pathJoin(inputSourceArch.pkg.serveRoot, relPath)), hash: hash }); }; var convertSourceMapPaths = function (sourcemap, f) { if (! sourcemap) { // Don't try to convert it if it doesn't exist return sourcemap; } var srcmap = JSON.parse(sourcemap); srcmap.sources = _.map(srcmap.sources, f); return JSON.stringify(srcmap); }; _.each(sourceItems, function (source) { var relPath = source.relPath; var fileOptions = _.clone(source.fileOptions) || {}; var absPath = files.pathResolve(inputSourceArch.pkg.sourceRoot, relPath); var filename = files.pathBasename(relPath); // readAndWatchFileWithHash returns an object carrying a buffer with the // file-contents. The buffer contains the original data of the file (no EOL // transforms from the tools/files.js part). var file = watch.readAndWatchFileWithHash(watchSet, absPath); var contents = file.contents; Console.nudge(true); if (contents === null) { // It really sucks to put this check here, since this isn't publish // code... if (source.relPath.match(/:/)) { buildmessage.error( "Couldn't build this package on Windows due to the following file " + "with a colon -- " + source.relPath + ". Please rename and " + "and re-publish the package."); } else { buildmessage.error("File not found: " + source.relPath); } // recover by ignoring return; } // Find the handler for source files with this extension. var handler = null; if (! fileOptions.isAsset) { var parts = filename.split('.'); for (var i = 1; i < parts.length; i++) { var extension = parts.slice(i).join('.'); if (_.has(allHandlersWithPkgs, extension)) { handler = allHandlersWithPkgs[extension].handler; break; } } } if (! handler) { // If we don't have an extension handler, serve this file as a // static resource on the client, or ignore it on the server. // // XXX This is pretty confusing, especially if you've // accidentally forgotten a plugin -- revisit? addAsset(contents, relPath, file.hash); return; } // This object is called a #CompileStep and it's the interface // to plugins that define new source file handlers (eg, // Coffeescript). // // Fields on CompileStep: // // - arch: the architecture for which we are building // - inputSize: total number of bytes in the input file // - inputPath: the filename and (relative) path of the input // file, eg, "foo.js". We don't provide a way to get the full // path because you're not supposed to read the file directly // off of disk. Instead you should call read(). That way we // can ensure that the version of the file that you use is // exactly the one that is recorded in the dependency // information. // - pathForSourceMap: If this file is to be included in a source map, // this is the name you should use for it in the map. // - rootOutputPath: on web targets, for resources such as // stylesheet and static assets, this is the root URL that // will get prepended to the paths you pick for your output // files so that you get your own namespace, for example // '/packages/foo'. null on non-web targets // - fileOptions: any options passed to "api.addFiles"; for // use by the plugin. The built-in "js" plugin uses the "bare" // option for files that shouldn't be wrapped in a closure. // - declaredExports: An array of symbols exported by this unibuild, or null // if it may not export any symbols (eg, test unibuilds). This is used by // CoffeeScript to ensure that it doesn't close over those symbols, eg. // - read(n): read from the input file. If n is given it should // be an integer, and you will receive the next n bytes of the // file as a Buffer. If n is omitted you get the rest of the // file. // - appendDocument({ section: "head", data: "my markup" }) // Browser targets only. Add markup to the "head" or "body" // Web targets only. Add markup to the "head" or "body" // section of the document. // - addStylesheet({ path: "my/stylesheet.css", data: "my css", // sourceMap: "stringified json sourcemap"}) // Web targets only. Add a stylesheet to the // document. 'path' is a requested URL for the stylesheet that // may or may not ultimately be honored. (Meteor will add // appropriate tags to cause the stylesheet to be loaded. It // will be subject to any stylesheet processing stages in // effect, such as minification.) // - addJavaScript({ path: "my/program.js", data: "my code", // sourcePath: "src/my/program.js", // bare: true }) // Add JavaScript code, which will be namespaced into this // package's environment (eg, it will see only the exports of // this package's imports), and which will be subject to // minification and so forth. Again, 'path' is merely a hint // that may or may not be honored. 'sourcePath' is the path // that will be used in any error messages generated (eg, // "foo.js:4:1: syntax error"). It must be present and should // be relative to the project root. Typically 'inputPath' will // do handsomely. "bare" means to not wrap the file in // a closure, so that its vars are shared with other files // in the module. // - addAsset({ path: "my/image.png", data: Buffer }) // Add a file to serve as-is over HTTP (web targets) or // to include as-is in the bundle (os targets). // This time `data` is a Buffer rather than a string. For // web targets, it will be served at the exact path you // request (concatenated with rootOutputPath). For server // targets, the file can be retrieved by passing path to // Assets.getText or Assets.getBinary. // - error({ message: "There's a problem in your source file", // sourcePath: "src/my/program.ext", line: 12, // column: 20, func: "doStuff" }) // Flag an error -- at a particular location in a source // file, if you like (you can even indicate a function name // to show in the error, like in stack traces). sourcePath, // line, column, and func are all optional. // // XXX for now, these handlers must only generate portable code // (code that isn't dependent on the arch, other than 'web' // vs 'os') -- they can look at the arch that is provided // but they can't rely on the running on that particular arch // (in the end, an arch-specific unibuild will be emitted only if // there are native node modules). Obviously this should // change. A first step would be a setOutputArch() function // analogous to what we do with native node modules, but maybe // what we want is the ability to ask the plugin ahead of time // how specific it would like to force unibuilds to be. // // XXX we handle encodings in a rather cavalier way and I // suspect we effectively end up assuming utf8. We can do better // than that! // // XXX addAsset probably wants to be able to set MIME type and // also control any manifest field we deem relevant (if any) // // XXX Some handlers process languages that have the concept of // include files. These are problematic because we need to // somehow instrument them to get the names and hashs of all of // the files that they read for dependency tracking purposes. We // don't have an API for that yet, so for now we provide a // workaround, which is that _fullInputPath contains the full // absolute path to the input files, which allows such a plugin // to set up its include search path. It's then on its own for // registering dependencies (for now..) // // XXX in the future we should give plugins an easy and clean // way to return errors (that could go in an overall list of // errors experienced across all files) var readOffset = 0; /** * The comments for this class aren't used to generate docs right now. * The docs live in the GitHub Wiki at: https://github.com/meteor/meteor/wiki/CompileStep-API-for-Build-Plugin-Source-Handlers * @class CompileStep * @summary The object passed into Plugin.registerSourceHandler * @global */ var compileStep = { /** * @summary The total number of bytes in the input file. * @memberOf CompileStep * @instance * @type {Integer} */ inputSize: contents.length, /** * @summary The filename and relative path of the input file. * Please don't use this filename to read the file from disk, instead * use [compileStep.read](CompileStep-read). * @type {String} * @instance * @memberOf CompileStep */ inputPath: files.convertToOSPath(relPath, true), /** * @summary The filename and absolute path of the input file. * Please don't use this filename to read the file from disk, instead * use [compileStep.read](CompileStep-read). * @type {String} * @instance * @memberOf CompileStep */ fullInputPath: files.convertToOSPath(absPath), // The below is used in the less and stylus packages... so it should be // public API. _fullInputPath: files.convertToOSPath(absPath), // avoid, see above.. // Used for one optimization. Don't rely on this otherwise. _hash: file.hash, // XXX duplicates _pathForSourceMap() in linker /** * @summary If you are generating a sourcemap for the compiled file, use * this path for the original file in the sourcemap. * @type {String} * @memberOf CompileStep * @instance */ pathForSourceMap: files.convertToOSPath( inputSourceArch.pkg.name ? inputSourceArch.pkg.name + "/" + relPath : files.pathBasename(relPath), true), // null if this is an app. intended to be used for the sources // dictionary for source maps. /** * @summary The name of the package in which the file being built exists. * @type {String} * @memberOf CompileStep * @instance */ packageName: inputSourceArch.pkg.name, /** * @summary On web targets, this will be the root URL prepended * to the paths you pick for your output files. For example, * it could be "/packages/my-package". * @type {String} * @memberOf CompileStep * @instance */ rootOutputPath: files.convertToOSPath( inputSourceArch.pkg.serveRoot, true), /** * @summary The architecture for which we are building. Can be "os", * "web.browser", or "web.cordova". * @type {String} * @memberOf CompileStep * @instance */ arch: inputSourceArch.arch, /** * @deprecated in 0.9.4 * This is a duplicate API of the above, we don't need it. */ archMatches: function (pattern) { return archinfo.matches(inputSourceArch.arch, pattern); }, /** * @summary Any options passed to "api.addFiles". * @type {Object} * @memberOf CompileStep * @instance */ fileOptions: fileOptions, /** * @summary The list of exports that the current package has defined. * Can be used to treat those symbols differently during compilation. * @type {Object} * @memberOf CompileStep * @instance */ declaredExports: _.pluck(inputSourceArch.declaredExports, 'name'), /** * @summary Read from the input file. If `n` is specified, returns the * next `n` bytes of the file as a Buffer. XXX not sure if this actually * returns a String sometimes... * @param {Integer} [n] The number of bytes to return. * @instance * @memberOf CompileStep * @returns {Buffer} */ read: function (n) { if (n === undefined || readOffset + n > contents.length) n = contents.length - readOffset; var ret = contents.slice(readOffset, readOffset + n); readOffset += n; return ret; }, /** * @summary Works in web targets only. Add markup to the `head` or `body` * section of the document. * @param {Object} options * @param {String} options.section Which section of the document should * be appended to. Can only be "head" or "body". * @param {String} options.data The content to append. * @memberOf CompileStep * @instance */ addHtml: function (options) { if (! archinfo.matches(inputSourceArch.arch, "web")) throw new Error("Document sections can only be emitted to " + "web targets"); if (options.section !== "head" && options.section !== "body") throw new Error("'section' must be 'head' or 'body'"); if (typeof options.data !== "string") throw new Error("'data' option to appendDocument must be a string"); resources.push({ type: options.section, data: new Buffer(files.convertToStandardLineEndings(options.data), 'utf8') }); }, /** * @deprecated in 0.9.4 */ appendDocument: function (options) { this.addHtml(options); }, /** * @summary Web targets only. Add a stylesheet to the document. * @param {Object} options * @param {String} path The requested path for the added CSS, may not be * satisfied if there are path conflicts. * @param {String} data The content of the stylesheet that should be * added. * @param {String} sourceMap A stringified JSON sourcemap, in case the * stylesheet was generated from a different file. * @memberOf CompileStep * @instance */ addStylesheet: function (options) { if (! archinfo.matches(inputSourceArch.arch, "web")) throw new Error("Stylesheets can only be emitted to " + "web targets"); if (typeof options.data !== "string") throw new Error("'data' option to addStylesheet must be a string"); resources.push({ type: "css", refreshable: true, data: new Buffer(files.convertToStandardLineEndings(options.data), 'utf8'), servePath: colonConverter.convert( files.pathJoin( inputSourceArch.pkg.serveRoot, files.convertToStandardPath(options.path, true))), sourceMap: convertSourceMapPaths(options.sourceMap, files.convertToStandardPath) }); }, /** * @summary Add JavaScript code. The code added will only see the * namespaces imported by this package as runtime dependencies using * ['api.use'](#PackageAPI-use). If the file being compiled was added * with the bare flag, the resulting JavaScript won't be wrapped in a * closure. * @param {Object} options * @param {String} options.path The path at which the JavaScript file * should be inserted, may not be honored in case of path conflicts. * @param {String} options.data The code to be added. * @param {String} options.sourcePath The path that will be used in * any error messages generated by this file, e.g. `foo.js:4:1: error`. * @memberOf CompileStep * @instance */ addJavaScript: function (options) { if (typeof options.data !== "string") throw new Error("'data' option to addJavaScript must be a string"); if (typeof options.sourcePath !== "string") throw new Error("'sourcePath' option must be supplied to addJavaScript. Consider passing inputPath."); // By default, use fileOptions for the `bare` option but also allow // overriding it with the options var bare = fileOptions.bare; if (options.hasOwnProperty("bare")) { bare = options.bare; } js.push({ source: files.convertToStandardLineEndings(options.data), sourcePath: files.convertToStandardPath(options.sourcePath, true), servePath: files.pathJoin( inputSourceArch.pkg.serveRoot, files.convertToStandardPath(options.path, true)), bare: !! bare, sourceMap: convertSourceMapPaths(options.sourceMap, files.convertToStandardPath), sourceHash: options._hash }); }, /** * @summary Add a file to serve as-is to the browser or to include on * the browser, depending on the target. On the web, it will be served * at the exact path requested. For server targets, it can be retrieved * using `Assets.getText` or `Assets.getBinary`. * @param {Object} options * @param {String} path The path at which to serve the asset. * @param {Buffer|String} data The data that should be placed in * the file. * @memberOf CompileStep * @instance */ addAsset: function (options) { if (! (options.data instanceof Buffer)) { if (_.isString(options.data)) { options.data = new Buffer(options.data); } else { throw new Error("'data' option to addAsset must be a Buffer or String."); } } addAsset(options.data, files.convertToStandardPath(options.path, true)); }, /** * @summary Display a build error. * @param {Object} options * @param {String} message The error message to display. * @param {String} [sourcePath] The path to display in the error message. * @param {Integer} line The line number to display in the error message. * @param {String} func The function name to display in the error message. * @memberOf CompileStep * @instance */ error: function (options) { buildmessage.error(options.message || ("error building " + relPath), { file: options.sourcePath, line: options.line ? options.line : undefined, column: options.column ? options.column : undefined, func: options.func ? options.func : undefined }); } }; try { (buildmessage.markBoundary(handler))(compileStep); } catch (e) { e.message = e.message + " (compiling " + relPath + ")"; buildmessage.exception(e); // Recover by ignoring this source file (as best we can -- the // handler might already have emitted resources) } }); // *** Run Phase 1 link // Load jsAnalyze from the js-analyze package... unless we are the // js-analyze package, in which case never mind. (The js-analyze package's // default unibuild is not allowed to depend on anything!) var jsAnalyze = null; if (! _.isEmpty(js) && inputSourceArch.pkg.name !== "js-analyze") { jsAnalyze = isopackets.load('js-analyze')['js-analyze'].JSAnalyze; } var results = linker.prelink({ inputFiles: js, useGlobalNamespace: isApp, // I was confused about this, so I am leaving a comment -- the // combinedServePath is either [pkgname].js or [pluginName]:plugin.js. // XXX: If we change this, we can get rid of source arch names! combinedServePath: isApp ? null : "/packages/" + colonConverter.convert( inputSourceArch.pkg.name + (inputSourceArch.kind === "main" ? "" : (":" + inputSourceArch.kind)) + ".js"), name: inputSourceArch.pkg.name || null, declaredExports: _.pluck(inputSourceArch.declaredExports, 'name'), jsAnalyze: jsAnalyze, noLineNumbers: noLineNumbers }); // *** Determine captured variables var packageVariables = []; var packageVariableNames = {}; _.each(inputSourceArch.declaredExports, function (symbol) { if (_.has(packageVariableNames, symbol.name)) return; packageVariables.push({ name: symbol.name, export: symbol.testOnly? "tests" : true }); packageVariableNames[symbol.name] = true; }); _.each(results.assignedVariables, function (name) { if (_.has(packageVariableNames, name)) return; packageVariables.push({ name: name }); packageVariableNames[name] = true; }); // *** Consider npm dependencies and portability var arch = inputSourceArch.arch; if (arch === "os" && ! isPortable) { // Contains non-portable compiled npm modules, so set arch correctly arch = archinfo.host(); } if (! archinfo.matches(arch, "os")) { // npm modules only work on server architectures nodeModulesPath = undefined; } // *** Output unibuild object isopk.addUnibuild({ kind: inputSourceArch.kind, arch: arch, uses: inputSourceArch.uses, implies: inputSourceArch.implies, watchSet: watchSet, nodeModulesPath: nodeModulesPath, prelinkFiles: results.files, packageVariables: packageVariables, resources: resources }); return { pluginProviderPackageNames: pluginProviderPackageNames }; }; // Iterates over each in options.dependencies as well as unibuilds implied by // them. The packages in question need to already be built and in // options.isopackCache. compiler.eachUsedUnibuild = function ( options, callback) { buildmessage.assertInCapture(); var dependencies = options.dependencies; var arch = options.arch; var isopackCache = options.isopackCache; var acceptableWeakPackages = options.acceptableWeakPackages || {}; var processedUnibuildId = {}; var usesToProcess = []; _.each(dependencies, function (use) { if (options.skipUnordered && use.unordered) return; if (use.weak && !_.has(acceptableWeakPackages, use.package)) return; usesToProcess.push(use); }); while (! _.isEmpty(usesToProcess)) { var use = usesToProcess.shift(); var usedPackage = isopackCache.getIsopack(use.package); // Ignore this package if we were told to skip debug-only packages and it is // debug-only. if (usedPackage.debugOnly && options.skipDebugOnly) continue; var unibuild = usedPackage.getUnibuildAtArch(arch); if (!unibuild) { // The package exists but there's no unibuild for us. A buildmessage has // already been issued. Recover by skipping. continue; } if (_.has(processedUnibuildId, unibuild.id)) continue; processedUnibuildId[unibuild.id] = true; callback(unibuild, { unordered: !!use.unordered, weak: !!use.weak }); _.each(unibuild.implies, function (implied) { usesToProcess.push(implied); }); } };
{ "content_hash": "2c2064e746ed114e1d79237993ad1042", "timestamp": "", "source": "github", "line_count": 912, "max_line_length": 130, "avg_line_length": 39.28508771929825, "alnum_prop": 0.6482918387853076, "repo_name": "alphanso/meteor", "id": "2c34c0aeadabce055f33c91bd25154e495ad7e9a", "size": "35828", "binary": false, "copies": "1", "ref": "refs/heads/devel", "path": "tools/compiler.js", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "235849" }, { "name": "C#", "bytes": "21958" }, { "name": "C++", "bytes": "202523" }, { "name": "CSS", "bytes": "51368" }, { "name": "CoffeeScript", "bytes": "33940" }, { "name": "HTML", "bytes": "144452" }, { "name": "JavaScript", "bytes": "5346026" }, { "name": "PowerShell", "bytes": "8336" }, { "name": "Python", "bytes": "10313" }, { "name": "Shell", "bytes": "46229" } ], "symlink_target": "" }
package com.se1.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.se1.dao.DatabaseOperation; import com.se1.dao.User; import com.se1.main.MainActivity; import com.se1.main.R; public class ResetPasswordActivity extends SherlockFragmentActivity { private DatabaseOperation datasource; int noOfAttempts; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_reset_password); getSupportActionBar().setTitle(R.string.title_activity_reset_password); final Button resetPassword = (Button)findViewById(R.id.resetPassword); final EditText oldPassword = (EditText)findViewById(R.id.oldPassText); final EditText newPassword = (EditText)findViewById(R.id.newPassText); noOfAttempts=0; datasource = new DatabaseOperation(this); datasource.open(); resetPassword.setOnClickListener( new View.OnClickListener() { public void onClick(View view) { User user=datasource.getUserDetail(); if(newPassword.getText().toString().equals("") || newPassword.getText().toString() == null ) { Toast.makeText(getApplicationContext(), "Please enter new Password", Toast.LENGTH_LONG).show(); } else if(user!=null && ((user.getEmailId()!= null || user.getEmailId().equalsIgnoreCase("")))) { if(user.getPassword().equals(oldPassword.getText().toString())) { datasource.resetPassword(user.getEmailId(),newPassword.getText().toString()); Toast.makeText(getApplicationContext(), "Password is Successfully Reset ", Toast.LENGTH_LONG).show(); goToLoginPage(user.getEmailId()); } else { setNoOfAttempts(); if(noOfAttempts == 3) { goToLoginPage(user.getEmailId()); } Toast.makeText(getApplicationContext(), "Please Enter Valid Password", Toast.LENGTH_LONG).show(); } } } }); } //Navigate to Login page public void goToHomePage() { Intent intent = new Intent(this, SettingsActivity.class); startActivity(intent); } //Navigate to Login page public void goToLoginPage(String emaildId) { datasource.removeSignIn(emaildId);// Go to login page and remove signup option Intent intent = new Intent(this, MainActivity.class); startActivity(intent); } public int getNoOfAttempts() { return noOfAttempts; } public void setNoOfAttempts() { noOfAttempts++; } }
{ "content_hash": "cfdc528ba64fde3e1bfd7c605bd17bf5", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 117, "avg_line_length": 39.53409090909091, "alnum_prop": 0.5536073584363322, "repo_name": "abhi389/CloudSyncApp", "id": "33be9e674b161c836317f368746378976df22363", "size": "3479", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CloudSync/src/com/se1/Activity/ResetPasswordActivity.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "646348" } ], "symlink_target": "" }
package net.sagon.agile.controller; import java.time.LocalDate; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.format.annotation.DateTimeFormat.ISO; public class AnalysisDates { @DateTimeFormat(iso = ISO.DATE) private LocalDate start; @DateTimeFormat(iso = ISO.DATE) private LocalDate end; public AnalysisDates() { } public AnalysisDates(LocalDate start, LocalDate end) { this.start = start; this.end = end; } public LocalDate getStart() { return start; } public void setStart(LocalDate start) { this.start = start; } public LocalDate getEnd() { return end; } public void setEnd(LocalDate end) { this.end = end; } }
{ "content_hash": "baae6740bc95989d2c077424fbda0e39", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 64, "avg_line_length": 20, "alnum_prop": 0.6564102564102564, "repo_name": "ksagon/agilecoach", "id": "f15b1a704952bb3dbaab24c554062c4ae5493bec", "size": "780", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/net/sagon/agile/controller/AnalysisDates.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "52444" }, { "name": "JavaScript", "bytes": "484" } ], "symlink_target": "" }
.class Landroid/content/ISyncServiceAdapter$Stub$Proxy; .super Ljava/lang/Object; .source "ISyncServiceAdapter.java" # interfaces .implements Landroid/content/ISyncServiceAdapter; # annotations .annotation system Ldalvik/annotation/EnclosingClass; value = Landroid/content/ISyncServiceAdapter$Stub; .end annotation .annotation system Ldalvik/annotation/InnerClass; accessFlags = 0xa name = "Proxy" .end annotation # instance fields .field private mRemote:Landroid/os/IBinder; # direct methods .method constructor <init>(Landroid/os/IBinder;)V .locals 0 invoke-direct {p0}, Ljava/lang/Object;-><init>()V iput-object p1, p0, Landroid/content/ISyncServiceAdapter$Stub$Proxy;->mRemote:Landroid/os/IBinder; return-void .end method # virtual methods .method public asBinder()Landroid/os/IBinder; .locals 1 iget-object v0, p0, Landroid/content/ISyncServiceAdapter$Stub$Proxy;->mRemote:Landroid/os/IBinder; return-object v0 .end method .method public cancelSync(Landroid/content/ISyncContext;)V .locals 5 .annotation system Ldalvik/annotation/Throws; value = { Landroid/os/RemoteException; } .end annotation const/4 v1, 0x0 invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel; move-result-object v0 :try_start_0 const-string/jumbo v2, "android.content.ISyncServiceAdapter" invoke-virtual {v0, v2}, Landroid/os/Parcel;->writeInterfaceToken(Ljava/lang/String;)V if-eqz p1, :cond_0 invoke-interface {p1}, Landroid/content/ISyncContext;->asBinder()Landroid/os/IBinder; move-result-object v1 :cond_0 invoke-virtual {v0, v1}, Landroid/os/Parcel;->writeStrongBinder(Landroid/os/IBinder;)V iget-object v1, p0, Landroid/content/ISyncServiceAdapter$Stub$Proxy;->mRemote:Landroid/os/IBinder; const/4 v2, 0x2 const/4 v3, 0x0 const/4 v4, 0x1 invoke-interface {v1, v2, v0, v3, v4}, Landroid/os/IBinder;->transact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z :try_end_0 .catchall {:try_start_0 .. :try_end_0} :catchall_0 invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V return-void :catchall_0 move-exception v1 invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V throw v1 .end method .method public getInterfaceDescriptor()Ljava/lang/String; .locals 1 const-string/jumbo v0, "android.content.ISyncServiceAdapter" return-object v0 .end method .method public startSync(Landroid/content/ISyncContext;Landroid/os/Bundle;)V .locals 5 .annotation system Ldalvik/annotation/Throws; value = { Landroid/os/RemoteException; } .end annotation const/4 v1, 0x0 invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel; move-result-object v0 :try_start_0 const-string/jumbo v2, "android.content.ISyncServiceAdapter" invoke-virtual {v0, v2}, Landroid/os/Parcel;->writeInterfaceToken(Ljava/lang/String;)V if-eqz p1, :cond_0 invoke-interface {p1}, Landroid/content/ISyncContext;->asBinder()Landroid/os/IBinder; move-result-object v1 :cond_0 invoke-virtual {v0, v1}, Landroid/os/Parcel;->writeStrongBinder(Landroid/os/IBinder;)V if-eqz p2, :cond_1 const/4 v1, 0x1 invoke-virtual {v0, v1}, Landroid/os/Parcel;->writeInt(I)V const/4 v1, 0x0 invoke-virtual {p2, v0, v1}, Landroid/os/Bundle;->writeToParcel(Landroid/os/Parcel;I)V :goto_0 iget-object v1, p0, Landroid/content/ISyncServiceAdapter$Stub$Proxy;->mRemote:Landroid/os/IBinder; const/4 v2, 0x1 const/4 v3, 0x0 const/4 v4, 0x1 invoke-interface {v1, v2, v0, v3, v4}, Landroid/os/IBinder;->transact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z :try_end_0 .catchall {:try_start_0 .. :try_end_0} :catchall_0 invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V return-void :cond_1 const/4 v1, 0x0 :try_start_1 invoke-virtual {v0, v1}, Landroid/os/Parcel;->writeInt(I)V :try_end_1 .catchall {:try_start_1 .. :try_end_1} :catchall_0 goto :goto_0 :catchall_0 move-exception v1 invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V throw v1 .end method
{ "content_hash": "04224b0a28cbefac115d2c6986b141d0", "timestamp": "", "source": "github", "line_count": 176, "max_line_length": 116, "avg_line_length": 24, "alnum_prop": 0.6934185606060606, "repo_name": "BatMan-Rom/ModdedFiles", "id": "f4f5a73c1dd140a3c5aae295f1f1f3de70c2cd7a", "size": "4224", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "framework.jar.out/smali/android/content/ISyncServiceAdapter$Stub$Proxy.smali", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "GLSL", "bytes": "15069" }, { "name": "HTML", "bytes": "139176" }, { "name": "Smali", "bytes": "541934400" } ], "symlink_target": "" }
/* * Power-Up Reset Overview * ----------------------- * * The ARM core starts executing code on reset with the program counter set * to 0x0000:0000. The LPC43xx contains a shadow pointer register that * allows areas of memory to be mapped to address 0x0000:0000. The default, * reset value of the shadow pointer is 0x1040:0000 so that on reset code in * the boot ROM is always executed first. * * The boot starts after reset is released. The IRC is selected as CPU clock * and the Cortex-M4 starts the boot loader. By default the JTAG access to the * chip is disabled at reset. The boot ROM determines the boot mode based on * the OTP BOOT_SRC value or reset state pins. For flash-based parts, the part * boots from internal flash by default. Otherwse, the boot ROM copies the * image to internal SRAM at location 0x1000:0000, sets the ARM's shadow * pointer to 0x1000:0000, and jumps to that location. * * However, using JTAG the executable image can be also loaded directly into * and executed from SRAM. */ #include <nuttx/config.h> #include <stdint.h> #include <assert.h> #include <debug.h> #include <nuttx/init.h> #include <arch/board/board.h> #include "up_arch.h" #include "up_internal.h" #include "nvic.h" #include "chip/lpc43_creg.h" #include "lpc43_rgu.h" #include "lpc43_cgu.h" #include "lpc43_emc.h" #include "lpc43_uart.h" #include "lpc43_userspace.h" /**************************************************************************** * Preprocessor Definitions ****************************************************************************/ /**************************************************************************** * Name: showprogress * * Description: * Print a character on the UART to show boot status. * ****************************************************************************/ #ifdef CONFIG_DEBUG # define showprogress(c) up_lowputc(c) #else # define showprogress(c) #endif /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: lpc43_setbootrom * * Description: * Set the shadow register to 0x1040:0000 and the VTOR to 0x0000:0000 so * that any exceptions (particulary things like hard faults) that occur * before we are initialized are caught by the BOOT ROM. * ****************************************************************************/ static inline void lpc43_setbootrom(void) { /* Set the shadow register to the beginning of the boot ROM (Only bits 12-31) */ putreg32(LPC43_ROM_BASE, LPC43_CREG_M4MEMMAP); /* Address zero now maps to the Boot ROM. Make sure the the VTOR will * use the ROM vector table at that address. */ putreg32(0, NVIC_VECTAB); } /**************************************************************************** * Name: lpc43_enabuffering * * Description: * If we are executing from external FLASH, then enable buffering. * ****************************************************************************/ #if defined(CONFIG_LPC43_BOOT_CS0FLASH) || defined(CONFIG_LPC43_BOOT_CS1FLASH) || \ defined(CONFIG_LPC43_BOOT_CS2FLASH) || defined(CONFIG_LPC43_BOOT_CS3FLASH) static inline void lpc43_enabuffering(void) { uint32_t regval; #ifdef CONFIG_LPC43_BOOT_CS0FLASH regval = getreg32(LPC43_EMC_STATCONFIG0); regval |= EMC_STATCONFIG_BENA putreg32(regval, LPC43_EMC_STATCONFIG0); #endif #ifdef CONFIG_LPC43_BOOT_CS1FLASH regval = getreg32(LPC43_EMC_STATCONFIG1); regval |= EMC_STATCONFIG_BENA putreg32(regval, LPC43_EMC_STATCONFIG1); #endif #ifdef CONFIG_LPC43_BOOT_CS2FLASH regval = getreg32(LPC43_EMC_STATCONFIG2); regval |= EMC_STATCONFIG_BENA putreg32(regval, LPC43_EMC_STATCONFIG2); #endif #ifdef CONFIG_LPC43_BOOT_CS3FLASH regval = getreg32(LPC43_EMC_STATCONFIG3); regval |= EMC_STATCONFIG_BENA putreg32(regval, LPC43_EMC_STATCONFIG3); #endif } #else # define lpc43_enabuffering() #endif /**************************************************************************** * Name: lpc43_fpuconfig * * Description: * Configure the FPU. Relative bit settings: * * CPACR: Enables access to CP10 and CP11 * CONTROL.FPCA: Determines whether the FP extension is active in the * current context: * FPCCR.ASPEN: Enables automatic FP state preservation, then the * processor sets this bit to 1 on successful completion of any FP * instruction. * FPCCR.LSPEN: Enables lazy context save of FP state. When this is * done, the processor reserves space on the stack for the FP state, * but does not save that state information to the stack. * * Software must not change the value of the ASPEN bit or LSPEN bit while either: * - the CPACR permits access to CP10 and CP11, that give access to the FP * extension, or * - the CONTROL.FPCA bit is set to 1 * ****************************************************************************/ #ifdef CONFIG_ARCH_FPU #ifdef CONFIG_ARMV7M_CMNVECTOR static inline void lpc43_fpuconfig(void) { uint32_t regval; /* Set CONTROL.FPCA so that we always get the extended context frame * with the volatile FP registers stacked above the basic context. */ regval = getcontrol(); regval |= (1 << 2); setcontrol(regval); /* Ensure that FPCCR.LSPEN is disabled, so that we don't have to contend * with the lazy FP context save behaviour. Clear FPCCR.ASPEN since we * are going to turn on CONTROL.FPCA for all contexts. */ regval = getreg32(NVIC_FPCCR); regval &= ~((1 << 31) | (1 << 30)); putreg32(regval, NVIC_FPCCR); /* Enable full access to CP10 and CP11 */ regval = getreg32(NVIC_CPACR); regval |= ((3 << (2*10)) | (3 << (2*11))); putreg32(regval, NVIC_CPACR); } #else static inline void lpc43_fpuconfig(void) { uint32_t regval; /* Clear CONTROL.FPCA so that we do not get the extended context frame * with the volatile FP registers stacked in the saved context. */ regval = getcontrol(); regval &= ~(1 << 2); setcontrol(regval); /* Ensure that FPCCR.LSPEN is disabled, so that we don't have to contend * with the lazy FP context save behaviour. Clear FPCCR.ASPEN since we * are going to keep CONTROL.FPCA off for all contexts. */ regval = getreg32(NVIC_FPCCR); regval &= ~((1 << 31) | (1 << 30)); putreg32(regval, NVIC_FPCCR); /* Enable full access to CP10 and CP11 */ regval = getreg32(NVIC_CPACR); regval |= ((3 << (2*10)) | (3 << (2*11))); putreg32(regval, NVIC_CPACR); } #endif #else # define lpc43_fpuconfig() #endif /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: _start * * Description: * This is the reset entry point. * ****************************************************************************/ void __start(void) { const uint32_t *src; uint32_t *dest; /* Reset as many of the LPC43 peripherals as possible. This is necessary * because the LPC43 does not provide any way of performing a full system * reset under debugger control. So, if CONFIG_DEBUG is set (indicating * that a debugger is being used?), the the boot logic will call this * function on all restarts. */ #ifdef CONFIG_DEBUG lpc43_softreset(); #endif /* Make sure that any exceptions (such as hard faults) that occur before * we are initialized are caught by the BOOT ROM. */ lpc43_setbootrom(); /* Configure the CGU clocking and the console uart so that we can get * debug output as soon as possible. */ lpc43_clockconfig(); lpc43_lowsetup(); showprogress('A'); /* If we are executing from external FLASH, then enable buffering */ lpc43_enabuffering(); /* Clear .bss. We'll do this inline (vs. calling memset) just to be * certain that there are no issues with the state of global variables. */ for (dest = &_sbss; dest < &_ebss; ) { *dest++ = 0; } showprogress('B'); /* Move the intialized data section from his temporary holding spot in * FLASH into the correct place in SRAM. The correct place in SRAM is * give by _sdata and _edata. The temporary location is in FLASH at the * end of all of the other read-only data (.text, .rodata) at _eronly. */ for (src = &_eronly, dest = &_sdata; dest < &_edata; ) { *dest++ = *src++; } showprogress('C'); /* Initialize the FPU (if configured) */ lpc43_fpuconfig(); showprogress('D'); /* Perform early serial initialization */ #ifdef USE_EARLYSERIALINIT up_earlyserialinit(); #endif showprogress('E'); /* For the case of the separate user-/kernel-space build, perform whatever * platform specific initialization of the user memory is required. * Normally this just means initializing the user space .data and .bss * segments. */ #ifdef CONFIG_NUTTX_KERNEL lpc43_userspace(); showprogress('F'); #endif /* Initialize onboard resources */ lpc43_boardinitialize(); showprogress('G'); /* Then start NuttX */ showprogress('\r'); showprogress('\n'); os_start(); /* Shouldn't get here */ for(;;); }
{ "content_hash": "939bdbca975f10a2bf77aaaea103efa2", "timestamp": "", "source": "github", "line_count": 327, "max_line_length": 83, "avg_line_length": 28.737003058103976, "alnum_prop": 0.5959348728317548, "repo_name": "gcds/project_xxx", "id": "bb9d8c6ab6f1b82e0dcf692a59d34fd148c5ba18", "size": "11239", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "nuttx/arch/arm/src/lpc43xx/lpc43_start.c", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package org.elasticsearch.xpack.sql.expression.function.aggregate; import org.elasticsearch.xpack.ql.expression.Expression; import org.elasticsearch.xpack.ql.tree.NodeInfo; import org.elasticsearch.xpack.ql.tree.Source; import java.util.List; /** * Find the last value of the field ordered by the 2nd argument (if provided) */ public class Last extends TopHits { public Last(Source source, Expression field, Expression sortField) { super(source, field, sortField); } @Override protected NodeInfo<Last> info() { return NodeInfo.create(this, Last::new, field(), orderField()); } @Override public Last replaceChildren(List<Expression> newChildren) { return new Last(source(), newChildren.get(0), newChildren.size() > 1 ? newChildren.get(1) : null); } }
{ "content_hash": "faccf5bb505980e154f93da3c397c75b", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 106, "avg_line_length": 29.107142857142858, "alnum_prop": 0.7116564417177914, "repo_name": "robin13/elasticsearch", "id": "81bd756d8086550cfca2ef9985db9d480e924e18", "size": "1067", "binary": false, "copies": "36", "ref": "refs/heads/master", "path": "x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Last.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "11082" }, { "name": "Batchfile", "bytes": "14049" }, { "name": "Emacs Lisp", "bytes": "3341" }, { "name": "FreeMarker", "bytes": "45" }, { "name": "Groovy", "bytes": "315863" }, { "name": "HTML", "bytes": "3399" }, { "name": "Java", "bytes": "40107206" }, { "name": "Perl", "bytes": "7271" }, { "name": "Python", "bytes": "54437" }, { "name": "Shell", "bytes": "108937" } ], "symlink_target": "" }
``` git clone https://github.com/narsi84/digilib.git digilib sudo apt-get install apache2 sudo apt-get install vim sudo apt-get install python-cffi sudo apt-get install libffi-dev sudo pip3 install Django sudo pip3 install djangorestframework sudo pip3 install django-cors-headers sudo pip3 install markdown sudo pip3 install django-filter sudo pip3 install --upgrade django-crispy-forms sudo pip3 install -U pyOpenSSL sudo pip3 install service_identity ``` # Setup Make sure VNC server is running, "Preferences->Raspberry pi configuration->Interfaces->VNC->Enabled" ## Start services on boot In /etc/rc.local, enter following lines above 'exit 0' ``` LOG=/home/pi/startup.log DJANGO_LOG=/home/pi/django.log date > $LOG echo "Starting apache" >> $LOG sudo service apache2 start >> $LOG 2>&1 echo "Starting ssh" >> $LOG sudo service ssh start ``` Since we are running with virtualenv, it cannot be loaded by boot. In /home/pi/.bashrc, add these lines at the end ``` echo "Starting Django" >> ~/startup.log source ~/venv/bin/activate ~/digilib/manage.py runserver 0.0.0.0:8000 > ~/django.log 2>&1 & ``` ## Set up django ``` sudo ln -sf /home/pi/digilib/static /var/www/html/digilib sudo mkdir /var/www/html/imgs sudo chown pi /var/www/html/imgs sudo mkdir /var/www/html/test sudo chown pi /var/www/html/test ``` ## Set up opencv Follow instructions in http://www.pyimagesearch.com/2016/04/18/install-guide-raspberry-pi-3-raspbian-jessie-opencv-3/ to install opencv ``` sudo reboot ``` You should now be able to access http://raspberrypi/digilib from within your home network
{ "content_hash": "d5d318b079b0980d6f044ee20292d42a", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 135, "avg_line_length": 25.596774193548388, "alnum_prop": 0.7511027095148078, "repo_name": "narsi84/digilib", "id": "5c988f88e699aaeb78ad35c10ca1777d398bca13", "size": "1602", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "843" }, { "name": "HTML", "bytes": "4358" }, { "name": "JavaScript", "bytes": "4551" }, { "name": "Python", "bytes": "22810" } ], "symlink_target": "" }
<h2>SubUnit</h2> <h4>Selections in THREE.js</h4> SubUnit gives you an ES6 version of D3 selections that work against a THREE.js scene graph. It allows you to select into the scene and use D3 style syntax. ```html npm install subunit ``` ```html bower install subunit ``` <img src="img/spiral-circle.png" height="250px"/> <img src="img/arcs.png" height="250px"/> <img src="img/earthquakes.png" height="250px"/> To run the demos, type npm install in the root folder to get the dependencies for the demos. Run a local server from the root folder... ```html cd subunit python -m SimpleHTTPServer 8000 (or your favorite local server) ```
{ "content_hash": "9a9ab7019564dfbe56b59f53653ac74a", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 156, "avg_line_length": 24.692307692307693, "alnum_prop": 0.7289719626168224, "repo_name": "aeschylus/subunit", "id": "89cc6719f74e510ff21286d7f19c28d769e435a8", "size": "642", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "635" }, { "name": "HTML", "bytes": "23491" }, { "name": "JavaScript", "bytes": "100366" } ], "symlink_target": "" }
=head1 LICENSE Copyright 2015 EMBL - European Bioinformatics Institute 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. =cut package Bio::SRAXml::Analysis::SimpleAnalysisType; use strict; use namespace::autoclean; use Moose; use Bio::SRAXml::Types; with 'Bio::SRAXml::Roles::AnalysisType'; has 'type' => ( is => 'rw', isa => 'Bio::SRAXml::SimpleAnalysisTypeEnum', required => 1 ); sub write_to_xml { my ( $self, $write_to_xml ) = @_; $write_to_xml->emptyTag( uc( $self->type() ) ); } __PACKAGE__->meta->make_immutable; 1;
{ "content_hash": "a897315a0b55bc368c6ce6fed498a122", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 90, "avg_line_length": 34.53333333333333, "alnum_prop": 0.7162162162162162, "repo_name": "FAANG/sra_xml", "id": "1ddb41c19e863a9b20b53fd9e35cff5b8f1c6f08", "size": "1037", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/Bio/SRAXml/Analysis/SimpleAnalysisType.pm", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Perl", "bytes": "88844" }, { "name": "Perl6", "bytes": "12454" } ], "symlink_target": "" }
/* eslint-disable */ /// <reference path="jqwidgets.d.ts" /> import '../jqwidgets/jqxcore.js'; import '../jqwidgets/jqxdata.js'; import '../jqwidgets/jqxbuttons.js'; import '../jqwidgets/jqxtagcloud.js'; import { Component, Input, Output, EventEmitter, ElementRef, OnChanges, SimpleChanges } from '@angular/core'; declare let JQXLite: any; @Component({ selector: 'jqxTagCloud', template: '<div><ng-content></ng-content></div>' }) export class jqxTagCloudComponent implements OnChanges { @Input('alterTextCase') attrAlterTextCase: string; @Input('disabled') attrDisabled: boolean; @Input('displayLimit') attrDisplayLimit: number; @Input('displayMember') attrDisplayMember: string; @Input('displayValue') attrDisplayValue: boolean; @Input('fontSizeUnit') attrFontSizeUnit: string; @Input('maxColor') attrMaxColor: string; @Input('maxFontSize') attrMaxFontSize: number; @Input('maxValueToDisplay') attrMaxValueToDisplay: number; @Input('minColor') attrMinColor: string; @Input('minFontSize') attrMinFontSize: number; @Input('minValueToDisplay') attrMinValueToDisplay: number; @Input('rtl') attrRtl: boolean; @Input('sortBy') attrSortBy: string; @Input('sortOrder') attrSortOrder: string; @Input('source') attrSource: jqwidgets.TagCloudSource; @Input('tagRenderer') attrTagRenderer: (itemData: jqwidgets.TagCloudTagRenderer['itemData'], minValue: jqwidgets.TagCloudTagRenderer['minValue'], valueRange: jqwidgets.TagCloudTagRenderer['valueRange']) => any; @Input('takeTopWeightedItems') attrTakeTopWeightedItems: boolean; @Input('textColor') attrTextColor: string; @Input('urlBase') attrUrlBase: string; @Input('urlMember') attrUrlMember: string; @Input('valueMember') attrValueMember: string; @Input('width') attrWidth: string | number; @Input('height') attrHeight: string | number; @Input('auto-create') autoCreate: boolean = true; properties: string[] = ['alterTextCase','disabled','displayLimit','displayMember','displayValue','fontSizeUnit','height','maxColor','maxFontSize','maxValueToDisplay','minColor','minFontSize','minValueToDisplay','rtl','sortBy','sortOrder','source','tagRenderer','takeTopWeightedItems','textColor','urlBase','urlMember','valueMember','width']; host: any; elementRef: ElementRef; widgetObject: jqwidgets.jqxTagCloud; constructor(containerElement: ElementRef) { this.elementRef = containerElement; } ngOnInit() { if (this.autoCreate) { this.createComponent(); } }; ngOnChanges(changes: SimpleChanges) { if (this.host) { for (let i = 0; i < this.properties.length; i++) { let attrName = 'attr' + this.properties[i].substring(0, 1).toUpperCase() + this.properties[i].substring(1); let areEqual: boolean = false; if (this[attrName] !== undefined) { if (typeof this[attrName] === 'object') { if (this[attrName] instanceof Array) { areEqual = this.arraysEqual(this[attrName], this.host.jqxTagCloud(this.properties[i])); } if (areEqual) { return false; } this.host.jqxTagCloud(this.properties[i], this[attrName]); continue; } if (this[attrName] !== this.host.jqxTagCloud(this.properties[i])) { this.host.jqxTagCloud(this.properties[i], this[attrName]); } } } } } arraysEqual(attrValue: any, hostValue: any): boolean { if ((attrValue && !hostValue) || (!attrValue && hostValue)) { return false; } if (attrValue.length != hostValue.length) { return false; } for (let i = 0; i < attrValue.length; i++) { if (attrValue[i] !== hostValue[i]) { return false; } } return true; } manageAttributes(): any { let options = {}; for (let i = 0; i < this.properties.length; i++) { let attrName = 'attr' + this.properties[i].substring(0, 1).toUpperCase() + this.properties[i].substring(1); if (this[attrName] !== undefined) { options[this.properties[i]] = this[attrName]; } } return options; } moveClasses(parentEl: HTMLElement, childEl: HTMLElement): void { let classes: any = parentEl.classList; if (classes.length > 0) { childEl.classList.add(...classes); } parentEl.className = ''; } moveStyles(parentEl: HTMLElement, childEl: HTMLElement): void { let style = parentEl.style.cssText; childEl.style.cssText = style parentEl.style.cssText = ''; } createComponent(options?: any): void { if (this.host) { return; } if (options) { JQXLite.extend(options, this.manageAttributes()); } else { options = this.manageAttributes(); } this.host = JQXLite(this.elementRef.nativeElement.firstChild); this.moveClasses(this.elementRef.nativeElement, this.host[0]); this.moveStyles(this.elementRef.nativeElement, this.host[0]); this.__wireEvents__(); this.widgetObject = jqwidgets.createInstance(this.host, 'jqxTagCloud', options); } createWidget(options?: any): void { this.createComponent(options); } __updateRect__() : void { if(this.host) this.host.css({ width: this.attrWidth, height: this.attrHeight }); } setOptions(options: any) : void { this.host.jqxTagCloud('setOptions', options); } // jqxTagCloudComponent properties alterTextCase(arg?: string): string { if (arg !== undefined) { this.host.jqxTagCloud('alterTextCase', arg); } else { return this.host.jqxTagCloud('alterTextCase'); } } disabled(arg?: boolean): boolean { if (arg !== undefined) { this.host.jqxTagCloud('disabled', arg); } else { return this.host.jqxTagCloud('disabled'); } } displayLimit(arg?: number): number { if (arg !== undefined) { this.host.jqxTagCloud('displayLimit', arg); } else { return this.host.jqxTagCloud('displayLimit'); } } displayMember(arg?: string): string { if (arg !== undefined) { this.host.jqxTagCloud('displayMember', arg); } else { return this.host.jqxTagCloud('displayMember'); } } displayValue(arg?: boolean): boolean { if (arg !== undefined) { this.host.jqxTagCloud('displayValue', arg); } else { return this.host.jqxTagCloud('displayValue'); } } fontSizeUnit(arg?: string): string { if (arg !== undefined) { this.host.jqxTagCloud('fontSizeUnit', arg); } else { return this.host.jqxTagCloud('fontSizeUnit'); } } height(arg?: number | string): number | string { if (arg !== undefined) { this.host.jqxTagCloud('height', arg); } else { return this.host.jqxTagCloud('height'); } } maxColor(arg?: string): string { if (arg !== undefined) { this.host.jqxTagCloud('maxColor', arg); } else { return this.host.jqxTagCloud('maxColor'); } } maxFontSize(arg?: number): number { if (arg !== undefined) { this.host.jqxTagCloud('maxFontSize', arg); } else { return this.host.jqxTagCloud('maxFontSize'); } } maxValueToDisplay(arg?: number): number { if (arg !== undefined) { this.host.jqxTagCloud('maxValueToDisplay', arg); } else { return this.host.jqxTagCloud('maxValueToDisplay'); } } minColor(arg?: string): string { if (arg !== undefined) { this.host.jqxTagCloud('minColor', arg); } else { return this.host.jqxTagCloud('minColor'); } } minFontSize(arg?: number): number { if (arg !== undefined) { this.host.jqxTagCloud('minFontSize', arg); } else { return this.host.jqxTagCloud('minFontSize'); } } minValueToDisplay(arg?: number): number { if (arg !== undefined) { this.host.jqxTagCloud('minValueToDisplay', arg); } else { return this.host.jqxTagCloud('minValueToDisplay'); } } rtl(arg?: boolean): boolean { if (arg !== undefined) { this.host.jqxTagCloud('rtl', arg); } else { return this.host.jqxTagCloud('rtl'); } } sortBy(arg?: string): string { if (arg !== undefined) { this.host.jqxTagCloud('sortBy', arg); } else { return this.host.jqxTagCloud('sortBy'); } } sortOrder(arg?: string): string { if (arg !== undefined) { this.host.jqxTagCloud('sortOrder', arg); } else { return this.host.jqxTagCloud('sortOrder'); } } source(arg?: jqwidgets.TagCloudSource): jqwidgets.TagCloudSource { if (arg !== undefined) { this.host.jqxTagCloud('source', arg); } else { return this.host.jqxTagCloud('source'); } } tagRenderer(arg?: (itemData: jqwidgets.TagCloudTagRenderer['itemData'], minValue: jqwidgets.TagCloudTagRenderer['minValue'], valueRange: jqwidgets.TagCloudTagRenderer['valueRange']) => any): (itemData: jqwidgets.TagCloudTagRenderer['itemData'], minValue: jqwidgets.TagCloudTagRenderer['minValue'], valueRange: jqwidgets.TagCloudTagRenderer['valueRange']) => any { if (arg !== undefined) { this.host.jqxTagCloud('tagRenderer', arg); } else { return this.host.jqxTagCloud('tagRenderer'); } } takeTopWeightedItems(arg?: boolean): boolean { if (arg !== undefined) { this.host.jqxTagCloud('takeTopWeightedItems', arg); } else { return this.host.jqxTagCloud('takeTopWeightedItems'); } } textColor(arg?: string): string { if (arg !== undefined) { this.host.jqxTagCloud('textColor', arg); } else { return this.host.jqxTagCloud('textColor'); } } urlBase(arg?: string): string { if (arg !== undefined) { this.host.jqxTagCloud('urlBase', arg); } else { return this.host.jqxTagCloud('urlBase'); } } urlMember(arg?: string): string { if (arg !== undefined) { this.host.jqxTagCloud('urlMember', arg); } else { return this.host.jqxTagCloud('urlMember'); } } valueMember(arg?: string): string { if (arg !== undefined) { this.host.jqxTagCloud('valueMember', arg); } else { return this.host.jqxTagCloud('valueMember'); } } width(arg?: string | number): string | number { if (arg !== undefined) { this.host.jqxTagCloud('width', arg); } else { return this.host.jqxTagCloud('width'); } } // jqxTagCloudComponent functions destroy(): void { this.host.jqxTagCloud('destroy'); } findTagIndex(tag: string): number { return this.host.jqxTagCloud('findTagIndex', tag); } getHiddenTagsList(): Array<any> { return this.host.jqxTagCloud('getHiddenTagsList'); } getRenderedTags(): Array<any> { return this.host.jqxTagCloud('getRenderedTags'); } getTagsList(): Array<any> { return this.host.jqxTagCloud('getTagsList'); } hideItem(index: number): void { this.host.jqxTagCloud('hideItem', index); } insertAt(index: number, item: any): void { this.host.jqxTagCloud('insertAt', index, item); } removeAt(index: number): void { this.host.jqxTagCloud('removeAt', index); } updateAt(index: number, item: any): void { this.host.jqxTagCloud('updateAt', index, item); } showItem(index: number): void { this.host.jqxTagCloud('showItem', index); } // jqxTagCloudComponent events @Output() onBindingComplete = new EventEmitter(); @Output() onItemClick = new EventEmitter(); __wireEvents__(): void { this.host.on('bindingComplete', (eventData: any) => { this.onBindingComplete.emit(eventData); }); this.host.on('itemClick', (eventData: any) => { this.onItemClick.emit(eventData); }); } } //jqxTagCloudComponent
{ "content_hash": "96c9268ef343dc84b4138d0e3c3c6a69", "timestamp": "", "source": "github", "line_count": 409, "max_line_length": 366, "avg_line_length": 30.17848410757946, "alnum_prop": 0.6015555375516487, "repo_name": "cdnjs/cdnjs", "id": "20fde629d092346f44eff69fc5cedc1460592ae6", "size": "12457", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ajax/libs/jqwidgets/12.1.2/jqwidgets-ts/angular_jqxtagcloud.ts", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<!DOCTYPE html> <html xmlns:msxsl="urn:schemas-microsoft-com:xslt"> <head> <meta content="en-us" http-equiv="Content-Language" /> <meta content="text/html; charset=utf-16" http-equiv="Content-Type" /> <title _locid="PortabilityAnalysis0">.NET Portability Report</title> <style> /* Body style, for the entire document */ body { background: #F3F3F4; color: #1E1E1F; font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; padding: 0; margin: 0; } /* Header1 style, used for the main title */ h1 { padding: 10px 0px 10px 10px; font-size: 21pt; background-color: #E2E2E2; border-bottom: 1px #C1C1C2 solid; color: #201F20; margin: 0; font-weight: normal; } /* Header2 style, used for "Overview" and other sections */ h2 { font-size: 18pt; font-weight: normal; padding: 15px 0 5px 0; margin: 0; } /* Header3 style, used for sub-sections, such as project name */ h3 { font-weight: normal; font-size: 15pt; margin: 0; padding: 15px 0 5px 0; background-color: transparent; } h4 { font-weight: normal; font-size: 12pt; margin: 0; padding: 0 0 0 0; background-color: transparent; } /* Color all hyperlinks one color */ a { color: #1382CE; } /* Paragraph text (for longer informational messages) */ p { font-size: 10pt; } /* Table styles */ table { border-spacing: 0 0; border-collapse: collapse; font-size: 10pt; } table th { background: #E7E7E8; text-align: left; text-decoration: none; font-weight: normal; padding: 3px 6px 3px 6px; } table td { vertical-align: top; padding: 3px 6px 5px 5px; margin: 0px; border: 1px solid #E7E7E8; background: #F7F7F8; } .NoBreakingChanges { color: darkgreen; font-weight:bold; } .FewBreakingChanges { color: orange; font-weight:bold; } .ManyBreakingChanges { color: red; font-weight:bold; } .BreakDetails { margin-left: 30px; } .CompatMessage { font-style: italic; font-size: 10pt; } .GoodMessage { color: darkgreen; } /* Local link is a style for hyperlinks that link to file:/// content, there are lots so color them as 'normal' text until the user mouse overs */ .localLink { color: #1E1E1F; background: #EEEEED; text-decoration: none; } .localLink:hover { color: #1382CE; background: #FFFF99; text-decoration: none; } /* Center text, used in the over views cells that contain message level counts */ .textCentered { text-align: center; } /* The message cells in message tables should take up all avaliable space */ .messageCell { width: 100%; } /* Padding around the content after the h1 */ #content { padding: 0px 12px 12px 12px; } /* The overview table expands to width, with a max width of 97% */ #overview table { width: auto; max-width: 75%; } /* The messages tables are always 97% width */ #messages table { width: 97%; } /* All Icons */ .IconSuccessEncoded, .IconInfoEncoded, .IconWarningEncoded, .IconErrorEncoded { min-width: 18px; min-height: 18px; background-repeat: no-repeat; background-position: center; } /* Success icon encoded */ .IconSuccessEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconSuccess#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABPElEQVR4Xp1Tv0vDUBi8FqeA4NpBcBLcWnQSApncOnTo4FSnjP0DsnXpH5CxiwbHDg4Zuj4oOEXiJgiC4FDcCkLWmIMc1Pfw+eMgQ77v3Xf3Pe51YKGqqisAEwCR1TIAsiAIblSo6xrdHeJR85Xle3mdmCQKb0PsfqyxxzM8K15HZADl/H5+sHpZwYfxyRjTs+kWwKBx8yoHd2mRiuzF8mkJniWH/13u3Fjrs/EdhsdDFHGB/DLXEJBDLh1MWPAhPo1BLB4WX5yQywHR+m3tVe/t97D52CB/ziG0nIgD/qDuYg8WuCcVZ2YGwlJ3YDugkpR/VNcAEx6GEKhERSr71FuO4YCM4XBdwKvecjIlkSnsO0Hyp/GxSeJAdzBKzpOtnPwyyiPdAZhpZptT04tU+zk7s8czeges//s5C5+CwqrR4/gw+AAAAABJRU5ErkJggg==); } /* Information icon encoded */ .IconInfoEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconInformation#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABHElEQVR4Xs2TsUoDQRRF7wwoziokjZUKadInhdhukR9YP8DMX1hYW+QvdsXa/QHBbcXC7W0CamWTQnclFutceIQJwwaWNLlwm5k5d94M76mmaeCrrmsLYOocY12FcxZFUeozCqKqqgYA8uevv1H6VuPxcwlfk5N92KHBxfFeCSAxxswlYAW/Xr989x/mv9gkhtyMDhcAxgzRsp7flj8B/HF1RsMXq+NZMkopaHe7lbKxQUEIGbKsYNoGn969060hZBkQex/W8oRQwsQaW2o3Ago2SVcJUzAgY3N0lTCZZm+zPS8HB51gMmS1DEYyOz9acKO1D8JWTlafKIMxdhvlfdyT94Vv5h7P8Ky7nQzACmhvKq3zk3PjW9asz9D/1oigecsioooAAAAASUVORK5CYII=); } /* Warning icon encoded */ .IconWarningEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconWarning#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAx0lEQVR4XpWSMQ7CMAxFf4xAyBMLCxMrO8dhaBcuwdCJS3RJBw7SA/QGTCxdWJgiQYWKXJWKIXHIlyw5lqr34tQgEOdcBsCOx5yZK3hCCKdYXneQkh4pEfqzLfu+wVDSyyzFoJjfz9NB+pAF+eizx2Vruts0k15mPgvS6GYvpVtQhB61IB/dk6AF6fS4Ben0uIX5odtFe8Q/eW1KvFeH4e8khT6+gm5B+t3juyDt7n0jpe+CANTd+oTUjN/U3yVaABnSUjFz/gFq44JaVSCXeQAAAABJRU5ErkJggg==); } /* Error icon encoded */ .IconErrorEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconError#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABQElEQVR4XqWTvUoEQRCE6wYPZUA80AfwAQz23uCMjA7MDRQEIzPBVEyNTQUFIw00vcQTTMzuAh/AxEQQT8HF/3G/oGGnEUGuoNnd6qoZuqltyKEsyzVJq5I6rnUp6SjGeGhESikzzlc1eL7opfuVbrqbU1Zw9NCgtQMaZpY0eNnaaL2fHusvTK5vKu7sjSS1Y4y3QUA6K3e3Mau5UFDyMP7tYF9o8cAHZv68vipoIJg971PZIZ5HiwdvYGGvFVFHmGmZ2MxwmQYPXubPl9Up0tfoMQGetXd6mRbvhBw+boZ6WF7Mbv1+GsHRk0fQmPAH1GfmZirbCfDJ61tw3Px8/8pZsPAG4jlVhcPgZ7adwNWBB68lkRQWFiTgFlbnLY3DGGM7izIJIyT/jjIvEJw6fdJTc6krDzh6aMwMP9bvDH4ADSsa9uSWVJkAAAAASUVORK5CYII=); } </style> </head> <body> <h1 _locid="PortabilityReport">.NET Portability Report</h1> <div id="content"> <div id="submissionId" style="font-size:8pt;"> <p> <i> Submission Id&nbsp; ffca441f-363f-4638-a01d-faa9e92f0c3d </i> </p> </div> <h2 _locid="SummaryTitle"> <a name="Portability Summary"></a>Portability Summary </h2> <div id="summary"> <table> <tbody> <tr> <th>Assembly</th> <th>ASP.NET 5,Version=v1.0</th> <th>Windows,Version=v8.1</th> <th>.NET Framework,Version=v4.6</th> <th>Windows Phone,Version=v8.1</th> </tr> <tr> <td><strong><a href="#IKVM.OpenJDK.Util">IKVM.OpenJDK.Util</a></strong></td> <td class="text-center">99.41 %</td> <td class="text-center">99.41 %</td> <td class="text-center">100.00 %</td> <td class="text-center">99.41 %</td> </tr> </tbody> </table> </div> <div id="details"> <a name="IKVM.OpenJDK.Util"><h3>IKVM.OpenJDK.Util</h3></a> <table> <tbody> <tr> <th>Target type</th> <th>ASP.NET 5,Version=v1.0</th> <th>Windows,Version=v8.1</th> <th>.NET Framework,Version=v4.6</th> <th>Windows Phone,Version=v8.1</th> <th>Recommended changes</th> </tr> <tr> <td>System.Diagnostics.DebuggableAttribute</td> <td class="IconErrorEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td style="padding-left:2em">#ctor(System.Boolean,System.Boolean)</td> <td class="IconErrorEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>System.Runtime.Serialization.IObjectReference</td> <td class="IconErrorEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td style="padding-left:2em">GetRealObject(System.Runtime.Serialization.StreamingContext)</td> <td class="IconErrorEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>System.Runtime.Serialization.ISerializable</td> <td class="IconErrorEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td style="padding-left:2em">GetObjectData(System.Runtime.Serialization.SerializationInfo,System.Runtime.Serialization.StreamingContext)</td> <td class="IconErrorEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>System.Runtime.Serialization.SerializationInfo</td> <td class="IconErrorEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td>Remove serialization constructors on custom Exception types</td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> </tbody> </table> <p> <a href="#Portability Summary">Back to Summary</a> </p> </div> </div> </body> </html>
{ "content_hash": "e64ce4f6e894310a75297d9b194cd360", "timestamp": "", "source": "github", "line_count": 359, "max_line_length": 562, "avg_line_length": 42.183844011142064, "alnum_prop": 0.4768885367142103, "repo_name": "kuhlenh/port-to-core", "id": "fda89b1deb52e83177343ad1c030399ed3cc0a99", "size": "15144", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "Reports/ad/advance.db.crawler.1.0.0/IKVM.OpenJDK.Util-net40.html", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "2323514650" } ], "symlink_target": "" }
<?php require_once '../OpenTokSDK.php'; // You must have a valid sessionId and an OpenTokSDK object $apiObj = new OpenTokSDK('11421872', '296cebc2fc4104cd348016667ffa2a3909ec636f'); $sessionId = '1_MX4xMTQyMTg3Mn5-MjAxMi0wNi0wOCAwMTowNjo1MC40NTMxMzIrMDA6MDB-MC40OTY0OTM3NjIzMjh'; // After creating a session, call generateToken(). Require parameter: SessionId $token = $apiObj->generateToken($sessionId); // Giving the token a moderator role, expire time 5 days from now, and connectionData to pass to other users in the session $token = $apiObj->generateToken($sessionId, RoleConstants::MODERATOR, time() + (5*24*60*60), "hello world!" ); echo $token; ?>
{ "content_hash": "b5fb2eb9fe2fd93cf6446b2fb5b8dee9", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 123, "avg_line_length": 34.94736842105263, "alnum_prop": 0.7620481927710844, "repo_name": "MatthewHerbst/DocConnect", "id": "31e640d981df5e890d7c29a400e77805c22ec570", "size": "1816", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tokbox/Opentok-PHP-SDK/sample/generateToken.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "249451" }, { "name": "Erlang", "bytes": "1077" }, { "name": "JavaScript", "bytes": "489605" }, { "name": "PHP", "bytes": "61944" } ], "symlink_target": "" }
package com.goticks import akka.actor.{Props, ActorSystem} import akka.testkit.{ImplicitSender, TestKit} import org.scalatest.{WordSpecLike, MustMatchers} class TickerSellerSpec extends TestKit(ActorSystem("testTickets")) with WordSpecLike with MustMatchers with ImplicitSender with StopSystemAfterAll { "The TicketSeller" must { "Sell tickets until they are sold out" in { import TicketSeller._ def mkTickets = (1 to 10).map(i=>Ticket(i)).toVector val event = "RHCP" val ticketingActor = system.actorOf(TicketSeller.props(event)) ticketingActor ! Add(mkTickets) ticketingActor ! Buy(1) expectMsg(Tickets(event, Vector(Ticket(1)))) val nrs = (2 to 10) nrs.foreach(_ => ticketingActor ! Buy(1)) val tickets = receiveN(9) tickets.zip(nrs).foreach { case (Tickets(event, Vector(Ticket(id))), ix) => id must be(ix) } ticketingActor ! Buy(1) expectMsg(Tickets(event)) } "Sell tickets in batches until they are sold out" in { import TicketSeller._ val firstBatchSize = 10 def mkTickets = (1 to (10 * firstBatchSize)).map(i=>Ticket(i)).toVector val event = "Madlib" val ticketingActor = system.actorOf(TicketSeller.props(event)) ticketingActor ! Add(mkTickets) ticketingActor ! Buy(firstBatchSize) val bought = (1 to firstBatchSize).map(Ticket).toVector expectMsg(Tickets(event, bought)) val secondBatchSize = 5 val nrBatches = 18 val batches = (1 to nrBatches * secondBatchSize) batches.foreach(_ => ticketingActor ! Buy(secondBatchSize)) val tickets = receiveN(nrBatches) tickets.zip(batches).foreach { case (Tickets(event, bought), ix) => bought.size must equal(secondBatchSize) val last = ix * secondBatchSize + firstBatchSize val first = ix * secondBatchSize + firstBatchSize - (secondBatchSize - 1) bought.map(_.id) must equal((first to last).toVector) case _ => } ticketingActor ! Buy(1) expectMsg(Tickets(event)) ticketingActor ! Buy(10) expectMsg(Tickets(event)) } } }
{ "content_hash": "516ea9c25d3d3b366c62598a47965238", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 98, "avg_line_length": 29.376623376623378, "alnum_prop": 0.6295313881520778, "repo_name": "gilbutITbook/006877", "id": "93d9a1c8a1b93978f5524ee7e199c7cb558e0a5c", "size": "2262", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "chapter-up-and-running/src/test/scala/com/goticks/TicketSellerSpec.scala", "mode": "33261", "license": "mit", "language": [ { "name": "Scala", "bytes": "511258" } ], "symlink_target": "" }
package com.hazelcast.jet.core; import com.hazelcast.internal.serialization.DataSerializerHook; import com.hazelcast.internal.serialization.impl.FactoryIdHelper; import com.hazelcast.jet.impl.connector.AbstractUpdateMapP.ApplyValuesEntryProcessor; import com.hazelcast.jet.impl.connector.UpdateMapP.ApplyFnEntryProcessor; import com.hazelcast.nio.serialization.DataSerializableFactory; import com.hazelcast.nio.serialization.IdentifiedDataSerializable; import com.hazelcast.spi.annotation.PrivateApi; import static com.hazelcast.jet.impl.JetFactoryIdHelper.JET_DS_FACTORY; import static com.hazelcast.jet.impl.JetFactoryIdHelper.JET_DS_FACTORY_ID; /** * A Java Service Provider hook for Hazelcast's Identified Data Serializable * mechanism. This is private API. */ @PrivateApi public final class JetDataSerializerHook implements DataSerializerHook { /** * Serialization ID of the {@link DAG} class. */ public static final int DAG = 0; /** * Serialization ID of the {@link Vertex} class. */ public static final int VERTEX = 1; /** * Serialization ID of the {@link Edge} class. */ public static final int EDGE = 2; /** * Serialization ID of the {@link ApplyFnEntryProcessor} class. */ public static final int APPLY_FN_ENTRY_PROCESSOR = 3; /** * Serialization ID of the {@link ApplyValuesEntryProcessor} class. */ public static final int APPLY_VALUE_ENTRY_PROCESSOR = 4; public static final int FACTORY_ID = FactoryIdHelper.getFactoryId(JET_DS_FACTORY, JET_DS_FACTORY_ID); @Override public int getFactoryId() { return FACTORY_ID; } @Override public DataSerializableFactory createFactory() { return new Factory(); } private static class Factory implements DataSerializableFactory { @Override public IdentifiedDataSerializable create(int typeId) { switch (typeId) { case DAG: return new DAG(); case EDGE: return new Edge(); case VERTEX: return new Vertex(); case APPLY_FN_ENTRY_PROCESSOR: return new ApplyFnEntryProcessor(); case APPLY_VALUE_ENTRY_PROCESSOR: return new ApplyValuesEntryProcessor(); default: throw new IllegalArgumentException("Unknown type id " + typeId); } } } }
{ "content_hash": "b3ee9d781d2a08c4d175b39d7aaa736f", "timestamp": "", "source": "github", "line_count": 75, "max_line_length": 105, "avg_line_length": 33.266666666666666, "alnum_prop": 0.662124248496994, "repo_name": "gurbuzali/hazelcast-jet", "id": "d648988729c45b2e904e4a917e49906c6426a71b", "size": "3120", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "hazelcast-jet-core/src/main/java/com/hazelcast/jet/core/JetDataSerializerHook.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1568" }, { "name": "Java", "bytes": "3684048" }, { "name": "Shell", "bytes": "12114" } ], "symlink_target": "" }
`kntest kubetest2 gke` command is a wrapper of `kubetest2-gke` [deployer](https://github.com/kubernetes-sigs/kubetest2/tree/master/kubetest2-gke) to make it easier to run integration tests for Knative. ## Usage This tool can be invoked from command line, and the supported flags could be checked from [kubetest2 common flags](../options.go) and [gke specific flags](./options.go).
{ "content_hash": "08ae1772abd731ef3699e6155ce3d29c", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 82, "avg_line_length": 42.55555555555556, "alnum_prop": 0.7728459530026109, "repo_name": "knative/test-infra", "id": "7cedef72065cfb6b72d648aa360e2dbfe33337e4", "size": "408", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "tools/kntest/pkg/kubetest2/gke/README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "12344" }, { "name": "Go", "bytes": "631330" }, { "name": "HCL", "bytes": "45167" }, { "name": "Jsonnet", "bytes": "68712" }, { "name": "Makefile", "bytes": "17028" }, { "name": "Python", "bytes": "1883" }, { "name": "Shell", "bytes": "16954" } ], "symlink_target": "" }
status: publish tags: - video - websights published: true title: "polyluxende Pornostarb\xC3\xA4ren" type: post meta: tags: "" layout: post --- Wie krass: <a href="http://www.pornstarbears.com/"><img src='/media/wp/thumb-050706pornostarbaeren.jpg' alt='Pornostarb&Atilde;&curren;ren' class="centered" /></a> Habe gerade einen Anbieter für <a href="http://www.pornstarbears.com/">Porno-Teddybären</a> gefunden. Das interessanteste, von den Figuren selbst mal abgesehen, sind wie immer die Namen: Die zwei da oben heißen <strong>Kenny Lingus und Honey Potts</strong>. <!--more--> Das erinnert mich unweigerlich an das Plakat eines Volksfests letzte Woche. Dort stand: <blockquote>"20 Uhr... (irgendeine Sängerin) meets <strong>Buddy Lotion</strong>"</blockquote> und bei diesem unglaublich schlechten Wortspiel musste ich mich unweigerlich fragen, ob es denn nun wirklich nur Musik ist, was sie da auf der Bühne vorführen. Ich muss zugeben, nachdem sich das ARD-Kulturmagazin <strong>Polylux</strong> jüngst mit dem <a href="http://de.wikipedia.org/wiki/Venus_%28Preis%29">Venus Award</a> befasst hat, waren mir Namen wie <a href="http://de.wikipedia.org/wiki/Tyra_Misoux">Tyra Misoux</a> etwas geläufiger... Vielleicht hat er seinen Namen aber auch nur bei einem Porno-Teddy geklaut? Man weiß es nicht ;) P.S.: Übrigens. <a href="http://www.polylux.de">Polylux</a>. Anschautipp. Machen gerade <a href="http://www.rbb-online.de/_/polylux/titas_lounge/index_jsp.html">Sommerpause</a>, sind aber bald wieder da. Sendeplatz: jeweils <a href="http://www.rbb-online.de/_/polylux/vorschau/index_jsp.html">Donnerstag, 23:30 Uhr</a>.
{ "content_hash": "46e2b9b541d958a9dc1cf8a9bf6dd675", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 542, "avg_line_length": 62.88461538461539, "alnum_prop": 0.7522935779816514, "repo_name": "fwenzel/fredericiana", "id": "319384901e4d25a1b9ae8512b9283322c7ccc57a", "size": "1650", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "site/_posts/2005-07-06-polyluxende-pornostarbaren.md", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "114123" }, { "name": "HTML", "bytes": "22292" }, { "name": "JavaScript", "bytes": "30332" }, { "name": "Ruby", "bytes": "8505" } ], "symlink_target": "" }
const es = require('event-stream'); /** Ugly hack for gulp-tsb */ function handleDeletions() { return es.mapSync(f => { if (/\.ts$/.test(f.relative) && !f.contents) { f.contents = Buffer.from(''); f.stat = { mtime: new Date() }; } return f; }); } let watch = void 0; if (!watch) { watch = process.platform === 'win32' ? require('./watch-win32') : require('gulp-watch'); } module.exports = function () { return watch.apply(null, arguments) .pipe(handleDeletions()); };
{ "content_hash": "d0d00eebf112b5bf0c6aa584d00eb0eb", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 89, "avg_line_length": 18.96153846153846, "alnum_prop": 0.6044624746450304, "repo_name": "0xmohit/vscode", "id": "94f73cdd4a058797caebcf7be83a3d37ce3f48fe", "size": "844", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "build/lib/watch/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "5838" }, { "name": "C", "bytes": "818" }, { "name": "C#", "bytes": "1640" }, { "name": "C++", "bytes": "1072" }, { "name": "CSS", "bytes": "498480" }, { "name": "Clojure", "bytes": "1206" }, { "name": "CoffeeScript", "bytes": "590" }, { "name": "Dockerfile", "bytes": "3689" }, { "name": "F#", "bytes": "634" }, { "name": "Go", "bytes": "652" }, { "name": "Groovy", "bytes": "3928" }, { "name": "HLSL", "bytes": "184" }, { "name": "HTML", "bytes": "37165" }, { "name": "Inno Setup", "bytes": "165483" }, { "name": "Java", "bytes": "599" }, { "name": "JavaScript", "bytes": "926375" }, { "name": "Lua", "bytes": "252" }, { "name": "Makefile", "bytes": "1380" }, { "name": "Objective-C", "bytes": "1387" }, { "name": "PHP", "bytes": "998" }, { "name": "Perl", "bytes": "857" }, { "name": "Perl 6", "bytes": "1065" }, { "name": "PowerShell", "bytes": "5118" }, { "name": "Python", "bytes": "2405" }, { "name": "R", "bytes": "362" }, { "name": "Roff", "bytes": "351" }, { "name": "Ruby", "bytes": "1703" }, { "name": "Rust", "bytes": "532" }, { "name": "ShaderLab", "bytes": "330" }, { "name": "Shell", "bytes": "29933" }, { "name": "Swift", "bytes": "284" }, { "name": "TypeScript", "bytes": "19113179" }, { "name": "Visual Basic", "bytes": "893" } ], "symlink_target": "" }
<?php /** * wallee SDK * * This library allows to interact with the wallee payment service. * * 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 Wallee\Sdk\Model; use \ArrayAccess; use \Wallee\Sdk\ObjectSerializer; /** * SubscriptionProductVersion model * * @category Class * @description * @package Wallee\Sdk * @author customweb GmbH * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 */ class SubscriptionProductVersion implements ModelInterface, ArrayAccess { const DISCRIMINATOR = null; /** * The original name of the model. * * @var string */ protected static $swaggerModelName = 'SubscriptionProductVersion'; /** * Array of property to type mappings. Used for (de)serialization * * @var string[] */ protected static $swaggerTypes = [ 'activated_on' => '\DateTime', 'billing_cycle' => 'string', 'comment' => 'string', 'created_on' => '\DateTime', 'default_currency' => 'string', 'enabled_currencies' => 'string[]', 'id' => 'int', 'increment_number' => 'int', 'linked_space_id' => 'int', 'minimal_number_of_periods' => 'int', 'name' => '\Wallee\Sdk\Model\DatabaseTranslatedString', 'number_of_notice_periods' => 'int', 'obsoleted_on' => '\DateTime', 'planned_purge_date' => '\DateTime', 'product' => '\Wallee\Sdk\Model\SubscriptionProduct', 'reference' => 'string', 'retiring_finished_on' => '\DateTime', 'retiring_started_on' => '\DateTime', 'state' => '\Wallee\Sdk\Model\SubscriptionProductVersionState', 'tax_calculation' => '\Wallee\Sdk\Model\TaxCalculation', 'version' => 'int' ]; /** * Array of property to format mappings. Used for (de)serialization * * @var string[] */ protected static $swaggerFormats = [ 'activated_on' => 'date-time', 'billing_cycle' => null, 'comment' => null, 'created_on' => 'date-time', 'default_currency' => null, 'enabled_currencies' => null, 'id' => 'int64', 'increment_number' => 'int32', 'linked_space_id' => 'int64', 'minimal_number_of_periods' => 'int32', 'name' => null, 'number_of_notice_periods' => 'int32', 'obsoleted_on' => 'date-time', 'planned_purge_date' => 'date-time', 'product' => null, 'reference' => null, 'retiring_finished_on' => 'date-time', 'retiring_started_on' => 'date-time', 'state' => null, 'tax_calculation' => null, 'version' => 'int32' ]; /** * Array of attributes where the key is the local name, * and the value is the original name * * @var string[] */ protected static $attributeMap = [ 'activated_on' => 'activatedOn', 'billing_cycle' => 'billingCycle', 'comment' => 'comment', 'created_on' => 'createdOn', 'default_currency' => 'defaultCurrency', 'enabled_currencies' => 'enabledCurrencies', 'id' => 'id', 'increment_number' => 'incrementNumber', 'linked_space_id' => 'linkedSpaceId', 'minimal_number_of_periods' => 'minimalNumberOfPeriods', 'name' => 'name', 'number_of_notice_periods' => 'numberOfNoticePeriods', 'obsoleted_on' => 'obsoletedOn', 'planned_purge_date' => 'plannedPurgeDate', 'product' => 'product', 'reference' => 'reference', 'retiring_finished_on' => 'retiringFinishedOn', 'retiring_started_on' => 'retiringStartedOn', 'state' => 'state', 'tax_calculation' => 'taxCalculation', 'version' => 'version' ]; /** * Array of attributes to setter functions (for deserialization of responses) * * @var string[] */ protected static $setters = [ 'activated_on' => 'setActivatedOn', 'billing_cycle' => 'setBillingCycle', 'comment' => 'setComment', 'created_on' => 'setCreatedOn', 'default_currency' => 'setDefaultCurrency', 'enabled_currencies' => 'setEnabledCurrencies', 'id' => 'setId', 'increment_number' => 'setIncrementNumber', 'linked_space_id' => 'setLinkedSpaceId', 'minimal_number_of_periods' => 'setMinimalNumberOfPeriods', 'name' => 'setName', 'number_of_notice_periods' => 'setNumberOfNoticePeriods', 'obsoleted_on' => 'setObsoletedOn', 'planned_purge_date' => 'setPlannedPurgeDate', 'product' => 'setProduct', 'reference' => 'setReference', 'retiring_finished_on' => 'setRetiringFinishedOn', 'retiring_started_on' => 'setRetiringStartedOn', 'state' => 'setState', 'tax_calculation' => 'setTaxCalculation', 'version' => 'setVersion' ]; /** * Array of attributes to getter functions (for serialization of requests) * * @var string[] */ protected static $getters = [ 'activated_on' => 'getActivatedOn', 'billing_cycle' => 'getBillingCycle', 'comment' => 'getComment', 'created_on' => 'getCreatedOn', 'default_currency' => 'getDefaultCurrency', 'enabled_currencies' => 'getEnabledCurrencies', 'id' => 'getId', 'increment_number' => 'getIncrementNumber', 'linked_space_id' => 'getLinkedSpaceId', 'minimal_number_of_periods' => 'getMinimalNumberOfPeriods', 'name' => 'getName', 'number_of_notice_periods' => 'getNumberOfNoticePeriods', 'obsoleted_on' => 'getObsoletedOn', 'planned_purge_date' => 'getPlannedPurgeDate', 'product' => 'getProduct', 'reference' => 'getReference', 'retiring_finished_on' => 'getRetiringFinishedOn', 'retiring_started_on' => 'getRetiringStartedOn', 'state' => 'getState', 'tax_calculation' => 'getTaxCalculation', 'version' => 'getVersion' ]; /** * Associative array for storing property values * * @var mixed[] */ protected $container = []; /** * Constructor * * @param mixed[] $data Associated array of property values * initializing the model */ public function __construct(array $data = null) { $this->container['activated_on'] = isset($data['activated_on']) ? $data['activated_on'] : null; $this->container['billing_cycle'] = isset($data['billing_cycle']) ? $data['billing_cycle'] : null; $this->container['comment'] = isset($data['comment']) ? $data['comment'] : null; $this->container['created_on'] = isset($data['created_on']) ? $data['created_on'] : null; $this->container['default_currency'] = isset($data['default_currency']) ? $data['default_currency'] : null; $this->container['enabled_currencies'] = isset($data['enabled_currencies']) ? $data['enabled_currencies'] : null; $this->container['id'] = isset($data['id']) ? $data['id'] : null; $this->container['increment_number'] = isset($data['increment_number']) ? $data['increment_number'] : null; $this->container['linked_space_id'] = isset($data['linked_space_id']) ? $data['linked_space_id'] : null; $this->container['minimal_number_of_periods'] = isset($data['minimal_number_of_periods']) ? $data['minimal_number_of_periods'] : null; $this->container['name'] = isset($data['name']) ? $data['name'] : null; $this->container['number_of_notice_periods'] = isset($data['number_of_notice_periods']) ? $data['number_of_notice_periods'] : null; $this->container['obsoleted_on'] = isset($data['obsoleted_on']) ? $data['obsoleted_on'] : null; $this->container['planned_purge_date'] = isset($data['planned_purge_date']) ? $data['planned_purge_date'] : null; $this->container['product'] = isset($data['product']) ? $data['product'] : null; $this->container['reference'] = isset($data['reference']) ? $data['reference'] : null; $this->container['retiring_finished_on'] = isset($data['retiring_finished_on']) ? $data['retiring_finished_on'] : null; $this->container['retiring_started_on'] = isset($data['retiring_started_on']) ? $data['retiring_started_on'] : null; $this->container['state'] = isset($data['state']) ? $data['state'] : null; $this->container['tax_calculation'] = isset($data['tax_calculation']) ? $data['tax_calculation'] : null; $this->container['version'] = isset($data['version']) ? $data['version'] : null; } /** * Show all the invalid properties with reasons. * * @return array invalid properties with reasons */ public function listInvalidProperties() { $invalidProperties = []; if (!is_null($this->container['reference']) && (mb_strlen($this->container['reference']) > 125)) { $invalidProperties[] = "invalid value for 'reference', the character length must be smaller than or equal to 125."; } return $invalidProperties; } /** * Array of property to type mappings. Used for (de)serialization * * @return array */ public static function swaggerTypes() { return self::$swaggerTypes; } /** * Array of property to format mappings. Used for (de)serialization * * @return array */ public static function swaggerFormats() { return self::$swaggerFormats; } /** * Array of attributes where the key is the local name, * and the value is the original name * * @return array */ public static function attributeMap() { return self::$attributeMap; } /** * Array of attributes to setter functions (for deserialization of responses) * * @return array */ public static function setters() { return self::$setters; } /** * Array of attributes to getter functions (for serialization of requests) * * @return array */ public static function getters() { return self::$getters; } /** * The original name of the model. * * @return string */ public function getModelName() { return self::$swaggerModelName; } /** * Validate all the properties in the model * return true if all passed * * @return bool True if all properties are valid */ public function valid() { return count($this->listInvalidProperties()) === 0; } /** * Gets activated_on * * @return \DateTime */ public function getActivatedOn() { return $this->container['activated_on']; } /** * Sets activated_on * * @param \DateTime $activated_on * * @return $this */ public function setActivatedOn($activated_on) { $this->container['activated_on'] = $activated_on; return $this; } /** * Gets billing_cycle * * @return string */ public function getBillingCycle() { return $this->container['billing_cycle']; } /** * Sets billing_cycle * * @param string $billing_cycle The billing cycle determines the rhythm with which the subscriber is billed. The charging may have different rhythm. * * @return $this */ public function setBillingCycle($billing_cycle) { $this->container['billing_cycle'] = $billing_cycle; return $this; } /** * Gets comment * * @return string */ public function getComment() { return $this->container['comment']; } /** * Sets comment * * @param string $comment The comment allows to provide a internal comment for the version. It helps to document why a product was changed. The comment is not disclosed to the subscriber. * * @return $this */ public function setComment($comment) { $this->container['comment'] = $comment; return $this; } /** * Gets created_on * * @return \DateTime */ public function getCreatedOn() { return $this->container['created_on']; } /** * Sets created_on * * @param \DateTime $created_on * * @return $this */ public function setCreatedOn($created_on) { $this->container['created_on'] = $created_on; return $this; } /** * Gets default_currency * * @return string */ public function getDefaultCurrency() { return $this->container['default_currency']; } /** * Sets default_currency * * @param string $default_currency The default currency has to be used in all fees. * * @return $this */ public function setDefaultCurrency($default_currency) { $this->container['default_currency'] = $default_currency; return $this; } /** * Gets enabled_currencies * * @return string[] */ public function getEnabledCurrencies() { return $this->container['enabled_currencies']; } /** * Sets enabled_currencies * * @param string[] $enabled_currencies The currencies which are enabled can be selected to define component fees. Currencies which are not enabled cannot be used to define fees. * * @return $this */ public function setEnabledCurrencies($enabled_currencies) { $this->container['enabled_currencies'] = $enabled_currencies; return $this; } /** * Gets id * * @return int */ public function getId() { return $this->container['id']; } /** * Sets id * * @param int $id The ID is the primary key of the entity. The ID identifies the entity uniquely. * * @return $this */ public function setId($id) { $this->container['id'] = $id; return $this; } /** * Gets increment_number * * @return int */ public function getIncrementNumber() { return $this->container['increment_number']; } /** * Sets increment_number * * @param int $increment_number The increment number represents the version number incremented whenever a new version is activated. * * @return $this */ public function setIncrementNumber($increment_number) { $this->container['increment_number'] = $increment_number; return $this; } /** * Gets linked_space_id * * @return int */ public function getLinkedSpaceId() { return $this->container['linked_space_id']; } /** * Sets linked_space_id * * @param int $linked_space_id The linked space id holds the ID of the space to which the entity belongs to. * * @return $this */ public function setLinkedSpaceId($linked_space_id) { $this->container['linked_space_id'] = $linked_space_id; return $this; } /** * Gets minimal_number_of_periods * * @return int */ public function getMinimalNumberOfPeriods() { return $this->container['minimal_number_of_periods']; } /** * Sets minimal_number_of_periods * * @param int $minimal_number_of_periods The minimal number of periods determines how long the subscription has to run before the subscription can be terminated. * * @return $this */ public function setMinimalNumberOfPeriods($minimal_number_of_periods) { $this->container['minimal_number_of_periods'] = $minimal_number_of_periods; return $this; } /** * Gets name * * @return \Wallee\Sdk\Model\DatabaseTranslatedString */ public function getName() { return $this->container['name']; } /** * Sets name * * @param \Wallee\Sdk\Model\DatabaseTranslatedString $name The product version name is the name of the product which is shown to the user for the version. When the visible product name should be changed for a particular product a new version has to be created which contains the new name of the product. * * @return $this */ public function setName($name) { $this->container['name'] = $name; return $this; } /** * Gets number_of_notice_periods * * @return int */ public function getNumberOfNoticePeriods() { return $this->container['number_of_notice_periods']; } /** * Sets number_of_notice_periods * * @param int $number_of_notice_periods The number of notice periods determines the number of periods which need to be paid between the request to terminate the subscription and the final period. * * @return $this */ public function setNumberOfNoticePeriods($number_of_notice_periods) { $this->container['number_of_notice_periods'] = $number_of_notice_periods; return $this; } /** * Gets obsoleted_on * * @return \DateTime */ public function getObsoletedOn() { return $this->container['obsoleted_on']; } /** * Sets obsoleted_on * * @param \DateTime $obsoleted_on * * @return $this */ public function setObsoletedOn($obsoleted_on) { $this->container['obsoleted_on'] = $obsoleted_on; return $this; } /** * Gets planned_purge_date * * @return \DateTime */ public function getPlannedPurgeDate() { return $this->container['planned_purge_date']; } /** * Sets planned_purge_date * * @param \DateTime $planned_purge_date The planned purge date indicates when the entity is permanently removed. When the date is null the entity is not planned to be removed. * * @return $this */ public function setPlannedPurgeDate($planned_purge_date) { $this->container['planned_purge_date'] = $planned_purge_date; return $this; } /** * Gets product * * @return \Wallee\Sdk\Model\SubscriptionProduct */ public function getProduct() { return $this->container['product']; } /** * Sets product * * @param \Wallee\Sdk\Model\SubscriptionProduct $product Each product version is linked to a product. * * @return $this */ public function setProduct($product) { $this->container['product'] = $product; return $this; } /** * Gets reference * * @return string */ public function getReference() { return $this->container['reference']; } /** * Sets reference * * @param string $reference The product version reference helps to identify the version. The reference is generated out of the product reference. * * @return $this */ public function setReference($reference) { if (!is_null($reference) && (mb_strlen($reference) > 125)) { throw new \InvalidArgumentException('invalid length for $reference when calling SubscriptionProductVersion., must be smaller than or equal to 125.'); } $this->container['reference'] = $reference; return $this; } /** * Gets retiring_finished_on * * @return \DateTime */ public function getRetiringFinishedOn() { return $this->container['retiring_finished_on']; } /** * Sets retiring_finished_on * * @param \DateTime $retiring_finished_on * * @return $this */ public function setRetiringFinishedOn($retiring_finished_on) { $this->container['retiring_finished_on'] = $retiring_finished_on; return $this; } /** * Gets retiring_started_on * * @return \DateTime */ public function getRetiringStartedOn() { return $this->container['retiring_started_on']; } /** * Sets retiring_started_on * * @param \DateTime $retiring_started_on * * @return $this */ public function setRetiringStartedOn($retiring_started_on) { $this->container['retiring_started_on'] = $retiring_started_on; return $this; } /** * Gets state * * @return \Wallee\Sdk\Model\SubscriptionProductVersionState */ public function getState() { return $this->container['state']; } /** * Sets state * * @param \Wallee\Sdk\Model\SubscriptionProductVersionState $state * * @return $this */ public function setState($state) { $this->container['state'] = $state; return $this; } /** * Gets tax_calculation * * @return \Wallee\Sdk\Model\TaxCalculation */ public function getTaxCalculation() { return $this->container['tax_calculation']; } /** * Sets tax_calculation * * @param \Wallee\Sdk\Model\TaxCalculation $tax_calculation Strategy that is used for tax calculation in fees. * * @return $this */ public function setTaxCalculation($tax_calculation) { $this->container['tax_calculation'] = $tax_calculation; return $this; } /** * Gets version * * @return int */ public function getVersion() { return $this->container['version']; } /** * Sets version * * @param int $version The version number indicates the version of the entity. The version is incremented whenever the entity is changed. * * @return $this */ public function setVersion($version) { $this->container['version'] = $version; return $this; } /** * Returns true if offset exists. False otherwise. * * @param integer $offset Offset * * @return boolean */ #[\ReturnTypeWillChange] public function offsetExists($offset) { return isset($this->container[$offset]); } /** * Gets offset. * * @param integer $offset Offset * * @return mixed */ #[\ReturnTypeWillChange] public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } /** * Sets value based on offset. * * @param integer $offset Offset * @param mixed $value Value to be set * * @return void */ #[\ReturnTypeWillChange] public function offsetSet($offset, $value) { if (is_null($offset)) { $this->container[] = $value; } else { $this->container[$offset] = $value; } } /** * Unsets offset. * * @param integer $offset Offset * * @return void */ #[\ReturnTypeWillChange] public function offsetUnset($offset) { unset($this->container[$offset]); } /** * Gets the string presentation of the object * * @return string */ public function __toString() { if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print return json_encode( ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT ); } return json_encode(ObjectSerializer::sanitizeForSerialization($this)); } }
{ "content_hash": "83c8236accb35f6a1f6f38ce91b29eb4", "timestamp": "", "source": "github", "line_count": 950, "max_line_length": 307, "avg_line_length": 25.771578947368422, "alnum_prop": 0.5687619981211453, "repo_name": "wallee-payment/wallee-php-sdk", "id": "4fe12bc244561bcf9935b5a074c26e8b6911f0e2", "size": "24483", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/Model/SubscriptionProductVersion.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "2580524" } ], "symlink_target": "" }
package client import ( "bufio" "encoding/json" "fmt" "io" "os" "strings" "github.com/docker/docker/api/types" Cli "github.com/docker/docker/cli" "github.com/docker/docker/cliconfig" flag "github.com/docker/docker/pkg/mflag" "github.com/docker/docker/pkg/term" "github.com/docker/docker/registry" ) // CmdLogin logs in or registers a user to a Docker registry service. // // If no server is specified, the user will be logged into or registered to the registry's index server. // // Usage: docker login SERVER func (cli *DockerCli) CmdLogin(args ...string) error { cmd := Cli.Subcmd("login", []string{"[SERVER]"}, "Register or log in to a Docker registry server, if no server is\nspecified \""+registry.INDEXSERVER+"\" is the default.", true) cmd.Require(flag.Max, 1) var username, password, email string cmd.StringVar(&username, []string{"u", "-username"}, "", "Username") cmd.StringVar(&password, []string{"p", "-password"}, "", "Password") cmd.StringVar(&email, []string{"e", "-email"}, "", "Email") cmd.ParseFlags(args, true) serverAddress := registry.INDEXSERVER if len(cmd.Args()) > 0 { serverAddress = cmd.Arg(0) } promptDefault := func(prompt string, configDefault string) { if configDefault == "" { fmt.Fprintf(cli.out, "%s: ", prompt) } else { fmt.Fprintf(cli.out, "%s (%s): ", prompt, configDefault) } } readInput := func(in io.Reader, out io.Writer) string { reader := bufio.NewReader(in) line, _, err := reader.ReadLine() if err != nil { fmt.Fprintln(out, err.Error()) os.Exit(1) } return string(line) } authconfig, ok := cli.configFile.AuthConfigs[serverAddress] if !ok { authconfig = cliconfig.AuthConfig{} } if username == "" { promptDefault("Username", authconfig.Username) username = readInput(cli.in, cli.out) username = strings.Trim(username, " ") if username == "" { username = authconfig.Username } } // Assume that a different username means they may not want to use // the password or email from the config file, so prompt them if username != authconfig.Username { if password == "" { oldState, err := term.SaveState(cli.inFd) if err != nil { return err } fmt.Fprintf(cli.out, "Password: ") term.DisableEcho(cli.inFd, oldState) password = readInput(cli.in, cli.out) fmt.Fprint(cli.out, "\n") term.RestoreTerminal(cli.inFd, oldState) if password == "" { return fmt.Errorf("Error : Password Required") } } if email == "" { promptDefault("Email", authconfig.Email) email = readInput(cli.in, cli.out) if email == "" { email = authconfig.Email } } } else { // However, if they don't override the username use the // password or email from the cmd line if specified. IOW, allow // then to change/override them. And if not specified, just // use what's in the config file if password == "" { password = authconfig.Password } if email == "" { email = authconfig.Email } } authconfig.Username = username authconfig.Password = password authconfig.Email = email authconfig.ServerAddress = serverAddress cli.configFile.AuthConfigs[serverAddress] = authconfig serverResp, err := cli.call("POST", "/auth", cli.configFile.AuthConfigs[serverAddress], nil) if serverResp.statusCode == 401 { delete(cli.configFile.AuthConfigs, serverAddress) if err2 := cli.configFile.Save(); err2 != nil { fmt.Fprintf(cli.out, "WARNING: could not save config file: %v\n", err2) } return err } if err != nil { return err } defer serverResp.body.Close() var response types.AuthResponse if err := json.NewDecoder(serverResp.body).Decode(&response); err != nil { // Upon error, remove entry delete(cli.configFile.AuthConfigs, serverAddress) return err } if err := cli.configFile.Save(); err != nil { return fmt.Errorf("Error saving config file: %v", err) } fmt.Fprintf(cli.out, "WARNING: login credentials saved in %s\n", cli.configFile.Filename()) if response.Status != "" { fmt.Fprintf(cli.out, "%s\n", response.Status) } return nil }
{ "content_hash": "f549a23ebd8c87ef002ef0dd84177ee3", "timestamp": "", "source": "github", "line_count": 147, "max_line_length": 178, "avg_line_length": 27.5578231292517, "alnum_prop": 0.6748950876326832, "repo_name": "xyliuke/docker", "id": "8c012737ff166a78125b62d0c1ef7ca0aa0a4176", "size": "4051", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "api/client/login.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "2839680" }, { "name": "Makefile", "bytes": "4030" }, { "name": "Perl", "bytes": "2199" }, { "name": "Shell", "bytes": "213605" }, { "name": "VimL", "bytes": "1317" } ], "symlink_target": "" }
COTTaskHelper ============= A thin wrapper around NSTask that provides block callbacks for task completion, error, and output. ````Objective-C NSTask *task = [[NSTask alloc] init]; [task setLaunchPath:@"/bin/bash"]; [task setArguments:@[@"-c", @"some command"]]; COTTaskHelper *taskHelper = [[COTTaskHelper alloc] init]; taskHelper.task = task; taskHelper.outputHandler = ^(NSData *outputData) { NSString *outputString = [[NSString alloc] initWithData:outputData encoding:NSASCIIStringEncoding]; NSLog(@"%@", outputString); }; taskHelper.completionHandler = ^{ NSLog(@"Task complete!"); }; taskHelper.errorHandler = ^(NSData *errorData) { NSString *errorString = [[NSString alloc] initWithData:errorData encoding:NSASCIIStringEncoding]; NSLog(@"%@", errorString); }; [taskHelper launch]; ````
{ "content_hash": "7655fe48408520e1fc6e28aa8e1d4457", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 101, "avg_line_length": 31.03846153846154, "alnum_prop": 0.7174721189591078, "repo_name": "clickontyler/COTTaskHelper", "id": "e07cc13cc2002bdd7b713dfd7c07ff5c3eb1b9a2", "size": "807", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "2452" } ], "symlink_target": "" }
package org.trifort.rootbeer.deadmethods; import java.util.ArrayList; import java.util.List; public class BlockParser { public static final int TYPE_FREE = 0; public static final int TYPE_DEFINE = 1; public static final int TYPE_DECLARE = 2; public static final int TYPE_METHOD = 3; public List<Block> parse(List<Segment> segments) { List<Block> ret = new ArrayList<Block>(); for(int i = 0; i < segments.size(); ++i){ Segment segment = segments.get(i); if(segment.getType() == SegmentParser.TYPE_DEFINE){ ret.add(new Block(segment, TYPE_DEFINE)); } else if(segment.getType() == SegmentParser.TYPE_FREE){ String str = segment.getString().trim(); if(str.isEmpty()){ continue; } char last_char = str.charAt(str.length() - 1); if(last_char == ';'){ ret.add(new Block(segment, TYPE_DECLARE)); } else { List<Segment> block_segments = new ArrayList<Segment>(); block_segments.add(segment); int brace_count = 0; if(last_char == '{'){ brace_count++; } for(int j = i + 1; j < segments.size(); ++j){ Segment curr = segments.get(j); if(curr.getType() == SegmentParser.TYPE_COMMENT){ continue; } block_segments.add(curr); String str2 = curr.getString().trim(); if(str2.isEmpty()){ continue; } char last_char2 = str2.charAt(str2.length() - 1); if(last_char2 == ';' && brace_count == 0){ ret.add(new Block(block_segments, TYPE_DECLARE)); i = j; break; } if(last_char2 == '{'){ brace_count++; } else if(last_char2 == '}'){ brace_count--; if(brace_count == 0){ ret.add(new Block(block_segments, TYPE_METHOD)); i = j; break; } } } } } } return ret; } }
{ "content_hash": "fefcccca4a82f4a67dff14a49d051032", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 66, "avg_line_length": 30.347826086956523, "alnum_prop": 0.5, "repo_name": "yarenty/rootbeer1", "id": "b6cb33ead7d5b0979bd03c6ff19926fd0c564545", "size": "2236", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/org/trifort/rootbeer/deadmethods/BlockParser.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1736" }, { "name": "C", "bytes": "131518" }, { "name": "GAP", "bytes": "1508" }, { "name": "Java", "bytes": "1130591" }, { "name": "Matlab", "bytes": "499" }, { "name": "PowerShell", "bytes": "2351" }, { "name": "Ruby", "bytes": "1192" }, { "name": "Shell", "bytes": "8179" } ], "symlink_target": "" }
 #include <aws/storagegateway/model/ShutdownGatewayResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::StorageGateway::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; ShutdownGatewayResult::ShutdownGatewayResult() { } ShutdownGatewayResult::ShutdownGatewayResult(const Aws::AmazonWebServiceResult<JsonValue>& result) { *this = result; } ShutdownGatewayResult& ShutdownGatewayResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { JsonView jsonValue = result.GetPayload().View(); if(jsonValue.ValueExists("GatewayARN")) { m_gatewayARN = jsonValue.GetString("GatewayARN"); } return *this; }
{ "content_hash": "9c5d7f8c5bcc86ed9e00e8a9981e059e", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 110, "avg_line_length": 23.10810810810811, "alnum_prop": 0.7730994152046784, "repo_name": "jt70471/aws-sdk-cpp", "id": "50d0426b81acf728a9fc7c89e9b05b142a276eee", "size": "974", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "aws-cpp-sdk-storagegateway/source/model/ShutdownGatewayResult.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "13452" }, { "name": "C++", "bytes": "278594037" }, { "name": "CMake", "bytes": "653931" }, { "name": "Dockerfile", "bytes": "5555" }, { "name": "HTML", "bytes": "4471" }, { "name": "Java", "bytes": "302182" }, { "name": "Python", "bytes": "110380" }, { "name": "Shell", "bytes": "4674" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>Simple Webpage for NYC</title> <!-- Bootstrap Core CSS --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- Custom CSS --> <link href="css/stylish-portfolio.css" rel="stylesheet"> <!-- Custom Fonts --> <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href="http://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,700,300italic,400italic,700italic" rel="stylesheet" type="text/css"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <!-- Navigation --> <a id="menu-toggle" href="#" class="btn btn-dark btn-lg toggle"><i class="fa fa-bars"></i></a> <nav id="sidebar-wrapper"> <ul class="sidebar-nav"> <a id="menu-close" href="#" class="btn btn-light btn-lg pull-right toggle"><i class="fa fa-times"></i></a> <li class="sidebar-brand"> <a href="#top" onclick = $("#menu-close").click(); >Home</a> </li> <li> <a href="about.html" onclick = $("#menu-close").click(); >About</a> </li> <li> <a href="#services" onclick = $("#menu-close").click(); >Places to visit</a> </li> <li> <a href="#plan" onclick=$("#menu-close").click();>Plan your reservations</a> </li> </ul> </nav> <!-- Header --> <header id="top" class="header"> <div class="text-vertical-center"> <h1><center><b>NYC</b></center></h1> <br> </div> </header> <section id="services" class="services bg-primary"> <div class="container"> <div class="row text-center"> <div class="container"> <div class="row"> <div class="col-lg-10 col-lg-offset-1 text-center"> <h2>Places to visit</h2> <hr class="small"> <div class="row"> <div class="col-md-6"> <div class="portfolio-item"> <a href="esb.html"> <h2>Central Park</h2> <img class="img-portfolio img-responsive" src="https://upload.wikimedia.org/wikipedia/commons/d/d9/Lower_Central_Park_Shot_5.JPG" style="width:304px;height:228px;"> </a> </div> </div> <div class="col-md-6"> <div class="portfolio-item"> <a href="sol.html"> <h2>Times Square</h2> <img class="img-portfolio img-responsive" src="https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQvWcoRJOvbKly8HhQMQZC1KwUorlLao0Aksz9ThTLkH9rD8D7d" style="width:304px;height:228px;"> </a> </div> </div> <div class="col-md-6"> <div class="portfolio-item"> <a href="tsq.html"> <h2>Statue of Liberty</h2> <img class="img-portfolio img-responsive" src="https://upload.wikimedia.org/wikipedia/commons/a/a1/Statue_of_Liberty_7.jpg" style="width:304px;height:228px;"> </a> </div> </div> <div class="col-md-6"> <div class="portfolio-item"> <a href="bb.html"> <h2>Empire State Building</h2> <img class="img-portfolio img-responsive" src="https://upload.wikimedia.org/wikipedia/commons/c/c7/Empire_State_Building_by_David_Shankbone_crop.jpg" style="width:304px;height:228px;"> </a> </div> </div> </div> <!-- /.row (nested) --> </div> <!-- /.col-lg-10 --> </div> <!-- /.row --> </div> <!-- /.container --> </section> <section id="plan" class="services bg-primary"> <div class="container"> <div class="row text-center"> <div class="container"> <div class="row"> <div class="col-lg-10 col-lg-offset-1 text-center"> <h2>Plan your reservations</h2> <hr class="small"> <div class="row"> <div class="col-md-3"> <div class="portfolio-item"> <h3>Motel</h3> <a href="reservation.html"> <h2>Motel Reservations</h2> <img class="img-portfolio img-responsive" src="http://www.san-diego-hitching-post-motels.com/images/ebb-tide-motel1.jpg" style="width:304px;height:228px;"> </a> </div> </div> <div class="col-md-3"> <div class="portfolio-item"> <h3>Car</h3> <a href="reservation.html"> <h2>Rent A Car</h2> <img class="img-portfolio img-responsive" src="http://pictures.dealer.com/m/merlekellyford/0099/9fb40cb5288e33f4bd0ecd6358e9c6f0x.jpg" style="width:304px;height:228px;"> </a> </div> </div> </div> <!-- /.row (nested) --> </div> <!-- /.col-lg-10 --> </div> <!-- /.row --> </div> <!-- /.container --> </section> <!-- jQuery --> <script src="js/jquery.js"></script> <!-- Bootstrap Core JavaScript --> <script src="js/bootstrap.min.js"></script> <script> // Closes the sidebar menu $("#menu-close").click(function(e) { e.preventDefault(); $("#sidebar-wrapper").toggleClass("active"); }); // Opens the sidebar menu $("#menu-toggle").click(function(e) { e.preventDefault(); $("#sidebar-wrapper").toggleClass("active"); }); // Scrolls to the selected menu item on the page $(function() { $('a[href*=#]:not([href=#])').click(function() { if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') || location.hostname == this.hostname) { var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) + ']'); if (target.length) { $('html,body').animate({ scrollTop: target.offset().top }, 1000); return false; } } }); }); </script> </body> </html>
{ "content_hash": "09903f03f0af9888fadda4b714cf0042", "timestamp": "", "source": "github", "line_count": 196, "max_line_length": 231, "avg_line_length": 44.80102040816327, "alnum_prop": 0.3991572713813916, "repo_name": "vjkatragadda/vjkatragadda.github.io", "id": "0ac5d69536c953848d48f00d0d35dd150c301c89", "size": "8783", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "index.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "28382" } ], "symlink_target": "" }
//----------------------------------------------------------------------- // <copyright file="DynamicAllocationActivitySchedulerRegistries.cs" company="Rare Crowds Inc"> // Copyright 2012-2013 Rare Crowds, 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. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace DynamicAllocationUtilities { /// <summary> /// TimeSlottedRegistry names for DynamicAllocation scheduled activity dispatchers /// </summary> public static class DynamicAllocationActivitySchedulerRegistries { /// <summary>Campaigns to reallocate TimeSlottedRegistry name</summary> public const string CampaignsToReallocate = "da-campaigns-toreallocate"; } }
{ "content_hash": "01cb3eade6e74496a65c5f361f5aa2ed", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 119, "avg_line_length": 45.93103448275862, "alnum_prop": 0.6268768768768769, "repo_name": "chinnurtb/OpenAdStack", "id": "95aaa0f8792a483394bb65e78467efdb86cbede6", "size": "1334", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ActivitiesCommon/DynamicAllocationUtilities/DynamicAllocationActivitySchedulerRegistries.cs", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<!DOCTYPE html> <!-- add true links and stuff--> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta charset="utf-8"> <meta name="viewpart" content="width=device-width, initial-scale=1.0, user-scalable=no"> <title> Grace Fioramonti-Gorchow - BIG </title> <link rel="stylesheet" href="style/main.css"> <link rel="stylesheet" href="style/bootstrap.css"> <link rel="stylesheet" href="style/animate.css"> <link rel="stylesheet" href="style/profile.css"> </head> <div class="container"> <div class="row profile"> <div class="col-md-3"> <div class="profile-sidebar"> <!-- SIDEBAR USERPIC --> <div class="profile-userpic"> <img src="images/bio_images/gracef.jpg" class="img-responsive" alt=""> </div> <!-- END SIDEBAR USERPIC --> <!-- SIDEBAR USER TITLE --> <div class="profile-usertitle"> <div class="profile-usertitle-name"> Grace Fioramonti-Gorchow </div> <div class="profile-usertitle-job"> Operations </div> </div> <!-- END SIDEBAR USER TITLE --> <!-- SIDEBAR BUTTONS --> <div class="profile-userbuttons"> <a href="mailto:gfioramont@haverford.edu?Subject=Email%20From%20BIG%20Site" target="_top"><button type="button" class="btn btn-success btn-sm">Email</button></a> </div> <!-- END SIDEBAR BUTTONS --> <!-- SIDEBAR MENU --> <div class="profile-usermenu"> <ul class="nav"> <li> <a> Haverford College</a> </li> <li> <a> Class of 2018 </a> </li> </ul> </div> <div class="profile-userbuttons"> <a href="index.html"><button type="button" class="btn btn-danger btn-sm">Back</button></a> </div> <!-- END MENU --> </div> </div> <div class="col-md-9"> <div class="profile-content"> Grace Fioramonti-Gorchow, Haverford College Class of 2018, is from Chicago, IL. Grace is a psychology major considering a potential health studies minor. At Haverford, she is a member of the women’s varsity squash team. Last summer she interned at PPM America. In her free time, you can find Grace eating mint chocolate chip ice cream, doodling in adult coloring books, and eagerly awaiting Shark Week. Reach out to her at <strong>gfioramont@haverford.edu</strong>. </div> </div> </div> </div> <center> </center> <br> <br> <script src="js/jquery-2.1.4.min.js"></script> <script src="js/bootstrap.min.js"></script> </html>
{ "content_hash": "93db630d7d82f8ae4b88e525f3a2f0af", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 482, "avg_line_length": 30.886363636363637, "alnum_prop": 0.5776306107431936, "repo_name": "gramsbyDill/Big_Source", "id": "cf56cbe3eeb585a35deae961bde0683790f74ce4", "size": "2720", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "About/grace_profile.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2020" }, { "name": "HTML", "bytes": "67014" }, { "name": "JavaScript", "bytes": "12554" } ], "symlink_target": "" }
<!doctype html> <!--[if lt IE 7]><html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]--> <!--[if (IE 7)&!(IEMobile)]><html class="no-js lt-ie9 lt-ie8" lang="en"><![endif]--> <!--[if (IE 8)&!(IEMobile)]><html class="no-js lt-ie9" lang="en"><![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang="en"><!--<![endif]--> <head> {% include head.html %} </head> <body id="post" {% if page.image.feature %}class="feature"{% endif %}> {% include browser-upgrade.html %} {% include navigation.html %} {% if page.image.feature %} <div class="entry-header"> {% if page.image.credit %}<div class="image-credit">Author: {% if page.image.creditlink %}<a href="{{ page.image.creditlink }}">{% endif %}{{ page.image.credit }}{% if page.image.creditlink %}</a>{% endif %}</div><!-- /.image-credit -->{% endif %} <div class="entry-image"> <!-- <img src="{{ site.url }}/images/{{ page.image.feature }}" alt="{{ page.title }}">--> <img srcset="data:image/gif;base64,R0lGODdhAQABAPAAAMPDwwAAACwAAAAAAQABAAACAkQBADs=" data-src="{{ site.url }}/images/{{ page.image.feature }}" alt="{{ page.title }}" class="lazyload" /> </div><!-- /.entry-image --> </div><!-- /.entry-header --> {% endif %} <div id="main" role="main"> <article class="hentry"> <header class="header-title"> <div class="header-title-wrap"> {% if page.link %} <h1 class="entry-title"><i class="fa fa-bookmark permalink"></i> <a href="{{ page.link }}">{{ page.title }}</a></h1> {% else %} <h1 class="entry-title"><a href="{{ site.url }}{{ page.url }}" rel="bookmark" title="{{ page.title }}">{{ page.title }}</a></h1> {% endif %} <h2><span class="entry-date date published"><time datetime="{{ page.date | date_to_xmlschema }}">{{ page.date | date: "%B %d, %Y" }}</time></span></h2> {% if site.reading_time %} <p class="entry-reading-time"> <i class="fa fa-clock-o"></i> {% include read-time.html %} </p><!-- /.entry-reading-time --> {% endif %} </div><!-- /.header-title-wrap --> </header> <div class="entry-content"> {{ content }} <footer class="entry-meta"> <span class="entry-tags">{% for tag in page.tags %}<a href="{{ site.url }}/tags/#{{ tag }}" title="Pages tagged {{ tag }}" class="tag"><span class="term">{{ tag }}</span></a>{% unless forloop.last %}{% endunless %}{% endfor %}</span> {% if page.modified %}<span>Updated on <span class="entry-date date updated"><time datetime="{{ page.modified }}">{{ page.modified | date: "%B %d, %Y" }}</time></span></span> <span class="author vcard"><span class="fn">{{ site.owner.name }}</span></span>{% endif %} {% if page.share != false %}{% include social-share.html %}{% endif %} </footer> </div><!-- /.entry-content --> <!-- {% if page.comments != false and site.disqus_shortname %}<section id="disqus_thread"></section>&lt;!&ndash; /#disqus_thread &ndash;&gt;{% endif %}--> {% if page.comments != false and site.disqus_shortname %}<div id="disqus_thread"></div><!-- /#disqus_thread -->{% endif %} {% if site.related_posts.size > 0 %}{% include read-more.html %}{% endif %} </article> </div><!-- /#main --> <div class="footer-wrapper"> <footer role="contentinfo"> {% include footer.html %} </footer> </div><!-- /.footer-wrapper --> {% include scripts.html %} </body> </html>
{ "content_hash": "e4f66a7aa8fd5f0cd4a851e197f26044", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 249, "avg_line_length": 50.985074626865675, "alnum_prop": 0.5652810304449649, "repo_name": "jyiL/jyiL.github.io", "id": "ebe900715c413eea872f7c533877be262d212741", "size": "3416", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_layouts/post.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "43807" }, { "name": "HTML", "bytes": "25365" }, { "name": "JavaScript", "bytes": "68083" }, { "name": "Ruby", "bytes": "134" } ], "symlink_target": "" }
package org.alfresco.repo.lotus.ws; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="checkinDocumentReturn" type="{http://webservices.clb.content.ibm.com}ClbCheckinResponse"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "checkinDocumentReturn" }) @XmlRootElement(name = "checkinDocumentResponse") public class CheckinDocumentResponse { @XmlElement(required = true) protected ClbCheckinResponse checkinDocumentReturn; /** * Gets the value of the checkinDocumentReturn property. * * @return * possible object is * {@link ClbCheckinResponse } * */ public ClbCheckinResponse getCheckinDocumentReturn() { return checkinDocumentReturn; } /** * Sets the value of the checkinDocumentReturn property. * * @param value * allowed object is * {@link ClbCheckinResponse } * */ public void setCheckinDocumentReturn(ClbCheckinResponse value) { this.checkinDocumentReturn = value; } }
{ "content_hash": "bf1ced42eb7dec6f4aa8933153977e30", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 119, "avg_line_length": 27.40625, "alnum_prop": 0.6476624857468644, "repo_name": "Alfresco/alfresco-quickr-connector", "id": "5cb719f4df4da49e9d3378ec379ad6fb255b4959", "size": "1754", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "quickr/source/generated/org/alfresco/repo/lotus/ws/CheckinDocumentResponse.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "910491" } ], "symlink_target": "" }
namespace VersionOne.Integration.Tfs.Listener.Config { partial class ConfigForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ConfigForm)); this.tcSettings = new System.Windows.Forms.TabControl(); this.tpVersionOne = new System.Windows.Forms.TabPage(); this.grpProxySettings = new System.Windows.Forms.GroupBox(); this.txtProxyDomain = new System.Windows.Forms.TextBox(); this.lblProxyDomain = new System.Windows.Forms.Label(); this.txtProxyPassword = new System.Windows.Forms.TextBox(); this.lblProxyPassword = new System.Windows.Forms.Label(); this.txtProxyUsername = new System.Windows.Forms.TextBox(); this.lblProxyUsername = new System.Windows.Forms.Label(); this.txtProxyUrl = new System.Windows.Forms.TextBox(); this.lblProxyUrl = new System.Windows.Forms.Label(); this.chkUseProxy = new System.Windows.Forms.CheckBox(); this.UseIntegratedAuthenticationCB = new System.Windows.Forms.CheckBox(); this.btnTestV1Connection = new System.Windows.Forms.Button(); this.V1PasswordTB = new System.Windows.Forms.MaskedTextBox(); this.lblVersionOnePassword = new System.Windows.Forms.Label(); this.lblVersionOneUsername = new System.Windows.Forms.Label(); this.V1UsernameTB = new System.Windows.Forms.TextBox(); this.lblVersionOneUrl = new System.Windows.Forms.Label(); this.V1URLTB = new System.Windows.Forms.TextBox(); this.tpTfsServer = new System.Windows.Forms.TabPage(); this.TFSTestEventsB = new System.Windows.Forms.Button(); this.SubscriptionsLV = new System.Windows.Forms.ListView(); this.columnHeader1 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeader2 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.UnsubscribeB = new System.Windows.Forms.Button(); this.lblListenerUrl = new System.Windows.Forms.Label(); this.TFSUpdateB = new System.Windows.Forms.Button(); this.ListenerURLTB = new System.Windows.Forms.TextBox(); this.TFSStatusLabel = new System.Windows.Forms.Label(); this.lblCurrentSubscriptions = new System.Windows.Forms.Label(); this.TFSConnectB = new System.Windows.Forms.Button(); this.TFSPasswordTB = new System.Windows.Forms.MaskedTextBox(); this.lblTfsPassword = new System.Windows.Forms.Label(); this.lblTfsUsername = new System.Windows.Forms.Label(); this.TFSUsernameTB = new System.Windows.Forms.TextBox(); this.lblTfsServerUrl = new System.Windows.Forms.Label(); this.TFSURLTB = new System.Windows.Forms.TextBox(); this.tpAdvanced = new System.Windows.Forms.TabPage(); this.txtDebugDescription = new System.Windows.Forms.TextBox(); this.chkDebugMode = new System.Windows.Forms.CheckBox(); this.RegExTB = new System.Windows.Forms.TextBox(); this.lblRegex = new System.Windows.Forms.Label(); this.txtMatchesDescription = new System.Windows.Forms.TextBox(); this.btnSaveAllSettings = new System.Windows.Forms.Button(); this.tbResults = new System.Windows.Forms.TextBox(); this.llClear = new System.Windows.Forms.LinkLabel(); this.tbBaseUrl = new System.Windows.Forms.TextBox(); this.lblTFSListenerUrl = new System.Windows.Forms.Label(); this.btnSetBaseListenerUrl = new System.Windows.Forms.Button(); this.tcSettings.SuspendLayout(); this.tpVersionOne.SuspendLayout(); this.grpProxySettings.SuspendLayout(); this.tpTfsServer.SuspendLayout(); this.tpAdvanced.SuspendLayout(); this.SuspendLayout(); // // tcSettings // this.tcSettings.Controls.Add(this.tpVersionOne); this.tcSettings.Controls.Add(this.tpTfsServer); this.tcSettings.Controls.Add(this.tpAdvanced); this.tcSettings.Location = new System.Drawing.Point(10, 57); this.tcSettings.Name = "tcSettings"; this.tcSettings.SelectedIndex = 0; this.tcSettings.Size = new System.Drawing.Size(441, 439); this.tcSettings.TabIndex = 0; // // tpVersionOne // this.tpVersionOne.Controls.Add(this.grpProxySettings); this.tpVersionOne.Controls.Add(this.UseIntegratedAuthenticationCB); this.tpVersionOne.Controls.Add(this.btnTestV1Connection); this.tpVersionOne.Controls.Add(this.V1PasswordTB); this.tpVersionOne.Controls.Add(this.lblVersionOnePassword); this.tpVersionOne.Controls.Add(this.lblVersionOneUsername); this.tpVersionOne.Controls.Add(this.V1UsernameTB); this.tpVersionOne.Controls.Add(this.lblVersionOneUrl); this.tpVersionOne.Controls.Add(this.V1URLTB); this.tpVersionOne.Location = new System.Drawing.Point(4, 22); this.tpVersionOne.Name = "tpVersionOne"; this.tpVersionOne.Padding = new System.Windows.Forms.Padding(3); this.tpVersionOne.Size = new System.Drawing.Size(433, 413); this.tpVersionOne.TabIndex = 0; this.tpVersionOne.Text = "VersionOne Server"; this.tpVersionOne.UseVisualStyleBackColor = true; // // grpProxySettings // this.grpProxySettings.Controls.Add(this.txtProxyDomain); this.grpProxySettings.Controls.Add(this.lblProxyDomain); this.grpProxySettings.Controls.Add(this.txtProxyPassword); this.grpProxySettings.Controls.Add(this.lblProxyPassword); this.grpProxySettings.Controls.Add(this.txtProxyUsername); this.grpProxySettings.Controls.Add(this.lblProxyUsername); this.grpProxySettings.Controls.Add(this.txtProxyUrl); this.grpProxySettings.Controls.Add(this.lblProxyUrl); this.grpProxySettings.Controls.Add(this.chkUseProxy); this.grpProxySettings.Location = new System.Drawing.Point(6, 143); this.grpProxySettings.Name = "grpProxySettings"; this.grpProxySettings.Size = new System.Drawing.Size(433, 184); this.grpProxySettings.TabIndex = 7; this.grpProxySettings.TabStop = false; this.grpProxySettings.Text = "Proxy Server Settings"; // // txtProxyDomain // this.txtProxyDomain.Location = new System.Drawing.Point(124, 149); this.txtProxyDomain.Name = "txtProxyDomain"; this.txtProxyDomain.Size = new System.Drawing.Size(303, 20); this.txtProxyDomain.TabIndex = 8; // // lblProxyDomain // this.lblProxyDomain.AutoSize = true; this.lblProxyDomain.Location = new System.Drawing.Point(14, 152); this.lblProxyDomain.Name = "lblProxyDomain"; this.lblProxyDomain.Size = new System.Drawing.Size(43, 13); this.lblProxyDomain.TabIndex = 7; this.lblProxyDomain.Text = "Domain"; // // txtProxyPassword // this.txtProxyPassword.Location = new System.Drawing.Point(124, 117); this.txtProxyPassword.Name = "txtProxyPassword"; this.txtProxyPassword.Size = new System.Drawing.Size(303, 20); this.txtProxyPassword.TabIndex = 6; this.txtProxyPassword.UseSystemPasswordChar = true; // // lblProxyPassword // this.lblProxyPassword.AutoSize = true; this.lblProxyPassword.Location = new System.Drawing.Point(14, 120); this.lblProxyPassword.Name = "lblProxyPassword"; this.lblProxyPassword.Size = new System.Drawing.Size(53, 13); this.lblProxyPassword.TabIndex = 5; this.lblProxyPassword.Text = "Password"; // // txtProxyUsername // this.txtProxyUsername.Location = new System.Drawing.Point(124, 85); this.txtProxyUsername.Name = "txtProxyUsername"; this.txtProxyUsername.Size = new System.Drawing.Size(303, 20); this.txtProxyUsername.TabIndex = 4; // // lblProxyUsername // this.lblProxyUsername.AutoSize = true; this.lblProxyUsername.Location = new System.Drawing.Point(14, 88); this.lblProxyUsername.Name = "lblProxyUsername"; this.lblProxyUsername.Size = new System.Drawing.Size(55, 13); this.lblProxyUsername.TabIndex = 3; this.lblProxyUsername.Text = "Username"; // // txtProxyUrl // this.txtProxyUrl.Location = new System.Drawing.Point(124, 53); this.txtProxyUrl.Name = "txtProxyUrl"; this.txtProxyUrl.Size = new System.Drawing.Size(303, 20); this.txtProxyUrl.TabIndex = 2; // // lblProxyUrl // this.lblProxyUrl.AutoSize = true; this.lblProxyUrl.Location = new System.Drawing.Point(14, 56); this.lblProxyUrl.Name = "lblProxyUrl"; this.lblProxyUrl.Size = new System.Drawing.Size(92, 13); this.lblProxyUrl.TabIndex = 1; this.lblProxyUrl.Text = "Proxy Server URL"; // // chkUseProxy // this.chkUseProxy.AutoSize = true; this.chkUseProxy.Location = new System.Drawing.Point(17, 23); this.chkUseProxy.Name = "chkUseProxy"; this.chkUseProxy.Size = new System.Drawing.Size(216, 17); this.chkUseProxy.TabIndex = 0; this.chkUseProxy.Text = "Use Proxy Server to Access VersionOne"; this.chkUseProxy.UseVisualStyleBackColor = true; this.chkUseProxy.CheckedChanged += new System.EventHandler(this.chkUseProxy_CheckedChanged); // // UseIntegratedAuthenticationCB // this.UseIntegratedAuthenticationCB.AutoSize = true; this.UseIntegratedAuthenticationCB.Location = new System.Drawing.Point(8, 115); this.UseIntegratedAuthenticationCB.Name = "UseIntegratedAuthenticationCB"; this.UseIntegratedAuthenticationCB.Size = new System.Drawing.Size(214, 17); this.UseIntegratedAuthenticationCB.TabIndex = 6; this.UseIntegratedAuthenticationCB.Text = "Use Windows Integrated Authentication"; this.UseIntegratedAuthenticationCB.UseVisualStyleBackColor = true; // // btnTestV1Connection // this.btnTestV1Connection.Location = new System.Drawing.Point(6, 343); this.btnTestV1Connection.Name = "btnTestV1Connection"; this.btnTestV1Connection.Size = new System.Drawing.Size(120, 23); this.btnTestV1Connection.TabIndex = 8; this.btnTestV1Connection.Text = "Test Connection"; this.btnTestV1Connection.UseVisualStyleBackColor = true; // // V1PasswordTB // this.V1PasswordTB.Location = new System.Drawing.Point(131, 75); this.V1PasswordTB.Name = "V1PasswordTB"; this.V1PasswordTB.Size = new System.Drawing.Size(302, 20); this.V1PasswordTB.TabIndex = 5; this.V1PasswordTB.UseSystemPasswordChar = true; // // lblVersionOnePassword // this.lblVersionOnePassword.AutoSize = true; this.lblVersionOnePassword.Location = new System.Drawing.Point(8, 78); this.lblVersionOnePassword.Name = "lblVersionOnePassword"; this.lblVersionOnePassword.Size = new System.Drawing.Size(111, 13); this.lblVersionOnePassword.TabIndex = 4; this.lblVersionOnePassword.Text = "VersionOne Password"; // // lblVersionOneUsername // this.lblVersionOneUsername.AutoSize = true; this.lblVersionOneUsername.Location = new System.Drawing.Point(8, 46); this.lblVersionOneUsername.Name = "lblVersionOneUsername"; this.lblVersionOneUsername.Size = new System.Drawing.Size(113, 13); this.lblVersionOneUsername.TabIndex = 2; this.lblVersionOneUsername.Text = "VersionOne Username"; // // V1UsernameTB // this.V1UsernameTB.Location = new System.Drawing.Point(131, 43); this.V1UsernameTB.Name = "V1UsernameTB"; this.V1UsernameTB.Size = new System.Drawing.Size(302, 20); this.V1UsernameTB.TabIndex = 3; // // lblVersionOneUrl // this.lblVersionOneUrl.AutoSize = true; this.lblVersionOneUrl.Location = new System.Drawing.Point(7, 14); this.lblVersionOneUrl.Name = "lblVersionOneUrl"; this.lblVersionOneUrl.Size = new System.Drawing.Size(121, 13); this.lblVersionOneUrl.TabIndex = 0; this.lblVersionOneUrl.Text = "VersionOne Server URL"; // // V1URLTB // this.V1URLTB.Location = new System.Drawing.Point(131, 11); this.V1URLTB.Name = "V1URLTB"; this.V1URLTB.Size = new System.Drawing.Size(302, 20); this.V1URLTB.TabIndex = 1; // // tpTfsServer // this.tpTfsServer.Controls.Add(this.TFSTestEventsB); this.tpTfsServer.Controls.Add(this.SubscriptionsLV); this.tpTfsServer.Controls.Add(this.UnsubscribeB); this.tpTfsServer.Controls.Add(this.lblListenerUrl); this.tpTfsServer.Controls.Add(this.TFSUpdateB); this.tpTfsServer.Controls.Add(this.ListenerURLTB); this.tpTfsServer.Controls.Add(this.TFSStatusLabel); this.tpTfsServer.Controls.Add(this.lblCurrentSubscriptions); this.tpTfsServer.Controls.Add(this.TFSConnectB); this.tpTfsServer.Controls.Add(this.TFSPasswordTB); this.tpTfsServer.Controls.Add(this.lblTfsPassword); this.tpTfsServer.Controls.Add(this.lblTfsUsername); this.tpTfsServer.Controls.Add(this.TFSUsernameTB); this.tpTfsServer.Controls.Add(this.lblTfsServerUrl); this.tpTfsServer.Controls.Add(this.TFSURLTB); this.tpTfsServer.Location = new System.Drawing.Point(4, 22); this.tpTfsServer.Name = "tpTfsServer"; this.tpTfsServer.Padding = new System.Windows.Forms.Padding(3); this.tpTfsServer.Size = new System.Drawing.Size(433, 413); this.tpTfsServer.TabIndex = 1; this.tpTfsServer.Text = "TFS Server"; this.tpTfsServer.UseVisualStyleBackColor = true; // // TFSTestEventsB // this.TFSTestEventsB.Location = new System.Drawing.Point(287, 378); this.TFSTestEventsB.Name = "TFSTestEventsB"; this.TFSTestEventsB.Size = new System.Drawing.Size(135, 23); this.TFSTestEventsB.TabIndex = 30; this.TFSTestEventsB.Text = "Test Events"; this.TFSTestEventsB.UseVisualStyleBackColor = true; // // SubscriptionsLV // this.SubscriptionsLV.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeader1, this.columnHeader2}); this.SubscriptionsLV.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable; this.SubscriptionsLV.Location = new System.Drawing.Point(7, 250); this.SubscriptionsLV.Name = "SubscriptionsLV"; this.SubscriptionsLV.Size = new System.Drawing.Size(435, 80); this.SubscriptionsLV.TabIndex = 29; this.SubscriptionsLV.UseCompatibleStateImageBehavior = false; this.SubscriptionsLV.View = System.Windows.Forms.View.Details; // // columnHeader1 // this.columnHeader1.Text = "Event"; this.columnHeader1.Width = 146; // // columnHeader2 // this.columnHeader2.Text = "Subscription URL"; this.columnHeader2.Width = 600; // // UnsubscribeB // this.UnsubscribeB.Location = new System.Drawing.Point(147, 378); this.UnsubscribeB.Name = "UnsubscribeB"; this.UnsubscribeB.Size = new System.Drawing.Size(135, 23); this.UnsubscribeB.TabIndex = 28; this.UnsubscribeB.Text = "Unsubscribe"; this.UnsubscribeB.UseVisualStyleBackColor = true; // // lblListenerUrl // this.lblListenerUrl.AutoSize = true; this.lblListenerUrl.Location = new System.Drawing.Point(6, 333); this.lblListenerUrl.Name = "lblListenerUrl"; this.lblListenerUrl.Size = new System.Drawing.Size(92, 13); this.lblListenerUrl.TabIndex = 26; this.lblListenerUrl.Text = "TFS Listener URL"; // // TFSUpdateB // this.TFSUpdateB.Location = new System.Drawing.Point(7, 378); this.TFSUpdateB.Name = "TFSUpdateB"; this.TFSUpdateB.Size = new System.Drawing.Size(135, 23); this.TFSUpdateB.TabIndex = 25; this.TFSUpdateB.Text = "Subscribe"; this.TFSUpdateB.UseVisualStyleBackColor = true; // // ListenerURLTB // this.ListenerURLTB.Enabled = false; this.ListenerURLTB.Location = new System.Drawing.Point(7, 349); this.ListenerURLTB.Name = "ListenerURLTB"; this.ListenerURLTB.Size = new System.Drawing.Size(435, 20); this.ListenerURLTB.TabIndex = 24; // // TFSStatusLabel // this.TFSStatusLabel.AutoSize = true; this.TFSStatusLabel.Location = new System.Drawing.Point(13, 213); this.TFSStatusLabel.Name = "TFSStatusLabel"; this.TFSStatusLabel.Size = new System.Drawing.Size(78, 13); this.TFSStatusLabel.TabIndex = 21; this.TFSStatusLabel.Text = "Not connected"; // // lblCurrentSubscriptions // this.lblCurrentSubscriptions.AutoSize = true; this.lblCurrentSubscriptions.Location = new System.Drawing.Point(6, 234); this.lblCurrentSubscriptions.Name = "lblCurrentSubscriptions"; this.lblCurrentSubscriptions.Size = new System.Drawing.Size(107, 13); this.lblCurrentSubscriptions.TabIndex = 20; this.lblCurrentSubscriptions.Text = "Current Subscriptions"; // // TFSConnectB // this.TFSConnectB.Location = new System.Drawing.Point(7, 181); this.TFSConnectB.Name = "TFSConnectB"; this.TFSConnectB.Size = new System.Drawing.Size(75, 23); this.TFSConnectB.TabIndex = 17; this.TFSConnectB.Text = "Connect"; this.TFSConnectB.UseVisualStyleBackColor = true; // // TFSPasswordTB // this.TFSPasswordTB.Location = new System.Drawing.Point(7, 135); this.TFSPasswordTB.Name = "TFSPasswordTB"; this.TFSPasswordTB.Size = new System.Drawing.Size(196, 20); this.TFSPasswordTB.TabIndex = 16; this.TFSPasswordTB.UseSystemPasswordChar = true; // // lblTfsPassword // this.lblTfsPassword.AutoSize = true; this.lblTfsPassword.Location = new System.Drawing.Point(7, 119); this.lblTfsPassword.Name = "lblTfsPassword"; this.lblTfsPassword.Size = new System.Drawing.Size(76, 13); this.lblTfsPassword.TabIndex = 15; this.lblTfsPassword.Text = "TFS Password"; // // lblTfsUsername // this.lblTfsUsername.AutoSize = true; this.lblTfsUsername.Location = new System.Drawing.Point(7, 69); this.lblTfsUsername.Name = "lblTfsUsername"; this.lblTfsUsername.Size = new System.Drawing.Size(78, 13); this.lblTfsUsername.TabIndex = 14; this.lblTfsUsername.Text = "TFS Username"; // // TFSUsernameTB // this.TFSUsernameTB.Location = new System.Drawing.Point(7, 85); this.TFSUsernameTB.Name = "TFSUsernameTB"; this.TFSUsernameTB.Size = new System.Drawing.Size(196, 20); this.TFSUsernameTB.TabIndex = 13; // // lblTfsServerUrl // this.lblTfsServerUrl.AutoSize = true; this.lblTfsServerUrl.Location = new System.Drawing.Point(7, 14); this.lblTfsServerUrl.Name = "lblTfsServerUrl"; this.lblTfsServerUrl.Size = new System.Drawing.Size(86, 13); this.lblTfsServerUrl.TabIndex = 12; this.lblTfsServerUrl.Text = "TFS Server URL"; // // TFSURLTB // this.TFSURLTB.Location = new System.Drawing.Point(7, 30); this.TFSURLTB.Name = "TFSURLTB"; this.TFSURLTB.Size = new System.Drawing.Size(435, 20); this.TFSURLTB.TabIndex = 11; // // tpAdvanced // this.tpAdvanced.AutoScroll = true; this.tpAdvanced.Controls.Add(this.txtDebugDescription); this.tpAdvanced.Controls.Add(this.chkDebugMode); this.tpAdvanced.Controls.Add(this.RegExTB); this.tpAdvanced.Controls.Add(this.lblRegex); this.tpAdvanced.Controls.Add(this.txtMatchesDescription); this.tpAdvanced.Location = new System.Drawing.Point(4, 22); this.tpAdvanced.Name = "tpAdvanced"; this.tpAdvanced.Padding = new System.Windows.Forms.Padding(3); this.tpAdvanced.Size = new System.Drawing.Size(433, 413); this.tpAdvanced.TabIndex = 2; this.tpAdvanced.Text = "Advanced"; this.tpAdvanced.UseVisualStyleBackColor = true; // // txtDebugDescription // this.txtDebugDescription.BackColor = System.Drawing.SystemColors.Control; this.txtDebugDescription.BorderStyle = System.Windows.Forms.BorderStyle.None; this.txtDebugDescription.Location = new System.Drawing.Point(9, 140); this.txtDebugDescription.Multiline = true; this.txtDebugDescription.Name = "txtDebugDescription"; this.txtDebugDescription.ReadOnly = true; this.txtDebugDescription.Size = new System.Drawing.Size(421, 45); this.txtDebugDescription.TabIndex = 5; // // chkDebugMode // this.chkDebugMode.AutoSize = true; this.chkDebugMode.Location = new System.Drawing.Point(9, 117); this.chkDebugMode.Name = "chkDebugMode"; this.chkDebugMode.Size = new System.Drawing.Size(88, 17); this.chkDebugMode.TabIndex = 4; this.chkDebugMode.Text = "Debug Mode"; this.chkDebugMode.UseVisualStyleBackColor = true; // // RegExTB // this.RegExTB.Location = new System.Drawing.Point(9, 23); this.RegExTB.Name = "RegExTB"; this.RegExTB.Size = new System.Drawing.Size(421, 20); this.RegExTB.TabIndex = 2; this.RegExTB.Text = "[A-Z]{1,2}-[0-9]+"; // // lblRegex // this.lblRegex.AutoSize = true; this.lblRegex.Location = new System.Drawing.Point(9, 7); this.lblRegex.Name = "lblRegex"; this.lblRegex.Size = new System.Drawing.Size(204, 13); this.lblRegex.TabIndex = 1; this.lblRegex.Text = "VersionOne Workitem Regular Expression"; // // txtMatchesDescription // this.txtMatchesDescription.BorderStyle = System.Windows.Forms.BorderStyle.None; this.txtMatchesDescription.Location = new System.Drawing.Point(9, 49); this.txtMatchesDescription.Multiline = true; this.txtMatchesDescription.Name = "txtMatchesDescription"; this.txtMatchesDescription.ReadOnly = true; this.txtMatchesDescription.Size = new System.Drawing.Size(421, 47); this.txtMatchesDescription.TabIndex = 0; this.txtMatchesDescription.Text = resources.GetString("txtMatchesDescription.Text"); // // btnSaveAllSettings // this.btnSaveAllSettings.Location = new System.Drawing.Point(153, 502); this.btnSaveAllSettings.Name = "btnSaveAllSettings"; this.btnSaveAllSettings.Size = new System.Drawing.Size(145, 28); this.btnSaveAllSettings.TabIndex = 32; this.btnSaveAllSettings.Text = "Save All Settings"; this.btnSaveAllSettings.UseVisualStyleBackColor = true; // // tbResults // this.tbResults.BackColor = System.Drawing.Color.Black; this.tbResults.ForeColor = System.Drawing.Color.White; this.tbResults.Location = new System.Drawing.Point(10, 533); this.tbResults.Multiline = true; this.tbResults.Name = "tbResults"; this.tbResults.ReadOnly = true; this.tbResults.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.tbResults.Size = new System.Drawing.Size(441, 100); this.tbResults.TabIndex = 10; // // llClear // this.llClear.AutoSize = true; this.llClear.Location = new System.Drawing.Point(420, 515); this.llClear.Name = "llClear"; this.llClear.Size = new System.Drawing.Size(31, 13); this.llClear.TabIndex = 34; this.llClear.TabStop = true; this.llClear.Text = "Clear"; this.llClear.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.llClear_LinkClicked); // // tbBaseUrl // this.tbBaseUrl.Location = new System.Drawing.Point(121, 26); this.tbBaseUrl.Name = "tbBaseUrl"; this.tbBaseUrl.Size = new System.Drawing.Size(243, 20); this.tbBaseUrl.TabIndex = 13; // // lblTFSListenerUrl // this.lblTFSListenerUrl.AutoSize = true; this.lblTFSListenerUrl.Location = new System.Drawing.Point(7, 29); this.lblTFSListenerUrl.Name = "lblTFSListenerUrl"; this.lblTFSListenerUrl.Size = new System.Drawing.Size(110, 13); this.lblTFSListenerUrl.TabIndex = 14; this.lblTFSListenerUrl.Text = "TFS Base Listener Url"; // // btnSetBaseListenerUrl // this.btnSetBaseListenerUrl.Location = new System.Drawing.Point(369, 26); this.btnSetBaseListenerUrl.Name = "btnSetBaseListenerUrl"; this.btnSetBaseListenerUrl.Size = new System.Drawing.Size(75, 20); this.btnSetBaseListenerUrl.TabIndex = 15; this.btnSetBaseListenerUrl.Text = "Refresh"; this.btnSetBaseListenerUrl.UseVisualStyleBackColor = true; // // ConfigForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(456, 636); this.Controls.Add(this.btnSetBaseListenerUrl); this.Controls.Add(this.lblTFSListenerUrl); this.Controls.Add(this.tbBaseUrl); this.Controls.Add(this.llClear); this.Controls.Add(this.btnSaveAllSettings); this.Controls.Add(this.tbResults); this.Controls.Add(this.tcSettings); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "ConfigForm"; this.Text = "VersionOne TFS Listener Configuration"; this.tcSettings.ResumeLayout(false); this.tpVersionOne.ResumeLayout(false); this.tpVersionOne.PerformLayout(); this.grpProxySettings.ResumeLayout(false); this.grpProxySettings.PerformLayout(); this.tpTfsServer.ResumeLayout(false); this.tpTfsServer.PerformLayout(); this.tpAdvanced.ResumeLayout(false); this.tpAdvanced.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TabControl tcSettings; private System.Windows.Forms.TabPage tpVersionOne; private System.Windows.Forms.TabPage tpTfsServer; private System.Windows.Forms.Button btnTestV1Connection; private System.Windows.Forms.MaskedTextBox V1PasswordTB; private System.Windows.Forms.Label lblVersionOnePassword; private System.Windows.Forms.Label lblVersionOneUsername; private System.Windows.Forms.TextBox V1UsernameTB; private System.Windows.Forms.Label lblVersionOneUrl; private System.Windows.Forms.TextBox V1URLTB; private System.Windows.Forms.Label lblCurrentSubscriptions; private System.Windows.Forms.Button TFSConnectB; private System.Windows.Forms.MaskedTextBox TFSPasswordTB; private System.Windows.Forms.Label lblTfsPassword; private System.Windows.Forms.Label lblTfsUsername; private System.Windows.Forms.TextBox TFSUsernameTB; private System.Windows.Forms.Label lblTfsServerUrl; private System.Windows.Forms.TextBox TFSURLTB; private System.Windows.Forms.Label TFSStatusLabel; private System.Windows.Forms.CheckBox UseIntegratedAuthenticationCB; private System.Windows.Forms.TextBox ListenerURLTB; private System.Windows.Forms.Label lblListenerUrl; private System.Windows.Forms.Button TFSUpdateB; private System.Windows.Forms.Button UnsubscribeB; private System.Windows.Forms.ListView SubscriptionsLV; private System.Windows.Forms.ColumnHeader columnHeader1; private System.Windows.Forms.ColumnHeader columnHeader2; private System.Windows.Forms.TabPage tpAdvanced; private System.Windows.Forms.TextBox RegExTB; private System.Windows.Forms.Label lblRegex; private System.Windows.Forms.TextBox txtMatchesDescription; private System.Windows.Forms.CheckBox chkDebugMode; private System.Windows.Forms.GroupBox grpProxySettings; private System.Windows.Forms.TextBox txtProxyDomain; private System.Windows.Forms.Label lblProxyDomain; private System.Windows.Forms.TextBox txtProxyPassword; private System.Windows.Forms.Label lblProxyPassword; private System.Windows.Forms.TextBox txtProxyUsername; private System.Windows.Forms.Label lblProxyUsername; private System.Windows.Forms.TextBox txtProxyUrl; private System.Windows.Forms.Label lblProxyUrl; private System.Windows.Forms.CheckBox chkUseProxy; private System.Windows.Forms.Button btnSaveAllSettings; private System.Windows.Forms.TextBox txtDebugDescription; private System.Windows.Forms.TextBox tbResults; private System.Windows.Forms.LinkLabel llClear; private System.Windows.Forms.TextBox tbBaseUrl; private System.Windows.Forms.Label lblTFSListenerUrl; private System.Windows.Forms.Button btnSetBaseListenerUrl; private System.Windows.Forms.Button TFSTestEventsB; } }
{ "content_hash": "2c52c470acf4b636a9b202c11127c182", "timestamp": "", "source": "github", "line_count": 655, "max_line_length": 142, "avg_line_length": 50.95114503816794, "alnum_prop": 0.6168459533155545, "repo_name": "versionone/VersionOne.Integration.TFS.Listener", "id": "87e620ccc19e7b07fd1340f415e90fe65eeaacd0", "size": "33373", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "VersionOne.Integration.Tfs.Listener.Config/ConfigForm.Designer.cs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "468" }, { "name": "C#", "bytes": "88910" }, { "name": "PowerShell", "bytes": "321" } ], "symlink_target": "" }
using System; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; namespace Azure.ResourceManager.Network { /// <summary> Deletes the specified subnet. </summary> public partial class SubnetsDeleteOperation : Operation<Response>, IOperationSource<Response> { private readonly ArmOperationHelpers<Response> _operation; internal SubnetsDeleteOperation(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, Request request, Response response) { _operation = new ArmOperationHelpers<Response>(this, clientDiagnostics, pipeline, request, response, OperationFinalStateVia.Location, "SubnetsDeleteOperation"); } /// <inheritdoc /> public override string Id => _operation.Id; /// <inheritdoc /> public override Response Value => _operation.Value; /// <inheritdoc /> public override bool HasCompleted => _operation.HasCompleted; /// <inheritdoc /> public override bool HasValue => _operation.HasValue; /// <inheritdoc /> public override Response GetRawResponse() => _operation.GetRawResponse(); /// <inheritdoc /> public override Response UpdateStatus(CancellationToken cancellationToken = default) => _operation.UpdateStatus(cancellationToken); /// <inheritdoc /> public override ValueTask<Response> UpdateStatusAsync(CancellationToken cancellationToken = default) => _operation.UpdateStatusAsync(cancellationToken); /// <inheritdoc /> public override ValueTask<Response<Response>> WaitForCompletionAsync(CancellationToken cancellationToken = default) => _operation.WaitForCompletionAsync(cancellationToken); /// <inheritdoc /> public override ValueTask<Response<Response>> WaitForCompletionAsync(TimeSpan pollingInterval, CancellationToken cancellationToken = default) => _operation.WaitForCompletionAsync(pollingInterval, cancellationToken); Response IOperationSource<Response>.CreateResult(Response response, CancellationToken cancellationToken) { return response; } async ValueTask<Response> IOperationSource<Response>.CreateResultAsync(Response response, CancellationToken cancellationToken) { return await new ValueTask<Response>(response).ConfigureAwait(false); } } }
{ "content_hash": "1a17169402fb6d4ce636a9ddd0fcfba3", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 223, "avg_line_length": 44, "alnum_prop": 0.7177685950413223, "repo_name": "brjohnstmsft/azure-sdk-for-net", "id": "80ad5212374ccebba8d6a7ba01d65f9813c70718", "size": "2558", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "sdk/network/Azure.ResourceManager.Network/src/Generated/SubnetsDeleteOperation.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "16774" }, { "name": "C#", "bytes": "36517517" }, { "name": "HTML", "bytes": "234899" }, { "name": "JavaScript", "bytes": "7875" }, { "name": "PowerShell", "bytes": "257257" }, { "name": "Shell", "bytes": "13061" }, { "name": "Smarty", "bytes": "11135" }, { "name": "TypeScript", "bytes": "143209" } ], "symlink_target": "" }
#ifndef BOOST_ASIO_DETAIL_ARRAY_FWD_HPP #define BOOST_ASIO_DETAIL_ARRAY_FWD_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) namespace boost { template<class T, std::size_t N> class array; } // namespace boost #endif // BOOST_ASIO_DETAIL_ARRAY_FWD_HPP
{ "content_hash": "69bc05dd017efb6e77ee2ae9676f413c", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 49, "avg_line_length": 21.0625, "alnum_prop": 0.6498516320474778, "repo_name": "benkaraban/anima-games-engine", "id": "e6158a5dae4e210849156643289a7a249d28d5b1", "size": "638", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "LibsExternes/Includes/boost/asio/detail/array_fwd.hpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "8772269" }, { "name": "C#", "bytes": "125904" }, { "name": "C++", "bytes": "74431764" }, { "name": "CMake", "bytes": "43555" }, { "name": "Java", "bytes": "95806" }, { "name": "Makefile", "bytes": "17914" }, { "name": "NSIS", "bytes": "17188" }, { "name": "Objective-C", "bytes": "50195" }, { "name": "Perl", "bytes": "6275" }, { "name": "Python", "bytes": "22678" }, { "name": "Shell", "bytes": "21728" } ], "symlink_target": "" }
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.08.07 at 06:17:52 PM CEST // package uk.gov.legislation.namespaces.legislation; import javax.xml.bind.annotation.*; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import java.util.ArrayList; import java.util.List; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element ref="{http://www.legislation.gov.uk/namespaces/legislation}Para" maxOccurs="unbounded"/&gt; * &lt;/sequence&gt; * &lt;attGroup ref="{http://www.legislation.gov.uk/namespaces/legislation}CommonAttributes"/&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "paras" }) @XmlRootElement(name = "Comment") public class Comment { @XmlElement(name = "Para", required = true) protected List<Para> paras; @XmlAttribute(name = "id") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) protected String id; @XmlAttribute(name = "lang", namespace = "http://www.w3.org/XML/1998/namespace") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "language") protected String lang; @XmlAttribute(name = "space", namespace = "http://www.w3.org/XML/1998/namespace") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) protected String space; @XmlAttribute(name = "base", namespace = "http://www.w3.org/XML/1998/namespace") @XmlSchemaType(name = "anyURI") protected String base; @XmlAttribute(name = "AltVersionRefs") @XmlIDREF @XmlSchemaType(name = "IDREFS") protected List<Object> altVersionRefs; /** * Gets the value of the paras property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the paras property. * * <p> * For example, to add a new item, do as follows: * <pre> * getParas().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Para } * * */ public List<Para> getParas() { if (paras == null) { paras = new ArrayList<>(); } return this.paras; } /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the lang property. * * @return * possible object is * {@link String } * */ public String getLang() { return lang; } /** * Sets the value of the lang property. * * @param value * allowed object is * {@link String } * */ public void setLang(String value) { this.lang = value; } /** * Gets the value of the space property. * * @return * possible object is * {@link String } * */ public String getSpace() { return space; } /** * Sets the value of the space property. * * @param value * allowed object is * {@link String } * */ public void setSpace(String value) { this.space = value; } /** * Gets the value of the base property. * * @return * possible object is * {@link String } * */ public String getBase() { return base; } /** * Sets the value of the base property. * * @param value * allowed object is * {@link String } * */ public void setBase(String value) { this.base = value; } /** * Gets the value of the altVersionRefs property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the altVersionRefs property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAltVersionRefs().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Object } * * */ public List<Object> getAltVersionRefs() { if (altVersionRefs == null) { altVersionRefs = new ArrayList<>(); } return this.altVersionRefs; } }
{ "content_hash": "bbae260a309baa67d7b3aac439f5cee4", "timestamp": "", "source": "github", "line_count": 219, "max_line_length": 114, "avg_line_length": 25.643835616438356, "alnum_prop": 0.5771011396011396, "repo_name": "digitalheir/java-legislation-gov-uk-library", "id": "79472783748f43896cc8b71e2972d14ee99117e9", "size": "5616", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/uk/gov/legislation/namespaces/legislation/Comment.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "4501081" }, { "name": "Ruby", "bytes": "1226" } ], "symlink_target": "" }
define(['require', 'mocha', 'chai', 'mocha-results'], function(require, mocha, chai, results) { mocha.setup('bdd'); expect = chai.expect require(['test/dib.test'], function() { if (window.mochaPhantomJS) { mochaPhantomJS.run(); } else { results(mocha.run()); } }); });
{ "content_hash": "c6e33980a430a566d1455de8815deb58", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 56, "avg_line_length": 22.428571428571427, "alnum_prop": 0.5668789808917197, "repo_name": "sailjs/dib", "id": "95096e808d1a6c44303aae409ffcaa32941b7ffa", "size": "314", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/www/js/suite.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "3610" } ], "symlink_target": "" }
from tethys_sdk.testing import TethysTestCase from tethys_compute.models.tethys_job import TethysJob from tethys_compute.models.condor.condor_py_workflow import CondorPyWorkflow from tethys_compute.models.condor.condor_workflow_job_node import CondorWorkflowJobNode from tethys_compute.models.condor.condor_workflow import CondorWorkflow from django.contrib.auth.models import User from unittest import mock import os import os.path class CondorPyWorkflowJobNodeTest(TethysTestCase): def set_up(self): path = os.path.dirname(__file__) self.workspace_dir = os.path.join(path, 'workspace') self.user = User.objects.create_user('tethys_super', 'user@example.com', 'pass') self.condorworkflow = CondorWorkflow( _max_jobs={'foo': 10}, _config='test_config', name='foo{id}', workspace=self.workspace_dir, user=self.user, ) self.condorworkflow.save() # To have a flow Node, we need to have a Condor Job which requires a CondorBase which requires a TethysJob self.id_value = CondorWorkflow.objects.get(name='foo{id}').condorpyworkflow_ptr_id self.condorpyworkflow = CondorPyWorkflow.objects.get(condorpyworkflow_id=self.id_value) self.condorworkflowjobnode = CondorWorkflowJobNode( name='Job1_NodeA', workflow=self.condorpyworkflow, _attributes={'test': 'one'}, _num_jobs=1, _remote_input_files=['test1.txt'], ) self.condorworkflowjobnode.save() def tear_down(self): self.condorworkflow.delete() self.condorworkflowjobnode.delete() def test_type_prop(self): self.assertEqual('JOB', self.condorworkflowjobnode.type) def test_workspace_prop(self): self.assertEqual('.', self.condorworkflowjobnode.workspace) @mock.patch('tethys_compute.models.condor.condor_workflow_job_node.CondorPyJob.condorpy_job') def test_job_prop(self, mock_cpj): # Condorpy_job Prop is already tested in CondorPyJob Test case self.assertEqual(mock_cpj, self.condorworkflowjobnode.job) @mock.patch('tethys_compute.models.condor.condor_workflow_job_node.CondorWorkflowNode.update_database_fields') @mock.patch('tethys_compute.models.condor.condor_workflow_job_node.CondorPyJob.update_database_fields') def test_update_database_fields(self, mock_pj_update, mock_wfn_update): # Execute self.condorworkflowjobnode.update_database_fields() # Check result mock_pj_update.assert_called_once() mock_wfn_update.assert_called_once() @mock.patch('tethys_compute.models.condor.condor_workflow_job_node.CondorWorkflowNode.update_database_fields') @mock.patch('tethys_compute.models.condor.condor_workflow_job_node.CondorPyJob.update_database_fields') def test_receiver_pre_save(self, mock_pj_update, mock_wfn_update): self.condorworkflowjobnode.save() # Check result mock_pj_update.assert_called_once() mock_wfn_update.assert_called_once() def test_job_post_save(self): # get the job tethys_job = TethysJob.objects.get(name='foo{id}') id_val = tethys_job.id # Run save to activate post save tethys_job.save() # Set up new name new_name = 'foo{id}'.format(id=id_val) # Get same tethys job with new name tethys_job = TethysJob.objects.get(name=new_name) # Check results self.assertIsInstance(tethys_job, TethysJob) self.assertEqual(new_name, tethys_job.name)
{ "content_hash": "455fff9064f758b1a6a9580ae9cab4cd", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 114, "avg_line_length": 39.67032967032967, "alnum_prop": 0.6842105263157895, "repo_name": "CI-WATER/tethys", "id": "c44dce957701fefade2686e3001464b13e306dbe", "size": "3610", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/unit_tests/test_tethys_compute/test_models/test_CondorWorkflowJobNode.py", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "CSS", "bytes": "175789" }, { "name": "HTML", "bytes": "149728" }, { "name": "JavaScript", "bytes": "360375" }, { "name": "Python", "bytes": "592551" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="io.github.longlinht.taobrowser.TaoBrowserActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent"/> </android.support.constraint.ConstraintLayout>
{ "content_hash": "b5b1592b3a8f8ce29cb93798929559aa", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 74, "avg_line_length": 45.26315789473684, "alnum_prop": 0.6755813953488372, "repo_name": "longlinht/TaoBrowser", "id": "86bc9cde062fbb1d93997df14711e10f9977f69c", "size": "860", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/layout/activity_tao_browser.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1528" } ], "symlink_target": "" }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; using System.Collections.Immutable; using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp { internal partial class LocalRewriter { public override BoundNode VisitTupleLiteral(BoundTupleLiteral node) { throw ExceptionUtilities.Unreachable(); } public override BoundNode VisitConvertedTupleLiteral(BoundConvertedTupleLiteral node) { return VisitTupleExpression(node); } private BoundNode VisitTupleExpression(BoundTupleExpression node) { ImmutableArray<BoundExpression> rewrittenArguments = VisitList(node.Arguments); return RewriteTupleCreationExpression(node, rewrittenArguments); } /// <summary> /// Converts the expression for creating a tuple instance into an expression creating a ValueTuple (if short) or nested ValueTuples (if longer). /// /// For instance, for a long tuple we'll generate: /// creationExpression(ctor=largestCtor, args=firstArgs+(nested creationExpression for remainder, with smaller ctor and next few args)) /// </summary> private BoundExpression RewriteTupleCreationExpression(BoundTupleExpression node, ImmutableArray<BoundExpression> rewrittenArguments) { Debug.Assert(node.Type is { }); return MakeTupleCreationExpression(node.Syntax, (NamedTypeSymbol)node.Type, rewrittenArguments); } private BoundExpression MakeTupleCreationExpression(SyntaxNode syntax, NamedTypeSymbol type, ImmutableArray<BoundExpression> rewrittenArguments) { Debug.Assert(type.IsTupleType); ArrayBuilder<NamedTypeSymbol> underlyingTupleTypeChain = ArrayBuilder<NamedTypeSymbol>.GetInstance(); NamedTypeSymbol.GetUnderlyingTypeChain(type, underlyingTupleTypeChain); try { // make a creation expression for the smallest type NamedTypeSymbol smallestType = underlyingTupleTypeChain.Pop(); ImmutableArray<BoundExpression> smallestCtorArguments = ImmutableArray.Create(rewrittenArguments, underlyingTupleTypeChain.Count * (NamedTypeSymbol.ValueTupleRestPosition - 1), smallestType.Arity); var smallestCtor = (MethodSymbol?)NamedTypeSymbol.GetWellKnownMemberInType(smallestType.OriginalDefinition, NamedTypeSymbol.GetTupleCtor(smallestType.Arity), _diagnostics, syntax); if (smallestCtor is null) { return _factory.BadExpression(type); } MethodSymbol smallestConstructor = smallestCtor.AsMember(smallestType); BoundObjectCreationExpression currentCreation = new BoundObjectCreationExpression(syntax, smallestConstructor, smallestCtorArguments); if (underlyingTupleTypeChain.Count > 0) { NamedTypeSymbol tuple8Type = underlyingTupleTypeChain.Peek(); var tuple8Ctor = (MethodSymbol?)NamedTypeSymbol.GetWellKnownMemberInType(tuple8Type.OriginalDefinition, NamedTypeSymbol.GetTupleCtor(NamedTypeSymbol.ValueTupleRestPosition), _diagnostics, syntax); if (tuple8Ctor is null) { return _factory.BadExpression(type); } // make successively larger creation expressions containing the previous one do { ImmutableArray<BoundExpression> ctorArguments = ImmutableArray.Create(rewrittenArguments, (underlyingTupleTypeChain.Count - 1) * (NamedTypeSymbol.ValueTupleRestPosition - 1), NamedTypeSymbol.ValueTupleRestPosition - 1) .Add(currentCreation); MethodSymbol constructor = tuple8Ctor.AsMember(underlyingTupleTypeChain.Pop()); currentCreation = new BoundObjectCreationExpression(syntax, constructor, ctorArguments); } while (underlyingTupleTypeChain.Count > 0); } currentCreation = currentCreation.Update( currentCreation.Constructor, currentCreation.Arguments, currentCreation.ArgumentNamesOpt, currentCreation.ArgumentRefKindsOpt, currentCreation.Expanded, currentCreation.ArgsToParamsOpt, currentCreation.DefaultArguments, currentCreation.ConstantValue, currentCreation.InitializerExpressionOpt, type); return currentCreation; } finally { underlyingTupleTypeChain.Free(); } } } }
{ "content_hash": "f708f037270f5124bc9265af6c2975c8", "timestamp": "", "source": "github", "line_count": 116, "max_line_length": 178, "avg_line_length": 52.94827586206897, "alnum_prop": 0.5475415174210355, "repo_name": "jasonmalinowski/roslyn", "id": "3124adf61698d689d5d2187aff93a81be98f62a9", "size": "6144", "binary": false, "copies": "6", "ref": "refs/heads/main", "path": "src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_TupleCreationExpression.cs", "mode": "33188", "license": "mit", "language": [ { "name": "1C Enterprise", "bytes": "257760" }, { "name": "Batchfile", "bytes": "8186" }, { "name": "C#", "bytes": "175203005" }, { "name": "C++", "bytes": "5602" }, { "name": "CMake", "bytes": "12939" }, { "name": "Dockerfile", "bytes": "441" }, { "name": "F#", "bytes": "549" }, { "name": "PowerShell", "bytes": "285127" }, { "name": "Shell", "bytes": "133800" }, { "name": "Vim Snippet", "bytes": "6353" }, { "name": "Visual Basic .NET", "bytes": "73887605" } ], "symlink_target": "" }
title: "Plugins" description: "Reference documentation for Sensu Plugins." version: 1.1 weight: 9 --- # Sensu Plugins ## Reference documentation - [What is a Sensu plugin?](#what-is-a-sensu-plugin) - [The Sensu Plugin specification](#the-sensu-plugin-specification) - [Where to find Sensu plugins](#where-to-find-sensu-plugins) - [The Sensu Plugins project](#the-sensu-plugins-project) - [Featured Sensu Plugins](#featured-sensu-plugins) - [Nagios plugins and the Nagios exchange](#nagios-plugins-and-the-nagios-exchange) - [Write you own custom plugins](#write-your-own-custom-plugins) - [Plugin execution](#plugin-execution) - [How and where are plugins executed?](#how-and-where-are-mutator-commands-executed) - [What programming languages are supported?](#what-programming-languages-are-supported) - [What is Sensu's `EMBEDDED_RUBY`?](#what-is-sensus-embeddedruby) - [Installing Sensu Plugins](#installing-sensu-plugins) - [Use `sensu-install` to install Sensu Plugins](#use-sensu-install-to-install-sensu-plugins) - [Alternative installation methods](#alternative-installation-methods) - [The Sensu Plugin gem](#the-sensu-plugin-gem) - [What is the `sensu-plugin` gem?](#what-is-the-sensu-plugin-gem) - [Plugin configuration](#plugin-configuration) - [Example check plugin definition](#example-check-plugin-definition) - [Sensu plugin definition specification](#sensu-plugin-definition-specification) ## What is a Sensu plugin? Sensu plugins provide executable scripts or other programs that can be used as [Sensu checks][1] (i.e. to monitor server resources, services, and application health, or collect & analyze metrics), [Sensu handlers][2] (i.e. to send notifications or perform other actions based on [Sensu events][3]), or [Sensu mutators][3] (i.e. to modify [event data][4] prior to handling). ### The Sensu Plugin specification Sensu Plugins provide executable scripts or other programs that can be used as a [Sensu check command][5], [pipe handler command][6], or [mutator command][7]. Sensu plugins must comply with a simple specification: - Accept input/data via `STDIN` (handler and mutator plugins only) - Optionally able to parse a JSON data payload (i.e. [event data][4]) - Output data to `STDOUT` or `STDERR` - Produce an exit status code to indicate state: - `0` indicates `OK` - `1` indicates `WARNING` - `2` indicates `CRITICAL` - exit status codes other than `0`, `1`, or `2` indicate an unknown or custom status - Optionally able to parse command line arguments to modify plugin behavior _PRO TIP: Those familiar with the [Nagios][14] monitoring system may recognize this specification, as it is the same one used by Nagios plugins. As a result, [Nagios plugins can be used with Sensu][15] without any modification._ ## Where to find Sensu Plugins ### The Sensu Plugins project The [Sensu Plugins project][8] is a community-powered [open source software project][9] that is organized by members of the Sensu community, in collaboration with the Sensu development team. The Sensu Plugins project currently maintains _hundreds_ of plugins providing various checks, handlers, and mutators which are used by thousands of organizations around the world. Most of the plugins maintained by the Sensu Plugins project are Ruby-based plugins which are [distributed via Rubygems.org][10] (and [installable via `sensu-install`][11]). ### Featured Sensu Plugins To help new users discover some of the most popular plugins for instrumenting their infrastructure and integrating Sensu with popular tools and services, a [featured plugins page][12] is provided on the Sensu website. These featured plugins are the same plugins developed and maintained by the [Sensu plugins project][13]. ### Nagios plugins and the Nagios Exchange As previously mentioned, the [Sensu Plugin specification][16] is 100% compatible with the [Nagios plugin specification][17]; as a result, **Nagios plugins may be used with Sensu without any modification**. Sensu allows you to bring new life to the 50+ plugins in the official [Nagios Plugins project][18] (which [began life in 1999][19], making it a very mature source for monitoring plugins), and over 4000 plugins available in the [Nagios Exchange][20]. ### Write your own custom plugins With a [simple specification][16], which makes it possible to [write Sensu plugins in almost any programming language][21], it's very easy to write your own custom plugins for Sensu. #### Example plugins The following example demonstrates how to write a very basic Sensu Plugin in the Ruby programming language. ~~~ ruby #!/usr/bin/env ruby # # A simple example handler plugin. require 'json' # Read the incoming JSON data from STDIN. event = JSON.parse(STDIN.read, :symbolize_names => true) # Create an output object using Ruby string interpolation output = "The check named #{event[:check][:name]} generated the following output: #{event[:output]}" # Convert the mutated event data back to JSON and output it to STDOUT. puts output ~~~ _NOTE: this example doesn't provide much in terms of functionality (it would simply be logged to the [Sensu server][23] log file), but it does provide a starting point for a simple custom plugin._ ## Plugin execution ### How and where are plugins executed? As mentioned elsewhere in the documentation (see: [check commands][5], [pipe handler commands][6], and [mutator commands][7]), all plugins are executed by a [Sensu client][24] or [Sensu server][23] as the `sensu` user. Plugins must be executable files that are discoverable on the Sensu system (i.e. installed in a system `$PATH` directory), or they must be referenced with an absolute path (e.g. `/opt/path/to/my/plugin`). _NOTE: By default, the Sensu installer packages will modify the system `$PATH` for the Sensu processes to include `/etc/sensu/plugins`. As a result, executable scripts (e.g. plugins) located in `/etc/sensu/plugins` will be valid commands. This allows command attributes to use "relative paths" for Sensu plugin commands;<br><br>e.g.: `"command": "check-http.rb -u https://sensuapp.org"`_ ### What programming languages are supported? Any programming language that can satisfy the [Sensu plugin specification][16] requirements &ndash; which is nearly any programming language in the world &ndash; can be used to write Sensu plugins. One of the primary advantages of writing Sensu plugins in the Ruby programming language is that Sensu itself is written in Ruby, [and all Sensu installer packages provide an embedded Ruby][25], eliminating the need to install or depend on a separate runtime. _NOTE: plugins written in programming languages other than Ruby will require the corresponding runtime to be installed in order for the plugin to run._ ### What is Sensu's `EMBEDDED_RUBY`? All Sensu Core installer packages provide an embedded Ruby runtime (i.e. even if a system Ruby is installed, Sensu will run on its own Ruby). This "vendored" Ruby runtime can be accessed by Ruby-based plugins by setting [Sensu's `EMBEDDED_RUBY` configuration variable][26] to `true`. _NOTE: in Sensu versions `>0.21.0`, all init/service scripts provided by the Sensu Core installer packages are setting Sensu's `EMBEDDED_RUBY` environment variable to `true`, making the use of Sensu's embedded Ruby the default behavior in modern Sensu releases._ ## Installing Sensu Plugins ### Use `sensu-install` to install Sensu Plugins The Sensu Core package provides a tool called `sensu-install` (a simple wrapper around the Ruby `gem` utility). The Sensu Install tool (`sensu-install`) simplifies installation of Ruby-based plugins. The `sensu-install` tool can be run with one or more arguments that determine the action(s) to take. ~~~ shell $ sensu-install -h Usage: sensu-install [options] -h, --help Display this message -v, --verbose Enable verbose logging -p, --plugin PLUGIN Install a Sensu PLUGIN -P, --plugins PLUGIN[,PLUGIN] PLUGIN or comma-delimited list of Sensu plugins to install -e, --extension EXTENSION Install a Sensu EXTENSION -E, --extensions EXTENSION[,EXT] EXTENSION or comma-delimited list of Sensu extensions to install -s, --source SOURCE Install Sensu plugins and extensions from a custom SOURCE -c, --clean Clean up (remove) other installed versions of the plugin(s) and/or extension(s) -x, --proxy PROXY Install Sensu plugins and extensions via a PROXY URL ~~~ _NOTE: `sensu-install` is only available in Sensu Core >= `0.21.0`._ #### EXAMPLE {#sensu-install-example} The following instructions will install the [Sensu HTTP plugin][22], using the `sensu-install` utility: ~~~ shell $ sudo sensu-install -p nginx [SENSU-INSTALL] installing Sensu plugins ... [SENSU-INSTALL] determining if Sensu plugin gem 'sensu-plugins-nginx' is already installed ... false [SENSU-INSTALL] Sensu plugin gems to be installed: ["sensu-plugins-nginx"] [SENSU-INSTALL] installing Sensu plugin gem 'sensu-plugins-nginx' Fetching: sensu-plugins-nginx-1.0.0.gem (100%) You can use the embedded Ruby by setting EMBEDDED_RUBY=true in /etc/default/sensu Successfully installed sensu-plugins-nginx-1.0.0 1 gem installed [SENSU-INSTALL] successfully installed Sensu plugins: ["nginx"] ~~~ To install a specific version of a plugin, simply provide a version number after the plugin name (separated by a colon); for example: ~~~ shell $ sudo sensu-install -p nginx:0.0.6 [SENSU-INSTALL] installing Sensu plugins ... [SENSU-INSTALL] determining if Sensu plugin gem 'sensu-plugins-nginx:0.0.6' is already installed ... false [SENSU-INSTALL] Sensu plugin gems to be installed: ["sensu-plugins-nginx:0.0.6"] [SENSU-INSTALL] installing Sensu plugin gem 'sensu-plugins-nginx:0.0.6' Fetching: mixlib-cli-1.5.0.gem (100%) Successfully installed mixlib-cli-1.5.0 Fetching: sensu-plugin-1.2.0.gem (100%) Successfully installed sensu-plugin-1.2.0 Fetching: sensu-plugins-nginx-0.0.6.gem (100%) You can use the embedded Ruby by setting EMBEDDED_RUBY=true in /etc/default/sensu Successfully installed sensu-plugins-nginx-0.0.6 3 gems installed [SENSU-INSTALL] successfully installed Sensu plugins: ["nginx:0.0.6"] ~~~ _NOTE: as shown in the examples above, the `sensu-install` utility will show the output of any gems (including gem dependencies) installed using `sensu-install`._ ### Alternative installation methods Coming soon... ## The Sensu Plugin gem ### What is the `sensu-plugin` gem? Although Sensu Plugins [may be written in any programming language][21], there are certain advantages of writing plugins in Ruby. From an operations perspective, Ruby-based plugins are convenient because they are able to run on [Sensu's embedded Ruby][25]. Ruby-based plugins also benefit from the [`sensu-plugin` gem][27] &mdash; a Ruby library that provides some built-in functionality and a number of helper classes and that simplify custom plugin development. Much of the built-in functionality provided by the `sensu-plugin` gem depends on custom client, check, and/or handler definition attributes, as documented below. ## Plugin configuration ### Example check plugin definition The following is an example [Sensu check definition][29] that uses the `check-http.rb` script provided by the [Sensu HTTP Plugin][22], and a [custom check definition attribute][28] called `refresh`. Although the `refresh` attribute itself is not directly supported by Sensu, the `sensu-plugin` gem does provide built-in support for reducing alert fatigue via the `Sensu::Plugin::Handler` class (i.e. only handling events on the first occurrence, and again every N occurrences, where N = `refresh`). ~~~ json { "checks": { "api_health": { "command": "check-http.rb -u https://api.example.com/health", "standalone": true, "interval": 60, "refresh": 60 } } } ~~~ ### Sensu plugin definition specification _NOTE: plugins based on the `sensu-plugin` gem derive configuration from [custom check definition attributes][28]. The configuration example(s) provided above, and the "specification" provided here are for clarification and convenience only (i.e. this "specification" is just an extension of the [check definition specification][29], and not a definition of a distinct Sensu primitive)._ #### Check definition attributes `occurrences` : description : The number of event occurrences that must occur before an event is handled for the check. _NOTE: Sensu Enterprise users will need to define `occurrences` as part of `handle_when` configuration, see [Built in Filters](enterprise-built-in-filters#the-handlewhen-filter) for more information._ : required : false : type : Integer : default : `1` : example : ~~~ shell "occurrences": 3 ~~~ `refresh` : description : Time in seconds until the event occurrence count is considered reset for the purpose of counting `occurrences`, to allow an event for the check to be handled again. For example, a check with a refresh of `1800` will have its events (recurrences) handled every 30 minutes, to remind users of the issue. _NOTE: Sensu Enterprise users will need to define `refresh` as part of `handle_when` configuration, see [Built in Filters](enterprise-built-in-filters#the-handlewhen-filter) for more information._ : required : false : type : Integer : default : `1800` : example : ~~~ shell "refresh": 3600 ~~~ `dependencies` : description : An array of check dependencies. Events for the check will not be handled if events exist for one or more of the check dependencies. A check dependency can be a check executed by the same Sensu client (eg. `check_app`), or a client/check pair (eg.`db-01/check_mysql`). : required : false : type : Array : example : ~~~ shell "dependencies": [ "check_app", "db-01/check_mysql" ] ~~~ `notification` : description : The notification message used for events created by the check, instead of the commonly used check output. This attribute is used by most notification event handlers that use the sensu-plugin library. : required : false : type : String : example : ~~~ shell "notification": "the shopping cart application is not responding to requests" ~~~ [1]: checks.html [2]: handlers.html [3]: events.html#event-data [4]: mutators.html [5]: checks.html#check-commands [6]: handlers.html#pipe-handler-commands [7]: mutators.html#mutator-commands [8]: http://sensu-plugins.io/ [9]: https://github.com/sensu-plugins [10]: https://rubygems.org/search?query=sensu-plugins- [11]: #use-sensu-install-to-install-sensu-plugins [12]: https://sensuapp.org/plugins [13]: #the-sensu-plugins-project [14]: https://www.nagios.org [15]: #nagios-plugins-and-the-nagios-exchange [16]: #the-sensu-plugin-specification [17]: https://assets.nagios.com/downloads/nagioscore/docs/nagioscore/3/en/pluginapi.html [18]: https://www.nagios.org/downloads/nagios-plugins/ [19]: https://www.nagios.org/about/history/ [20]: https://exchange.nagios.org/ [21]: #what-programming-languages-are-supported [22]: https://github.com/sensu-plugins/sensu-plugins-http [23]: server.html [24]: clients.html [25]: #what-is-sensus-embeddedruby [26]: configuration.html#configuration-variables [27]: https://github.com/sensu-plugins/sensu-plugin [28]: checks.html#custom-attributes [29]: checks.html#check-definition-attributes
{ "content_hash": "fc32ad3a803ccfbff8368a85c2c3dd6c", "timestamp": "", "source": "github", "line_count": 385, "max_line_length": 130, "avg_line_length": 40.25714285714286, "alnum_prop": 0.7430156784308665, "repo_name": "palourde/sensu-docs", "id": "7dd1b901f07cf175055bae9ac3e4fd6d12d60c2e", "size": "15503", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/1.1/reference/plugins.md", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "74696" }, { "name": "Shell", "bytes": "12056" } ], "symlink_target": "" }
A look at some of the options available to the `Drawers` component in [Feathers](http://feathersui.com/), presented as a mobile app. ## Requirements In addition to Starling Framwork and Feathers, this example project requires the MetalWorksMobileTheme example theme. You can find the SWC file for this theme at the following location in the Feathers release build: themes/MetalWorksMobileTheme/swc/MetalWorksMobileTheme.swc ## Web Demo View the [Drawers Explorer](http://feathersui.com/examples/drawers-explorer/) in your browser.
{ "content_hash": "bc243d07510bc5f8e276e09028d8e4b5", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 215, "avg_line_length": 48.72727272727273, "alnum_prop": 0.8003731343283582, "repo_name": "pol2095/feathers", "id": "a619557ee4173c457998127dd45996a14daf98cc", "size": "565", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "examples/DrawersExplorer/README.md", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "ActionScript", "bytes": "4747305" } ], "symlink_target": "" }