hexsha
stringlengths 40
40
| repo
stringlengths 5
114
| path
stringlengths 4
295
| license
listlengths 1
10
| language
stringclasses 5
values | identifier
stringlengths 1
116
| original_docstring
stringlengths 133
7.85k
| docstring
stringlengths 7
2.1k
| docstring_tokens
listlengths 3
399
| code
stringlengths 350
22.6k
| code_tokens
listlengths 20
3.22k
| short_docstring
stringlengths 0
1.32k
| short_docstring_tokens
listlengths 0
359
| comment
listlengths 0
1.22k
| parameters
listlengths 0
13
| docstring_params
dict | has_error
bool 1
class | ast_depth
int64 13
29
| code_length
int64 151
3k
| original_docstring_length
int64 76
449
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
517ddca6a913d245e8bbd7b5e1f89f65ea2941fd
|
upeshpv/fluent-fluentd
|
lib/fluent/compat/handle_tag_and_time_mixin.rb
|
[
"Apache-2.0"
] |
Ruby
|
Fluent
|
#
# Fluentd
#
# 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.
#
|
Fluentd
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
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.
|
[
"Fluentd",
"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",
"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",
"."
] |
module Fluent
module Compat
module HandleTagAndTimeMixin
def self.included(klass)
klass.instance_eval {
config_param :include_time_key, :bool, default: false
config_param :time_key, :string, default: 'time'
config_param :time_format, :string, default: nil
config_param :time_as_epoch, :bool, default: false
config_param :include_tag_key, :bool, default: false
config_param :tag_key, :string, default: 'tag'
config_param :localtime, :bool, default: true
config_param :timezone, :string, default: nil
}
end
def configure(conf)
super
if conf['utc']
@localtime = false
end
@timef = Fluent::TimeFormatter.new(@time_format, @localtime, @timezone)
if @time_as_epoch && !@include_time_key
log.warn "time_as_epoch will be ignored because include_time_key is false"
end
end
def filter_record(tag, time, record)
if @include_tag_key
record[@tag_key] = tag
end
if @include_time_key
if @time_as_epoch
record[@time_key] = time.to_i
else
record[@time_key] = @timef.format(time)
end
end
end
end
end
end
|
[
"module",
"Fluent",
"module",
"Compat",
"module",
"HandleTagAndTimeMixin",
"def",
"self",
".",
"included",
"(",
"klass",
")",
"klass",
".",
"instance_eval",
"{",
"config_param",
":include_time_key",
",",
":bool",
",",
"default",
":",
"false",
"config_param",
":time_key",
",",
":string",
",",
"default",
":",
"'time'",
"config_param",
":time_format",
",",
":string",
",",
"default",
":",
"nil",
"config_param",
":time_as_epoch",
",",
":bool",
",",
"default",
":",
"false",
"config_param",
":include_tag_key",
",",
":bool",
",",
"default",
":",
"false",
"config_param",
":tag_key",
",",
":string",
",",
"default",
":",
"'tag'",
"config_param",
":localtime",
",",
":bool",
",",
"default",
":",
"true",
"config_param",
":timezone",
",",
":string",
",",
"default",
":",
"nil",
"}",
"end",
"def",
"configure",
"(",
"conf",
")",
"super",
"if",
"conf",
"[",
"'utc'",
"]",
"@localtime",
"=",
"false",
"end",
"@timef",
"=",
"Fluent",
"::",
"TimeFormatter",
".",
"new",
"(",
"@time_format",
",",
"@localtime",
",",
"@timezone",
")",
"if",
"@time_as_epoch",
"&&",
"!",
"@include_time_key",
"log",
".",
"warn",
"\"time_as_epoch will be ignored because include_time_key is false\"",
"end",
"end",
"def",
"filter_record",
"(",
"tag",
",",
"time",
",",
"record",
")",
"if",
"@include_tag_key",
"record",
"[",
"@tag_key",
"]",
"=",
"tag",
"end",
"if",
"@include_time_key",
"if",
"@time_as_epoch",
"record",
"[",
"@time_key",
"]",
"=",
"time",
".",
"to_i",
"else",
"record",
"[",
"@time_key",
"]",
"=",
"@timef",
".",
"format",
"(",
"time",
")",
"end",
"end",
"end",
"end",
"end",
"end"
] |
Fluentd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
|
[
"Fluentd",
"Licensed",
"under",
"the",
"Apache",
"License",
"Version",
"2",
".",
"0",
"(",
"the",
"\"",
"License",
"\"",
")",
";",
"you",
"may",
"not",
"use",
"this",
"file",
"except",
"in",
"compliance",
"with",
"the",
"License",
"."
] |
[] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 16
| 316
| 134
|
eb38ae9a4d5220490dd7a94f2906faa47a98a9f4
|
blackberry/bb-spark-cordova
|
BBMEnterprise/www/classes/Messages.js
|
[
"Apache-2.0"
] |
JavaScript
|
IdentitiesGet
|
/**
* class IdentitiesGet
* @classdesc
* Requests that the given list of identities, either application user ids or
* Spark Communications regIds, be resolved to find the associated identity
* information, and returned via an 'identities' message.
*
* Identities for which identity information cannot be found are omitted from
* the results.
*
* Overlapping 'identitiesGet' requests are issued in parallel. Issuing too
* many parallel requests at once can exceed system limits and cause those
* requests to fail.
*/
|
class IdentitiesGet
@classdesc
Requests that the given list of identities, either application user ids or
Spark Communications regIds, be resolved to find the associated identity
information, and returned via an 'identities' message.
Identities for which identity information cannot be found are omitted from
the results.
Overlapping 'identitiesGet' requests are issued in parallel. Issuing too
many parallel requests at once can exceed system limits and cause those
requests to fail.
|
[
"class",
"IdentitiesGet",
"@classdesc",
"Requests",
"that",
"the",
"given",
"list",
"of",
"identities",
"either",
"application",
"user",
"ids",
"or",
"Spark",
"Communications",
"regIds",
"be",
"resolved",
"to",
"find",
"the",
"associated",
"identity",
"information",
"and",
"returned",
"via",
"an",
"'",
"identities",
"'",
"message",
".",
"Identities",
"for",
"which",
"identity",
"information",
"cannot",
"be",
"found",
"are",
"omitted",
"from",
"the",
"results",
".",
"Overlapping",
"'",
"identitiesGet",
"'",
"requests",
"are",
"issued",
"in",
"parallel",
".",
"Issuing",
"too",
"many",
"parallel",
"requests",
"at",
"once",
"can",
"exceed",
"system",
"limits",
"and",
"cause",
"those",
"requests",
"to",
"fail",
"."
] |
class IdentitiesGet extends Message {
constructor(parameters) {
if(parameters.appUserIds !== undefined) {
if(typeof parameters.appUserIds !== "object"
|| !Array.isArray(parameters.appUserIds)) {
throw new TypeError('parameters.appUserIds must be of type array');
}
}
if(parameters.regIds !== undefined) {
if(typeof parameters.regIds !== "object"
|| !Array.isArray(parameters.regIds)) {
throw new TypeError('parameters.regIds must be of type array');
}
}
if(typeof parameters.cookie !== "string") {
throw new TypeError('parameters.cookie must be of type string');
}
super(parameters);
this.name = 'identitiesGet';
}
updateList() {
return [
];
}
}
|
[
"class",
"IdentitiesGet",
"extends",
"Message",
"{",
"constructor",
"(",
"parameters",
")",
"{",
"if",
"(",
"parameters",
".",
"appUserIds",
"!==",
"undefined",
")",
"{",
"if",
"(",
"typeof",
"parameters",
".",
"appUserIds",
"!==",
"\"object\"",
"||",
"!",
"Array",
".",
"isArray",
"(",
"parameters",
".",
"appUserIds",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'parameters.appUserIds must be of type array'",
")",
";",
"}",
"}",
"if",
"(",
"parameters",
".",
"regIds",
"!==",
"undefined",
")",
"{",
"if",
"(",
"typeof",
"parameters",
".",
"regIds",
"!==",
"\"object\"",
"||",
"!",
"Array",
".",
"isArray",
"(",
"parameters",
".",
"regIds",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'parameters.regIds must be of type array'",
")",
";",
"}",
"}",
"if",
"(",
"typeof",
"parameters",
".",
"cookie",
"!==",
"\"string\"",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'parameters.cookie must be of type string'",
")",
";",
"}",
"super",
"(",
"parameters",
")",
";",
"this",
".",
"name",
"=",
"'identitiesGet'",
";",
"}",
"updateList",
"(",
")",
"{",
"return",
"[",
"]",
";",
"}",
"}"
] |
class IdentitiesGet
@classdesc
Requests that the given list of identities, either application user ids or
Spark Communications regIds, be resolved to find the associated identity
information, and returned via an 'identities' message.
|
[
"class",
"IdentitiesGet",
"@classdesc",
"Requests",
"that",
"the",
"given",
"list",
"of",
"identities",
"either",
"application",
"user",
"ids",
"or",
"Spark",
"Communications",
"regIds",
"be",
"resolved",
"to",
"find",
"the",
"associated",
"identity",
"information",
"and",
"returned",
"via",
"an",
"'",
"identities",
"'",
"message",
"."
] |
[] |
[
{
"param": "Message",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "Message",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 14
| 163
| 115
|
67df3c3804802e9e78662eb299f3a86465657a1a
|
SymphonyOSF/oss-allegro
|
allegro-api/src/main/java/com/symphony/oss/allegro/api/AllegroMultiTenantApi.java
|
[
"Apache-2.0"
] |
Java
|
AbstractBuilder
|
/**
* The builder implementation.
*
* This is implemented as an abstract class to allow for sub-classing in future.
*
* Any sub-class of AllegroApi would need to implement its own Abstract sub-class of this class
* and then a concrete Builder class which is itself a sub-class of that.
*
* @author Bruce Skingle
*
* @param <T> The type of the concrete Builder
* @param <B> The type of the built class, some subclass of AllegroApi
*/
|
The builder implementation.
This is implemented as an abstract class to allow for sub-classing in future.
Any sub-class of AllegroApi would need to implement its own Abstract sub-class of this class
and then a concrete Builder class which is itself a sub-class of that.
@author Bruce Skingle
@param The type of the concrete Builder
@param The type of the built class, some subclass of AllegroApi
|
[
"The",
"builder",
"implementation",
".",
"This",
"is",
"implemented",
"as",
"an",
"abstract",
"class",
"to",
"allow",
"for",
"sub",
"-",
"classing",
"in",
"future",
".",
"Any",
"sub",
"-",
"class",
"of",
"AllegroApi",
"would",
"need",
"to",
"implement",
"its",
"own",
"Abstract",
"sub",
"-",
"class",
"of",
"this",
"class",
"and",
"then",
"a",
"concrete",
"Builder",
"class",
"which",
"is",
"itself",
"a",
"sub",
"-",
"class",
"of",
"that",
".",
"@author",
"Bruce",
"Skingle",
"@param",
"The",
"type",
"of",
"the",
"concrete",
"Builder",
"@param",
"The",
"type",
"of",
"the",
"built",
"class",
"some",
"subclass",
"of",
"AllegroApi"
] |
protected static abstract class AbstractBuilder<T extends AbstractBuilder<T,B>, B extends IAllegroMultiTenantApi>
extends AllegroBaseApi.AbstractBuilder<IAllegroMultiTenantConfiguration,
AllegroMultiTenantConfiguration.AbstractAllegroMultiTenantConfigurationBuilder<?, IAllegroMultiTenantConfiguration>, T, B>
{
private static final ObjectMapper MAPPER = new ObjectMapper();
protected PodAndUserId configuredUserId_;
protected String keyId_;
public AbstractBuilder(Class<T> type)
{
super(type, new AllegroMultiTenantConfiguration.Builder());
}
@Override
public T withConfiguration(Reader reader)
{
withConfiguration(allegroModelRegistry_.parseOne(reader, AllegroMultiTenantConfiguration.TYPE_ID, IAllegroMultiTenantConfiguration.class));
return self();
}
@Deprecated
public T withUserId(PodAndUserId userId)
{
configBuilder_.withUserId(userId);
builderSet_ = true;
return self();
}
@Deprecated
public T withUserId(long userId)
{
configBuilder_.withUserId(userId);
builderSet_ = true;
return self();
}
@Deprecated
public T withKeyId(String keyId)
{
configBuilder_.withKeyId(keyId);
builderSet_ = true;
return self();
}
@Deprecated
public T withPrincipalCredentialFile(String principalCredentialFile)
{
if(principalCredentialFile == null)
throw new IllegalArgumentException("Credential is required");
File file = new File(principalCredentialFile);
if(!file.canRead())
throw new IllegalArgumentException("Credential file \"" + file.getAbsolutePath() + "\" is unreadable");
try
{
ModelRegistry modelRegistry = new ModelRegistry()
.withFactories(ObjectModel.FACTORIES)
.withFactories(CoreModel.FACTORIES)
.withFactories(AuthcModel.FACTORIES)
;
IImmutableJsonDomNode json = JacksonAdaptor.adapt(MAPPER.readTree(file)).immutify();
PrincipalCredential principalCredential = new PrincipalCredential((ImmutableJsonObject)json, modelRegistry);
withRsaCredential(principalCredential.getPrivateKey());
withKeyId(principalCredential.getKeyId().toString());
withUserId(principalCredential.getUserId());
}
catch (IOException e)
{
throw new IllegalArgumentException("Unable to read credential file \"" + file.getAbsolutePath() + "\".", e);
}
return self();
}
@Override
protected void validate(FaultAccumulator faultAccumulator)
{
super.validate(faultAccumulator);
if(config_.getPrincipalCredential() != null) {
IPrincipalCredential principalCredential = config_.getPrincipalCredential();
rsaCredential_ = CipherSuiteUtils.privateKeyFromPem(principalCredential.getEncodedPrivateKey());
keyId_ = principalCredential.getKeyId().toString();
configuredUserId_ = principalCredential.getUserId();
}
else if(config_.getPrincipalCredentialFile() != null)
{
File file = new File(config_.getPrincipalCredentialFile());
if(!file.canRead())
throw new IllegalArgumentException("PrincipalCredential file \"" + file.getAbsolutePath() + "\" is unreadable");
try(Reader reader = new FileReader(file))
{
IPrincipalCredential principalCredential = allegroModelRegistry_.parseOne(reader, PrincipalCredential.TYPE_ID, IPrincipalCredential.class);
rsaCredential_ = CipherSuiteUtils.privateKeyFromPem(principalCredential.getEncodedPrivateKey());
keyId_ = principalCredential.getKeyId().toString();
configuredUserId_ = principalCredential.getUserId();
}
catch (IOException e)
{
throw new IllegalArgumentException("Unable to read credential file \"" + file.getAbsolutePath() + "\".", e);
}
}
else
{
keyId_ = config_.getKeyId();
configuredUserId_ = config_.getUserId();
}
if(rsaCredential_ == null)
{
faultAccumulator.error("rsaCredential is required");
}
faultAccumulator.checkNotNull(configuredUserId_, "User ID");
}
}
|
[
"protected",
"static",
"abstract",
"class",
"AbstractBuilder",
"<",
"T",
"extends",
"AbstractBuilder",
"<",
"T",
",",
"B",
">",
",",
"B",
"extends",
"IAllegroMultiTenantApi",
">",
"extends",
"AllegroBaseApi",
".",
"AbstractBuilder",
"<",
"IAllegroMultiTenantConfiguration",
",",
"AllegroMultiTenantConfiguration",
".",
"AbstractAllegroMultiTenantConfigurationBuilder",
"<",
"?",
",",
"IAllegroMultiTenantConfiguration",
">",
",",
"T",
",",
"B",
">",
"{",
"private",
"static",
"final",
"ObjectMapper",
"MAPPER",
"=",
"new",
"ObjectMapper",
"(",
")",
";",
"protected",
"PodAndUserId",
"configuredUserId_",
";",
"protected",
"String",
"keyId_",
";",
"public",
"AbstractBuilder",
"(",
"Class",
"<",
"T",
">",
"type",
")",
"{",
"super",
"(",
"type",
",",
"new",
"AllegroMultiTenantConfiguration",
".",
"Builder",
"(",
")",
")",
";",
"}",
"@",
"Override",
"public",
"T",
"withConfiguration",
"(",
"Reader",
"reader",
")",
"{",
"withConfiguration",
"(",
"allegroModelRegistry_",
".",
"parseOne",
"(",
"reader",
",",
"AllegroMultiTenantConfiguration",
".",
"TYPE_ID",
",",
"IAllegroMultiTenantConfiguration",
".",
"class",
")",
")",
";",
"return",
"self",
"(",
")",
";",
"}",
"@",
"Deprecated",
"public",
"T",
"withUserId",
"(",
"PodAndUserId",
"userId",
")",
"{",
"configBuilder_",
".",
"withUserId",
"(",
"userId",
")",
";",
"builderSet_",
"=",
"true",
";",
"return",
"self",
"(",
")",
";",
"}",
"@",
"Deprecated",
"public",
"T",
"withUserId",
"(",
"long",
"userId",
")",
"{",
"configBuilder_",
".",
"withUserId",
"(",
"userId",
")",
";",
"builderSet_",
"=",
"true",
";",
"return",
"self",
"(",
")",
";",
"}",
"@",
"Deprecated",
"public",
"T",
"withKeyId",
"(",
"String",
"keyId",
")",
"{",
"configBuilder_",
".",
"withKeyId",
"(",
"keyId",
")",
";",
"builderSet_",
"=",
"true",
";",
"return",
"self",
"(",
")",
";",
"}",
"@",
"Deprecated",
"public",
"T",
"withPrincipalCredentialFile",
"(",
"String",
"principalCredentialFile",
")",
"{",
"if",
"(",
"principalCredentialFile",
"==",
"null",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"",
"Credential is required",
"\"",
")",
";",
"File",
"file",
"=",
"new",
"File",
"(",
"principalCredentialFile",
")",
";",
"if",
"(",
"!",
"file",
".",
"canRead",
"(",
")",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"",
"Credential file ",
"\\\"",
"\"",
"+",
"file",
".",
"getAbsolutePath",
"(",
")",
"+",
"\"",
"\\\"",
" is unreadable",
"\"",
")",
";",
"try",
"{",
"ModelRegistry",
"modelRegistry",
"=",
"new",
"ModelRegistry",
"(",
")",
".",
"withFactories",
"(",
"ObjectModel",
".",
"FACTORIES",
")",
".",
"withFactories",
"(",
"CoreModel",
".",
"FACTORIES",
")",
".",
"withFactories",
"(",
"AuthcModel",
".",
"FACTORIES",
")",
";",
"IImmutableJsonDomNode",
"json",
"=",
"JacksonAdaptor",
".",
"adapt",
"(",
"MAPPER",
".",
"readTree",
"(",
"file",
")",
")",
".",
"immutify",
"(",
")",
";",
"PrincipalCredential",
"principalCredential",
"=",
"new",
"PrincipalCredential",
"(",
"(",
"ImmutableJsonObject",
")",
"json",
",",
"modelRegistry",
")",
";",
"withRsaCredential",
"(",
"principalCredential",
".",
"getPrivateKey",
"(",
")",
")",
";",
"withKeyId",
"(",
"principalCredential",
".",
"getKeyId",
"(",
")",
".",
"toString",
"(",
")",
")",
";",
"withUserId",
"(",
"principalCredential",
".",
"getUserId",
"(",
")",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"",
"Unable to read credential file ",
"\\\"",
"\"",
"+",
"file",
".",
"getAbsolutePath",
"(",
")",
"+",
"\"",
"\\\"",
".",
"\"",
",",
"e",
")",
";",
"}",
"return",
"self",
"(",
")",
";",
"}",
"@",
"Override",
"protected",
"void",
"validate",
"(",
"FaultAccumulator",
"faultAccumulator",
")",
"{",
"super",
".",
"validate",
"(",
"faultAccumulator",
")",
";",
"if",
"(",
"config_",
".",
"getPrincipalCredential",
"(",
")",
"!=",
"null",
")",
"{",
"IPrincipalCredential",
"principalCredential",
"=",
"config_",
".",
"getPrincipalCredential",
"(",
")",
";",
"rsaCredential_",
"=",
"CipherSuiteUtils",
".",
"privateKeyFromPem",
"(",
"principalCredential",
".",
"getEncodedPrivateKey",
"(",
")",
")",
";",
"keyId_",
"=",
"principalCredential",
".",
"getKeyId",
"(",
")",
".",
"toString",
"(",
")",
";",
"configuredUserId_",
"=",
"principalCredential",
".",
"getUserId",
"(",
")",
";",
"}",
"else",
"if",
"(",
"config_",
".",
"getPrincipalCredentialFile",
"(",
")",
"!=",
"null",
")",
"{",
"File",
"file",
"=",
"new",
"File",
"(",
"config_",
".",
"getPrincipalCredentialFile",
"(",
")",
")",
";",
"if",
"(",
"!",
"file",
".",
"canRead",
"(",
")",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"",
"PrincipalCredential file ",
"\\\"",
"\"",
"+",
"file",
".",
"getAbsolutePath",
"(",
")",
"+",
"\"",
"\\\"",
" is unreadable",
"\"",
")",
";",
"try",
"(",
"Reader",
"reader",
"=",
"new",
"FileReader",
"(",
"file",
")",
")",
"{",
"IPrincipalCredential",
"principalCredential",
"=",
"allegroModelRegistry_",
".",
"parseOne",
"(",
"reader",
",",
"PrincipalCredential",
".",
"TYPE_ID",
",",
"IPrincipalCredential",
".",
"class",
")",
";",
"rsaCredential_",
"=",
"CipherSuiteUtils",
".",
"privateKeyFromPem",
"(",
"principalCredential",
".",
"getEncodedPrivateKey",
"(",
")",
")",
";",
"keyId_",
"=",
"principalCredential",
".",
"getKeyId",
"(",
")",
".",
"toString",
"(",
")",
";",
"configuredUserId_",
"=",
"principalCredential",
".",
"getUserId",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"",
"Unable to read credential file ",
"\\\"",
"\"",
"+",
"file",
".",
"getAbsolutePath",
"(",
")",
"+",
"\"",
"\\\"",
".",
"\"",
",",
"e",
")",
";",
"}",
"}",
"else",
"{",
"keyId_",
"=",
"config_",
".",
"getKeyId",
"(",
")",
";",
"configuredUserId_",
"=",
"config_",
".",
"getUserId",
"(",
")",
";",
"}",
"if",
"(",
"rsaCredential_",
"==",
"null",
")",
"{",
"faultAccumulator",
".",
"error",
"(",
"\"",
"rsaCredential is required",
"\"",
")",
";",
"}",
"faultAccumulator",
".",
"checkNotNull",
"(",
"configuredUserId_",
",",
"\"",
"User ID",
"\"",
")",
";",
"}",
"}"
] |
The builder implementation.
|
[
"The",
"builder",
"implementation",
"."
] |
[] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 18
| 878
| 120
|
b51a6c909768faaad75fac98fc502e453fe3b04b
|
ctingwai/markdownotebook
|
src/NotebookMenu.js
|
[
"MIT"
] |
JavaScript
|
NotebookMenu
|
/**
* Component to create a notebook menu
*
* @props props.onNotebookCreate Function called to create a new notebook
* @props props.onNotebookEdit Function called to edit a notebook
* arg1: current notebook name,
* arg2: new notebook name
* @props props.onNotebookDelete Function called to delete an entire notebook,
* arg1: notebook
* @props props.items Array of notes in the following format:
* [
* {
* name: <name of the notebook>,
* notes: [
* {
* title: <title of the note>,
* created: <create date of the note>,
* text: <note's contents>
* }
* ]
* }
* ]
* @props props.edit Function call to edit a note
* @props props.deleteNote Function called to delete a note
*
* @props state.notebookName The name of the new notebook
* @props state.notebooks Array of notes same format as props.items
* @props state.errorTitle Store the title of the error message
* @props state.errorMessage Store the error message
* @props state.createNotebook Store the current state of notebook creation
*
* @function refresh Method called to refresh the notebooks when it is edited
* */
|
@function refresh Method called to refresh the notebooks when it is edited
|
[
"@function",
"refresh",
"Method",
"called",
"to",
"refresh",
"the",
"notebooks",
"when",
"it",
"is",
"edited"
] |
class NotebookMenu extends Component {
constructor() {
super();
this.state = {
createNotebook: '',
notebookName: '',
notebooks: [],
errorTitle: '',
errorMessage: '',
confirmation: {
show: false,
header: '',
icon: '',
description: '',
onConfirm: null,
onCancel: null
},
edit: {
original: null,
newName: null,
show: false,
header: null,
inputs: []
}
};
}
componentWillMount() {
this.setState({notebooks: this.props.items});
}
validateNotebook() {
let exists = this.state.notebooks.find((item) => {
return item.name.toLowerCase() === this.state.notebookName.toLowerCase()
});
if(exists) {
this.setState({
errorTitle: 'Notebook Exists',
errorMessage: 'The supplied notebook name already existed, please use another name.'
});
return false;
}
if(this.state.notebookName == '') {
this.setState({
errorTitle: 'Invalid Name',
errorMessage: 'Notebook name cannot be empty'
});
return false;
}
if(!/^[a-zA-Z0-9_ ]+$/g.test(this.state.notebookName)) {
this.setState({
errorTitle: 'Invalid Name',
errorMessage: 'Only alphabet, numbers, underscore, and space is allowed'
});
return false;
}
return true;
}
createNotebook(e) {
this.setState({
errorTitle: '',
errorMessage: '',
createNotebook: 'creating'
});
if(this.validateNotebook()) {
if(this.props.onNotebookCreate(this.state.notebookName)) {
let notebooks = this.state.notebooks;
//notebooks.push({name: this.state.notebookName, notes: []});
this.setState({notebooks: notebooks, notebookName: '', createNotebook: 'created'});
}
} else {
this.setState({createNotebook: 'failed'});
}
}
handleKeyUp(e) {
if(this.state.createNotebook !== '') {
this.setState({createNotebook: ''});
}
this.setState({notebookName: e.target.value});
}
refresh(newNotebooks) {
this.setState({notebooks: newNotebooks});
}
handleNotebookDelete() {
let notebook = this.state.confirmation.id;
this.setState({notebooks: this.props.onNotebookDelete(notebook)});
this.clearConfirmation();
}
handleNotebookEdit() {
let original = this.state.edit.original,
newName = this.state.edit.newName;
this.setState({notebooks: this.props.onNotebookEdit(original, newName)});
this.clearEditForm();
}
clearConfirmation() {
this.setState({
confirmation: {
id: null,
show: false,
header: '',
icon: '',
description: '',
onConfirm: null,
onCancel: null
}
});
}
confirmNotebookDelete(notebook) {
let desc = 'All notes contained within the notebook, ' + notebook + ', will be removed. ' +
'Are your sure you want to delete this notebook?';
this.setState({
confirmation: {
id: notebook,
header: 'Are you sure you want to remove ' + notebook + '?',
show: true,
icon: 'icon warning sign',
description: desc,
onConfirm: this.handleNotebookDelete.bind(this),
onCancel: this.clearConfirmation.bind(this)
}
});
}
updateNotebookFormState(e) {
console.log(e.target.value);
this.setState({
edit: {
show: this.state.edit.show,
header: this.state.edit.header,
original: this.state.edit.original,
newName: e.target.value,
inputs: this.state.edit.inputs
}
});
}
showEditNotebookForm(notebook) {
this.setState({
edit: {
show: true,
header: 'Edit Notebook',
original: notebook,
newName: notebook,
inputs: [
<div className='ui form' key='modal-form-input'>
<div className='field'>
<label>New Notebook Name</label>
<input type='text' defaultValue={notebook} onChange={this.updateNotebookFormState.bind(this)} />
</div>
</div>
]
}
});
}
clearEditForm() {
this.setState({
edit: {
original: null,
newName: null,
show: false,
header: null,
inputs: []
}
});
}
render() {
let errorMsg = (
<div className="ui error message">
<div className="header">{this.state.errorTitle}</div>
<p>{this.state.errorMessage}</p>
</div>
);
let createNbBtn = 'ui labeled icon button primary';
let createNbIcon = 'icon book';
let createNbText = 'Create Notebook';
if(this.state.createNotebook == 'creating') {
createNbBtn = 'ui labeled icon button secondary loading';
} else if(this.state.createNotebook == 'created') {
createNbBtn = 'ui labeled icon button secondary positive labeled icon';
createNbIcon = 'icon checkmark';
createNbText = 'Notebook Created';
} else if(this.state.createNotebook == 'failed') {
createNbBtn = 'ui labeled icon button secondary negative labeled icon';
createNbIcon = 'icon remove';
createNbText = 'Create Failed';
}
return (
<div className='notebook-menu'>
<div className='ui stacked header'>Notebooks</div>
<NoteList notebooks={this.state.notebooks} edit={this.props.edit}
deleteNotebook={this.confirmNotebookDelete.bind(this)}
editNotebook={this.showEditNotebookForm.bind(this)}
deleteNote={this.props.deleteNote} />
<div className="ui horizontal divider"></div>
{this.state.errorTitle ? errorMsg : null}
<div className='ui action input' style={{width: '100%'}}>
<input type='text' placeholder='Enter notebook name'
value={this.state.notebookName}
onKeyUp={this.handleKeyUp.bind(this)}
onChange={this.handleKeyUp.bind(this)} />
<a className={createNbBtn}
onClick={this.createNotebook.bind(this)}>
<i className={createNbIcon} /> {createNbText}</a>
</div>
<ConfirmationModal header={this.state.confirmation.header}
show={this.state.confirmation.show}
hidden={this.clearConfirmation.bind(this)}
icon={this.state.confirmation.icon}
description={this.state.confirmation.description}
onConfirm={this.state.confirmation.onConfirm}
onCancel={this.state.confirmation.onCancel} />
<ModalForm header={this.state.edit.header}
show={this.state.edit.show}
hidden={this.clearEditForm.bind(this)}
inputs={this.state.edit.inputs}
submit={this.handleNotebookEdit.bind(this)} />
</div>
);
}
}
|
[
"class",
"NotebookMenu",
"extends",
"Component",
"{",
"constructor",
"(",
")",
"{",
"super",
"(",
")",
";",
"this",
".",
"state",
"=",
"{",
"createNotebook",
":",
"''",
",",
"notebookName",
":",
"''",
",",
"notebooks",
":",
"[",
"]",
",",
"errorTitle",
":",
"''",
",",
"errorMessage",
":",
"''",
",",
"confirmation",
":",
"{",
"show",
":",
"false",
",",
"header",
":",
"''",
",",
"icon",
":",
"''",
",",
"description",
":",
"''",
",",
"onConfirm",
":",
"null",
",",
"onCancel",
":",
"null",
"}",
",",
"edit",
":",
"{",
"original",
":",
"null",
",",
"newName",
":",
"null",
",",
"show",
":",
"false",
",",
"header",
":",
"null",
",",
"inputs",
":",
"[",
"]",
"}",
"}",
";",
"}",
"componentWillMount",
"(",
")",
"{",
"this",
".",
"setState",
"(",
"{",
"notebooks",
":",
"this",
".",
"props",
".",
"items",
"}",
")",
";",
"}",
"validateNotebook",
"(",
")",
"{",
"let",
"exists",
"=",
"this",
".",
"state",
".",
"notebooks",
".",
"find",
"(",
"(",
"item",
")",
"=>",
"{",
"return",
"item",
".",
"name",
".",
"toLowerCase",
"(",
")",
"===",
"this",
".",
"state",
".",
"notebookName",
".",
"toLowerCase",
"(",
")",
"}",
")",
";",
"if",
"(",
"exists",
")",
"{",
"this",
".",
"setState",
"(",
"{",
"errorTitle",
":",
"'Notebook Exists'",
",",
"errorMessage",
":",
"'The supplied notebook name already existed, please use another name.'",
"}",
")",
";",
"return",
"false",
";",
"}",
"if",
"(",
"this",
".",
"state",
".",
"notebookName",
"==",
"''",
")",
"{",
"this",
".",
"setState",
"(",
"{",
"errorTitle",
":",
"'Invalid Name'",
",",
"errorMessage",
":",
"'Notebook name cannot be empty'",
"}",
")",
";",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"/",
"^[a-zA-Z0-9_ ]+$",
"/",
"g",
".",
"test",
"(",
"this",
".",
"state",
".",
"notebookName",
")",
")",
"{",
"this",
".",
"setState",
"(",
"{",
"errorTitle",
":",
"'Invalid Name'",
",",
"errorMessage",
":",
"'Only alphabet, numbers, underscore, and space is allowed'",
"}",
")",
";",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}",
"createNotebook",
"(",
"e",
")",
"{",
"this",
".",
"setState",
"(",
"{",
"errorTitle",
":",
"''",
",",
"errorMessage",
":",
"''",
",",
"createNotebook",
":",
"'creating'",
"}",
")",
";",
"if",
"(",
"this",
".",
"validateNotebook",
"(",
")",
")",
"{",
"if",
"(",
"this",
".",
"props",
".",
"onNotebookCreate",
"(",
"this",
".",
"state",
".",
"notebookName",
")",
")",
"{",
"let",
"notebooks",
"=",
"this",
".",
"state",
".",
"notebooks",
";",
"this",
".",
"setState",
"(",
"{",
"notebooks",
":",
"notebooks",
",",
"notebookName",
":",
"''",
",",
"createNotebook",
":",
"'created'",
"}",
")",
";",
"}",
"}",
"else",
"{",
"this",
".",
"setState",
"(",
"{",
"createNotebook",
":",
"'failed'",
"}",
")",
";",
"}",
"}",
"handleKeyUp",
"(",
"e",
")",
"{",
"if",
"(",
"this",
".",
"state",
".",
"createNotebook",
"!==",
"''",
")",
"{",
"this",
".",
"setState",
"(",
"{",
"createNotebook",
":",
"''",
"}",
")",
";",
"}",
"this",
".",
"setState",
"(",
"{",
"notebookName",
":",
"e",
".",
"target",
".",
"value",
"}",
")",
";",
"}",
"refresh",
"(",
"newNotebooks",
")",
"{",
"this",
".",
"setState",
"(",
"{",
"notebooks",
":",
"newNotebooks",
"}",
")",
";",
"}",
"handleNotebookDelete",
"(",
")",
"{",
"let",
"notebook",
"=",
"this",
".",
"state",
".",
"confirmation",
".",
"id",
";",
"this",
".",
"setState",
"(",
"{",
"notebooks",
":",
"this",
".",
"props",
".",
"onNotebookDelete",
"(",
"notebook",
")",
"}",
")",
";",
"this",
".",
"clearConfirmation",
"(",
")",
";",
"}",
"handleNotebookEdit",
"(",
")",
"{",
"let",
"original",
"=",
"this",
".",
"state",
".",
"edit",
".",
"original",
",",
"newName",
"=",
"this",
".",
"state",
".",
"edit",
".",
"newName",
";",
"this",
".",
"setState",
"(",
"{",
"notebooks",
":",
"this",
".",
"props",
".",
"onNotebookEdit",
"(",
"original",
",",
"newName",
")",
"}",
")",
";",
"this",
".",
"clearEditForm",
"(",
")",
";",
"}",
"clearConfirmation",
"(",
")",
"{",
"this",
".",
"setState",
"(",
"{",
"confirmation",
":",
"{",
"id",
":",
"null",
",",
"show",
":",
"false",
",",
"header",
":",
"''",
",",
"icon",
":",
"''",
",",
"description",
":",
"''",
",",
"onConfirm",
":",
"null",
",",
"onCancel",
":",
"null",
"}",
"}",
")",
";",
"}",
"confirmNotebookDelete",
"(",
"notebook",
")",
"{",
"let",
"desc",
"=",
"'All notes contained within the notebook, '",
"+",
"notebook",
"+",
"', will be removed. '",
"+",
"'Are your sure you want to delete this notebook?'",
";",
"this",
".",
"setState",
"(",
"{",
"confirmation",
":",
"{",
"id",
":",
"notebook",
",",
"header",
":",
"'Are you sure you want to remove '",
"+",
"notebook",
"+",
"'?'",
",",
"show",
":",
"true",
",",
"icon",
":",
"'icon warning sign'",
",",
"description",
":",
"desc",
",",
"onConfirm",
":",
"this",
".",
"handleNotebookDelete",
".",
"bind",
"(",
"this",
")",
",",
"onCancel",
":",
"this",
".",
"clearConfirmation",
".",
"bind",
"(",
"this",
")",
"}",
"}",
")",
";",
"}",
"updateNotebookFormState",
"(",
"e",
")",
"{",
"console",
".",
"log",
"(",
"e",
".",
"target",
".",
"value",
")",
";",
"this",
".",
"setState",
"(",
"{",
"edit",
":",
"{",
"show",
":",
"this",
".",
"state",
".",
"edit",
".",
"show",
",",
"header",
":",
"this",
".",
"state",
".",
"edit",
".",
"header",
",",
"original",
":",
"this",
".",
"state",
".",
"edit",
".",
"original",
",",
"newName",
":",
"e",
".",
"target",
".",
"value",
",",
"inputs",
":",
"this",
".",
"state",
".",
"edit",
".",
"inputs",
"}",
"}",
")",
";",
"}",
"showEditNotebookForm",
"(",
"notebook",
")",
"{",
"this",
".",
"setState",
"(",
"{",
"edit",
":",
"{",
"show",
":",
"true",
",",
"header",
":",
"'Edit Notebook'",
",",
"original",
":",
"notebook",
",",
"newName",
":",
"notebook",
",",
"inputs",
":",
"[",
"<",
"div",
"className",
"=",
"'ui form'",
"key",
"=",
"'modal-form-input'",
">",
"\n ",
"<",
"div",
"className",
"=",
"'field'",
">",
"\n ",
"<",
"label",
">",
"New Notebook Name",
"<",
"/",
"label",
">",
"\n ",
"<",
"input",
"type",
"=",
"'text'",
"defaultValue",
"=",
"{",
"notebook",
"}",
"onChange",
"=",
"{",
"this",
".",
"updateNotebookFormState",
".",
"bind",
"(",
"this",
")",
"}",
"/",
">",
"\n ",
"<",
"/",
"div",
">",
"\n ",
"<",
"/",
"div",
">",
"]",
"}",
"}",
")",
";",
"}",
"clearEditForm",
"(",
")",
"{",
"this",
".",
"setState",
"(",
"{",
"edit",
":",
"{",
"original",
":",
"null",
",",
"newName",
":",
"null",
",",
"show",
":",
"false",
",",
"header",
":",
"null",
",",
"inputs",
":",
"[",
"]",
"}",
"}",
")",
";",
"}",
"render",
"(",
")",
"{",
"let",
"errorMsg",
"=",
"(",
"<",
"div",
"className",
"=",
"\"ui error message\"",
">",
"\n ",
"<",
"div",
"className",
"=",
"\"header\"",
">",
"{",
"this",
".",
"state",
".",
"errorTitle",
"}",
"<",
"/",
"div",
">",
"\n ",
"<",
"p",
">",
"{",
"this",
".",
"state",
".",
"errorMessage",
"}",
"<",
"/",
"p",
">",
"\n ",
"<",
"/",
"div",
">",
")",
";",
"let",
"createNbBtn",
"=",
"'ui labeled icon button primary'",
";",
"let",
"createNbIcon",
"=",
"'icon book'",
";",
"let",
"createNbText",
"=",
"'Create Notebook'",
";",
"if",
"(",
"this",
".",
"state",
".",
"createNotebook",
"==",
"'creating'",
")",
"{",
"createNbBtn",
"=",
"'ui labeled icon button secondary loading'",
";",
"}",
"else",
"if",
"(",
"this",
".",
"state",
".",
"createNotebook",
"==",
"'created'",
")",
"{",
"createNbBtn",
"=",
"'ui labeled icon button secondary positive labeled icon'",
";",
"createNbIcon",
"=",
"'icon checkmark'",
";",
"createNbText",
"=",
"'Notebook Created'",
";",
"}",
"else",
"if",
"(",
"this",
".",
"state",
".",
"createNotebook",
"==",
"'failed'",
")",
"{",
"createNbBtn",
"=",
"'ui labeled icon button secondary negative labeled icon'",
";",
"createNbIcon",
"=",
"'icon remove'",
";",
"createNbText",
"=",
"'Create Failed'",
";",
"}",
"return",
"(",
"<",
"div",
"className",
"=",
"'notebook-menu'",
">",
"\n ",
"<",
"div",
"className",
"=",
"'ui stacked header'",
">",
"Notebooks",
"<",
"/",
"div",
">",
"\n ",
"<",
"NoteList",
"notebooks",
"=",
"{",
"this",
".",
"state",
".",
"notebooks",
"}",
"edit",
"=",
"{",
"this",
".",
"props",
".",
"edit",
"}",
"deleteNotebook",
"=",
"{",
"this",
".",
"confirmNotebookDelete",
".",
"bind",
"(",
"this",
")",
"}",
"editNotebook",
"=",
"{",
"this",
".",
"showEditNotebookForm",
".",
"bind",
"(",
"this",
")",
"}",
"deleteNote",
"=",
"{",
"this",
".",
"props",
".",
"deleteNote",
"}",
"/",
">",
"\n ",
"<",
"div",
"className",
"=",
"\"ui horizontal divider\"",
">",
"<",
"/",
"div",
">",
"\n ",
"{",
"this",
".",
"state",
".",
"errorTitle",
"?",
"errorMsg",
":",
"null",
"}",
"\n ",
"<",
"div",
"className",
"=",
"'ui action input'",
"style",
"=",
"{",
"{",
"width",
":",
"'100%'",
"}",
"}",
">",
"\n ",
"<",
"input",
"type",
"=",
"'text'",
"placeholder",
"=",
"'Enter notebook name'",
"value",
"=",
"{",
"this",
".",
"state",
".",
"notebookName",
"}",
"onKeyUp",
"=",
"{",
"this",
".",
"handleKeyUp",
".",
"bind",
"(",
"this",
")",
"}",
"onChange",
"=",
"{",
"this",
".",
"handleKeyUp",
".",
"bind",
"(",
"this",
")",
"}",
"/",
">",
"\n ",
"<",
"a",
"className",
"=",
"{",
"createNbBtn",
"}",
"onClick",
"=",
"{",
"this",
".",
"createNotebook",
".",
"bind",
"(",
"this",
")",
"}",
">",
"\n ",
"<",
"i",
"className",
"=",
"{",
"createNbIcon",
"}",
"/",
">",
" ",
"{",
"createNbText",
"}",
"<",
"/",
"a",
">",
"\n ",
"<",
"/",
"div",
">",
"\n ",
"<",
"ConfirmationModal",
"header",
"=",
"{",
"this",
".",
"state",
".",
"confirmation",
".",
"header",
"}",
"show",
"=",
"{",
"this",
".",
"state",
".",
"confirmation",
".",
"show",
"}",
"hidden",
"=",
"{",
"this",
".",
"clearConfirmation",
".",
"bind",
"(",
"this",
")",
"}",
"icon",
"=",
"{",
"this",
".",
"state",
".",
"confirmation",
".",
"icon",
"}",
"description",
"=",
"{",
"this",
".",
"state",
".",
"confirmation",
".",
"description",
"}",
"onConfirm",
"=",
"{",
"this",
".",
"state",
".",
"confirmation",
".",
"onConfirm",
"}",
"onCancel",
"=",
"{",
"this",
".",
"state",
".",
"confirmation",
".",
"onCancel",
"}",
"/",
">",
"\n ",
"<",
"ModalForm",
"header",
"=",
"{",
"this",
".",
"state",
".",
"edit",
".",
"header",
"}",
"show",
"=",
"{",
"this",
".",
"state",
".",
"edit",
".",
"show",
"}",
"hidden",
"=",
"{",
"this",
".",
"clearEditForm",
".",
"bind",
"(",
"this",
")",
"}",
"inputs",
"=",
"{",
"this",
".",
"state",
".",
"edit",
".",
"inputs",
"}",
"submit",
"=",
"{",
"this",
".",
"handleNotebookEdit",
".",
"bind",
"(",
"this",
")",
"}",
"/",
">",
"\n ",
"<",
"/",
"div",
">",
")",
";",
"}",
"}"
] |
Component to create a notebook menu
@props props.onNotebookCreate Function called to create a new notebook
@props props.onNotebookEdit Function called to edit a notebook
arg1: current notebook name,
arg2: new notebook name
@props props.onNotebookDelete Function called to delete an entire notebook,
arg1: notebook
@props props.items Array of notes in the following format:
[
{
name: <name of the notebook>,
notes: [
{
title: <title of the note>,
created: <create date of the note>,
text: <note's contents>
}
]
}
]
@props props.edit Function call to edit a note
@props props.deleteNote Function called to delete a note
|
[
"Component",
"to",
"create",
"a",
"notebook",
"menu",
"@props",
"props",
".",
"onNotebookCreate",
"Function",
"called",
"to",
"create",
"a",
"new",
"notebook",
"@props",
"props",
".",
"onNotebookEdit",
"Function",
"called",
"to",
"edit",
"a",
"notebook",
"arg1",
":",
"current",
"notebook",
"name",
"arg2",
":",
"new",
"notebook",
"name",
"@props",
"props",
".",
"onNotebookDelete",
"Function",
"called",
"to",
"delete",
"an",
"entire",
"notebook",
"arg1",
":",
"notebook",
"@props",
"props",
".",
"items",
"Array",
"of",
"notes",
"in",
"the",
"following",
"format",
":",
"[",
"{",
"name",
":",
"<name",
"of",
"the",
"notebook",
">",
"notes",
":",
"[",
"{",
"title",
":",
"<title",
"of",
"the",
"note",
">",
"created",
":",
"<create",
"date",
"of",
"the",
"note",
">",
"text",
":",
"<note",
"'",
"s",
"contents",
">",
"}",
"]",
"}",
"]",
"@props",
"props",
".",
"edit",
"Function",
"call",
"to",
"edit",
"a",
"note",
"@props",
"props",
".",
"deleteNote",
"Function",
"called",
"to",
"delete",
"a",
"note"
] |
[
"//notebooks.push({name: this.state.notebookName, notes: []});"
] |
[
{
"param": "Component",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "Component",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 21
| 1,520
| 271
|
9f038e87b57fad8d5be2af1f55b88608bad009da
|
smittytone/FeatherClock
|
clock-matrix-esp32.py
|
[
"MIT"
] |
Python
|
HT16K33
|
A simple, generic driver for the I2C-connected Holtek HT16K33 controller chip.
This release supports MicroPython and CircuitPython
Version: 3.0.2
Bus: I2C
Author: Tony Smith (@smittytone)
License: MIT
Copyright: 2020
|
A simple, generic driver for the I2C-connected Holtek HT16K33 controller chip.
3.0.2
Bus: I2C
Author: Tony Smith (@smittytone)
License: MIT
Copyright: 2020
|
[
"A",
"simple",
"generic",
"driver",
"for",
"the",
"I2C",
"-",
"connected",
"Holtek",
"HT16K33",
"controller",
"chip",
".",
"3",
".",
"0",
".",
"2",
"Bus",
":",
"I2C",
"Author",
":",
"Tony",
"Smith",
"(",
"@smittytone",
")",
"License",
":",
"MIT",
"Copyright",
":",
"2020"
] |
class HT16K33:
"""
A simple, generic driver for the I2C-connected Holtek HT16K33 controller chip.
This release supports MicroPython and CircuitPython
Version: 3.0.2
Bus: I2C
Author: Tony Smith (@smittytone)
License: MIT
Copyright: 2020
"""
# *********** CONSTANTS **********
HT16K33_GENERIC_DISPLAY_ON = 0x81
HT16K33_GENERIC_DISPLAY_OFF = 0x80
HT16K33_GENERIC_SYSTEM_ON = 0x21
HT16K33_GENERIC_SYSTEM_OFF = 0x20
HT16K33_GENERIC_DISPLAY_ADDRESS = 0x00
HT16K33_GENERIC_CMD_BRIGHTNESS = 0xE0
HT16K33_GENERIC_CMD_BLINK = 0x81
# *********** PRIVATE PROPERTIES **********
i2c = None
address = 0
brightness = 15
flash_rate = 0
# *********** CONSTRUCTOR **********
def __init__(self, i2c, i2c_address):
assert 0x00 <= i2c_address < 0x80, "ERROR - Invalid I2C address in HT16K33()"
self.i2c = i2c
self.address = i2c_address
self.power_on()
# *********** PUBLIC METHODS **********
def set_blink_rate(self, rate=0):
"""
Set the display's flash rate.
Only four values (in Hz) are permitted: 0, 2, 1, and 0,5.
Args:
rate (int): The chosen flash rate. Default: 0Hz (no flash).
"""
assert rate in (0, 0.5, 1, 2), "ERROR - Invalid blink rate set in set_blink_rate()"
self.blink_rate = rate & 0x03
self._write_cmd(self.HT16K33_GENERIC_CMD_BLINK | rate << 1)
def set_brightness(self, brightness=15):
"""
Set the display's brightness (ie. duty cycle).
Brightness values range from 0 (dim, but not off) to 15 (max. brightness).
Args:
brightness (int): The chosen flash rate. Default: 15 (100%).
"""
if brightness < 0 or brightness > 15: brightness = 15
self.brightness = brightness
self._write_cmd(self.HT16K33_GENERIC_CMD_BRIGHTNESS | brightness)
def draw(self):
"""
Writes the current display buffer to the display itself.
Call this method after updating the buffer to update
the LED itself.
"""
self._render()
def clear(self):
"""
Clear the buffer.
Returns:
The instance (self)
"""
for i in range(0, len(self.buffer)): self.buffer[i] = 0x00
return self
def power_on(self):
"""
Power on the controller and display.
"""
self._write_cmd(self.HT16K33_GENERIC_SYSTEM_ON)
self._write_cmd(self.HT16K33_GENERIC_DISPLAY_ON)
def power_off(self):
"""
Power on the controller and display.
"""
self._write_cmd(self.HT16K33_GENERIC_DISPLAY_OFF)
self._write_cmd(self.HT16K33_GENERIC_SYSTEM_OFF)
# ********** PRIVATE METHODS **********
def _render(self):
"""
Write the display buffer out to I2C
"""
buffer = bytearray(len(self.buffer) + 1)
buffer[1:] = self.buffer
buffer[0] = 0x00
self.i2c.writeto(self.address, bytes(buffer))
def _write_cmd(self, byte):
"""
Writes a single command to the HT16K33. A private method.
"""
self.i2c.writeto(self.address, bytes([byte]))
|
[
"class",
"HT16K33",
":",
"HT16K33_GENERIC_DISPLAY_ON",
"=",
"0x81",
"HT16K33_GENERIC_DISPLAY_OFF",
"=",
"0x80",
"HT16K33_GENERIC_SYSTEM_ON",
"=",
"0x21",
"HT16K33_GENERIC_SYSTEM_OFF",
"=",
"0x20",
"HT16K33_GENERIC_DISPLAY_ADDRESS",
"=",
"0x00",
"HT16K33_GENERIC_CMD_BRIGHTNESS",
"=",
"0xE0",
"HT16K33_GENERIC_CMD_BLINK",
"=",
"0x81",
"i2c",
"=",
"None",
"address",
"=",
"0",
"brightness",
"=",
"15",
"flash_rate",
"=",
"0",
"def",
"__init__",
"(",
"self",
",",
"i2c",
",",
"i2c_address",
")",
":",
"assert",
"0x00",
"<=",
"i2c_address",
"<",
"0x80",
",",
"\"ERROR - Invalid I2C address in HT16K33()\"",
"self",
".",
"i2c",
"=",
"i2c",
"self",
".",
"address",
"=",
"i2c_address",
"self",
".",
"power_on",
"(",
")",
"def",
"set_blink_rate",
"(",
"self",
",",
"rate",
"=",
"0",
")",
":",
"\"\"\"\n Set the display's flash rate.\n\n Only four values (in Hz) are permitted: 0, 2, 1, and 0,5.\n\n Args:\n rate (int): The chosen flash rate. Default: 0Hz (no flash).\n \"\"\"",
"assert",
"rate",
"in",
"(",
"0",
",",
"0.5",
",",
"1",
",",
"2",
")",
",",
"\"ERROR - Invalid blink rate set in set_blink_rate()\"",
"self",
".",
"blink_rate",
"=",
"rate",
"&",
"0x03",
"self",
".",
"_write_cmd",
"(",
"self",
".",
"HT16K33_GENERIC_CMD_BLINK",
"|",
"rate",
"<<",
"1",
")",
"def",
"set_brightness",
"(",
"self",
",",
"brightness",
"=",
"15",
")",
":",
"\"\"\"\n Set the display's brightness (ie. duty cycle).\n\n Brightness values range from 0 (dim, but not off) to 15 (max. brightness).\n\n Args:\n brightness (int): The chosen flash rate. Default: 15 (100%).\n \"\"\"",
"if",
"brightness",
"<",
"0",
"or",
"brightness",
">",
"15",
":",
"brightness",
"=",
"15",
"self",
".",
"brightness",
"=",
"brightness",
"self",
".",
"_write_cmd",
"(",
"self",
".",
"HT16K33_GENERIC_CMD_BRIGHTNESS",
"|",
"brightness",
")",
"def",
"draw",
"(",
"self",
")",
":",
"\"\"\"\n Writes the current display buffer to the display itself.\n\n Call this method after updating the buffer to update\n the LED itself.\n \"\"\"",
"self",
".",
"_render",
"(",
")",
"def",
"clear",
"(",
"self",
")",
":",
"\"\"\"\n Clear the buffer.\n\n Returns:\n The instance (self)\n \"\"\"",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"self",
".",
"buffer",
")",
")",
":",
"self",
".",
"buffer",
"[",
"i",
"]",
"=",
"0x00",
"return",
"self",
"def",
"power_on",
"(",
"self",
")",
":",
"\"\"\"\n Power on the controller and display.\n \"\"\"",
"self",
".",
"_write_cmd",
"(",
"self",
".",
"HT16K33_GENERIC_SYSTEM_ON",
")",
"self",
".",
"_write_cmd",
"(",
"self",
".",
"HT16K33_GENERIC_DISPLAY_ON",
")",
"def",
"power_off",
"(",
"self",
")",
":",
"\"\"\"\n Power on the controller and display.\n \"\"\"",
"self",
".",
"_write_cmd",
"(",
"self",
".",
"HT16K33_GENERIC_DISPLAY_OFF",
")",
"self",
".",
"_write_cmd",
"(",
"self",
".",
"HT16K33_GENERIC_SYSTEM_OFF",
")",
"def",
"_render",
"(",
"self",
")",
":",
"\"\"\"\n Write the display buffer out to I2C\n \"\"\"",
"buffer",
"=",
"bytearray",
"(",
"len",
"(",
"self",
".",
"buffer",
")",
"+",
"1",
")",
"buffer",
"[",
"1",
":",
"]",
"=",
"self",
".",
"buffer",
"buffer",
"[",
"0",
"]",
"=",
"0x00",
"self",
".",
"i2c",
".",
"writeto",
"(",
"self",
".",
"address",
",",
"bytes",
"(",
"buffer",
")",
")",
"def",
"_write_cmd",
"(",
"self",
",",
"byte",
")",
":",
"\"\"\"\n Writes a single command to the HT16K33. A private method.\n \"\"\"",
"self",
".",
"i2c",
".",
"writeto",
"(",
"self",
".",
"address",
",",
"bytes",
"(",
"[",
"byte",
"]",
")",
")"
] |
A simple, generic driver for the I2C-connected Holtek HT16K33 controller chip.
|
[
"A",
"simple",
"generic",
"driver",
"for",
"the",
"I2C",
"-",
"connected",
"Holtek",
"HT16K33",
"controller",
"chip",
"."
] |
[
"\"\"\"\n A simple, generic driver for the I2C-connected Holtek HT16K33 controller chip.\n This release supports MicroPython and CircuitPython\n\n Version: 3.0.2\n Bus: I2C\n Author: Tony Smith (@smittytone)\n License: MIT\n Copyright: 2020\n \"\"\"",
"# *********** CONSTANTS **********",
"# *********** PRIVATE PROPERTIES **********",
"# *********** CONSTRUCTOR **********",
"# *********** PUBLIC METHODS **********",
"\"\"\"\n Set the display's flash rate.\n\n Only four values (in Hz) are permitted: 0, 2, 1, and 0,5.\n\n Args:\n rate (int): The chosen flash rate. Default: 0Hz (no flash).\n \"\"\"",
"\"\"\"\n Set the display's brightness (ie. duty cycle).\n\n Brightness values range from 0 (dim, but not off) to 15 (max. brightness).\n\n Args:\n brightness (int): The chosen flash rate. Default: 15 (100%).\n \"\"\"",
"\"\"\"\n Writes the current display buffer to the display itself.\n\n Call this method after updating the buffer to update\n the LED itself.\n \"\"\"",
"\"\"\"\n Clear the buffer.\n\n Returns:\n The instance (self)\n \"\"\"",
"\"\"\"\n Power on the controller and display.\n \"\"\"",
"\"\"\"\n Power on the controller and display.\n \"\"\"",
"# ********** PRIVATE METHODS **********",
"\"\"\"\n Write the display buffer out to I2C\n \"\"\"",
"\"\"\"\n Writes a single command to the HT16K33. A private method.\n \"\"\""
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 13
| 924
| 82
|
b1c59013623e4fffe34803a6b8ce5cf243fd312d
|
runtimeverification/k
|
kernel/src/main/java/org/kframework/parser/inner/kernel/EarleyParser.java
|
[
"BSD-3-Clause"
] |
Java
|
EarleyState
|
/**
* An Earley parser parse state. Consists of an inlined LR(0) item (see {@link LRItem}) and an index within the
* sentence being parsed where the parse state began.
*
* Each parse state also has a parse tree associated with it, in the form of a Set<PStack<Term>> object.
* Each element in the set represents a single possible parse at this state, with one element in the PStack for each
* non-terminal left of the "dot" on the right-hand-side of the production.
*
* Additionally, we compute the value `ntItem` which corresponds to the number of non-terminals left of the "dot" in
* the LR(0) item this state corresponds to.
*/
|
An Earley parser parse state. Consists of an inlined LR(0) item and an index within the
sentence being parsed where the parse state began.
Each parse state also has a parse tree associated with it, in the form of a Set> object.
Each element in the set represents a single possible parse at this state, with one element in the PStack for each
non-terminal left of the "dot" on the right-hand-side of the production.
Additionally, we compute the value `ntItem` which corresponds to the number of non-terminals left of the "dot" in
the LR(0) item this state corresponds to.
|
[
"An",
"Earley",
"parser",
"parse",
"state",
".",
"Consists",
"of",
"an",
"inlined",
"LR",
"(",
"0",
")",
"item",
"and",
"an",
"index",
"within",
"the",
"sentence",
"being",
"parsed",
"where",
"the",
"parse",
"state",
"began",
".",
"Each",
"parse",
"state",
"also",
"has",
"a",
"parse",
"tree",
"associated",
"with",
"it",
"in",
"the",
"form",
"of",
"a",
"Set",
">",
"object",
".",
"Each",
"element",
"in",
"the",
"set",
"represents",
"a",
"single",
"possible",
"parse",
"at",
"this",
"state",
"with",
"one",
"element",
"in",
"the",
"PStack",
"for",
"each",
"non",
"-",
"terminal",
"left",
"of",
"the",
"\"",
"dot",
"\"",
"on",
"the",
"right",
"-",
"hand",
"-",
"side",
"of",
"the",
"production",
".",
"Additionally",
"we",
"compute",
"the",
"value",
"`",
"ntItem",
"`",
"which",
"corresponds",
"to",
"the",
"number",
"of",
"non",
"-",
"terminals",
"left",
"of",
"the",
"\"",
"dot",
"\"",
"in",
"the",
"LR",
"(",
"0",
")",
"item",
"this",
"state",
"corresponds",
"to",
"."
] |
private static final class EarleyState {
public EarleyState(EarleyProduction prod, int item, int start) {
this.prod = prod;
this.item = item;
this.start = start;
int ntItem = 0;
for (int k = 0; k < item; k++) {
if (prod.items.get(k).isNonTerminal()) {
ntItem++;
}
}
this.ntItem = ntItem;
}
final EarleyProduction prod;
final int item;
final int start;
final int ntItem;
Set<PStack<Term>> parseTree;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
EarleyState that = (EarleyState) o;
return item == that.item && start == that.start && prod.equals(that.prod);
}
@Override
public int hashCode() {
return Objects.hash(prod, item, start);
}
public String toString() {
return "(" + prod.toString() + ", " + item + ", " + start + ")";
}
public Set<PStack<Term>> parseTree() {
if (parseTree == null) {
return EMPTY_PARSE_TREE;
}
return parseTree;
}
}
|
[
"private",
"static",
"final",
"class",
"EarleyState",
"{",
"public",
"EarleyState",
"(",
"EarleyProduction",
"prod",
",",
"int",
"item",
",",
"int",
"start",
")",
"{",
"this",
".",
"prod",
"=",
"prod",
";",
"this",
".",
"item",
"=",
"item",
";",
"this",
".",
"start",
"=",
"start",
";",
"int",
"ntItem",
"=",
"0",
";",
"for",
"(",
"int",
"k",
"=",
"0",
";",
"k",
"<",
"item",
";",
"k",
"++",
")",
"{",
"if",
"(",
"prod",
".",
"items",
".",
"get",
"(",
"k",
")",
".",
"isNonTerminal",
"(",
")",
")",
"{",
"ntItem",
"++",
";",
"}",
"}",
"this",
".",
"ntItem",
"=",
"ntItem",
";",
"}",
"final",
"EarleyProduction",
"prod",
";",
"final",
"int",
"item",
";",
"final",
"int",
"start",
";",
"final",
"int",
"ntItem",
";",
"Set",
"<",
"PStack",
"<",
"Term",
">",
">",
"parseTree",
";",
"@",
"Override",
"public",
"boolean",
"equals",
"(",
"Object",
"o",
")",
"{",
"if",
"(",
"this",
"==",
"o",
")",
"return",
"true",
";",
"if",
"(",
"o",
"==",
"null",
"||",
"getClass",
"(",
")",
"!=",
"o",
".",
"getClass",
"(",
")",
")",
"return",
"false",
";",
"EarleyState",
"that",
"=",
"(",
"EarleyState",
")",
"o",
";",
"return",
"item",
"==",
"that",
".",
"item",
"&&",
"start",
"==",
"that",
".",
"start",
"&&",
"prod",
".",
"equals",
"(",
"that",
".",
"prod",
")",
";",
"}",
"@",
"Override",
"public",
"int",
"hashCode",
"(",
")",
"{",
"return",
"Objects",
".",
"hash",
"(",
"prod",
",",
"item",
",",
"start",
")",
";",
"}",
"public",
"String",
"toString",
"(",
")",
"{",
"return",
"\"",
"(",
"\"",
"+",
"prod",
".",
"toString",
"(",
")",
"+",
"\"",
", ",
"\"",
"+",
"item",
"+",
"\"",
", ",
"\"",
"+",
"start",
"+",
"\"",
")",
"\"",
";",
"}",
"public",
"Set",
"<",
"PStack",
"<",
"Term",
">",
">",
"parseTree",
"(",
")",
"{",
"if",
"(",
"parseTree",
"==",
"null",
")",
"{",
"return",
"EMPTY_PARSE_TREE",
";",
"}",
"return",
"parseTree",
";",
"}",
"}"
] |
An Earley parser parse state.
|
[
"An",
"Earley",
"parser",
"parse",
"state",
"."
] |
[] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 14
| 289
| 165
|
3b0463367ec8e50bfc2bbae9c613f1ce14d172d9
|
sunboy0523/gatk
|
src/main/java/org/broadinstitute/hellbender/tools/walkers/haplotypecaller/Kmer.java
|
[
"BSD-3-Clause"
] |
Java
|
Kmer
|
/**
* Fast wrapper for byte[] kmers
*
* This objects has several important features that make it better than using a raw byte[] for a kmer:
*
* -- Can create kmer from a range of a larger byte[], allowing us to avoid Array.copyOfRange
* -- Fast equals and hashcode methods
* -- can get actual byte[] of the kmer, even if it's from a larger byte[], and this operation
* only does the work of that operation once, updating its internal state
*/
|
Fast wrapper for byte[] kmers
This objects has several important features that make it better than using a raw byte[] for a kmer.
Can create kmer from a range of a larger byte[], allowing us to avoid Array.copyOfRange
Fast equals and hashcode methods
can get actual byte[] of the kmer, even if it's from a larger byte[], and this operation
only does the work of that operation once, updating its internal state
|
[
"Fast",
"wrapper",
"for",
"byte",
"[]",
"kmers",
"This",
"objects",
"has",
"several",
"important",
"features",
"that",
"make",
"it",
"better",
"than",
"using",
"a",
"raw",
"byte",
"[]",
"for",
"a",
"kmer",
".",
"Can",
"create",
"kmer",
"from",
"a",
"range",
"of",
"a",
"larger",
"byte",
"[]",
"allowing",
"us",
"to",
"avoid",
"Array",
".",
"copyOfRange",
"Fast",
"equals",
"and",
"hashcode",
"methods",
"can",
"get",
"actual",
"byte",
"[]",
"of",
"the",
"kmer",
"even",
"if",
"it",
"'",
"s",
"from",
"a",
"larger",
"byte",
"[]",
"and",
"this",
"operation",
"only",
"does",
"the",
"work",
"of",
"that",
"operation",
"once",
"updating",
"its",
"internal",
"state"
] |
public final class Kmer {
// this values may be updated in the course of interacting with this kmer
private byte[] bases;
private int start;
// two constants
private final int length;
private final int hash;
/**
* Create a new kmer using all bases in kmer
* @param kmer a non-null byte[]. The input array must not be modified by the caller.
*/
public Kmer(final byte[] kmer) {
this(kmer, 0, kmer.length);
}
/**
* Create a new kmer based on the string kmer
*
* This is not a good method to use for performance
*
* @param kmer the bases as a string
*/
public Kmer(final String kmer) {
this(Utils.nonNull(kmer).getBytes());
}
/**
* Create a new kmer backed by the bases in bases, spanning start -> start + length
*
* Under no circumstances can bases be modified anywhere in the client code. This does not make a copy
* of bases for performance reasons
*
* @param bases an array of bases
* @param start the start of the kmer in bases, must be >= 0 and < bases.length
* @param length the length of the kmer. Must be >= 0 and start + length < bases.length
*/
public Kmer(final byte[] bases, final int start, final int length) {
this.bases = Utils.nonNull(bases, "bases cannot be null");
Utils.validateArg(start >= 0, () -> "start must be >= 0 but got " + start);
Utils.validateArg( length >= 0, () -> "length must be >= 0 but got " + length);
Utils.validateArg(start + length <= bases.length, () -> "start + length " + (start + length) + " must be <= bases.length " + bases.length + " but got " + start + " with length " + length);
this.start = start;
this.length = length;
hash = hashCode(bases, start, length);
}
/**
* Compute the hashcode for a KMer.
* Equivalent to <code>new String(bases, start, length).hashCode()</code>
*/
private static int hashCode(final byte[] bases, final int start, final int length) {
if (length == 0){
return 0;
}
int h = 0;
for (int i = start, stop = start + length; i < stop; i++) {
h = 31 * h + bases[i];
}
return h;
}
/**
* Create a derived shallow kmer that starts at newStart and has newLength bases
* @param newStart the new start of kmer, where 0 means that start of the kmer, 1 means skip the first base
* @param newLength the new length
* @return a new kmer based on the data in this kmer. Does not make a copy, so shares most of the data
*/
public Kmer subKmer(final int newStart, final int newLength) {
return new Kmer(bases, start + newStart, newLength);
}
/**
* Get the bases of this kmer. May create a copy of the bases, depending on how this kmer was constructed.
*
* Note that this function is efficient in that if it needs to copy the bases this only occurs once.
*
* @return a non-null byte[] containing length() bases of this kmer, regardless of how this kmer was created
*/
public byte[] bases() {
if ( start != 0 || bases.length != length ) {
// update operation. Rip out the exact byte[] and update start so we don't ever do this again
bases = Arrays.copyOfRange(bases, start, start + length);
start = 0;
}
return bases;
}
/**
* The length of this kmer
* @return an integer >= 0
*/
public int length() {
return length;
}
/**
* Gets a set of differing positions and bases from another k-mer, limiting up to a max distance.
* For example, if this = "ACATT" and other = "ACGGT":
* - if maxDistance < 2 then -1 will be returned, since distance between kmers is 2.
* - If maxDistance >=2, then 2 will be returned, and arrays will be filled as follows:
* differingIndeces = {2,3}
* differingBases = {'G','G'}
* @param other Other k-mer to test
* @param maxDistance Maximum distance to search. If this and other k-mers are beyond this Hamming distance,
* search is aborted and -1 is returned
* @param differingIndeces Array with indices of differing bytes in array
* @param differingBases Actual differing bases
* @return Set of mappings of form (int->byte), where each elements represents index
* of k-mer array where bases mismatch, and the byte is the base from other kmer.
* If both k-mers differ by more than maxDistance, returns null
*/
public int getDifferingPositions(final Kmer other,
final int maxDistance,
final int[] differingIndeces,
final byte[] differingBases) {
Utils.nonNull(other);
Utils.nonNull(differingIndeces);
Utils.nonNull(differingBases);
Utils.validateArg(maxDistance > 0, "maxDistance must be positive but was " + maxDistance);
int dist = 0;
if (length == other.length()) {
final byte[] f2 = other.bases;
for (int i=0; i < length; i++) {
if (bases[start + i] != f2[i]) {
differingIndeces[dist] = i;
differingBases[dist++] = f2[i];
if (dist > maxDistance) {
return -1;
}
}
}
}
return dist;
}
@Override
public String toString() {
return "Kmer{" + new String(bases,start,length) + '}';
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Kmer)) {
return false;
}
final Kmer kmer = (Kmer) o;
// very fast test. If hash aren't equal you are done, otherwise compare the bases
if ( hash != kmer.hash || length != kmer.length ) {
return false;
}
return Utils.equalRange(bases, start, kmer.bases, kmer.start, length);
}
@Override
public int hashCode() {
return hash;
}
@VisibleForTesting
int start() {
return start;
}
}
|
[
"public",
"final",
"class",
"Kmer",
"{",
"private",
"byte",
"[",
"]",
"bases",
";",
"private",
"int",
"start",
";",
"private",
"final",
"int",
"length",
";",
"private",
"final",
"int",
"hash",
";",
"/**\n * Create a new kmer using all bases in kmer\n * @param kmer a non-null byte[]. The input array must not be modified by the caller.\n */",
"public",
"Kmer",
"(",
"final",
"byte",
"[",
"]",
"kmer",
")",
"{",
"this",
"(",
"kmer",
",",
"0",
",",
"kmer",
".",
"length",
")",
";",
"}",
"/**\n * Create a new kmer based on the string kmer\n *\n * This is not a good method to use for performance\n *\n * @param kmer the bases as a string\n */",
"public",
"Kmer",
"(",
"final",
"String",
"kmer",
")",
"{",
"this",
"(",
"Utils",
".",
"nonNull",
"(",
"kmer",
")",
".",
"getBytes",
"(",
")",
")",
";",
"}",
"/**\n * Create a new kmer backed by the bases in bases, spanning start -> start + length\n *\n * Under no circumstances can bases be modified anywhere in the client code. This does not make a copy\n * of bases for performance reasons\n *\n * @param bases an array of bases\n * @param start the start of the kmer in bases, must be >= 0 and < bases.length\n * @param length the length of the kmer. Must be >= 0 and start + length < bases.length\n */",
"public",
"Kmer",
"(",
"final",
"byte",
"[",
"]",
"bases",
",",
"final",
"int",
"start",
",",
"final",
"int",
"length",
")",
"{",
"this",
".",
"bases",
"=",
"Utils",
".",
"nonNull",
"(",
"bases",
",",
"\"",
"bases cannot be null",
"\"",
")",
";",
"Utils",
".",
"validateArg",
"(",
"start",
">=",
"0",
",",
"(",
")",
"->",
"\"",
"start must be >= 0 but got ",
"\"",
"+",
"start",
")",
";",
"Utils",
".",
"validateArg",
"(",
"length",
">=",
"0",
",",
"(",
")",
"->",
"\"",
"length must be >= 0 but got ",
"\"",
"+",
"length",
")",
";",
"Utils",
".",
"validateArg",
"(",
"start",
"+",
"length",
"<=",
"bases",
".",
"length",
",",
"(",
")",
"->",
"\"",
"start + length ",
"\"",
"+",
"(",
"start",
"+",
"length",
")",
"+",
"\"",
" must be <= bases.length ",
"\"",
"+",
"bases",
".",
"length",
"+",
"\"",
" but got ",
"\"",
"+",
"start",
"+",
"\"",
" with length ",
"\"",
"+",
"length",
")",
";",
"this",
".",
"start",
"=",
"start",
";",
"this",
".",
"length",
"=",
"length",
";",
"hash",
"=",
"hashCode",
"(",
"bases",
",",
"start",
",",
"length",
")",
";",
"}",
"/**\n * Compute the hashcode for a KMer.\n * Equivalent to <code>new String(bases, start, length).hashCode()</code>\n */",
"private",
"static",
"int",
"hashCode",
"(",
"final",
"byte",
"[",
"]",
"bases",
",",
"final",
"int",
"start",
",",
"final",
"int",
"length",
")",
"{",
"if",
"(",
"length",
"==",
"0",
")",
"{",
"return",
"0",
";",
"}",
"int",
"h",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"start",
",",
"stop",
"=",
"start",
"+",
"length",
";",
"i",
"<",
"stop",
";",
"i",
"++",
")",
"{",
"h",
"=",
"31",
"*",
"h",
"+",
"bases",
"[",
"i",
"]",
";",
"}",
"return",
"h",
";",
"}",
"/**\n * Create a derived shallow kmer that starts at newStart and has newLength bases\n * @param newStart the new start of kmer, where 0 means that start of the kmer, 1 means skip the first base\n * @param newLength the new length\n * @return a new kmer based on the data in this kmer. Does not make a copy, so shares most of the data\n */",
"public",
"Kmer",
"subKmer",
"(",
"final",
"int",
"newStart",
",",
"final",
"int",
"newLength",
")",
"{",
"return",
"new",
"Kmer",
"(",
"bases",
",",
"start",
"+",
"newStart",
",",
"newLength",
")",
";",
"}",
"/**\n * Get the bases of this kmer. May create a copy of the bases, depending on how this kmer was constructed.\n *\n * Note that this function is efficient in that if it needs to copy the bases this only occurs once.\n *\n * @return a non-null byte[] containing length() bases of this kmer, regardless of how this kmer was created\n */",
"public",
"byte",
"[",
"]",
"bases",
"(",
")",
"{",
"if",
"(",
"start",
"!=",
"0",
"||",
"bases",
".",
"length",
"!=",
"length",
")",
"{",
"bases",
"=",
"Arrays",
".",
"copyOfRange",
"(",
"bases",
",",
"start",
",",
"start",
"+",
"length",
")",
";",
"start",
"=",
"0",
";",
"}",
"return",
"bases",
";",
"}",
"/**\n * The length of this kmer\n * @return an integer >= 0\n */",
"public",
"int",
"length",
"(",
")",
"{",
"return",
"length",
";",
"}",
"/**\n * Gets a set of differing positions and bases from another k-mer, limiting up to a max distance.\n * For example, if this = \"ACATT\" and other = \"ACGGT\":\n * - if maxDistance < 2 then -1 will be returned, since distance between kmers is 2.\n * - If maxDistance >=2, then 2 will be returned, and arrays will be filled as follows:\n * differingIndeces = {2,3}\n * differingBases = {'G','G'}\n * @param other Other k-mer to test\n * @param maxDistance Maximum distance to search. If this and other k-mers are beyond this Hamming distance,\n * search is aborted and -1 is returned\n * @param differingIndeces Array with indices of differing bytes in array\n * @param differingBases Actual differing bases\n * @return Set of mappings of form (int->byte), where each elements represents index\n * of k-mer array where bases mismatch, and the byte is the base from other kmer.\n * If both k-mers differ by more than maxDistance, returns null\n */",
"public",
"int",
"getDifferingPositions",
"(",
"final",
"Kmer",
"other",
",",
"final",
"int",
"maxDistance",
",",
"final",
"int",
"[",
"]",
"differingIndeces",
",",
"final",
"byte",
"[",
"]",
"differingBases",
")",
"{",
"Utils",
".",
"nonNull",
"(",
"other",
")",
";",
"Utils",
".",
"nonNull",
"(",
"differingIndeces",
")",
";",
"Utils",
".",
"nonNull",
"(",
"differingBases",
")",
";",
"Utils",
".",
"validateArg",
"(",
"maxDistance",
">",
"0",
",",
"\"",
"maxDistance must be positive but was ",
"\"",
"+",
"maxDistance",
")",
";",
"int",
"dist",
"=",
"0",
";",
"if",
"(",
"length",
"==",
"other",
".",
"length",
"(",
")",
")",
"{",
"final",
"byte",
"[",
"]",
"f2",
"=",
"other",
".",
"bases",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"bases",
"[",
"start",
"+",
"i",
"]",
"!=",
"f2",
"[",
"i",
"]",
")",
"{",
"differingIndeces",
"[",
"dist",
"]",
"=",
"i",
";",
"differingBases",
"[",
"dist",
"++",
"]",
"=",
"f2",
"[",
"i",
"]",
";",
"if",
"(",
"dist",
">",
"maxDistance",
")",
"{",
"return",
"-",
"1",
";",
"}",
"}",
"}",
"}",
"return",
"dist",
";",
"}",
"@",
"Override",
"public",
"String",
"toString",
"(",
")",
"{",
"return",
"\"",
"Kmer{",
"\"",
"+",
"new",
"String",
"(",
"bases",
",",
"start",
",",
"length",
")",
"+",
"'}'",
";",
"}",
"@",
"Override",
"public",
"boolean",
"equals",
"(",
"final",
"Object",
"o",
")",
"{",
"if",
"(",
"this",
"==",
"o",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"!",
"(",
"o",
"instanceof",
"Kmer",
")",
")",
"{",
"return",
"false",
";",
"}",
"final",
"Kmer",
"kmer",
"=",
"(",
"Kmer",
")",
"o",
";",
"if",
"(",
"hash",
"!=",
"kmer",
".",
"hash",
"||",
"length",
"!=",
"kmer",
".",
"length",
")",
"{",
"return",
"false",
";",
"}",
"return",
"Utils",
".",
"equalRange",
"(",
"bases",
",",
"start",
",",
"kmer",
".",
"bases",
",",
"kmer",
".",
"start",
",",
"length",
")",
";",
"}",
"@",
"Override",
"public",
"int",
"hashCode",
"(",
")",
"{",
"return",
"hash",
";",
"}",
"@",
"VisibleForTesting",
"int",
"start",
"(",
")",
"{",
"return",
"start",
";",
"}",
"}"
] |
Fast wrapper for byte[] kmers
This objects has several important features that make it better than using a raw byte[] for a kmer:
|
[
"Fast",
"wrapper",
"for",
"byte",
"[]",
"kmers",
"This",
"objects",
"has",
"several",
"important",
"features",
"that",
"make",
"it",
"better",
"than",
"using",
"a",
"raw",
"byte",
"[]",
"for",
"a",
"kmer",
":"
] |
[
"// this values may be updated in the course of interacting with this kmer",
"// two constants",
"// update operation. Rip out the exact byte[] and update start so we don't ever do this again",
"// very fast test. If hash aren't equal you are done, otherwise compare the bases"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 18
| 1,548
| 107
|
1ae6040d4acaed5e9b0452a9c698a69b05625a57
|
ranma42/dotNext
|
src/DotNext/Buffers/SparseBufferWriter.cs
|
[
"MIT"
] |
C#
|
SparseBufferWriter
|
/// <summary>
/// Represents builder of the sparse memory buffer.
/// </summary>
/// <remarks>
/// All members of <see cref="IBufferWriter{T}"/> are explicitly implemented because their
/// usage can produce holes in the sparse buffer. To avoid holes, use public members only.
/// </remarks>
/// <typeparam name="T">The type of the elements in the memory.</typeparam>
/// <seealso cref="PooledArrayBufferWriter{T}"/>
/// <seealso cref="PooledBufferWriter{T}"/>
|
Represents builder of the sparse memory buffer.
|
[
"Represents",
"builder",
"of",
"the",
"sparse",
"memory",
"buffer",
"."
] |
[DebuggerDisplay("WrittenCount = {" + nameof(WrittenCount) + "}, FragmentedBytes = {" + nameof(FragmentedBytes) + "}")]
public partial class SparseBufferWriter<T> : Disposable, IEnumerable<ReadOnlyMemory<T>>, IGrowableBuffer<T>, ISupplier<ReadOnlySequence<T>>
{
private readonly int chunkSize;
private readonly MemoryAllocator<T>? allocator;
private readonly unsafe delegate*<int, ref int, int> growth;
private int chunkIndex;
private MemoryChunk? first;
[SuppressMessage("Usage", "CA2213", Justification = "Disposed as a part of the linked list")]
private MemoryChunk? last;
private long length;
public SparseBufferWriter(int chunkSize, SparseBufferGrowth growth = SparseBufferGrowth.None, MemoryAllocator<T>? allocator = null)
{
if (chunkSize <= 0)
throw new ArgumentOutOfRangeException(nameof(chunkSize));
this.chunkSize = chunkSize;
this.allocator = allocator;
unsafe
{
this.growth = growth switch
{
SparseBufferGrowth.Linear => &BufferHelpers.LinearGrowth,
SparseBufferGrowth.Exponential => &BufferHelpers.ExponentialGrowth,
_ => &BufferHelpers.NoGrowth,
};
}
}
public SparseBufferWriter(MemoryPool<T> pool)
{
chunkSize = -1;
allocator = pool.ToAllocator();
unsafe
{
growth = &BufferHelpers.NoGrowth;
}
}
public SparseBufferWriter()
: this(MemoryPool<T>.Shared)
{
}
internal MemoryChunk? FirstChunk => first;
public long WrittenCount
{
get
{
ThrowIfDisposed();
return length;
}
}
public bool IsSingleSegment => ReferenceEquals(first, last);
public bool TryGetWrittenContent(out ReadOnlyMemory<T> segment)
{
ThrowIfDisposed();
if (IsSingleSegment)
{
segment = first is null ? ReadOnlyMemory<T>.Empty : first.WrittenMemory;
return true;
}
segment = default;
return false;
}
private long FragmentedBytes
{
get
{
var result = 0L;
for (MemoryChunk? current = first, next; current is not null; current = next)
{
next = current.Next;
if (next is not null && next.WrittenMemory.Length > 0)
result += current.FreeCapacity;
}
return result;
}
}
public unsafe void Write(ReadOnlySpan<T> input)
{
ThrowIfDisposed();
if (last is null)
first = last = new PooledMemoryChunk(allocator, chunkSize);
for (int writtenCount; !input.IsEmpty; length += writtenCount)
{
writtenCount = last.Write(input);
if (writtenCount == 0)
last = new PooledMemoryChunk(allocator, growth(chunkSize, ref chunkIndex), last);
else
input = input.Slice(writtenCount);
}
}
public void Write(ReadOnlyMemory<T> input, bool copyMemory = true)
{
ThrowIfDisposed();
if (input.IsEmpty)
goto exit;
if (copyMemory)
{
Write(input.Span);
}
else if (last is null)
{
first = last = new ImportedMemoryChunk(input);
length += input.Length;
}
else
{
last = new ImportedMemoryChunk(input, last);
length += input.Length;
}
exit:
return;
}
public void Write(in ReadOnlySequence<T> sequence, bool copyMemory = true)
{
foreach (var segment in sequence)
Write(segment, copyMemory);
}
public void CopyTo<TConsumer>(TConsumer consumer)
where TConsumer : notnull, IReadOnlySpanConsumer<T>
{
ThrowIfDisposed();
for (MemoryChunk? current = first; current is not null; current = current.Next)
{
var buffer = current.WrittenMemory.Span;
consumer.Invoke(buffer);
}
}
async ValueTask IGrowableBuffer<T>.CopyToAsync<TConsumer>(TConsumer consumer, CancellationToken token)
{
ThrowIfDisposed();
for (MemoryChunk? current = first; current is not null; current = current.Next)
{
await consumer.Invoke(current.WrittenMemory, token).ConfigureAwait(false);
}
}
public void CopyTo<TArg>(ReadOnlySpanAction<T, TArg> writer, TArg arg)
=> CopyTo(new DelegatingReadOnlySpanConsumer<T, TArg>(writer, arg));
public int CopyTo(Span<T> output)
{
ThrowIfDisposed();
var total = 0;
for (MemoryChunk? current = first; current is not null && !output.IsEmpty; current = current.Next)
{
var buffer = current.WrittenMemory.Span;
buffer.CopyTo(output, out var writtenCount);
output = output.Slice(writtenCount);
total += writtenCount;
}
return total;
}
public void Clear()
{
ThrowIfDisposed();
ReleaseChunks();
length = 0L;
}
ReadOnlySequence<T> ISupplier<ReadOnlySequence<T>>.Invoke()
=> TryGetWrittenContent(out var segment) ? new ReadOnlySequence<T>(segment) : BufferHelpers.ToReadOnlySequence(this);
public Enumerator GetEnumerator()
{
ThrowIfDisposed();
return new Enumerator(first);
}
IEnumerator<ReadOnlyMemory<T>> IEnumerable<ReadOnlyMemory<T>>.GetEnumerator()
=> GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
private void ReleaseChunks()
{
for (MemoryChunk? current = first, next; current is not null; current = next)
{
next = current.Next;
current.Dispose();
}
first = last = null;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
ReleaseChunks();
}
base.Dispose(disposing);
}
public override string ToString()
{
return typeof(T) == typeof(char) && length <= int.MaxValue ? BuildString(first, (int)length) : GetType().ToString();
static void FillChars(Span<char> output, MemoryChunk? chunk)
{
Debug.Assert(typeof(T) == typeof(char));
ReadOnlySpan<T> input;
for (var offset = 0; chunk is not null; offset += input.Length, chunk = chunk.Next)
{
input = chunk.WrittenMemory.Span;
ref var firstChar = ref Unsafe.As<T, char>(ref GetReference(input));
CreateReadOnlySpan<char>(ref firstChar, input.Length).CopyTo(output.Slice(offset));
}
}
static string BuildString(MemoryChunk? first, int length)
=> length > 0 ? string.Create(length, first, FillChars) : string.Empty;
}
}
|
[
"[",
"DebuggerDisplay",
"(",
"\"",
"WrittenCount = {",
"\"",
"+",
"nameof",
"(",
"WrittenCount",
")",
"+",
"\"",
"}, FragmentedBytes = {",
"\"",
"+",
"nameof",
"(",
"FragmentedBytes",
")",
"+",
"\"",
"}",
"\"",
")",
"]",
"public",
"partial",
"class",
"SparseBufferWriter",
"<",
"T",
">",
":",
"Disposable",
",",
"IEnumerable",
"<",
"ReadOnlyMemory",
"<",
"T",
">",
">",
",",
"IGrowableBuffer",
"<",
"T",
">",
",",
"ISupplier",
"<",
"ReadOnlySequence",
"<",
"T",
">",
">",
"{",
"private",
"readonly",
"int",
"chunkSize",
";",
"private",
"readonly",
"MemoryAllocator",
"<",
"T",
">",
"?",
"allocator",
";",
"private",
"readonly",
"unsafe",
"delegate",
"*",
"<",
"int",
",",
"ref",
"int",
",",
"int",
">",
"growth",
";",
"private",
"int",
"chunkIndex",
";",
"private",
"MemoryChunk",
"?",
"first",
";",
"[",
"SuppressMessage",
"(",
"\"",
"Usage",
"\"",
",",
"\"",
"CA2213",
"\"",
",",
"Justification",
"=",
"\"",
"Disposed as a part of the linked list",
"\"",
")",
"]",
"private",
"MemoryChunk",
"?",
"last",
";",
"private",
"long",
"length",
";",
"public",
"SparseBufferWriter",
"(",
"int",
"chunkSize",
",",
"SparseBufferGrowth",
"growth",
"=",
"SparseBufferGrowth",
".",
"None",
",",
"MemoryAllocator",
"<",
"T",
">",
"?",
"allocator",
"=",
"null",
")",
"{",
"if",
"(",
"chunkSize",
"<=",
"0",
")",
"throw",
"new",
"ArgumentOutOfRangeException",
"(",
"nameof",
"(",
"chunkSize",
")",
")",
";",
"this",
".",
"chunkSize",
"=",
"chunkSize",
";",
"this",
".",
"allocator",
"=",
"allocator",
";",
"unsafe",
"{",
"this",
".",
"growth",
"=",
"growth",
"switch",
"{",
"SparseBufferGrowth",
".",
"Linear",
"=>",
"&",
"BufferHelpers",
".",
"LinearGrowth",
",",
"SparseBufferGrowth",
".",
"Exponential",
"=>",
"&",
"BufferHelpers",
".",
"ExponentialGrowth",
",",
"_",
"=>",
"&",
"BufferHelpers",
".",
"NoGrowth",
",",
"}",
";",
"}",
"}",
"public",
"SparseBufferWriter",
"(",
"MemoryPool",
"<",
"T",
">",
"pool",
")",
"{",
"chunkSize",
"=",
"-",
"1",
";",
"allocator",
"=",
"pool",
".",
"ToAllocator",
"(",
")",
";",
"unsafe",
"{",
"growth",
"=",
"&",
"BufferHelpers",
".",
"NoGrowth",
";",
"}",
"}",
"public",
"SparseBufferWriter",
"(",
")",
":",
"this",
"(",
"MemoryPool",
"<",
"T",
">",
".",
"Shared",
")",
"{",
"}",
"internal",
"MemoryChunk",
"?",
"FirstChunk",
"=>",
"first",
";",
"public",
"long",
"WrittenCount",
"{",
"get",
"{",
"ThrowIfDisposed",
"(",
")",
";",
"return",
"length",
";",
"}",
"}",
"public",
"bool",
"IsSingleSegment",
"=>",
"ReferenceEquals",
"(",
"first",
",",
"last",
")",
";",
"public",
"bool",
"TryGetWrittenContent",
"(",
"out",
"ReadOnlyMemory",
"<",
"T",
">",
"segment",
")",
"{",
"ThrowIfDisposed",
"(",
")",
";",
"if",
"(",
"IsSingleSegment",
")",
"{",
"segment",
"=",
"first",
"is",
"null",
"?",
"ReadOnlyMemory",
"<",
"T",
">",
".",
"Empty",
":",
"first",
".",
"WrittenMemory",
";",
"return",
"true",
";",
"}",
"segment",
"=",
"default",
";",
"return",
"false",
";",
"}",
"private",
"long",
"FragmentedBytes",
"{",
"get",
"{",
"var",
"result",
"=",
"0L",
";",
"for",
"(",
"MemoryChunk",
"?",
"current",
"=",
"first",
",",
"next",
";",
"current",
"is",
"not",
"null",
";",
"current",
"=",
"next",
")",
"{",
"next",
"=",
"current",
".",
"Next",
";",
"if",
"(",
"next",
"is",
"not",
"null",
"&&",
"next",
".",
"WrittenMemory",
".",
"Length",
">",
"0",
")",
"result",
"+=",
"current",
".",
"FreeCapacity",
";",
"}",
"return",
"result",
";",
"}",
"}",
"public",
"unsafe",
"void",
"Write",
"(",
"ReadOnlySpan",
"<",
"T",
">",
"input",
")",
"{",
"ThrowIfDisposed",
"(",
")",
";",
"if",
"(",
"last",
"is",
"null",
")",
"first",
"=",
"last",
"=",
"new",
"PooledMemoryChunk",
"(",
"allocator",
",",
"chunkSize",
")",
";",
"for",
"(",
"int",
"writtenCount",
";",
"!",
"input",
".",
"IsEmpty",
";",
"length",
"+=",
"writtenCount",
")",
"{",
"writtenCount",
"=",
"last",
".",
"Write",
"(",
"input",
")",
";",
"if",
"(",
"writtenCount",
"==",
"0",
")",
"last",
"=",
"new",
"PooledMemoryChunk",
"(",
"allocator",
",",
"growth",
"(",
"chunkSize",
",",
"ref",
"chunkIndex",
")",
",",
"last",
")",
";",
"else",
"input",
"=",
"input",
".",
"Slice",
"(",
"writtenCount",
")",
";",
"}",
"}",
"public",
"void",
"Write",
"(",
"ReadOnlyMemory",
"<",
"T",
">",
"input",
",",
"bool",
"copyMemory",
"=",
"true",
")",
"{",
"ThrowIfDisposed",
"(",
")",
";",
"if",
"(",
"input",
".",
"IsEmpty",
")",
"goto",
"exit",
";",
"if",
"(",
"copyMemory",
")",
"{",
"Write",
"(",
"input",
".",
"Span",
")",
";",
"}",
"else",
"if",
"(",
"last",
"is",
"null",
")",
"{",
"first",
"=",
"last",
"=",
"new",
"ImportedMemoryChunk",
"(",
"input",
")",
";",
"length",
"+=",
"input",
".",
"Length",
";",
"}",
"else",
"{",
"last",
"=",
"new",
"ImportedMemoryChunk",
"(",
"input",
",",
"last",
")",
";",
"length",
"+=",
"input",
".",
"Length",
";",
"}",
"exit",
":",
"return",
";",
"}",
"public",
"void",
"Write",
"(",
"in",
"ReadOnlySequence",
"<",
"T",
">",
"sequence",
",",
"bool",
"copyMemory",
"=",
"true",
")",
"{",
"foreach",
"(",
"var",
"segment",
"in",
"sequence",
")",
"Write",
"(",
"segment",
",",
"copyMemory",
")",
";",
"}",
"public",
"void",
"CopyTo",
"<",
"TConsumer",
">",
"(",
"TConsumer",
"consumer",
")",
"where",
"TConsumer",
":",
"notnull",
",",
"IReadOnlySpanConsumer",
"<",
"T",
">",
"{",
"ThrowIfDisposed",
"(",
")",
";",
"for",
"(",
"MemoryChunk",
"?",
"current",
"=",
"first",
";",
"current",
"is",
"not",
"null",
";",
"current",
"=",
"current",
".",
"Next",
")",
"{",
"var",
"buffer",
"=",
"current",
".",
"WrittenMemory",
".",
"Span",
";",
"consumer",
".",
"Invoke",
"(",
"buffer",
")",
";",
"}",
"}",
"async",
"ValueTask",
"IGrowableBuffer",
"<",
"T",
">",
".",
"CopyToAsync",
"<",
"TConsumer",
">",
"(",
"TConsumer",
"consumer",
",",
"CancellationToken",
"token",
")",
"{",
"ThrowIfDisposed",
"(",
")",
";",
"for",
"(",
"MemoryChunk",
"?",
"current",
"=",
"first",
";",
"current",
"is",
"not",
"null",
";",
"current",
"=",
"current",
".",
"Next",
")",
"{",
"await",
"consumer",
".",
"Invoke",
"(",
"current",
".",
"WrittenMemory",
",",
"token",
")",
".",
"ConfigureAwait",
"(",
"false",
")",
";",
"}",
"}",
"public",
"void",
"CopyTo",
"<",
"TArg",
">",
"(",
"ReadOnlySpanAction",
"<",
"T",
",",
"TArg",
">",
"writer",
",",
"TArg",
"arg",
")",
"=>",
"CopyTo",
"(",
"new",
"DelegatingReadOnlySpanConsumer",
"<",
"T",
",",
"TArg",
">",
"(",
"writer",
",",
"arg",
")",
")",
";",
"public",
"int",
"CopyTo",
"(",
"Span",
"<",
"T",
">",
"output",
")",
"{",
"ThrowIfDisposed",
"(",
")",
";",
"var",
"total",
"=",
"0",
";",
"for",
"(",
"MemoryChunk",
"?",
"current",
"=",
"first",
";",
"current",
"is",
"not",
"null",
"&&",
"!",
"output",
".",
"IsEmpty",
";",
"current",
"=",
"current",
".",
"Next",
")",
"{",
"var",
"buffer",
"=",
"current",
".",
"WrittenMemory",
".",
"Span",
";",
"buffer",
".",
"CopyTo",
"(",
"output",
",",
"out",
"var",
"writtenCount",
")",
";",
"output",
"=",
"output",
".",
"Slice",
"(",
"writtenCount",
")",
";",
"total",
"+=",
"writtenCount",
";",
"}",
"return",
"total",
";",
"}",
"public",
"void",
"Clear",
"(",
")",
"{",
"ThrowIfDisposed",
"(",
")",
";",
"ReleaseChunks",
"(",
")",
";",
"length",
"=",
"0L",
";",
"}",
"ReadOnlySequence",
"<",
"T",
">",
"ISupplier",
"<",
"ReadOnlySequence",
"<",
"T",
">",
">",
".",
"Invoke",
"(",
")",
"=>",
"TryGetWrittenContent",
"(",
"out",
"var",
"segment",
")",
"?",
"new",
"ReadOnlySequence",
"<",
"T",
">",
"(",
"segment",
")",
":",
"BufferHelpers",
".",
"ToReadOnlySequence",
"(",
"this",
")",
";",
"public",
"Enumerator",
"GetEnumerator",
"(",
")",
"{",
"ThrowIfDisposed",
"(",
")",
";",
"return",
"new",
"Enumerator",
"(",
"first",
")",
";",
"}",
"IEnumerator",
"<",
"ReadOnlyMemory",
"<",
"T",
">",
">",
"IEnumerable",
"<",
"ReadOnlyMemory",
"<",
"T",
">",
">",
".",
"GetEnumerator",
"(",
")",
"=>",
"GetEnumerator",
"(",
")",
";",
"IEnumerator",
"IEnumerable",
".",
"GetEnumerator",
"(",
")",
"=>",
"GetEnumerator",
"(",
")",
";",
"private",
"void",
"ReleaseChunks",
"(",
")",
"{",
"for",
"(",
"MemoryChunk",
"?",
"current",
"=",
"first",
",",
"next",
";",
"current",
"is",
"not",
"null",
";",
"current",
"=",
"next",
")",
"{",
"next",
"=",
"current",
".",
"Next",
";",
"current",
".",
"Dispose",
"(",
")",
";",
"}",
"first",
"=",
"last",
"=",
"null",
";",
"}",
"protected",
"override",
"void",
"Dispose",
"(",
"bool",
"disposing",
")",
"{",
"if",
"(",
"disposing",
")",
"{",
"ReleaseChunks",
"(",
")",
";",
"}",
"base",
".",
"Dispose",
"(",
"disposing",
")",
";",
"}",
"public",
"override",
"string",
"ToString",
"(",
")",
"{",
"return",
"typeof",
"(",
"T",
")",
"==",
"typeof",
"(",
"char",
")",
"&&",
"length",
"<=",
"int",
".",
"MaxValue",
"?",
"BuildString",
"(",
"first",
",",
"(",
"int",
")",
"length",
")",
":",
"GetType",
"(",
")",
".",
"ToString",
"(",
")",
";",
"static",
"void",
"FillChars",
"(",
"Span",
"<",
"char",
">",
"output",
",",
"MemoryChunk",
"?",
"chunk",
")",
"{",
"Debug",
".",
"Assert",
"(",
"typeof",
"(",
"T",
")",
"==",
"typeof",
"(",
"char",
")",
")",
";",
"ReadOnlySpan",
"<",
"T",
">",
"input",
";",
"for",
"(",
"var",
"offset",
"=",
"0",
";",
"chunk",
"is",
"not",
"null",
";",
"offset",
"+=",
"input",
".",
"Length",
",",
"chunk",
"=",
"chunk",
".",
"Next",
")",
"{",
"input",
"=",
"chunk",
".",
"WrittenMemory",
".",
"Span",
";",
"ref",
"var",
"firstChar",
"=",
"ref",
"Unsafe",
".",
"As",
"<",
"T",
",",
"char",
">",
"(",
"ref",
"GetReference",
"(",
"input",
")",
")",
";",
"CreateReadOnlySpan",
"<",
"char",
">",
"(",
"ref",
"firstChar",
",",
"input",
".",
"Length",
")",
".",
"CopyTo",
"(",
"output",
".",
"Slice",
"(",
"offset",
")",
")",
";",
"}",
"}",
"static",
"string",
"BuildString",
"(",
"MemoryChunk",
"?",
"first",
",",
"int",
"length",
")",
"=>",
"length",
">",
"0",
"?",
"string",
".",
"Create",
"(",
"length",
",",
"first",
",",
"FillChars",
")",
":",
"string",
".",
"Empty",
";",
"}",
"}"
] |
Represents builder of the sparse memory buffer.
|
[
"Represents",
"builder",
"of",
"the",
"sparse",
"memory",
"buffer",
"."
] |
[
"// used for linear and exponential allocation strategies only",
"/// <summary>",
"/// Initializes a new builder with the specified size of memory block.",
"/// </summary>",
"/// <param name=\"chunkSize\">The size of the memory block representing single segment within sequence.</param>",
"/// <param name=\"growth\">Specifies how the memory should be allocated for each subsequent chunk in this buffer.</param>",
"/// <param name=\"allocator\">The allocator used to rent the segments.</param>",
"/// <exception cref=\"ArgumentOutOfRangeException\"><paramref name=\"chunkSize\"/> is less than or equal to zero.</exception>",
"/// <summary>",
"/// Initializes a new builder with automatically selected",
"/// chunk size.",
"/// </summary>",
"/// <param name=\"pool\">Memory pool used to allocate memory chunks.</param>",
"/// <summary>",
"/// Initializes a new builder which uses <see cref=\"MemoryPool{T}.Shared\"/>",
"/// as a default allocator of buffers.",
"/// </summary>",
"/// <summary>",
"/// Gets the number of written elements.",
"/// </summary>",
"/// <exception cref=\"ObjectDisposedException\">The builder has been disposed.</exception>",
"/// <summary>",
"/// Gets a value indicating that this buffer consists of a single segment.",
"/// </summary>",
"/// <summary>",
"/// Attempts to get the underlying buffer if it is presented by a single segment.",
"/// </summary>",
"/// <param name=\"segment\">The single segment representing written content.</param>",
"/// <returns><see langword=\"true\"/> if this buffer is represented by a single segment; otherwise, <see langword=\"false\"/>.</returns>",
"/// <exception cref=\"ObjectDisposedException\">The builder has been disposed.</exception>",
"/// <summary>",
"/// Writes the block of memory to this builder.",
"/// </summary>",
"/// <param name=\"input\">The memory block to be written to this builder.</param>",
"/// <exception cref=\"ObjectDisposedException\">The builder has been disposed.</exception>",
"// no more space in the last chunk, allocate a new one",
"/// <summary>",
"/// Writes the block of memory to this builder.",
"/// </summary>",
"/// <param name=\"input\">The memory block to be written to this builder.</param>",
"/// <param name=\"copyMemory\"><see langword=\"true\"/> to copy the content of the input buffer; <see langword=\"false\"/> to import the memory block.</param>",
"/// <exception cref=\"ObjectDisposedException\">The builder has been disposed.</exception>",
"/// <summary>",
"/// Writes a sequence of memory blocks to this builder.",
"/// </summary>",
"/// <param name=\"sequence\">A sequence of memory blocks.</param>",
"/// <param name=\"copyMemory\"><see langword=\"true\"/> to copy the content of the input buffer; <see langword=\"false\"/> to import memory blocks.</param>",
"/// <exception cref=\"ObjectDisposedException\">The builder has been disposed.</exception>",
"/// <summary>",
"/// Passes the contents of this builder to the consumer.",
"/// </summary>",
"/// <param name=\"consumer\">The consumer of this buffer.</param>",
"/// <typeparam name=\"TConsumer\">The type of the consumer.</typeparam>",
"/// <inheritdoc />",
"/// <summary>",
"/// Passes the contents of this builder to the callback.",
"/// </summary>",
"/// <param name=\"writer\">The callback used to accept memory segments representing the contents of this builder.</param>",
"/// <param name=\"arg\">The argument to be passed to the callback.</param>",
"/// <typeparam name=\"TArg\">The type of the argument to tbe passed to the callback.</typeparam>",
"/// <exception cref=\"ObjectDisposedException\">The builder has been disposed.</exception>",
"/// <summary>",
"/// Copies the contents of this builder to the specified memory block.",
"/// </summary>",
"/// <param name=\"output\">The memory block to be modified.</param>",
"/// <returns>The actual number of copied elements.</returns>",
"/// <exception cref=\"ObjectDisposedException\">The builder has been disposed.</exception>",
"/// <summary>",
"/// Clears internal buffers so this builder can be reused.",
"/// </summary>",
"/// <exception cref=\"ObjectDisposedException\">The builder has been disposed.</exception>",
"/// <inheritdoc />",
"/// <summary>",
"/// Gets enumerator over memory segments.",
"/// </summary>",
"/// <returns>The enumerator over memory segments.</returns>",
"/// <exception cref=\"ObjectDisposedException\">The builder has been disposed.</exception>",
"/// <inheritdoc />",
"/// <inheritdoc />",
"/// <inheritdoc />",
"/// <summary>",
"/// Returns the textual representation of this buffer.",
"/// </summary>",
"/// <returns>The textual representation of this buffer.</returns>"
] |
[
{
"param": "Disposable",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "Disposable",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": [
{
"identifier": "remarks",
"docstring": "All members of are explicitly implemented because their\nusage can produce holes in the sparse buffer. To avoid holes, use public members only.",
"docstring_tokens": [
"All",
"members",
"of",
"are",
"explicitly",
"implemented",
"because",
"their",
"usage",
"can",
"produce",
"holes",
"in",
"the",
"sparse",
"buffer",
".",
"To",
"avoid",
"holes",
"use",
"public",
"members",
"only",
"."
]
},
{
"identifier": "typeparam",
"docstring": "The type of the elements in the memory.",
"docstring_tokens": [
"The",
"type",
"of",
"the",
"elements",
"in",
"the",
"memory",
"."
]
},
{
"identifier": "seealso",
"docstring": null,
"docstring_tokens": [
"None"
]
},
{
"identifier": "seealso",
"docstring": null,
"docstring_tokens": [
"None"
]
}
]
}
| false
| 19
| 1,456
| 107
|
a3a45a950353dde323fb3f552411bd302b5e526c
|
jeroen-mostert/CodeContracts
|
Microsoft.Research/CodeAnalysis/ControlFlow.cs
|
[
"MIT"
] |
C#
|
APC
|
/// <summary>
/// An abstract program point representing a particular control point including possible finally continuations
///
/// The point is an index into a CFGBlock. If the block has a label at that index, the point represents the program
/// point just PRIOR to the execution of the code at that label.
/// If the point is past the sequence of labels in that CFGBlock, then the program point represents the excecution
/// point just after the last instruction in the block (or predecessor blocks).
/// </summary>
|
An abstract program point representing a particular control point including possible finally continuations
The point is an index into a CFGBlock. If the block has a label at that index, the point represents the program
point just PRIOR to the execution of the code at that label.
If the point is past the sequence of labels in that CFGBlock, then the program point represents the excecution
point just after the last instruction in the block (or predecessor blocks).
|
[
"An",
"abstract",
"program",
"point",
"representing",
"a",
"particular",
"control",
"point",
"including",
"possible",
"finally",
"continuations",
"The",
"point",
"is",
"an",
"index",
"into",
"a",
"CFGBlock",
".",
"If",
"the",
"block",
"has",
"a",
"label",
"at",
"that",
"index",
"the",
"point",
"represents",
"the",
"program",
"point",
"just",
"PRIOR",
"to",
"the",
"execution",
"of",
"the",
"code",
"at",
"that",
"label",
".",
"If",
"the",
"point",
"is",
"past",
"the",
"sequence",
"of",
"labels",
"in",
"that",
"CFGBlock",
"then",
"the",
"program",
"point",
"represents",
"the",
"excecution",
"point",
"just",
"after",
"the",
"last",
"instruction",
"in",
"the",
"block",
"(",
"or",
"predecessor",
"blocks",
")",
"."
] |
public class APC : IEquatable<APC> {
public static readonly APC Dummy = new APC(null, 0, null);
public readonly CFGBlock Block;
public readonly int Index;
public readonly SubroutineContext SubroutineContext;
public APC(CFGBlock block, int index,
SubroutineContext subroutineContext) {
this.Block = block;
this.Index = index;
this.SubroutineContext = subroutineContext;
#if CHECK_RECURSIVE_APCS
for (; subroutineContext != null; subroutineContext = subroutineContext.Tail)
{
Debug.Assert(block.Subroutine != subroutineContext.Head.One.Subroutine);
}
#endif
}
public APC Post()
{
if (this.Index < this.Block.Count)
{
return new APC(this.Block, this.Index + 1, this.SubroutineContext);
}
return this;
}
public static APC ForEnd(CFGBlock block,
SubroutineContext subroutineContext) {
return new APC(block, block.Count, subroutineContext);
}
public string AlternateSourceContext()
{
return String.Format("{0}[0x{1:x}]", this.Block.Subroutine.Name, this.Block.ILOffset(this));
}
public bool HasRealSourceContext
{
get
{
string realSC = this.Block.SourceContext(this);
return realSC != null;
}
}
public string PrimarySourceContext()
{
string realSC = this.Block.SourceContext(this);
if (realSC != null) return realSC;
return AlternateSourceContext();
}
public int ILOffset
{
get
{
return this.Block.ILOffset(this);
}
}
private APC(APC from)
{
this.Index = from.Index;
this.Block = from.Block;
this.SubroutineContext = null;
}
public APC WithoutContext
{
get
{
return new APC(this);
}
}
public static void ToString(StringBuilder sb, SubroutineContext finallyContext)
{
bool seenFirst = false;
while (finallyContext != null)
{
if (!seenFirst) { sb.Append(" {"); seenFirst = true; } else { sb.Append(", "); }
sb.AppendFormat("(SR{2} {0},{1}) [{3}]", finallyContext.Head.One.Index, finallyContext.Head.Two.Index, finallyContext.Head.One.Subroutine.Id, finallyContext.Head.Three);
finallyContext = finallyContext.Tail;
}
if (seenFirst)
{
sb.Append("}");
}
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("[");
sb.AppendFormat("SR{2} {0},{1}", this.Block.Index, this.Index, this.Block.Subroutine.Id);
ToString(sb, this.SubroutineContext);
sb.Append("]");
return sb.ToString();
}
#region IEquatable<APC> Members
public bool Equals(APC that)
{
if (this.Block != that.Block) return false;
if (this.Index != that.Index) return false;
if (this.SubroutineContext != that.SubroutineContext) return false;
return true;
}
#endregion
public bool InsideRequiresAtCallInsideContract
{
get
{
if (this.Block.Subroutine.IsRequires)
{
if (this.SubroutineContext != null)
{
for (SubroutineContext context = this.SubroutineContext; context != null; context = context.Tail)
{
if (context.Head.Three == "entry") { return false; }
if (context.Head.Three.StartsWith("before"))
{
Subroutine sub = context.Head.One.Subroutine;
return sub.IsEnsuresOrOld || sub.IsRequires || sub.IsInvariant;
}
}
throw new NotImplementedException();
}
}
return false;
}
}
public bool InsideRequiresAtCall
{
get {
if (this.Block.Subroutine.IsRequires)
{
if (this.SubroutineContext != null)
{
for (SubroutineContext context = this.SubroutineContext; context != null; context = context.Tail)
{
if (context.Head.Three == "entry") { return false; }
if (context.Head.Three.StartsWith("before")) { return true; }
}
throw new NotImplementedException();
}
}
return false;
}
}
public bool InsideEnsuresAtCall
{
get {
if (this.Block.Subroutine.IsEnsuresOrOld)
{
if (this.SubroutineContext != null)
{
for (SubroutineContext context = this.SubroutineContext; context != null; context = context.Tail)
{
if (context.Head.Three == "exit") { return false; }
if (context.Head.Three == "oldmanifest") { return false; }
if (context.Head.Three.StartsWith("after")) { return true; }
}
throw new NotImplementedException();
}
}
return false;
}
}
public bool InsideInvariantAtCall
{
get
{
if (this.Block.Subroutine.IsInvariant)
{
if (this.SubroutineContext != null)
{
for (SubroutineContext context = this.SubroutineContext; context != null; context = context.Tail)
{
if (context.Head.Three == "exit") { return false; }
if (context.Head.Three == "entry") { return false; }
if (context.Head.Three.StartsWith("after")) { return true; }
}
throw new NotImplementedException();
}
}
return false;
}
}
public bool InsideInvariantInMethod
{
get
{
if (this.Block.Subroutine.IsInvariant)
{
if (this.SubroutineContext != null)
{
for (SubroutineContext context = this.SubroutineContext; context != null; context = context.Tail)
{
if (context.Head.Three == "exit") { return true; }
if (context.Head.Three == "entry") { return true; }
if (context.Head.Three.StartsWith("after")) { return true; }
}
return false;
}
}
return false;
}
}
internal bool InsideInvariantOnExit
{
get {
if (this.Block.Subroutine.IsInvariant)
{
if (this.SubroutineContext != null)
{
for (SubroutineContext context = this.SubroutineContext; context != null; context = context.Tail)
{
if (context.Head.Three == "exit") { return true; }
if (context.Head.Three == "entry") { return false; }
if (context.Head.Three.StartsWith("after")) { return false; }
}
throw new NotImplementedException();
}
}
return false;
}
}
public bool InsideContract
{
get
{
Subroutine subr = this.Block.Subroutine;
if (subr.IsContract) return true;
return false;
}
}
public bool InsideOldManifestation
{
get
{
Subroutine subr = this.Block.Subroutine;
if (subr.IsOldValue)
{
for (SubroutineContext context = this.SubroutineContext; context != null; context = context.Tail)
{
if (context.Head.Three == "oldmanifest") return true;
}
}
return false;
}
}
public bool IsCompilerGenerated
{
get
{
if (this.Block.Subroutine.IsCompilerGenerated)
{
return true;
}
else
{
if (this.SubroutineContext != null)
{
for (SubroutineContext context = this.SubroutineContext; context != null; context = context.Tail)
{
if (context.Head.One.Subroutine.IsCompilerGenerated) return true;
}
}
}
return false;
}
}
public override bool Equals(object obj)
{
APC that = obj as APC;
if (that == null) return false;
return this.Index == that.Index && this.Block == that.Block && this.SubroutineContext == that.SubroutineContext;
}
public override int GetHashCode()
{
return this.Index + this.Block.Index;
}
}
|
[
"public",
"class",
"APC",
":",
"IEquatable",
"<",
"APC",
">",
"{",
"public",
"static",
"readonly",
"APC",
"Dummy",
"=",
"new",
"APC",
"(",
"null",
",",
"0",
",",
"null",
")",
";",
"public",
"readonly",
"CFGBlock",
"Block",
";",
"public",
"readonly",
"int",
"Index",
";",
"public",
"readonly",
"SubroutineContext",
"SubroutineContext",
";",
"public",
"APC",
"(",
"CFGBlock",
"block",
",",
"int",
"index",
",",
"SubroutineContext",
"subroutineContext",
")",
"{",
"this",
".",
"Block",
"=",
"block",
";",
"this",
".",
"Index",
"=",
"index",
";",
"this",
".",
"SubroutineContext",
"=",
"subroutineContext",
";",
"if",
"CHECK_RECURSIVE_APCS",
"for",
"(",
";",
"subroutineContext",
"!=",
"null",
";",
"subroutineContext",
"=",
"subroutineContext",
".",
"Tail",
")",
"{",
"Debug",
".",
"Assert",
"(",
"block",
".",
"Subroutine",
"!=",
"subroutineContext",
".",
"Head",
".",
"One",
".",
"Subroutine",
")",
";",
"}",
"endif",
"}",
"public",
"APC",
"Post",
"(",
")",
"{",
"if",
"(",
"this",
".",
"Index",
"<",
"this",
".",
"Block",
".",
"Count",
")",
"{",
"return",
"new",
"APC",
"(",
"this",
".",
"Block",
",",
"this",
".",
"Index",
"+",
"1",
",",
"this",
".",
"SubroutineContext",
")",
";",
"}",
"return",
"this",
";",
"}",
"public",
"static",
"APC",
"ForEnd",
"(",
"CFGBlock",
"block",
",",
"SubroutineContext",
"subroutineContext",
")",
"{",
"return",
"new",
"APC",
"(",
"block",
",",
"block",
".",
"Count",
",",
"subroutineContext",
")",
";",
"}",
"public",
"string",
"AlternateSourceContext",
"(",
")",
"{",
"return",
"String",
".",
"Format",
"(",
"\"",
"{0}[0x{1:x}]",
"\"",
",",
"this",
".",
"Block",
".",
"Subroutine",
".",
"Name",
",",
"this",
".",
"Block",
".",
"ILOffset",
"(",
"this",
")",
")",
";",
"}",
"public",
"bool",
"HasRealSourceContext",
"{",
"get",
"{",
"string",
"realSC",
"=",
"this",
".",
"Block",
".",
"SourceContext",
"(",
"this",
")",
";",
"return",
"realSC",
"!=",
"null",
";",
"}",
"}",
"public",
"string",
"PrimarySourceContext",
"(",
")",
"{",
"string",
"realSC",
"=",
"this",
".",
"Block",
".",
"SourceContext",
"(",
"this",
")",
";",
"if",
"(",
"realSC",
"!=",
"null",
")",
"return",
"realSC",
";",
"return",
"AlternateSourceContext",
"(",
")",
";",
"}",
"public",
"int",
"ILOffset",
"{",
"get",
"{",
"return",
"this",
".",
"Block",
".",
"ILOffset",
"(",
"this",
")",
";",
"}",
"}",
"private",
"APC",
"(",
"APC",
"from",
")",
"{",
"this",
".",
"Index",
"=",
"from",
".",
"Index",
";",
"this",
".",
"Block",
"=",
"from",
".",
"Block",
";",
"this",
".",
"SubroutineContext",
"=",
"null",
";",
"}",
"public",
"APC",
"WithoutContext",
"{",
"get",
"{",
"return",
"new",
"APC",
"(",
"this",
")",
";",
"}",
"}",
"public",
"static",
"void",
"ToString",
"(",
"StringBuilder",
"sb",
",",
"SubroutineContext",
"finallyContext",
")",
"{",
"bool",
"seenFirst",
"=",
"false",
";",
"while",
"(",
"finallyContext",
"!=",
"null",
")",
"{",
"if",
"(",
"!",
"seenFirst",
")",
"{",
"sb",
".",
"Append",
"(",
"\"",
" {",
"\"",
")",
";",
"seenFirst",
"=",
"true",
";",
"}",
"else",
"{",
"sb",
".",
"Append",
"(",
"\"",
", ",
"\"",
")",
";",
"}",
"sb",
".",
"AppendFormat",
"(",
"\"",
"(SR{2} {0},{1}) [{3}]",
"\"",
",",
"finallyContext",
".",
"Head",
".",
"One",
".",
"Index",
",",
"finallyContext",
".",
"Head",
".",
"Two",
".",
"Index",
",",
"finallyContext",
".",
"Head",
".",
"One",
".",
"Subroutine",
".",
"Id",
",",
"finallyContext",
".",
"Head",
".",
"Three",
")",
";",
"finallyContext",
"=",
"finallyContext",
".",
"Tail",
";",
"}",
"if",
"(",
"seenFirst",
")",
"{",
"sb",
".",
"Append",
"(",
"\"",
"}",
"\"",
")",
";",
"}",
"}",
"public",
"override",
"string",
"ToString",
"(",
")",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"sb",
".",
"Append",
"(",
"\"",
"[",
"\"",
")",
";",
"sb",
".",
"AppendFormat",
"(",
"\"",
"SR{2} {0},{1}",
"\"",
",",
"this",
".",
"Block",
".",
"Index",
",",
"this",
".",
"Index",
",",
"this",
".",
"Block",
".",
"Subroutine",
".",
"Id",
")",
";",
"ToString",
"(",
"sb",
",",
"this",
".",
"SubroutineContext",
")",
";",
"sb",
".",
"Append",
"(",
"\"",
"]",
"\"",
")",
";",
"return",
"sb",
".",
"ToString",
"(",
")",
";",
"}",
"region",
" IEquatable<APC> Members",
"public",
"bool",
"Equals",
"(",
"APC",
"that",
")",
"{",
"if",
"(",
"this",
".",
"Block",
"!=",
"that",
".",
"Block",
")",
"return",
"false",
";",
"if",
"(",
"this",
".",
"Index",
"!=",
"that",
".",
"Index",
")",
"return",
"false",
";",
"if",
"(",
"this",
".",
"SubroutineContext",
"!=",
"that",
".",
"SubroutineContext",
")",
"return",
"false",
";",
"return",
"true",
";",
"}",
"endregion",
"public",
"bool",
"InsideRequiresAtCallInsideContract",
"{",
"get",
"{",
"if",
"(",
"this",
".",
"Block",
".",
"Subroutine",
".",
"IsRequires",
")",
"{",
"if",
"(",
"this",
".",
"SubroutineContext",
"!=",
"null",
")",
"{",
"for",
"(",
"SubroutineContext",
"context",
"=",
"this",
".",
"SubroutineContext",
";",
"context",
"!=",
"null",
";",
"context",
"=",
"context",
".",
"Tail",
")",
"{",
"if",
"(",
"context",
".",
"Head",
".",
"Three",
"==",
"\"",
"entry",
"\"",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"context",
".",
"Head",
".",
"Three",
".",
"StartsWith",
"(",
"\"",
"before",
"\"",
")",
")",
"{",
"Subroutine",
"sub",
"=",
"context",
".",
"Head",
".",
"One",
".",
"Subroutine",
";",
"return",
"sub",
".",
"IsEnsuresOrOld",
"||",
"sub",
".",
"IsRequires",
"||",
"sub",
".",
"IsInvariant",
";",
"}",
"}",
"throw",
"new",
"NotImplementedException",
"(",
")",
";",
"}",
"}",
"return",
"false",
";",
"}",
"}",
"public",
"bool",
"InsideRequiresAtCall",
"{",
"get",
"{",
"if",
"(",
"this",
".",
"Block",
".",
"Subroutine",
".",
"IsRequires",
")",
"{",
"if",
"(",
"this",
".",
"SubroutineContext",
"!=",
"null",
")",
"{",
"for",
"(",
"SubroutineContext",
"context",
"=",
"this",
".",
"SubroutineContext",
";",
"context",
"!=",
"null",
";",
"context",
"=",
"context",
".",
"Tail",
")",
"{",
"if",
"(",
"context",
".",
"Head",
".",
"Three",
"==",
"\"",
"entry",
"\"",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"context",
".",
"Head",
".",
"Three",
".",
"StartsWith",
"(",
"\"",
"before",
"\"",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"throw",
"new",
"NotImplementedException",
"(",
")",
";",
"}",
"}",
"return",
"false",
";",
"}",
"}",
"public",
"bool",
"InsideEnsuresAtCall",
"{",
"get",
"{",
"if",
"(",
"this",
".",
"Block",
".",
"Subroutine",
".",
"IsEnsuresOrOld",
")",
"{",
"if",
"(",
"this",
".",
"SubroutineContext",
"!=",
"null",
")",
"{",
"for",
"(",
"SubroutineContext",
"context",
"=",
"this",
".",
"SubroutineContext",
";",
"context",
"!=",
"null",
";",
"context",
"=",
"context",
".",
"Tail",
")",
"{",
"if",
"(",
"context",
".",
"Head",
".",
"Three",
"==",
"\"",
"exit",
"\"",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"context",
".",
"Head",
".",
"Three",
"==",
"\"",
"oldmanifest",
"\"",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"context",
".",
"Head",
".",
"Three",
".",
"StartsWith",
"(",
"\"",
"after",
"\"",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"throw",
"new",
"NotImplementedException",
"(",
")",
";",
"}",
"}",
"return",
"false",
";",
"}",
"}",
"public",
"bool",
"InsideInvariantAtCall",
"{",
"get",
"{",
"if",
"(",
"this",
".",
"Block",
".",
"Subroutine",
".",
"IsInvariant",
")",
"{",
"if",
"(",
"this",
".",
"SubroutineContext",
"!=",
"null",
")",
"{",
"for",
"(",
"SubroutineContext",
"context",
"=",
"this",
".",
"SubroutineContext",
";",
"context",
"!=",
"null",
";",
"context",
"=",
"context",
".",
"Tail",
")",
"{",
"if",
"(",
"context",
".",
"Head",
".",
"Three",
"==",
"\"",
"exit",
"\"",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"context",
".",
"Head",
".",
"Three",
"==",
"\"",
"entry",
"\"",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"context",
".",
"Head",
".",
"Three",
".",
"StartsWith",
"(",
"\"",
"after",
"\"",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"throw",
"new",
"NotImplementedException",
"(",
")",
";",
"}",
"}",
"return",
"false",
";",
"}",
"}",
"public",
"bool",
"InsideInvariantInMethod",
"{",
"get",
"{",
"if",
"(",
"this",
".",
"Block",
".",
"Subroutine",
".",
"IsInvariant",
")",
"{",
"if",
"(",
"this",
".",
"SubroutineContext",
"!=",
"null",
")",
"{",
"for",
"(",
"SubroutineContext",
"context",
"=",
"this",
".",
"SubroutineContext",
";",
"context",
"!=",
"null",
";",
"context",
"=",
"context",
".",
"Tail",
")",
"{",
"if",
"(",
"context",
".",
"Head",
".",
"Three",
"==",
"\"",
"exit",
"\"",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"context",
".",
"Head",
".",
"Three",
"==",
"\"",
"entry",
"\"",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"context",
".",
"Head",
".",
"Three",
".",
"StartsWith",
"(",
"\"",
"after",
"\"",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}",
"}",
"return",
"false",
";",
"}",
"}",
"internal",
"bool",
"InsideInvariantOnExit",
"{",
"get",
"{",
"if",
"(",
"this",
".",
"Block",
".",
"Subroutine",
".",
"IsInvariant",
")",
"{",
"if",
"(",
"this",
".",
"SubroutineContext",
"!=",
"null",
")",
"{",
"for",
"(",
"SubroutineContext",
"context",
"=",
"this",
".",
"SubroutineContext",
";",
"context",
"!=",
"null",
";",
"context",
"=",
"context",
".",
"Tail",
")",
"{",
"if",
"(",
"context",
".",
"Head",
".",
"Three",
"==",
"\"",
"exit",
"\"",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"context",
".",
"Head",
".",
"Three",
"==",
"\"",
"entry",
"\"",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"context",
".",
"Head",
".",
"Three",
".",
"StartsWith",
"(",
"\"",
"after",
"\"",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"throw",
"new",
"NotImplementedException",
"(",
")",
";",
"}",
"}",
"return",
"false",
";",
"}",
"}",
"public",
"bool",
"InsideContract",
"{",
"get",
"{",
"Subroutine",
"subr",
"=",
"this",
".",
"Block",
".",
"Subroutine",
";",
"if",
"(",
"subr",
".",
"IsContract",
")",
"return",
"true",
";",
"return",
"false",
";",
"}",
"}",
"public",
"bool",
"InsideOldManifestation",
"{",
"get",
"{",
"Subroutine",
"subr",
"=",
"this",
".",
"Block",
".",
"Subroutine",
";",
"if",
"(",
"subr",
".",
"IsOldValue",
")",
"{",
"for",
"(",
"SubroutineContext",
"context",
"=",
"this",
".",
"SubroutineContext",
";",
"context",
"!=",
"null",
";",
"context",
"=",
"context",
".",
"Tail",
")",
"{",
"if",
"(",
"context",
".",
"Head",
".",
"Three",
"==",
"\"",
"oldmanifest",
"\"",
")",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}",
"}",
"public",
"bool",
"IsCompilerGenerated",
"{",
"get",
"{",
"if",
"(",
"this",
".",
"Block",
".",
"Subroutine",
".",
"IsCompilerGenerated",
")",
"{",
"return",
"true",
";",
"}",
"else",
"{",
"if",
"(",
"this",
".",
"SubroutineContext",
"!=",
"null",
")",
"{",
"for",
"(",
"SubroutineContext",
"context",
"=",
"this",
".",
"SubroutineContext",
";",
"context",
"!=",
"null",
";",
"context",
"=",
"context",
".",
"Tail",
")",
"{",
"if",
"(",
"context",
".",
"Head",
".",
"One",
".",
"Subroutine",
".",
"IsCompilerGenerated",
")",
"return",
"true",
";",
"}",
"}",
"}",
"return",
"false",
";",
"}",
"}",
"public",
"override",
"bool",
"Equals",
"(",
"object",
"obj",
")",
"{",
"APC",
"that",
"=",
"obj",
"as",
"APC",
";",
"if",
"(",
"that",
"==",
"null",
")",
"return",
"false",
";",
"return",
"this",
".",
"Index",
"==",
"that",
".",
"Index",
"&&",
"this",
".",
"Block",
"==",
"that",
".",
"Block",
"&&",
"this",
".",
"SubroutineContext",
"==",
"that",
".",
"SubroutineContext",
";",
"}",
"public",
"override",
"int",
"GetHashCode",
"(",
")",
"{",
"return",
"this",
".",
"Index",
"+",
"this",
".",
"Block",
".",
"Index",
";",
"}",
"}"
] |
An abstract program point representing a particular control point including possible finally continuations
|
[
"An",
"abstract",
"program",
"point",
"representing",
"a",
"particular",
"control",
"point",
"including",
"possible",
"finally",
"continuations"
] |
[
"/// <summary>",
"/// The logical block containing this abstract PC",
"/// </summary>",
"/// <summary>",
"/// The index within the block of this abstract PC",
"/// </summary>",
"/// <summary>",
"/// Fault/Finally edges. (from,to) that are currently being traversed.",
"/// The current block/index is executing on some handler of the first edge in the",
"/// finally edges. If the current handler ends(endfinally), the next handler on the",
"/// edge is retrieved and made the current program point. If no more handlers are on the",
"/// edge, the edge is popped and the target of the edge becomes the new current point.",
"/// NOTE: if the edge targets a catch/filter handler entry point, then fault handlers",
"/// are visited, otherwise only finally handlers.",
"/// </summary>",
"/*?*/",
"/// <summary>",
"/// Construct APC",
"/// </summary>",
"/*?*/",
"/// <summary>",
"/// Copy constructor that removes subroutine context",
"/// </summary>",
"//^ [StateIndependent]",
"// find if we are inside another contract"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 21
| 1,777
| 108
|
c1ddce0e9ed2c09a799183958bf4efef5c06ad67
|
GiorgioPaoletti-Unicam/Jbudget
|
src/test/java/it/unicam/cs/pa/jbudget105056/model/AccountImplementationTest.java
|
[
"MIT"
] |
Java
|
AccountImplementationTest
|
/**
* Test verificare il funzionamento della classe AccountImplementation
*
* @author Giorgio Paoletti
* [email protected]
* matricola: 105056
*
* @version Terza Consegna 18/07/2020
*
*/
|
Test verificare il funzionamento della classe AccountImplementation
|
[
"Test",
"verificare",
"il",
"funzionamento",
"della",
"classe",
"AccountImplementation"
] |
class AccountImplementationTest {
private static Account cassa;
private static Account contoBancario;
private static Account hype;
private static Account cartaDiDebito;
/**
* si occupa di creare le istanze degli account utilizzati nei test a seguire
*/
@BeforeEach
void BeforeEach() {
cassa = AccountImplementation.getInstance(AccountType.ASSETS, "Cassa", "Portafoglio Personale", 0);
contoBancario = AccountImplementation.getInstance(AccountType.ASSETS, "Conto Bancario", "Conto Bancario Personale", 2500);
hype = AccountImplementation.getInstance(AccountType.ASSETS, "HYPE", "Carta Prepagata", 500);
cartaDiDebito = AccountImplementation.getInstance(AccountType.LIABILITIES, "Carta di Debito", "Carta di Debito", 0);
}
/**
* si occupa di verificare il corretto comportamento dei metodi getIstance e getIstanceById
*/
@Test
void getIstance() {
Account cassaCopy = AccountImplementation.getInstance(AccountType.ASSETS, "Cassa", "Portafoglio Personale", 0);
assertEquals(cassa, cassaCopy);
Account cassaCopyByID = AccountImplementation.getInstanceByID(cassa.getID());
assertEquals(cassa, cassaCopyByID);
}
/**
* si occupa di verificare il corretto comportamento dei metodi addMovement in presenza di un account di tipo Assets
*/
@Test
void addMovementToAssetAccount() {
Movement cenaPizza = MovementImplementation.getInstance("Cena pizza", 12.50, MovementType.DEBIT);
//Movimento non appartiene a nessuna transazione
assertThrows(IllegalStateException.class, () -> cassa.addMovement(cenaPizza));
Transaction cenaPizzaTrans = TransactionImplementation.getInstance(new Date());
cenaPizzaTrans.addMovement(cenaPizza);
//Insufficient balance
assertThrows(IllegalStateException.class, () -> cassa.addMovement(cenaPizza));
cassa.addMovement(createRegaloNonnaMovement());
cassa.addMovement(cenaPizza);
assertEquals(37.50, cassa.getBalance());
}
/**
* si occupa di verificare il corretto comportamento dei metodi addMovement in presenza di un account di tipo Liabilities
*/
@Test
void addMovementToLiabilitiesAccount() {
Movement stivaliNuovi = MovementImplementation.getInstance("Stivali Nuovi", 69.99, MovementType.DEBIT);
Transaction stivaliNuoviTrans = TransactionImplementation.getInstance(new Date());
stivaliNuoviTrans.addMovement(stivaliNuovi);
cartaDiDebito.addMovement(stivaliNuovi);
assertEquals(cartaDiDebito.getBalance(), -69.99);
//non posso aggiungere movimenti di tipo CREDIT a un Account LIABILITIES
assertThrows(IllegalStateException.class, () -> cartaDiDebito.addMovement(createRegaloNonnaMovement()));
}
/**
* si occupa di vicare il corretto funzionamento del metodo getMovements a cui viene passato un predicato
*/
@Test
void getMovementsByPredicate() {
Movement regaloNonna = createRegaloNonnaMovement();
cassa.addMovement(regaloNonna);
assertEquals(cassa.getMovements(m -> m.getID() == regaloNonna.getID()).get(0), regaloNonna);
}
/**
* si occupa di verificare il corretto funzionamento del metodo removeMovement
*/
@Test
void removeMovement() {
Movement regaloNonna = createRegaloNonnaMovement();
cassa.addMovement(regaloNonna);
cassa.removeMovement(MovementImplementation.getInstanceByID(regaloNonna.getID()));
assertTrue(cassa.getMovements().isEmpty());
assertEquals(0.00, cassa.getBalance());
}
/**
*
* @return Movimento giocattolo per i test
*/
Movement createRegaloNonnaMovement() {
Movement regaloNonna = MovementImplementation.getInstance("Regalo Nonna", 50.00, MovementType.CREDITS);
Transaction regaloNonnaTrans = TransactionImplementation.getInstance(new Date());
regaloNonnaTrans.addMovement(regaloNonna);
return regaloNonna;
}
}
|
[
"class",
"AccountImplementationTest",
"{",
"private",
"static",
"Account",
"cassa",
";",
"private",
"static",
"Account",
"contoBancario",
";",
"private",
"static",
"Account",
"hype",
";",
"private",
"static",
"Account",
"cartaDiDebito",
";",
"/**\r\n * si occupa di creare le istanze degli account utilizzati nei test a seguire\r\n */",
"@",
"BeforeEach",
"void",
"BeforeEach",
"(",
")",
"{",
"cassa",
"=",
"AccountImplementation",
".",
"getInstance",
"(",
"AccountType",
".",
"ASSETS",
",",
"\"",
"Cassa",
"\"",
",",
"\"",
"Portafoglio Personale",
"\"",
",",
"0",
")",
";",
"contoBancario",
"=",
"AccountImplementation",
".",
"getInstance",
"(",
"AccountType",
".",
"ASSETS",
",",
"\"",
"Conto Bancario",
"\"",
",",
"\"",
"Conto Bancario Personale",
"\"",
",",
"2500",
")",
";",
"hype",
"=",
"AccountImplementation",
".",
"getInstance",
"(",
"AccountType",
".",
"ASSETS",
",",
"\"",
"HYPE",
"\"",
",",
"\"",
"Carta Prepagata",
"\"",
",",
"500",
")",
";",
"cartaDiDebito",
"=",
"AccountImplementation",
".",
"getInstance",
"(",
"AccountType",
".",
"LIABILITIES",
",",
"\"",
"Carta di Debito",
"\"",
",",
"\"",
"Carta di Debito",
"\"",
",",
"0",
")",
";",
"}",
"/**\r\n * si occupa di verificare il corretto comportamento dei metodi getIstance e getIstanceById\r\n */",
"@",
"Test",
"void",
"getIstance",
"(",
")",
"{",
"Account",
"cassaCopy",
"=",
"AccountImplementation",
".",
"getInstance",
"(",
"AccountType",
".",
"ASSETS",
",",
"\"",
"Cassa",
"\"",
",",
"\"",
"Portafoglio Personale",
"\"",
",",
"0",
")",
";",
"assertEquals",
"(",
"cassa",
",",
"cassaCopy",
")",
";",
"Account",
"cassaCopyByID",
"=",
"AccountImplementation",
".",
"getInstanceByID",
"(",
"cassa",
".",
"getID",
"(",
")",
")",
";",
"assertEquals",
"(",
"cassa",
",",
"cassaCopyByID",
")",
";",
"}",
"/**\r\n * si occupa di verificare il corretto comportamento dei metodi addMovement in presenza di un account di tipo Assets\r\n */",
"@",
"Test",
"void",
"addMovementToAssetAccount",
"(",
")",
"{",
"Movement",
"cenaPizza",
"=",
"MovementImplementation",
".",
"getInstance",
"(",
"\"",
"Cena pizza",
"\"",
",",
"12.50",
",",
"MovementType",
".",
"DEBIT",
")",
";",
"assertThrows",
"(",
"IllegalStateException",
".",
"class",
",",
"(",
")",
"->",
"cassa",
".",
"addMovement",
"(",
"cenaPizza",
")",
")",
";",
"Transaction",
"cenaPizzaTrans",
"=",
"TransactionImplementation",
".",
"getInstance",
"(",
"new",
"Date",
"(",
")",
")",
";",
"cenaPizzaTrans",
".",
"addMovement",
"(",
"cenaPizza",
")",
";",
"assertThrows",
"(",
"IllegalStateException",
".",
"class",
",",
"(",
")",
"->",
"cassa",
".",
"addMovement",
"(",
"cenaPizza",
")",
")",
";",
"cassa",
".",
"addMovement",
"(",
"createRegaloNonnaMovement",
"(",
")",
")",
";",
"cassa",
".",
"addMovement",
"(",
"cenaPizza",
")",
";",
"assertEquals",
"(",
"37.50",
",",
"cassa",
".",
"getBalance",
"(",
")",
")",
";",
"}",
"/**\r\n * si occupa di verificare il corretto comportamento dei metodi addMovement in presenza di un account di tipo Liabilities\r\n */",
"@",
"Test",
"void",
"addMovementToLiabilitiesAccount",
"(",
")",
"{",
"Movement",
"stivaliNuovi",
"=",
"MovementImplementation",
".",
"getInstance",
"(",
"\"",
"Stivali Nuovi",
"\"",
",",
"69.99",
",",
"MovementType",
".",
"DEBIT",
")",
";",
"Transaction",
"stivaliNuoviTrans",
"=",
"TransactionImplementation",
".",
"getInstance",
"(",
"new",
"Date",
"(",
")",
")",
";",
"stivaliNuoviTrans",
".",
"addMovement",
"(",
"stivaliNuovi",
")",
";",
"cartaDiDebito",
".",
"addMovement",
"(",
"stivaliNuovi",
")",
";",
"assertEquals",
"(",
"cartaDiDebito",
".",
"getBalance",
"(",
")",
",",
"-",
"69.99",
")",
";",
"assertThrows",
"(",
"IllegalStateException",
".",
"class",
",",
"(",
")",
"->",
"cartaDiDebito",
".",
"addMovement",
"(",
"createRegaloNonnaMovement",
"(",
")",
")",
")",
";",
"}",
"/**\r\n * si occupa di vicare il corretto funzionamento del metodo getMovements a cui viene passato un predicato\r\n */",
"@",
"Test",
"void",
"getMovementsByPredicate",
"(",
")",
"{",
"Movement",
"regaloNonna",
"=",
"createRegaloNonnaMovement",
"(",
")",
";",
"cassa",
".",
"addMovement",
"(",
"regaloNonna",
")",
";",
"assertEquals",
"(",
"cassa",
".",
"getMovements",
"(",
"m",
"->",
"m",
".",
"getID",
"(",
")",
"==",
"regaloNonna",
".",
"getID",
"(",
")",
")",
".",
"get",
"(",
"0",
")",
",",
"regaloNonna",
")",
";",
"}",
"/**\r\n * si occupa di verificare il corretto funzionamento del metodo removeMovement\r\n */",
"@",
"Test",
"void",
"removeMovement",
"(",
")",
"{",
"Movement",
"regaloNonna",
"=",
"createRegaloNonnaMovement",
"(",
")",
";",
"cassa",
".",
"addMovement",
"(",
"regaloNonna",
")",
";",
"cassa",
".",
"removeMovement",
"(",
"MovementImplementation",
".",
"getInstanceByID",
"(",
"regaloNonna",
".",
"getID",
"(",
")",
")",
")",
";",
"assertTrue",
"(",
"cassa",
".",
"getMovements",
"(",
")",
".",
"isEmpty",
"(",
")",
")",
";",
"assertEquals",
"(",
"0.00",
",",
"cassa",
".",
"getBalance",
"(",
")",
")",
";",
"}",
"/**\r\n *\r\n * @return Movimento giocattolo per i test\r\n */",
"Movement",
"createRegaloNonnaMovement",
"(",
")",
"{",
"Movement",
"regaloNonna",
"=",
"MovementImplementation",
".",
"getInstance",
"(",
"\"",
"Regalo Nonna",
"\"",
",",
"50.00",
",",
"MovementType",
".",
"CREDITS",
")",
";",
"Transaction",
"regaloNonnaTrans",
"=",
"TransactionImplementation",
".",
"getInstance",
"(",
"new",
"Date",
"(",
")",
")",
";",
"regaloNonnaTrans",
".",
"addMovement",
"(",
"regaloNonna",
")",
";",
"return",
"regaloNonna",
";",
"}",
"}"
] |
Test verificare il funzionamento della classe AccountImplementation
|
[
"Test",
"verificare",
"il",
"funzionamento",
"della",
"classe",
"AccountImplementation"
] |
[
"//Movimento non appartiene a nessuna transazione\r",
"//Insufficient balance\r",
"//non posso aggiungere movimenti di tipo CREDIT a un Account LIABILITIES\r"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 15
| 986
| 82
|
eb83948be3185adf9e2c628d5e3aea99556954d1
|
Sarafossati/ACME-new
|
node_modules/@stencil/core/cli/index.js
|
[
"MIT"
] |
JavaScript
|
AutocompletePrompt
|
/**
* TextPrompt Base Element
* @param {Object} opts Options
* @param {String} opts.message Message
* @param {Array} opts.choices Array of auto-complete choices objects
* @param {Function} [opts.suggest] Filter function. Defaults to sort by title
* @param {Number} [opts.limit=10] Max number of results to show
* @param {Number} [opts.cursor=0] Cursor start position
* @param {String} [opts.style='default'] Render style
* @param {String} [opts.fallback] Fallback message - initial to default value
* @param {String} [opts.initial] Index of the default value
* @param {Stream} [opts.stdin] The Readable stream to listen to
* @param {Stream} [opts.stdout] The Writable stream to write readline data to
* @param {String} [opts.noMatches] The no matches found label
*/
|
TextPrompt Base Element
@param {Object} opts Options
@param {String} opts.message Message
@param {Array} opts.choices Array of auto-complete choices objects
@param {Function} [opts.suggest] Filter function.
|
[
"TextPrompt",
"Base",
"Element",
"@param",
"{",
"Object",
"}",
"opts",
"Options",
"@param",
"{",
"String",
"}",
"opts",
".",
"message",
"Message",
"@param",
"{",
"Array",
"}",
"opts",
".",
"choices",
"Array",
"of",
"auto",
"-",
"complete",
"choices",
"objects",
"@param",
"{",
"Function",
"}",
"[",
"opts",
".",
"suggest",
"]",
"Filter",
"function",
"."
] |
class AutocompletePrompt extends prompt {
constructor(opts = {}) {
super(opts);
this.msg = opts.message;
this.suggest = opts.suggest;
this.choices = opts.choices;
this.initial = typeof opts.initial === 'number' ? opts.initial : getIndex(opts.choices, opts.initial);
this.select = this.initial || opts.cursor || 0;
this.i18n = {
noMatches: opts.noMatches || 'no matches found'
};
this.fallback = opts.fallback || this.initial;
this.suggestions = [];
this.input = '';
this.limit = opts.limit || 10;
this.cursor = 0;
this.transform = style$7.render(opts.style);
this.scale = this.transform.scale;
this.render = this.render.bind(this);
this.complete = this.complete.bind(this);
this.clear = clear$7('');
this.complete(this.render);
this.render();
}
set fallback(fb) {
this._fb = Number.isSafeInteger(parseInt(fb)) ? parseInt(fb) : fb;
}
get fallback() {
let choice;
if (typeof this._fb === 'number') choice = this.choices[this._fb];else if (typeof this._fb === 'string') choice = {
title: this._fb
};
return choice || this._fb || {
title: this.i18n.noMatches
};
}
moveSelect(i) {
this.select = i;
if (this.suggestions.length > 0) this.value = getVal(this.suggestions, i);else this.value = this.fallback.value;
this.fire();
}
complete(cb) {
var _this = this;
return _asyncToGenerator$3(function* () {
const p = _this.completing = _this.suggest(_this.input, _this.choices);
const suggestions = yield p;
if (_this.completing !== p) return;
_this.suggestions = suggestions.map((s, i, arr) => ({
title: getTitle(arr, i),
value: getVal(arr, i),
description: s.description
}));
_this.completing = false;
const l = Math.max(suggestions.length - 1, 0);
_this.moveSelect(Math.min(l, _this.select));
cb && cb();
})();
}
reset() {
this.input = '';
this.complete(() => {
this.moveSelect(this.initial !== void 0 ? this.initial : 0);
this.render();
});
this.render();
}
abort() {
this.done = this.aborted = true;
this.fire();
this.render();
this.out.write('\n');
this.close();
}
submit() {
this.done = true;
this.aborted = false;
this.fire();
this.render();
this.out.write('\n');
this.close();
}
_(c, key) {
let s1 = this.input.slice(0, this.cursor);
let s2 = this.input.slice(this.cursor);
this.input = `${s1}${c}${s2}`;
this.cursor = s1.length + 1;
this.complete(this.render);
this.render();
}
delete() {
if (this.cursor === 0) return this.bell();
let s1 = this.input.slice(0, this.cursor - 1);
let s2 = this.input.slice(this.cursor);
this.input = `${s1}${s2}`;
this.complete(this.render);
this.cursor = this.cursor - 1;
this.render();
}
deleteForward() {
if (this.cursor * this.scale >= this.rendered.length) return this.bell();
let s1 = this.input.slice(0, this.cursor);
let s2 = this.input.slice(this.cursor + 1);
this.input = `${s1}${s2}`;
this.complete(this.render);
this.render();
}
first() {
this.moveSelect(0);
this.render();
}
last() {
this.moveSelect(this.suggestions.length - 1);
this.render();
}
up() {
if (this.select <= 0) return this.bell();
this.moveSelect(this.select - 1);
this.render();
}
down() {
if (this.select >= this.suggestions.length - 1) return this.bell();
this.moveSelect(this.select + 1);
this.render();
}
next() {
if (this.select === this.suggestions.length - 1) {
this.moveSelect(0);
} else this.moveSelect(this.select + 1);
this.render();
}
nextPage() {
this.moveSelect(Math.min(this.select + this.limit, this.suggestions.length - 1));
this.render();
}
prevPage() {
this.moveSelect(Math.max(this.select - this.limit, 0));
this.render();
}
left() {
if (this.cursor <= 0) return this.bell();
this.cursor = this.cursor - 1;
this.render();
}
right() {
if (this.cursor * this.scale >= this.rendered.length) return this.bell();
this.cursor = this.cursor + 1;
this.render();
}
renderOption(v, hovered, isStart, isEnd) {
let desc;
let prefix = isStart ? figures$6.arrowUp : isEnd ? figures$6.arrowDown : ' ';
let title = hovered ? kleur.cyan().underline(v.title) : v.title;
prefix = (hovered ? kleur.cyan(figures$6.pointer) + ' ' : ' ') + prefix;
if (v.description) {
desc = ` - ${v.description}`;
if (prefix.length + title.length + desc.length >= this.out.columns || v.description.split(/\r?\n/).length > 1) {
desc = '\n' + wrap$3(v.description, {
margin: 3,
width: this.out.columns
});
}
}
return prefix + ' ' + title + kleur.gray(desc || '');
}
render() {
if (this.closed) return;
if (this.firstRender) this.out.write(cursor$9.hide);else this.out.write(clear$7(this.outputText));
super.render();
let _entriesToDisplay = entriesToDisplay$3(this.select, this.choices.length, this.limit),
startIndex = _entriesToDisplay.startIndex,
endIndex = _entriesToDisplay.endIndex;
this.outputText = [style$7.symbol(this.done, this.aborted), kleur.bold(this.msg), style$7.delimiter(this.completing), this.done && this.suggestions[this.select] ? this.suggestions[this.select].title : this.rendered = this.transform.render(this.input)].join(' ');
if (!this.done) {
const suggestions = this.suggestions.slice(startIndex, endIndex).map((item, i) => this.renderOption(item, this.select === i + startIndex, i === 0 && startIndex > 0, i + startIndex === endIndex - 1 && endIndex < this.choices.length)).join('\n');
this.outputText += `\n` + (suggestions || kleur.gray(this.fallback.title));
}
this.out.write(erase$6.line + cursor$9.to(0) + this.outputText);
}
}
|
[
"class",
"AutocompletePrompt",
"extends",
"prompt",
"{",
"constructor",
"(",
"opts",
"=",
"{",
"}",
")",
"{",
"super",
"(",
"opts",
")",
";",
"this",
".",
"msg",
"=",
"opts",
".",
"message",
";",
"this",
".",
"suggest",
"=",
"opts",
".",
"suggest",
";",
"this",
".",
"choices",
"=",
"opts",
".",
"choices",
";",
"this",
".",
"initial",
"=",
"typeof",
"opts",
".",
"initial",
"===",
"'number'",
"?",
"opts",
".",
"initial",
":",
"getIndex",
"(",
"opts",
".",
"choices",
",",
"opts",
".",
"initial",
")",
";",
"this",
".",
"select",
"=",
"this",
".",
"initial",
"||",
"opts",
".",
"cursor",
"||",
"0",
";",
"this",
".",
"i18n",
"=",
"{",
"noMatches",
":",
"opts",
".",
"noMatches",
"||",
"'no matches found'",
"}",
";",
"this",
".",
"fallback",
"=",
"opts",
".",
"fallback",
"||",
"this",
".",
"initial",
";",
"this",
".",
"suggestions",
"=",
"[",
"]",
";",
"this",
".",
"input",
"=",
"''",
";",
"this",
".",
"limit",
"=",
"opts",
".",
"limit",
"||",
"10",
";",
"this",
".",
"cursor",
"=",
"0",
";",
"this",
".",
"transform",
"=",
"style$7",
".",
"render",
"(",
"opts",
".",
"style",
")",
";",
"this",
".",
"scale",
"=",
"this",
".",
"transform",
".",
"scale",
";",
"this",
".",
"render",
"=",
"this",
".",
"render",
".",
"bind",
"(",
"this",
")",
";",
"this",
".",
"complete",
"=",
"this",
".",
"complete",
".",
"bind",
"(",
"this",
")",
";",
"this",
".",
"clear",
"=",
"clear$7",
"(",
"''",
")",
";",
"this",
".",
"complete",
"(",
"this",
".",
"render",
")",
";",
"this",
".",
"render",
"(",
")",
";",
"}",
"set",
"fallback",
"(",
"fb",
")",
"{",
"this",
".",
"_fb",
"=",
"Number",
".",
"isSafeInteger",
"(",
"parseInt",
"(",
"fb",
")",
")",
"?",
"parseInt",
"(",
"fb",
")",
":",
"fb",
";",
"}",
"get",
"fallback",
"(",
")",
"{",
"let",
"choice",
";",
"if",
"(",
"typeof",
"this",
".",
"_fb",
"===",
"'number'",
")",
"choice",
"=",
"this",
".",
"choices",
"[",
"this",
".",
"_fb",
"]",
";",
"else",
"if",
"(",
"typeof",
"this",
".",
"_fb",
"===",
"'string'",
")",
"choice",
"=",
"{",
"title",
":",
"this",
".",
"_fb",
"}",
";",
"return",
"choice",
"||",
"this",
".",
"_fb",
"||",
"{",
"title",
":",
"this",
".",
"i18n",
".",
"noMatches",
"}",
";",
"}",
"moveSelect",
"(",
"i",
")",
"{",
"this",
".",
"select",
"=",
"i",
";",
"if",
"(",
"this",
".",
"suggestions",
".",
"length",
">",
"0",
")",
"this",
".",
"value",
"=",
"getVal",
"(",
"this",
".",
"suggestions",
",",
"i",
")",
";",
"else",
"this",
".",
"value",
"=",
"this",
".",
"fallback",
".",
"value",
";",
"this",
".",
"fire",
"(",
")",
";",
"}",
"complete",
"(",
"cb",
")",
"{",
"var",
"_this",
"=",
"this",
";",
"return",
"_asyncToGenerator$3",
"(",
"function",
"*",
"(",
")",
"{",
"const",
"p",
"=",
"_this",
".",
"completing",
"=",
"_this",
".",
"suggest",
"(",
"_this",
".",
"input",
",",
"_this",
".",
"choices",
")",
";",
"const",
"suggestions",
"=",
"yield",
"p",
";",
"if",
"(",
"_this",
".",
"completing",
"!==",
"p",
")",
"return",
";",
"_this",
".",
"suggestions",
"=",
"suggestions",
".",
"map",
"(",
"(",
"s",
",",
"i",
",",
"arr",
")",
"=>",
"(",
"{",
"title",
":",
"getTitle",
"(",
"arr",
",",
"i",
")",
",",
"value",
":",
"getVal",
"(",
"arr",
",",
"i",
")",
",",
"description",
":",
"s",
".",
"description",
"}",
")",
")",
";",
"_this",
".",
"completing",
"=",
"false",
";",
"const",
"l",
"=",
"Math",
".",
"max",
"(",
"suggestions",
".",
"length",
"-",
"1",
",",
"0",
")",
";",
"_this",
".",
"moveSelect",
"(",
"Math",
".",
"min",
"(",
"l",
",",
"_this",
".",
"select",
")",
")",
";",
"cb",
"&&",
"cb",
"(",
")",
";",
"}",
")",
"(",
")",
";",
"}",
"reset",
"(",
")",
"{",
"this",
".",
"input",
"=",
"''",
";",
"this",
".",
"complete",
"(",
"(",
")",
"=>",
"{",
"this",
".",
"moveSelect",
"(",
"this",
".",
"initial",
"!==",
"void",
"0",
"?",
"this",
".",
"initial",
":",
"0",
")",
";",
"this",
".",
"render",
"(",
")",
";",
"}",
")",
";",
"this",
".",
"render",
"(",
")",
";",
"}",
"abort",
"(",
")",
"{",
"this",
".",
"done",
"=",
"this",
".",
"aborted",
"=",
"true",
";",
"this",
".",
"fire",
"(",
")",
";",
"this",
".",
"render",
"(",
")",
";",
"this",
".",
"out",
".",
"write",
"(",
"'\\n'",
")",
";",
"this",
".",
"close",
"(",
")",
";",
"}",
"submit",
"(",
")",
"{",
"this",
".",
"done",
"=",
"true",
";",
"this",
".",
"aborted",
"=",
"false",
";",
"this",
".",
"fire",
"(",
")",
";",
"this",
".",
"render",
"(",
")",
";",
"this",
".",
"out",
".",
"write",
"(",
"'\\n'",
")",
";",
"this",
".",
"close",
"(",
")",
";",
"}",
"_",
"(",
"c",
",",
"key",
")",
"{",
"let",
"s1",
"=",
"this",
".",
"input",
".",
"slice",
"(",
"0",
",",
"this",
".",
"cursor",
")",
";",
"let",
"s2",
"=",
"this",
".",
"input",
".",
"slice",
"(",
"this",
".",
"cursor",
")",
";",
"this",
".",
"input",
"=",
"`",
"${",
"s1",
"}",
"${",
"c",
"}",
"${",
"s2",
"}",
"`",
";",
"this",
".",
"cursor",
"=",
"s1",
".",
"length",
"+",
"1",
";",
"this",
".",
"complete",
"(",
"this",
".",
"render",
")",
";",
"this",
".",
"render",
"(",
")",
";",
"}",
"delete",
"(",
")",
"{",
"if",
"(",
"this",
".",
"cursor",
"===",
"0",
")",
"return",
"this",
".",
"bell",
"(",
")",
";",
"let",
"s1",
"=",
"this",
".",
"input",
".",
"slice",
"(",
"0",
",",
"this",
".",
"cursor",
"-",
"1",
")",
";",
"let",
"s2",
"=",
"this",
".",
"input",
".",
"slice",
"(",
"this",
".",
"cursor",
")",
";",
"this",
".",
"input",
"=",
"`",
"${",
"s1",
"}",
"${",
"s2",
"}",
"`",
";",
"this",
".",
"complete",
"(",
"this",
".",
"render",
")",
";",
"this",
".",
"cursor",
"=",
"this",
".",
"cursor",
"-",
"1",
";",
"this",
".",
"render",
"(",
")",
";",
"}",
"deleteForward",
"(",
")",
"{",
"if",
"(",
"this",
".",
"cursor",
"*",
"this",
".",
"scale",
">=",
"this",
".",
"rendered",
".",
"length",
")",
"return",
"this",
".",
"bell",
"(",
")",
";",
"let",
"s1",
"=",
"this",
".",
"input",
".",
"slice",
"(",
"0",
",",
"this",
".",
"cursor",
")",
";",
"let",
"s2",
"=",
"this",
".",
"input",
".",
"slice",
"(",
"this",
".",
"cursor",
"+",
"1",
")",
";",
"this",
".",
"input",
"=",
"`",
"${",
"s1",
"}",
"${",
"s2",
"}",
"`",
";",
"this",
".",
"complete",
"(",
"this",
".",
"render",
")",
";",
"this",
".",
"render",
"(",
")",
";",
"}",
"first",
"(",
")",
"{",
"this",
".",
"moveSelect",
"(",
"0",
")",
";",
"this",
".",
"render",
"(",
")",
";",
"}",
"last",
"(",
")",
"{",
"this",
".",
"moveSelect",
"(",
"this",
".",
"suggestions",
".",
"length",
"-",
"1",
")",
";",
"this",
".",
"render",
"(",
")",
";",
"}",
"up",
"(",
")",
"{",
"if",
"(",
"this",
".",
"select",
"<=",
"0",
")",
"return",
"this",
".",
"bell",
"(",
")",
";",
"this",
".",
"moveSelect",
"(",
"this",
".",
"select",
"-",
"1",
")",
";",
"this",
".",
"render",
"(",
")",
";",
"}",
"down",
"(",
")",
"{",
"if",
"(",
"this",
".",
"select",
">=",
"this",
".",
"suggestions",
".",
"length",
"-",
"1",
")",
"return",
"this",
".",
"bell",
"(",
")",
";",
"this",
".",
"moveSelect",
"(",
"this",
".",
"select",
"+",
"1",
")",
";",
"this",
".",
"render",
"(",
")",
";",
"}",
"next",
"(",
")",
"{",
"if",
"(",
"this",
".",
"select",
"===",
"this",
".",
"suggestions",
".",
"length",
"-",
"1",
")",
"{",
"this",
".",
"moveSelect",
"(",
"0",
")",
";",
"}",
"else",
"this",
".",
"moveSelect",
"(",
"this",
".",
"select",
"+",
"1",
")",
";",
"this",
".",
"render",
"(",
")",
";",
"}",
"nextPage",
"(",
")",
"{",
"this",
".",
"moveSelect",
"(",
"Math",
".",
"min",
"(",
"this",
".",
"select",
"+",
"this",
".",
"limit",
",",
"this",
".",
"suggestions",
".",
"length",
"-",
"1",
")",
")",
";",
"this",
".",
"render",
"(",
")",
";",
"}",
"prevPage",
"(",
")",
"{",
"this",
".",
"moveSelect",
"(",
"Math",
".",
"max",
"(",
"this",
".",
"select",
"-",
"this",
".",
"limit",
",",
"0",
")",
")",
";",
"this",
".",
"render",
"(",
")",
";",
"}",
"left",
"(",
")",
"{",
"if",
"(",
"this",
".",
"cursor",
"<=",
"0",
")",
"return",
"this",
".",
"bell",
"(",
")",
";",
"this",
".",
"cursor",
"=",
"this",
".",
"cursor",
"-",
"1",
";",
"this",
".",
"render",
"(",
")",
";",
"}",
"right",
"(",
")",
"{",
"if",
"(",
"this",
".",
"cursor",
"*",
"this",
".",
"scale",
">=",
"this",
".",
"rendered",
".",
"length",
")",
"return",
"this",
".",
"bell",
"(",
")",
";",
"this",
".",
"cursor",
"=",
"this",
".",
"cursor",
"+",
"1",
";",
"this",
".",
"render",
"(",
")",
";",
"}",
"renderOption",
"(",
"v",
",",
"hovered",
",",
"isStart",
",",
"isEnd",
")",
"{",
"let",
"desc",
";",
"let",
"prefix",
"=",
"isStart",
"?",
"figures$6",
".",
"arrowUp",
":",
"isEnd",
"?",
"figures$6",
".",
"arrowDown",
":",
"' '",
";",
"let",
"title",
"=",
"hovered",
"?",
"kleur",
".",
"cyan",
"(",
")",
".",
"underline",
"(",
"v",
".",
"title",
")",
":",
"v",
".",
"title",
";",
"prefix",
"=",
"(",
"hovered",
"?",
"kleur",
".",
"cyan",
"(",
"figures$6",
".",
"pointer",
")",
"+",
"' '",
":",
"' '",
")",
"+",
"prefix",
";",
"if",
"(",
"v",
".",
"description",
")",
"{",
"desc",
"=",
"`",
"${",
"v",
".",
"description",
"}",
"`",
";",
"if",
"(",
"prefix",
".",
"length",
"+",
"title",
".",
"length",
"+",
"desc",
".",
"length",
">=",
"this",
".",
"out",
".",
"columns",
"||",
"v",
".",
"description",
".",
"split",
"(",
"/",
"\\r?\\n",
"/",
")",
".",
"length",
">",
"1",
")",
"{",
"desc",
"=",
"'\\n'",
"+",
"wrap$3",
"(",
"v",
".",
"description",
",",
"{",
"margin",
":",
"3",
",",
"width",
":",
"this",
".",
"out",
".",
"columns",
"}",
")",
";",
"}",
"}",
"return",
"prefix",
"+",
"' '",
"+",
"title",
"+",
"kleur",
".",
"gray",
"(",
"desc",
"||",
"''",
")",
";",
"}",
"render",
"(",
")",
"{",
"if",
"(",
"this",
".",
"closed",
")",
"return",
";",
"if",
"(",
"this",
".",
"firstRender",
")",
"this",
".",
"out",
".",
"write",
"(",
"cursor$9",
".",
"hide",
")",
";",
"else",
"this",
".",
"out",
".",
"write",
"(",
"clear$7",
"(",
"this",
".",
"outputText",
")",
")",
";",
"super",
".",
"render",
"(",
")",
";",
"let",
"_entriesToDisplay",
"=",
"entriesToDisplay$3",
"(",
"this",
".",
"select",
",",
"this",
".",
"choices",
".",
"length",
",",
"this",
".",
"limit",
")",
",",
"startIndex",
"=",
"_entriesToDisplay",
".",
"startIndex",
",",
"endIndex",
"=",
"_entriesToDisplay",
".",
"endIndex",
";",
"this",
".",
"outputText",
"=",
"[",
"style$7",
".",
"symbol",
"(",
"this",
".",
"done",
",",
"this",
".",
"aborted",
")",
",",
"kleur",
".",
"bold",
"(",
"this",
".",
"msg",
")",
",",
"style$7",
".",
"delimiter",
"(",
"this",
".",
"completing",
")",
",",
"this",
".",
"done",
"&&",
"this",
".",
"suggestions",
"[",
"this",
".",
"select",
"]",
"?",
"this",
".",
"suggestions",
"[",
"this",
".",
"select",
"]",
".",
"title",
":",
"this",
".",
"rendered",
"=",
"this",
".",
"transform",
".",
"render",
"(",
"this",
".",
"input",
")",
"]",
".",
"join",
"(",
"' '",
")",
";",
"if",
"(",
"!",
"this",
".",
"done",
")",
"{",
"const",
"suggestions",
"=",
"this",
".",
"suggestions",
".",
"slice",
"(",
"startIndex",
",",
"endIndex",
")",
".",
"map",
"(",
"(",
"item",
",",
"i",
")",
"=>",
"this",
".",
"renderOption",
"(",
"item",
",",
"this",
".",
"select",
"===",
"i",
"+",
"startIndex",
",",
"i",
"===",
"0",
"&&",
"startIndex",
">",
"0",
",",
"i",
"+",
"startIndex",
"===",
"endIndex",
"-",
"1",
"&&",
"endIndex",
"<",
"this",
".",
"choices",
".",
"length",
")",
")",
".",
"join",
"(",
"'\\n'",
")",
";",
"this",
".",
"outputText",
"+=",
"`",
"\\n",
"`",
"+",
"(",
"suggestions",
"||",
"kleur",
".",
"gray",
"(",
"this",
".",
"fallback",
".",
"title",
")",
")",
";",
"}",
"this",
".",
"out",
".",
"write",
"(",
"erase$6",
".",
"line",
"+",
"cursor$9",
".",
"to",
"(",
"0",
")",
"+",
"this",
".",
"outputText",
")",
";",
"}",
"}"
] |
TextPrompt Base Element
@param {Object} opts Options
@param {String} opts.message Message
@param {Array} opts.choices Array of auto-complete choices objects
@param {Function} [opts.suggest] Filter function.
|
[
"TextPrompt",
"Base",
"Element",
"@param",
"{",
"Object",
"}",
"opts",
"Options",
"@param",
"{",
"String",
"}",
"opts",
".",
"message",
"Message",
"@param",
"{",
"Array",
"}",
"opts",
".",
"choices",
"Array",
"of",
"auto",
"-",
"complete",
"choices",
"objects",
"@param",
"{",
"Function",
"}",
"[",
"opts",
".",
"suggest",
"]",
"Filter",
"function",
"."
] |
[] |
[
{
"param": "prompt",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "prompt",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 21
| 1,575
| 204
|
27fc931812083a5a39e8b070ab929e2b93b01c5d
|
ani03sha/Leetcoding
|
may-2021-leetcoding-challenge/src/main/java/org/redquark/leetcode/challenge/Problem09_ConstructTargetArrayWithMultipleSums.java
|
[
"MIT"
] |
Java
|
Problem09_ConstructTargetArrayWithMultipleSums
|
/**
* @author Anirudh Sharma
* <p>
* Given an array of integers target. From a starting array, A consisting of all 1's,
* you may perform the following procedure :
* <p>
* - let x be the sum of all elements currently in your array.
* - choose index i, such that 0 <= i < target.size and set the value of A at index i to x.
* - You may repeat this procedure as many times as needed.
* <p>
* Return True if it is possible to construct the target array from A otherwise return False.
* <p>
* Constraints:
* <p>
* N == target.length
* 1 <= target.length <= 5 * 10^4
* 1 <= target[i] <= 10^9
*/
|
@author Anirudh Sharma
Given an array of integers target. From a starting array, A consisting of all 1's,
you may perform the following procedure :
- let x be the sum of all elements currently in your array.
- choose index i, such that 0 <= i < target.size and set the value of A at index i to x.
- You may repeat this procedure as many times as needed.
Return True if it is possible to construct the target array from A otherwise return False.
|
[
"@author",
"Anirudh",
"Sharma",
"Given",
"an",
"array",
"of",
"integers",
"target",
".",
"From",
"a",
"starting",
"array",
"A",
"consisting",
"of",
"all",
"1",
"'",
"s",
"you",
"may",
"perform",
"the",
"following",
"procedure",
":",
"-",
"let",
"x",
"be",
"the",
"sum",
"of",
"all",
"elements",
"currently",
"in",
"your",
"array",
".",
"-",
"choose",
"index",
"i",
"such",
"that",
"0",
"<",
"=",
"i",
"<",
"target",
".",
"size",
"and",
"set",
"the",
"value",
"of",
"A",
"at",
"index",
"i",
"to",
"x",
".",
"-",
"You",
"may",
"repeat",
"this",
"procedure",
"as",
"many",
"times",
"as",
"needed",
".",
"Return",
"True",
"if",
"it",
"is",
"possible",
"to",
"construct",
"the",
"target",
"array",
"from",
"A",
"otherwise",
"return",
"False",
"."
] |
public class Problem09_ConstructTargetArrayWithMultipleSums {
public boolean isPossible(int[] target) {
// Special case
if (target == null || target.length == 0) {
return false;
}
// Priority queue (max heap) to store items of array
Queue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b - a);
// Cumulative sum of all the elements in the queue
int cumulativeSum = 0;
// Loop through every element in the array and store it in the heap
for (int t : target) {
maxHeap.add(t);
cumulativeSum += t;
}
// Loop until the queue is empty
while (maxHeap.peek() != null && maxHeap.peek() != 1) {
// Get the root of the heap
Integer root = maxHeap.poll();
if (root != null) {
// Subtract this from the cumulative sum
cumulativeSum -= root;
// Base case
if (root <= cumulativeSum || cumulativeSum < 1) {
return false;
}
root %= cumulativeSum;
cumulativeSum += root;
maxHeap.add(root);
}
}
return true;
}
}
|
[
"public",
"class",
"Problem09_ConstructTargetArrayWithMultipleSums",
"{",
"public",
"boolean",
"isPossible",
"(",
"int",
"[",
"]",
"target",
")",
"{",
"if",
"(",
"target",
"==",
"null",
"||",
"target",
".",
"length",
"==",
"0",
")",
"{",
"return",
"false",
";",
"}",
"Queue",
"<",
"Integer",
">",
"maxHeap",
"=",
"new",
"PriorityQueue",
"<",
">",
"(",
"(",
"a",
",",
"b",
")",
"->",
"b",
"-",
"a",
")",
";",
"int",
"cumulativeSum",
"=",
"0",
";",
"for",
"(",
"int",
"t",
":",
"target",
")",
"{",
"maxHeap",
".",
"add",
"(",
"t",
")",
";",
"cumulativeSum",
"+=",
"t",
";",
"}",
"while",
"(",
"maxHeap",
".",
"peek",
"(",
")",
"!=",
"null",
"&&",
"maxHeap",
".",
"peek",
"(",
")",
"!=",
"1",
")",
"{",
"Integer",
"root",
"=",
"maxHeap",
".",
"poll",
"(",
")",
";",
"if",
"(",
"root",
"!=",
"null",
")",
"{",
"cumulativeSum",
"-=",
"root",
";",
"if",
"(",
"root",
"<=",
"cumulativeSum",
"||",
"cumulativeSum",
"<",
"1",
")",
"{",
"return",
"false",
";",
"}",
"root",
"%=",
"cumulativeSum",
";",
"cumulativeSum",
"+=",
"root",
";",
"maxHeap",
".",
"add",
"(",
"root",
")",
";",
"}",
"}",
"return",
"true",
";",
"}",
"}"
] |
@author Anirudh Sharma
<p>
Given an array of integers target.
|
[
"@author",
"Anirudh",
"Sharma",
"<p",
">",
"Given",
"an",
"array",
"of",
"integers",
"target",
"."
] |
[
"// Special case",
"// Priority queue (max heap) to store items of array",
"// Cumulative sum of all the elements in the queue",
"// Loop through every element in the array and store it in the heap",
"// Loop until the queue is empty",
"// Get the root of the heap",
"// Subtract this from the cumulative sum",
"// Base case"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 13
| 265
| 172
|
ee4b5987f004a66fb996ad3fa67afe5dbdfe7609
|
yskopets/web-services-statistics
|
web-services-statistics/src/main/java/com/github/toolbelt/web/services/statistics/filter/StatisticsCollectingPrintWriter.java
|
[
"Apache-2.0"
] |
Java
|
StatisticsCollectingPrintWriter
|
/**
* {@code Decorator} of {@link javax.servlet.ServletResponse#getWriter()} that collects generic response {@code metrics},
* such as {@code Time Till First Response Byte In Millis} and {@code Response Body Written Chars Count}.
*
* @author <a href="mailto:[email protected]">Yaroslav Skopets</a>
*/
|
Decorator of javax.servlet.ServletResponse#getWriter() that collects generic response metrics,
such as Time Till First Response Byte In Millis and Response Body Written Chars Count.
@author Yaroslav Skopets
|
[
"Decorator",
"of",
"javax",
".",
"servlet",
".",
"ServletResponse#getWriter",
"()",
"that",
"collects",
"generic",
"response",
"metrics",
"such",
"as",
"Time",
"Till",
"First",
"Response",
"Byte",
"In",
"Millis",
"and",
"Response",
"Body",
"Written",
"Chars",
"Count",
".",
"@author",
"Yaroslav",
"Skopets"
] |
public class StatisticsCollectingPrintWriter extends DelegatingPrintWriter {
private static final Logger LOG = LoggerFactory.getLogger(StatisticsCollectingPrintWriter.class);
private static final Function<Class, String> CLASS_NAME_FUNCTION = new Function<Class, String>() {
@Override
public String apply(Class aClass) {
return aClass.getName();
}
};
private static final long UNKNOWN_WRITTEN_CHARS_COUNT = 0L;
private static final Long UNKNOWN_TIME_FIRST_CHAR_WRITTEN_MILLIS = null;
private static final Field PRINT_WRITER_OUT_FIELD = ReflectionUtils.findField(PrintWriter.class, "out", Writer.class);
private static final ImmutableSet<Class> ATTESTED_PRINT_WRITER_CLASSES = ImmutableSet.<Class>of(PrintWriter.class);
private static final ImmutableSet<String> SUPPORTED_PRINT_WRITER_CLASSES;
static {
ReflectionUtils.makeAccessible(PRINT_WRITER_OUT_FIELD);
SUPPORTED_PRINT_WRITER_CLASSES = ImmutableSet.<String>builder()
.addAll(Iterables.transform(ATTESTED_PRINT_WRITER_CLASSES, CLASS_NAME_FUNCTION))
// Piggyback on standard Spring facilities in order to define a list of PrintWriter subclasses that can be reliably instrumented
.addAll(SpringFactoriesLoader.loadFactoryNames(StatisticsCollectingPrintWriter.class, StatisticsCollectingPrintWriter.class.getClassLoader()))
.build();
}
private final StatisticsCollectingWriter instrumentedWriter;
public StatisticsCollectingPrintWriter(PrintWriter actualPrintWriter, Clock clock) {
this(actualPrintWriter, clock, SUPPORTED_PRINT_WRITER_CLASSES);
}
@VisibleForTesting
public StatisticsCollectingPrintWriter(PrintWriter actualPrintWriter, Clock clock, Class... supportedPrintWriterClasses) {
this(actualPrintWriter, clock, FluentIterable.from(
ImmutableSet.<Class>builder()
.addAll(ATTESTED_PRINT_WRITER_CLASSES)
.add(supportedPrintWriterClasses)
.build())
.transform(CLASS_NAME_FUNCTION)
.toSet());
}
protected StatisticsCollectingPrintWriter(PrintWriter actualPrintWriter, Clock clock, ImmutableSet<String> supportedPrintWriterClasses) {
super(actualPrintWriter);
this.instrumentedWriter = instrument(actualPrintWriter, clock, supportedPrintWriterClasses);
}
protected StatisticsCollectingWriter instrument(PrintWriter actualPrintWriter, Clock clock, ImmutableSet<String> supportedPrintWriterClasses) {
final String printWriterClass = actualPrintWriter.getClass().getName();
if (supportedPrintWriterClasses.contains(printWriterClass)) {
final Writer actualWriter = (Writer) ReflectionUtils.getField(PRINT_WRITER_OUT_FIELD, actualPrintWriter);
final StatisticsCollectingWriter instrumentedWriter = new StatisticsCollectingWriter(actualWriter, clock);
ReflectionUtils.setField(PRINT_WRITER_OUT_FIELD, actualPrintWriter, instrumentedWriter);
return instrumentedWriter;
} else {
LOG.warn("Can't instrument PrintWriter of type '{}'.\n" +
"Consequently, generic response metrics, such as `Time Till First Response Byte In Millis` and " +
"`Response Body Written Chars Count`, will be unavailable for that output stream.\n" +
"\n" +
"In order to resolve the issue, you need to study the source code of '{}'\n" +
"and make sure instrumentation will work properly with it.\n" +
"Once you're certain, put a file `META-INF/spring.factories` with the following contents somewhere on the application classpath:\n" +
"\n" +
"---------------------------------------------------------------------------------------------------------------------------------------------------------------------\n" +
"| Contents of an example `META-INF/spring.factories` file that enables instrumentation of '{}':\n" +
"---------------------------------------------------------------------------------------------------------------------------------------------------------------------\n" +
"| # Piggyback on standard Spring facilities in order to define a list of PrintWriter subclasses that can be reliably instrumented\n" +
"| com.github.toolbelt.web.services.statistics.filter.StatisticsCollectingPrintWriter=\\\n" +
"| %{}\n" +
"---------------------------------------------------------------------------------------------------------------------------------------------------------------------\n",
printWriterClass, printWriterClass, printWriterClass, printWriterClass);
}
return null;
}
public boolean isStatisticsCollected() {
return instrumentedWriter != null;
}
public long getWrittenCharsCount() {
return instrumentedWriter != null ? instrumentedWriter.getWrittenCharsCount() : UNKNOWN_WRITTEN_CHARS_COUNT;
}
public Long getTimeFirstCharWrittenMillis() {
return instrumentedWriter != null ? instrumentedWriter.getTimeFirstCharWrittenMillis() : UNKNOWN_TIME_FIRST_CHAR_WRITTEN_MILLIS;
}
}
|
[
"public",
"class",
"StatisticsCollectingPrintWriter",
"extends",
"DelegatingPrintWriter",
"{",
"private",
"static",
"final",
"Logger",
"LOG",
"=",
"LoggerFactory",
".",
"getLogger",
"(",
"StatisticsCollectingPrintWriter",
".",
"class",
")",
";",
"private",
"static",
"final",
"Function",
"<",
"Class",
",",
"String",
">",
"CLASS_NAME_FUNCTION",
"=",
"new",
"Function",
"<",
"Class",
",",
"String",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"String",
"apply",
"(",
"Class",
"aClass",
")",
"{",
"return",
"aClass",
".",
"getName",
"(",
")",
";",
"}",
"}",
";",
"private",
"static",
"final",
"long",
"UNKNOWN_WRITTEN_CHARS_COUNT",
"=",
"0L",
";",
"private",
"static",
"final",
"Long",
"UNKNOWN_TIME_FIRST_CHAR_WRITTEN_MILLIS",
"=",
"null",
";",
"private",
"static",
"final",
"Field",
"PRINT_WRITER_OUT_FIELD",
"=",
"ReflectionUtils",
".",
"findField",
"(",
"PrintWriter",
".",
"class",
",",
"\"",
"out",
"\"",
",",
"Writer",
".",
"class",
")",
";",
"private",
"static",
"final",
"ImmutableSet",
"<",
"Class",
">",
"ATTESTED_PRINT_WRITER_CLASSES",
"=",
"ImmutableSet",
".",
"<",
"Class",
">",
"of",
"(",
"PrintWriter",
".",
"class",
")",
";",
"private",
"static",
"final",
"ImmutableSet",
"<",
"String",
">",
"SUPPORTED_PRINT_WRITER_CLASSES",
";",
"static",
"{",
"ReflectionUtils",
".",
"makeAccessible",
"(",
"PRINT_WRITER_OUT_FIELD",
")",
";",
"SUPPORTED_PRINT_WRITER_CLASSES",
"=",
"ImmutableSet",
".",
"<",
"String",
">",
"builder",
"(",
")",
".",
"addAll",
"(",
"Iterables",
".",
"transform",
"(",
"ATTESTED_PRINT_WRITER_CLASSES",
",",
"CLASS_NAME_FUNCTION",
")",
")",
".",
"addAll",
"(",
"SpringFactoriesLoader",
".",
"loadFactoryNames",
"(",
"StatisticsCollectingPrintWriter",
".",
"class",
",",
"StatisticsCollectingPrintWriter",
".",
"class",
".",
"getClassLoader",
"(",
")",
")",
")",
".",
"build",
"(",
")",
";",
"}",
"private",
"final",
"StatisticsCollectingWriter",
"instrumentedWriter",
";",
"public",
"StatisticsCollectingPrintWriter",
"(",
"PrintWriter",
"actualPrintWriter",
",",
"Clock",
"clock",
")",
"{",
"this",
"(",
"actualPrintWriter",
",",
"clock",
",",
"SUPPORTED_PRINT_WRITER_CLASSES",
")",
";",
"}",
"@",
"VisibleForTesting",
"public",
"StatisticsCollectingPrintWriter",
"(",
"PrintWriter",
"actualPrintWriter",
",",
"Clock",
"clock",
",",
"Class",
"...",
"supportedPrintWriterClasses",
")",
"{",
"this",
"(",
"actualPrintWriter",
",",
"clock",
",",
"FluentIterable",
".",
"from",
"(",
"ImmutableSet",
".",
"<",
"Class",
">",
"builder",
"(",
")",
".",
"addAll",
"(",
"ATTESTED_PRINT_WRITER_CLASSES",
")",
".",
"add",
"(",
"supportedPrintWriterClasses",
")",
".",
"build",
"(",
")",
")",
".",
"transform",
"(",
"CLASS_NAME_FUNCTION",
")",
".",
"toSet",
"(",
")",
")",
";",
"}",
"protected",
"StatisticsCollectingPrintWriter",
"(",
"PrintWriter",
"actualPrintWriter",
",",
"Clock",
"clock",
",",
"ImmutableSet",
"<",
"String",
">",
"supportedPrintWriterClasses",
")",
"{",
"super",
"(",
"actualPrintWriter",
")",
";",
"this",
".",
"instrumentedWriter",
"=",
"instrument",
"(",
"actualPrintWriter",
",",
"clock",
",",
"supportedPrintWriterClasses",
")",
";",
"}",
"protected",
"StatisticsCollectingWriter",
"instrument",
"(",
"PrintWriter",
"actualPrintWriter",
",",
"Clock",
"clock",
",",
"ImmutableSet",
"<",
"String",
">",
"supportedPrintWriterClasses",
")",
"{",
"final",
"String",
"printWriterClass",
"=",
"actualPrintWriter",
".",
"getClass",
"(",
")",
".",
"getName",
"(",
")",
";",
"if",
"(",
"supportedPrintWriterClasses",
".",
"contains",
"(",
"printWriterClass",
")",
")",
"{",
"final",
"Writer",
"actualWriter",
"=",
"(",
"Writer",
")",
"ReflectionUtils",
".",
"getField",
"(",
"PRINT_WRITER_OUT_FIELD",
",",
"actualPrintWriter",
")",
";",
"final",
"StatisticsCollectingWriter",
"instrumentedWriter",
"=",
"new",
"StatisticsCollectingWriter",
"(",
"actualWriter",
",",
"clock",
")",
";",
"ReflectionUtils",
".",
"setField",
"(",
"PRINT_WRITER_OUT_FIELD",
",",
"actualPrintWriter",
",",
"instrumentedWriter",
")",
";",
"return",
"instrumentedWriter",
";",
"}",
"else",
"{",
"LOG",
".",
"warn",
"(",
"\"",
"Can't instrument PrintWriter of type '{}'.",
"\\n",
"\"",
"+",
"\"",
"Consequently, generic response metrics, such as `Time Till First Response Byte In Millis` and ",
"\"",
"+",
"\"",
"`Response Body Written Chars Count`, will be unavailable for that output stream.",
"\\n",
"\"",
"+",
"\"",
"\\n",
"\"",
"+",
"\"",
"In order to resolve the issue, you need to study the source code of '{}'",
"\\n",
"\"",
"+",
"\"",
"and make sure instrumentation will work properly with it.",
"\\n",
"\"",
"+",
"\"",
"Once you're certain, put a file `META-INF/spring.factories` with the following contents somewhere on the application classpath:",
"\\n",
"\"",
"+",
"\"",
"\\n",
"\"",
"+",
"\"",
"---------------------------------------------------------------------------------------------------------------------------------------------------------------------",
"\\n",
"\"",
"+",
"\"",
"| Contents of an example `META-INF/spring.factories` file that enables instrumentation of '{}':",
"\\n",
"\"",
"+",
"\"",
"---------------------------------------------------------------------------------------------------------------------------------------------------------------------",
"\\n",
"\"",
"+",
"\"",
"| # Piggyback on standard Spring facilities in order to define a list of PrintWriter subclasses that can be reliably instrumented",
"\\n",
"\"",
"+",
"\"",
"| com.github.toolbelt.web.services.statistics.filter.StatisticsCollectingPrintWriter=",
"\\\\",
"\\n",
"\"",
"+",
"\"",
"| %{}",
"\\n",
"\"",
"+",
"\"",
"---------------------------------------------------------------------------------------------------------------------------------------------------------------------",
"\\n",
"\"",
",",
"printWriterClass",
",",
"printWriterClass",
",",
"printWriterClass",
",",
"printWriterClass",
")",
";",
"}",
"return",
"null",
";",
"}",
"public",
"boolean",
"isStatisticsCollected",
"(",
")",
"{",
"return",
"instrumentedWriter",
"!=",
"null",
";",
"}",
"public",
"long",
"getWrittenCharsCount",
"(",
")",
"{",
"return",
"instrumentedWriter",
"!=",
"null",
"?",
"instrumentedWriter",
".",
"getWrittenCharsCount",
"(",
")",
":",
"UNKNOWN_WRITTEN_CHARS_COUNT",
";",
"}",
"public",
"Long",
"getTimeFirstCharWrittenMillis",
"(",
")",
"{",
"return",
"instrumentedWriter",
"!=",
"null",
"?",
"instrumentedWriter",
".",
"getTimeFirstCharWrittenMillis",
"(",
")",
":",
"UNKNOWN_TIME_FIRST_CHAR_WRITTEN_MILLIS",
";",
"}",
"}"
] |
{@code Decorator} of {@link javax.servlet.ServletResponse#getWriter()} that collects generic response {@code metrics},
such as {@code Time Till First Response Byte In Millis} and {@code Response Body Written Chars Count}.
|
[
"{",
"@code",
"Decorator",
"}",
"of",
"{",
"@link",
"javax",
".",
"servlet",
".",
"ServletResponse#getWriter",
"()",
"}",
"that",
"collects",
"generic",
"response",
"{",
"@code",
"metrics",
"}",
"such",
"as",
"{",
"@code",
"Time",
"Till",
"First",
"Response",
"Byte",
"In",
"Millis",
"}",
"and",
"{",
"@code",
"Response",
"Body",
"Written",
"Chars",
"Count",
"}",
"."
] |
[
"// Piggyback on standard Spring facilities in order to define a list of PrintWriter subclasses that can be reliably instrumented"
] |
[
{
"param": "DelegatingPrintWriter",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "DelegatingPrintWriter",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 25
| 960
| 76
|
71398d31ffe7b956b3c2823f2fda9d79baccde48
|
OviedoRobotics/FtcRobotController
|
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/AutonomousRducks.java
|
[
"MIT"
] |
Java
|
FreightFrenzyPipeline
|
/* Skystone image procesing pipeline to be run upon receipt of each frame from the camera.
* Note that the processFrame() method is called serially from the frame worker thread -
* that is, a new camera frame will not come in while you're still processing a previous one.
* In other words, the processFrame() method will never be called multiple times simultaneously.
*
* However, the rendering of your processed image to the viewport is done in parallel to the
* frame worker thread. That is, the amount of time it takes to render the image to the
* viewport does NOT impact the amount of frames per second that your pipeline can process.
*
* IMPORTANT NOTE: this pipeline is NOT invoked on your OpMode thread. It is invoked on the
* frame worker thread. This should not be a problem in the vast majority of cases. However,
* if you're doing something weird where you do need it synchronized with your OpMode thread,
* then you will need to account for that accordingly.
*/
|
Skystone image procesing pipeline to be run upon receipt of each frame from the camera.
Note that the processFrame() method is called serially from the frame worker thread
that is, a new camera frame will not come in while you're still processing a previous one.
In other words, the processFrame() method will never be called multiple times simultaneously.
However, the rendering of your processed image to the viewport is done in parallel to the
frame worker thread. That is, the amount of time it takes to render the image to the
viewport does NOT impact the amount of frames per second that your pipeline can process.
IMPORTANT NOTE: this pipeline is NOT invoked on your OpMode thread. It is invoked on the
frame worker thread. This should not be a problem in the vast majority of cases. However,
if you're doing something weird where you do need it synchronized with your OpMode thread,
then you will need to account for that accordingly.
|
[
"Skystone",
"image",
"procesing",
"pipeline",
"to",
"be",
"run",
"upon",
"receipt",
"of",
"each",
"frame",
"from",
"the",
"camera",
".",
"Note",
"that",
"the",
"processFrame",
"()",
"method",
"is",
"called",
"serially",
"from",
"the",
"frame",
"worker",
"thread",
"that",
"is",
"a",
"new",
"camera",
"frame",
"will",
"not",
"come",
"in",
"while",
"you",
"'",
"re",
"still",
"processing",
"a",
"previous",
"one",
".",
"In",
"other",
"words",
"the",
"processFrame",
"()",
"method",
"will",
"never",
"be",
"called",
"multiple",
"times",
"simultaneously",
".",
"However",
"the",
"rendering",
"of",
"your",
"processed",
"image",
"to",
"the",
"viewport",
"is",
"done",
"in",
"parallel",
"to",
"the",
"frame",
"worker",
"thread",
".",
"That",
"is",
"the",
"amount",
"of",
"time",
"it",
"takes",
"to",
"render",
"the",
"image",
"to",
"the",
"viewport",
"does",
"NOT",
"impact",
"the",
"amount",
"of",
"frames",
"per",
"second",
"that",
"your",
"pipeline",
"can",
"process",
".",
"IMPORTANT",
"NOTE",
":",
"this",
"pipeline",
"is",
"NOT",
"invoked",
"on",
"your",
"OpMode",
"thread",
".",
"It",
"is",
"invoked",
"on",
"the",
"frame",
"worker",
"thread",
".",
"This",
"should",
"not",
"be",
"a",
"problem",
"in",
"the",
"vast",
"majority",
"of",
"cases",
".",
"However",
"if",
"you",
"'",
"re",
"doing",
"something",
"weird",
"where",
"you",
"do",
"need",
"it",
"synchronized",
"with",
"your",
"OpMode",
"thread",
"then",
"you",
"will",
"need",
"to",
"account",
"for",
"that",
"accordingly",
"."
] |
class FreightFrenzyPipeline extends OpenCvPipeline
{
/*
* NOTE: if you wish to use additional Mat objects in your processing pipeline, it is
* highly recommended to declare them here as instance variables and re-use them for
* each invocation of processFrame(), rather than declaring them as new local variables
* each time through processFrame(). This removes the danger of causing a memory leak
* by forgetting to call mat.release(), and it also reduces memory pressure by not
* constantly allocating and freeing large chunks of memory.
*/
private Mat YCrCb = new Mat();
private Mat Cb = new Mat();
private Mat subMat1;
private Mat subMat2;
private Mat subMat3;
private int max;
private int avg1;
private int avg2;
private int avg3;
private Point skystone = new Point(); // Team Element (populated once we find it!)
private Point sub1PointA = new Point( 37,190); // 15x15 pixels on LEFT
private Point sub1PointB = new Point( 52,205);
private Point sub2PointA = new Point(156,190); // 15x15 pixels on CENTER
private Point sub2PointB = new Point(171,205);
private Point sub3PointA = new Point(265,190); // 15x15 pixels on RIGHT
private Point sub3PointB = new Point(280,205);
@Override
public Mat processFrame(Mat input)
{
// Convert image frame from RGB to YCrCb
Imgproc.cvtColor(input, YCrCb, Imgproc.COLOR_RGB2YCrCb);
// Extract the Cb channel from the image frame
Core.extractChannel(YCrCb, Cb, 2);
// Pull data for the three sample zones from the Cb channel
subMat1 = Cb.submat(new Rect(sub1PointA,sub1PointB) );
subMat2 = Cb.submat(new Rect(sub2PointA,sub2PointB) );
subMat3 = Cb.submat(new Rect(sub3PointA,sub3PointB) );
// Average the three sample zones
avg1 = (int)Core.mean(subMat1).val[0];
avg2 = (int)Core.mean(subMat2).val[0];
avg3 = (int)Core.mean(subMat3).val[0];
// Draw rectangles around the sample zones
Imgproc.rectangle(input, sub1PointA, sub1PointB, new Scalar(0, 0, 255), 1);
Imgproc.rectangle(input, sub2PointA, sub2PointB, new Scalar(0, 0, 255), 1);
Imgproc.rectangle(input, sub3PointA, sub3PointB, new Scalar(0, 0, 255), 1);
// Determine which sample zone had the lowest contrast from blue (lightest color)
max = Math.min(avg1, Math.min(avg2, avg3));
// Draw a circle on the detected skystone
if(max == avg1) {
skystone.x = (sub1PointA.x + sub1PointB.x) / 2;
skystone.y = (sub1PointA.y + sub1PointB.y) / 2;
Imgproc.circle(input, skystone, 5, new Scalar(225, 52, 235), -1);
blockLevel = 1;
} else if(max == avg2) {
skystone.x = (sub2PointA.x + sub2PointB.x) / 2;
skystone.y = (sub2PointA.y + sub2PointB.y) / 2;
Imgproc.circle(input, skystone, 5, new Scalar(225, 52, 235), -1);
blockLevel = 2;
} else if(max == avg3) {
skystone.x = (sub3PointA.x + sub3PointB.x) / 2;
skystone.y = (sub3PointA.y + sub3PointB.y) / 2;
Imgproc.circle(input, skystone, 5, new Scalar(225, 52, 235), -1);
blockLevel = 3;
} else {
blockLevel = 3;
}
// Free the allocated submat memory
subMat1.release();
subMat1 = null;
subMat2.release();
subMat2 = null;
subMat3.release();
subMat3 = null;
return input;
}
}
|
[
"class",
"FreightFrenzyPipeline",
"extends",
"OpenCvPipeline",
"{",
"/*\r\n * NOTE: if you wish to use additional Mat objects in your processing pipeline, it is\r\n * highly recommended to declare them here as instance variables and re-use them for\r\n * each invocation of processFrame(), rather than declaring them as new local variables\r\n * each time through processFrame(). This removes the danger of causing a memory leak\r\n * by forgetting to call mat.release(), and it also reduces memory pressure by not\r\n * constantly allocating and freeing large chunks of memory.\r\n */",
"private",
"Mat",
"YCrCb",
"=",
"new",
"Mat",
"(",
")",
";",
"private",
"Mat",
"Cb",
"=",
"new",
"Mat",
"(",
")",
";",
"private",
"Mat",
"subMat1",
";",
"private",
"Mat",
"subMat2",
";",
"private",
"Mat",
"subMat3",
";",
"private",
"int",
"max",
";",
"private",
"int",
"avg1",
";",
"private",
"int",
"avg2",
";",
"private",
"int",
"avg3",
";",
"private",
"Point",
"skystone",
"=",
"new",
"Point",
"(",
")",
";",
"private",
"Point",
"sub1PointA",
"=",
"new",
"Point",
"(",
"37",
",",
"190",
")",
";",
"private",
"Point",
"sub1PointB",
"=",
"new",
"Point",
"(",
"52",
",",
"205",
")",
";",
"private",
"Point",
"sub2PointA",
"=",
"new",
"Point",
"(",
"156",
",",
"190",
")",
";",
"private",
"Point",
"sub2PointB",
"=",
"new",
"Point",
"(",
"171",
",",
"205",
")",
";",
"private",
"Point",
"sub3PointA",
"=",
"new",
"Point",
"(",
"265",
",",
"190",
")",
";",
"private",
"Point",
"sub3PointB",
"=",
"new",
"Point",
"(",
"280",
",",
"205",
")",
";",
"@",
"Override",
"public",
"Mat",
"processFrame",
"(",
"Mat",
"input",
")",
"{",
"Imgproc",
".",
"cvtColor",
"(",
"input",
",",
"YCrCb",
",",
"Imgproc",
".",
"COLOR_RGB2YCrCb",
")",
";",
"Core",
".",
"extractChannel",
"(",
"YCrCb",
",",
"Cb",
",",
"2",
")",
";",
"subMat1",
"=",
"Cb",
".",
"submat",
"(",
"new",
"Rect",
"(",
"sub1PointA",
",",
"sub1PointB",
")",
")",
";",
"subMat2",
"=",
"Cb",
".",
"submat",
"(",
"new",
"Rect",
"(",
"sub2PointA",
",",
"sub2PointB",
")",
")",
";",
"subMat3",
"=",
"Cb",
".",
"submat",
"(",
"new",
"Rect",
"(",
"sub3PointA",
",",
"sub3PointB",
")",
")",
";",
"avg1",
"=",
"(",
"int",
")",
"Core",
".",
"mean",
"(",
"subMat1",
")",
".",
"val",
"[",
"0",
"]",
";",
"avg2",
"=",
"(",
"int",
")",
"Core",
".",
"mean",
"(",
"subMat2",
")",
".",
"val",
"[",
"0",
"]",
";",
"avg3",
"=",
"(",
"int",
")",
"Core",
".",
"mean",
"(",
"subMat3",
")",
".",
"val",
"[",
"0",
"]",
";",
"Imgproc",
".",
"rectangle",
"(",
"input",
",",
"sub1PointA",
",",
"sub1PointB",
",",
"new",
"Scalar",
"(",
"0",
",",
"0",
",",
"255",
")",
",",
"1",
")",
";",
"Imgproc",
".",
"rectangle",
"(",
"input",
",",
"sub2PointA",
",",
"sub2PointB",
",",
"new",
"Scalar",
"(",
"0",
",",
"0",
",",
"255",
")",
",",
"1",
")",
";",
"Imgproc",
".",
"rectangle",
"(",
"input",
",",
"sub3PointA",
",",
"sub3PointB",
",",
"new",
"Scalar",
"(",
"0",
",",
"0",
",",
"255",
")",
",",
"1",
")",
";",
"max",
"=",
"Math",
".",
"min",
"(",
"avg1",
",",
"Math",
".",
"min",
"(",
"avg2",
",",
"avg3",
")",
")",
";",
"if",
"(",
"max",
"==",
"avg1",
")",
"{",
"skystone",
".",
"x",
"=",
"(",
"sub1PointA",
".",
"x",
"+",
"sub1PointB",
".",
"x",
")",
"/",
"2",
";",
"skystone",
".",
"y",
"=",
"(",
"sub1PointA",
".",
"y",
"+",
"sub1PointB",
".",
"y",
")",
"/",
"2",
";",
"Imgproc",
".",
"circle",
"(",
"input",
",",
"skystone",
",",
"5",
",",
"new",
"Scalar",
"(",
"225",
",",
"52",
",",
"235",
")",
",",
"-",
"1",
")",
";",
"blockLevel",
"=",
"1",
";",
"}",
"else",
"if",
"(",
"max",
"==",
"avg2",
")",
"{",
"skystone",
".",
"x",
"=",
"(",
"sub2PointA",
".",
"x",
"+",
"sub2PointB",
".",
"x",
")",
"/",
"2",
";",
"skystone",
".",
"y",
"=",
"(",
"sub2PointA",
".",
"y",
"+",
"sub2PointB",
".",
"y",
")",
"/",
"2",
";",
"Imgproc",
".",
"circle",
"(",
"input",
",",
"skystone",
",",
"5",
",",
"new",
"Scalar",
"(",
"225",
",",
"52",
",",
"235",
")",
",",
"-",
"1",
")",
";",
"blockLevel",
"=",
"2",
";",
"}",
"else",
"if",
"(",
"max",
"==",
"avg3",
")",
"{",
"skystone",
".",
"x",
"=",
"(",
"sub3PointA",
".",
"x",
"+",
"sub3PointB",
".",
"x",
")",
"/",
"2",
";",
"skystone",
".",
"y",
"=",
"(",
"sub3PointA",
".",
"y",
"+",
"sub3PointB",
".",
"y",
")",
"/",
"2",
";",
"Imgproc",
".",
"circle",
"(",
"input",
",",
"skystone",
",",
"5",
",",
"new",
"Scalar",
"(",
"225",
",",
"52",
",",
"235",
")",
",",
"-",
"1",
")",
";",
"blockLevel",
"=",
"3",
";",
"}",
"else",
"{",
"blockLevel",
"=",
"3",
";",
"}",
"subMat1",
".",
"release",
"(",
")",
";",
"subMat1",
"=",
"null",
";",
"subMat2",
".",
"release",
"(",
")",
";",
"subMat2",
"=",
"null",
";",
"subMat3",
".",
"release",
"(",
")",
";",
"subMat3",
"=",
"null",
";",
"return",
"input",
";",
"}",
"}"
] |
Skystone image procesing pipeline to be run upon receipt of each frame from the camera.
|
[
"Skystone",
"image",
"procesing",
"pipeline",
"to",
"be",
"run",
"upon",
"receipt",
"of",
"each",
"frame",
"from",
"the",
"camera",
"."
] |
[
"// Team Element (populated once we find it!)\r",
"// 15x15 pixels on LEFT\r",
"// 15x15 pixels on CENTER\r",
"// 15x15 pixels on RIGHT\r",
"// Convert image frame from RGB to YCrCb\r",
"// Extract the Cb channel from the image frame\r",
"// Pull data for the three sample zones from the Cb channel\r",
"// Average the three sample zones\r",
"// Draw rectangles around the sample zones\r",
"// Determine which sample zone had the lowest contrast from blue (lightest color)\r",
"// Draw a circle on the detected skystone\r",
"// Free the allocated submat memory\r"
] |
[
{
"param": "OpenCvPipeline",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "OpenCvPipeline",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 15
| 1,056
| 221
|
92de63aae5d98b41e41b25067c9c5f0b1332670b
|
yuanl/jina
|
jina/logging/logger.py
|
[
"Apache-2.0"
] |
Python
|
JinaLogger
|
Build a logger for a context.
:param context: The context identifier of the class, module or method.
:param log_config: The configuration file for the logger.
:param identity: The id of the group the messages from this logger will belong, used by fluentd default
configuration to group logs by pod.
:param workspace_path: The workspace path where the log will be stored at (only apply to fluentd)
:returns: an executor object.
|
Build a logger for a context.
|
[
"Build",
"a",
"logger",
"for",
"a",
"context",
"."
] |
class JinaLogger:
"""
Build a logger for a context.
:param context: The context identifier of the class, module or method.
:param log_config: The configuration file for the logger.
:param identity: The id of the group the messages from this logger will belong, used by fluentd default
configuration to group logs by pod.
:param workspace_path: The workspace path where the log will be stored at (only apply to fluentd)
:returns: an executor object.
"""
supported = {'FileHandler', 'StreamHandler', 'SysLogHandler', 'FluentHandler'}
def __init__(self,
context: str,
name: Optional[str] = None,
log_config: Optional[str] = None,
identity: Optional[str] = None,
workspace_path: Optional[str] = None,
quiet: bool = False,
**kwargs):
from .. import __uptime__
if not log_config:
log_config = os.getenv('JINA_LOG_CONFIG',
resource_filename('jina', '/'.join(
('resources', 'logging.default.yml'))))
if quiet or os.getenv('JINA_LOG_CONFIG', None) == 'QUIET':
log_config = resource_filename('jina', '/'.join(
('resources', 'logging.quiet.yml')))
if not identity:
identity = os.getenv('JINA_LOG_ID', None)
if not name:
name = os.getenv('JINA_POD_NAME', context)
# Remove all handlers associated with the root logger object.
for handler in logging.root.handlers[:]:
logging.root.removeHandler(handler)
self.logger = logging.getLogger(context)
self.logger.propagate = False
if workspace_path is None:
workspace_path = os.getenv('JINA_LOG_WORKSPACE', '/tmp/jina/')
context_vars = {'name': name,
'uptime': __uptime__,
'context': context,
'workspace_path': workspace_path}
if identity:
context_vars['log_id'] = identity
self.add_handlers(log_config, **context_vars)
# note logger.success isn't default there
success_level = LogVerbosity.SUCCESS.value # between WARNING and INFO
logging.addLevelName(success_level, 'SUCCESS')
setattr(self.logger, 'success', lambda message: self.logger.log(success_level, message))
self.info = self.logger.info
self.critical = self.logger.critical
self.debug = self.logger.debug
self.error = self.logger.error
self.warning = self.logger.warning
self.success = self.logger.success
@property
def handlers(self):
"""
Get the handlers of the logger.
:returns: Handlers of logger.
"""
return self.logger.handlers
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
def close(self):
"""Close all the handlers."""
for handler in self.logger.handlers:
handler.close()
def add_handlers(self, config_path: str = None, **kwargs):
"""
Add handlers from config file.
:param config_path: Path of config file.
:param kwargs: Extra parameters.
"""
self.logger.handlers = []
with open(config_path) as fp:
config = JAML.load(fp)
for h in config['handlers']:
cfg = config['configs'].get(h, None)
fmt = getattr(formatter, cfg.get('formatter', 'PlainFormatter'))
if h not in self.supported or not cfg:
raise ValueError(f'can not find configs for {h}, maybe it is not supported')
handler = None
if h == 'StreamHandler':
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(fmt(cfg['format'].format_map(kwargs)))
elif h == 'SysLogHandler':
if cfg['host'] and cfg['port']:
handler = SysLogHandlerWrapper(address=(cfg['host'], cfg['port']))
else:
# a UNIX socket is used
if platform.system() == 'Darwin':
handler = SysLogHandlerWrapper(address='/var/run/syslog')
else:
handler = SysLogHandlerWrapper(address='/dev/log')
if handler:
handler.ident = cfg.get('ident', '')
handler.setFormatter(fmt(cfg['format'].format_map(kwargs)))
try:
handler._connect_unixsocket(handler.address)
except OSError:
handler = None
pass
elif h == 'FileHandler':
handler = logging.FileHandler(cfg['output'].format_map(kwargs), delay=True)
handler.setFormatter(fmt(cfg['format'].format_map(kwargs)))
elif h == 'FluentHandler':
from ..importer import ImportExtensions
with ImportExtensions(required=False, verbose=False):
from fluent import asynchandler as fluentasynchandler
from fluent.handler import FluentRecordFormatter
handler = fluentasynchandler.FluentHandler(cfg['tag'],
host=cfg['host'],
port=cfg['port'], queue_circular=True)
cfg['format'].update(kwargs)
fmt = FluentRecordFormatter(cfg['format'])
handler.setFormatter(fmt)
if handler:
self.logger.addHandler(handler)
verbose_level = LogVerbosity.from_string(config['level'])
if 'JINA_LOG_LEVEL' in os.environ:
verbose_level = LogVerbosity.from_string(os.environ['JINA_LOG_LEVEL'])
self.logger.setLevel(verbose_level.value)
|
[
"class",
"JinaLogger",
":",
"supported",
"=",
"{",
"'FileHandler'",
",",
"'StreamHandler'",
",",
"'SysLogHandler'",
",",
"'FluentHandler'",
"}",
"def",
"__init__",
"(",
"self",
",",
"context",
":",
"str",
",",
"name",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"log_config",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"identity",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"workspace_path",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"quiet",
":",
"bool",
"=",
"False",
",",
"**",
"kwargs",
")",
":",
"from",
".",
".",
"import",
"__uptime__",
"if",
"not",
"log_config",
":",
"log_config",
"=",
"os",
".",
"getenv",
"(",
"'JINA_LOG_CONFIG'",
",",
"resource_filename",
"(",
"'jina'",
",",
"'/'",
".",
"join",
"(",
"(",
"'resources'",
",",
"'logging.default.yml'",
")",
")",
")",
")",
"if",
"quiet",
"or",
"os",
".",
"getenv",
"(",
"'JINA_LOG_CONFIG'",
",",
"None",
")",
"==",
"'QUIET'",
":",
"log_config",
"=",
"resource_filename",
"(",
"'jina'",
",",
"'/'",
".",
"join",
"(",
"(",
"'resources'",
",",
"'logging.quiet.yml'",
")",
")",
")",
"if",
"not",
"identity",
":",
"identity",
"=",
"os",
".",
"getenv",
"(",
"'JINA_LOG_ID'",
",",
"None",
")",
"if",
"not",
"name",
":",
"name",
"=",
"os",
".",
"getenv",
"(",
"'JINA_POD_NAME'",
",",
"context",
")",
"for",
"handler",
"in",
"logging",
".",
"root",
".",
"handlers",
"[",
":",
"]",
":",
"logging",
".",
"root",
".",
"removeHandler",
"(",
"handler",
")",
"self",
".",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"context",
")",
"self",
".",
"logger",
".",
"propagate",
"=",
"False",
"if",
"workspace_path",
"is",
"None",
":",
"workspace_path",
"=",
"os",
".",
"getenv",
"(",
"'JINA_LOG_WORKSPACE'",
",",
"'/tmp/jina/'",
")",
"context_vars",
"=",
"{",
"'name'",
":",
"name",
",",
"'uptime'",
":",
"__uptime__",
",",
"'context'",
":",
"context",
",",
"'workspace_path'",
":",
"workspace_path",
"}",
"if",
"identity",
":",
"context_vars",
"[",
"'log_id'",
"]",
"=",
"identity",
"self",
".",
"add_handlers",
"(",
"log_config",
",",
"**",
"context_vars",
")",
"success_level",
"=",
"LogVerbosity",
".",
"SUCCESS",
".",
"value",
"logging",
".",
"addLevelName",
"(",
"success_level",
",",
"'SUCCESS'",
")",
"setattr",
"(",
"self",
".",
"logger",
",",
"'success'",
",",
"lambda",
"message",
":",
"self",
".",
"logger",
".",
"log",
"(",
"success_level",
",",
"message",
")",
")",
"self",
".",
"info",
"=",
"self",
".",
"logger",
".",
"info",
"self",
".",
"critical",
"=",
"self",
".",
"logger",
".",
"critical",
"self",
".",
"debug",
"=",
"self",
".",
"logger",
".",
"debug",
"self",
".",
"error",
"=",
"self",
".",
"logger",
".",
"error",
"self",
".",
"warning",
"=",
"self",
".",
"logger",
".",
"warning",
"self",
".",
"success",
"=",
"self",
".",
"logger",
".",
"success",
"@",
"property",
"def",
"handlers",
"(",
"self",
")",
":",
"\"\"\"\n Get the handlers of the logger.\n\n :returns: Handlers of logger.\n \"\"\"",
"return",
"self",
".",
"logger",
".",
"handlers",
"def",
"__enter__",
"(",
"self",
")",
":",
"return",
"self",
"def",
"__exit__",
"(",
"self",
",",
"exc_type",
",",
"exc_val",
",",
"exc_tb",
")",
":",
"self",
".",
"close",
"(",
")",
"def",
"close",
"(",
"self",
")",
":",
"\"\"\"Close all the handlers.\"\"\"",
"for",
"handler",
"in",
"self",
".",
"logger",
".",
"handlers",
":",
"handler",
".",
"close",
"(",
")",
"def",
"add_handlers",
"(",
"self",
",",
"config_path",
":",
"str",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"\"\"\"\n Add handlers from config file.\n\n :param config_path: Path of config file.\n :param kwargs: Extra parameters.\n \"\"\"",
"self",
".",
"logger",
".",
"handlers",
"=",
"[",
"]",
"with",
"open",
"(",
"config_path",
")",
"as",
"fp",
":",
"config",
"=",
"JAML",
".",
"load",
"(",
"fp",
")",
"for",
"h",
"in",
"config",
"[",
"'handlers'",
"]",
":",
"cfg",
"=",
"config",
"[",
"'configs'",
"]",
".",
"get",
"(",
"h",
",",
"None",
")",
"fmt",
"=",
"getattr",
"(",
"formatter",
",",
"cfg",
".",
"get",
"(",
"'formatter'",
",",
"'PlainFormatter'",
")",
")",
"if",
"h",
"not",
"in",
"self",
".",
"supported",
"or",
"not",
"cfg",
":",
"raise",
"ValueError",
"(",
"f'can not find configs for {h}, maybe it is not supported'",
")",
"handler",
"=",
"None",
"if",
"h",
"==",
"'StreamHandler'",
":",
"handler",
"=",
"logging",
".",
"StreamHandler",
"(",
"sys",
".",
"stdout",
")",
"handler",
".",
"setFormatter",
"(",
"fmt",
"(",
"cfg",
"[",
"'format'",
"]",
".",
"format_map",
"(",
"kwargs",
")",
")",
")",
"elif",
"h",
"==",
"'SysLogHandler'",
":",
"if",
"cfg",
"[",
"'host'",
"]",
"and",
"cfg",
"[",
"'port'",
"]",
":",
"handler",
"=",
"SysLogHandlerWrapper",
"(",
"address",
"=",
"(",
"cfg",
"[",
"'host'",
"]",
",",
"cfg",
"[",
"'port'",
"]",
")",
")",
"else",
":",
"if",
"platform",
".",
"system",
"(",
")",
"==",
"'Darwin'",
":",
"handler",
"=",
"SysLogHandlerWrapper",
"(",
"address",
"=",
"'/var/run/syslog'",
")",
"else",
":",
"handler",
"=",
"SysLogHandlerWrapper",
"(",
"address",
"=",
"'/dev/log'",
")",
"if",
"handler",
":",
"handler",
".",
"ident",
"=",
"cfg",
".",
"get",
"(",
"'ident'",
",",
"''",
")",
"handler",
".",
"setFormatter",
"(",
"fmt",
"(",
"cfg",
"[",
"'format'",
"]",
".",
"format_map",
"(",
"kwargs",
")",
")",
")",
"try",
":",
"handler",
".",
"_connect_unixsocket",
"(",
"handler",
".",
"address",
")",
"except",
"OSError",
":",
"handler",
"=",
"None",
"pass",
"elif",
"h",
"==",
"'FileHandler'",
":",
"handler",
"=",
"logging",
".",
"FileHandler",
"(",
"cfg",
"[",
"'output'",
"]",
".",
"format_map",
"(",
"kwargs",
")",
",",
"delay",
"=",
"True",
")",
"handler",
".",
"setFormatter",
"(",
"fmt",
"(",
"cfg",
"[",
"'format'",
"]",
".",
"format_map",
"(",
"kwargs",
")",
")",
")",
"elif",
"h",
"==",
"'FluentHandler'",
":",
"from",
".",
".",
"importer",
"import",
"ImportExtensions",
"with",
"ImportExtensions",
"(",
"required",
"=",
"False",
",",
"verbose",
"=",
"False",
")",
":",
"from",
"fluent",
"import",
"asynchandler",
"as",
"fluentasynchandler",
"from",
"fluent",
".",
"handler",
"import",
"FluentRecordFormatter",
"handler",
"=",
"fluentasynchandler",
".",
"FluentHandler",
"(",
"cfg",
"[",
"'tag'",
"]",
",",
"host",
"=",
"cfg",
"[",
"'host'",
"]",
",",
"port",
"=",
"cfg",
"[",
"'port'",
"]",
",",
"queue_circular",
"=",
"True",
")",
"cfg",
"[",
"'format'",
"]",
".",
"update",
"(",
"kwargs",
")",
"fmt",
"=",
"FluentRecordFormatter",
"(",
"cfg",
"[",
"'format'",
"]",
")",
"handler",
".",
"setFormatter",
"(",
"fmt",
")",
"if",
"handler",
":",
"self",
".",
"logger",
".",
"addHandler",
"(",
"handler",
")",
"verbose_level",
"=",
"LogVerbosity",
".",
"from_string",
"(",
"config",
"[",
"'level'",
"]",
")",
"if",
"'JINA_LOG_LEVEL'",
"in",
"os",
".",
"environ",
":",
"verbose_level",
"=",
"LogVerbosity",
".",
"from_string",
"(",
"os",
".",
"environ",
"[",
"'JINA_LOG_LEVEL'",
"]",
")",
"self",
".",
"logger",
".",
"setLevel",
"(",
"verbose_level",
".",
"value",
")"
] |
Build a logger for a context.
|
[
"Build",
"a",
"logger",
"for",
"a",
"context",
"."
] |
[
"\"\"\"\n Build a logger for a context.\n\n :param context: The context identifier of the class, module or method.\n :param log_config: The configuration file for the logger.\n :param identity: The id of the group the messages from this logger will belong, used by fluentd default\n configuration to group logs by pod.\n :param workspace_path: The workspace path where the log will be stored at (only apply to fluentd)\n :returns: an executor object.\n \"\"\"",
"# Remove all handlers associated with the root logger object.",
"# note logger.success isn't default there",
"# between WARNING and INFO",
"\"\"\"\n Get the handlers of the logger.\n\n :returns: Handlers of logger.\n \"\"\"",
"\"\"\"Close all the handlers.\"\"\"",
"\"\"\"\n Add handlers from config file.\n\n :param config_path: Path of config file.\n :param kwargs: Extra parameters.\n \"\"\"",
"# a UNIX socket is used"
] |
[] |
{
"returns": [
{
"docstring": "an executor object.",
"docstring_tokens": [
"an",
"executor",
"object",
"."
],
"type": null
}
],
"raises": [],
"params": [],
"outlier_params": [
{
"identifier": "context",
"type": null,
"docstring": "The context identifier of the class, module or method.",
"docstring_tokens": [
"The",
"context",
"identifier",
"of",
"the",
"class",
"module",
"or",
"method",
"."
],
"default": null,
"is_optional": null
},
{
"identifier": "log_config",
"type": null,
"docstring": "The configuration file for the logger.",
"docstring_tokens": [
"The",
"configuration",
"file",
"for",
"the",
"logger",
"."
],
"default": null,
"is_optional": null
},
{
"identifier": "identity",
"type": null,
"docstring": "The id of the group the messages from this logger will belong, used by fluentd default\nconfiguration to group logs by pod.",
"docstring_tokens": [
"The",
"id",
"of",
"the",
"group",
"the",
"messages",
"from",
"this",
"logger",
"will",
"belong",
"used",
"by",
"fluentd",
"default",
"configuration",
"to",
"group",
"logs",
"by",
"pod",
"."
],
"default": null,
"is_optional": null
},
{
"identifier": "workspace_path",
"type": null,
"docstring": "The workspace path where the log will be stored at (only apply to fluentd)",
"docstring_tokens": [
"The",
"workspace",
"path",
"where",
"the",
"log",
"will",
"be",
"stored",
"at",
"(",
"only",
"apply",
"to",
"fluentd",
")"
],
"default": null,
"is_optional": null
}
],
"others": []
}
| false
| 22
| 1,152
| 102
|
b844be01103728755a32648a31026d4c9ddd403e
|
robinnorth/NotchSolution
|
Runtime/Base/Adaptation/BlendedClipsAdaptor.cs
|
[
"MIT"
] |
C#
|
BlendedClipsAdaptor
|
/// <summary>
/// Holds 2 <see cref="AnimationClip"/>. With any weight `float` given,
/// it performs an adaptation with Playables API in <see cref="Adapt(float, Animator)"/>, you
/// provide the target <see cref="Animator"/> each time you use it.
/// </summary>
/// <remarks>
/// It is an "adaptor" because it is the one that cause an adaptation.
/// </remarks>
|
Holds 2 . With any weight `float` given,
it performs an adaptation with Playables API in , you
provide the target each time you use it.
|
[
"Holds",
"2",
".",
"With",
"any",
"weight",
"`",
"float",
"`",
"given",
"it",
"performs",
"an",
"adaptation",
"with",
"Playables",
"API",
"in",
"you",
"provide",
"the",
"target",
"each",
"time",
"you",
"use",
"it",
"."
] |
[Serializable]
internal class BlendedClipsAdaptor
{
#pragma warning disable 0649
[SerializeField] AnimationClip normalState;
[SerializeField] AnimationClip fullyAdaptedState;
[Tooltip("A curve which maps to the current blend percentage between normal and adapted state it should be (Y axis, 0 to 1, 1 for fully adapted state")]
[SerializeField] AnimationCurve adaptationCurve;
#pragma warning restore 0649
#if UNITY_EDITOR
public void AssignAdaptationClips(AnimationClip normalState, AnimationClip adaptedState)
{
this.normalState = normalState;
this.fullyAdaptedState = adaptedState;
}
public bool TryGetLinkedControllerAsset(out RuntimeAnimatorController controllerAsset)
{
controllerAsset = null;
var normalControllerPath = AssetDatabase.GetAssetPath(normalState);
var adaptedControllerPath = AssetDatabase.GetAssetPath(fullyAdaptedState);
bool linked = Adaptable && (normalControllerPath == adaptedControllerPath);
if(linked)
{
controllerAsset = AssetDatabase.LoadAssetAtPath<RuntimeAnimatorController>(normalControllerPath);
}
return linked;
}
#endif
public BlendedClipsAdaptor(AnimationCurve defaultCurve)
{
this.adaptationCurve = defaultCurve;
}
internal bool Adaptable => !(adaptationCurve == null || normalState == null || fullyAdaptedState == null);
public void Adapt(float valueForAdaptationCurve, Animator animator)
{
if (!Adaptable) return;
float blend = adaptationCurve.Evaluate(valueForAdaptationCurve);
PlayableGraph pg = PlayableGraph.Create("AdaptationGraph");
pg.SetTimeUpdateMode(DirectorUpdateMode.Manual);
var mixer = AnimationMixerPlayable.Create(pg, 2, normalizeWeights: true);
mixer.SetInputWeight(inputIndex: 0, weight: 1 - blend);
mixer.SetInputWeight(inputIndex: 1, weight: blend);
var normalStateAcp = AnimationClipPlayable.Create(pg, normalState);
var fullyAdaptedStateAcp = AnimationClipPlayable.Create(pg, fullyAdaptedState);
pg.Connect(normalStateAcp, sourceOutputPort: 0, mixer, destinationInputPort: 0);
pg.Connect(fullyAdaptedStateAcp, sourceOutputPort: 0, mixer, destinationInputPort: 1);
var output = AnimationPlayableOutput.Create(pg, "AdaptationGraphOutput", animator);
output.SetSourcePlayable(mixer);
pg.Evaluate();
pg.Destroy();
}
}
|
[
"[",
"Serializable",
"]",
"internal",
"class",
"BlendedClipsAdaptor",
"{",
"pragma",
"warning",
"disable",
"0649",
"[",
"SerializeField",
"]",
"AnimationClip",
"normalState",
";",
"[",
"SerializeField",
"]",
"AnimationClip",
"fullyAdaptedState",
";",
"[",
"Tooltip",
"(",
"\"",
"A curve which maps to the current blend percentage between normal and adapted state it should be (Y axis, 0 to 1, 1 for fully adapted state",
"\"",
")",
"]",
"[",
"SerializeField",
"]",
"AnimationCurve",
"adaptationCurve",
";",
"pragma",
"warning",
"restore",
"0649",
"if",
"UNITY_EDITOR",
"public",
"void",
"AssignAdaptationClips",
"(",
"AnimationClip",
"normalState",
",",
"AnimationClip",
"adaptedState",
")",
"{",
"this",
".",
"normalState",
"=",
"normalState",
";",
"this",
".",
"fullyAdaptedState",
"=",
"adaptedState",
";",
"}",
"public",
"bool",
"TryGetLinkedControllerAsset",
"(",
"out",
"RuntimeAnimatorController",
"controllerAsset",
")",
"{",
"controllerAsset",
"=",
"null",
";",
"var",
"normalControllerPath",
"=",
"AssetDatabase",
".",
"GetAssetPath",
"(",
"normalState",
")",
";",
"var",
"adaptedControllerPath",
"=",
"AssetDatabase",
".",
"GetAssetPath",
"(",
"fullyAdaptedState",
")",
";",
"bool",
"linked",
"=",
"Adaptable",
"&&",
"(",
"normalControllerPath",
"==",
"adaptedControllerPath",
")",
";",
"if",
"(",
"linked",
")",
"{",
"controllerAsset",
"=",
"AssetDatabase",
".",
"LoadAssetAtPath",
"<",
"RuntimeAnimatorController",
">",
"(",
"normalControllerPath",
")",
";",
"}",
"return",
"linked",
";",
"}",
"endif",
"public",
"BlendedClipsAdaptor",
"(",
"AnimationCurve",
"defaultCurve",
")",
"{",
"this",
".",
"adaptationCurve",
"=",
"defaultCurve",
";",
"}",
"internal",
"bool",
"Adaptable",
"=>",
"!",
"(",
"adaptationCurve",
"==",
"null",
"||",
"normalState",
"==",
"null",
"||",
"fullyAdaptedState",
"==",
"null",
")",
";",
"public",
"void",
"Adapt",
"(",
"float",
"valueForAdaptationCurve",
",",
"Animator",
"animator",
")",
"{",
"if",
"(",
"!",
"Adaptable",
")",
"return",
";",
"float",
"blend",
"=",
"adaptationCurve",
".",
"Evaluate",
"(",
"valueForAdaptationCurve",
")",
";",
"PlayableGraph",
"pg",
"=",
"PlayableGraph",
".",
"Create",
"(",
"\"",
"AdaptationGraph",
"\"",
")",
";",
"pg",
".",
"SetTimeUpdateMode",
"(",
"DirectorUpdateMode",
".",
"Manual",
")",
";",
"var",
"mixer",
"=",
"AnimationMixerPlayable",
".",
"Create",
"(",
"pg",
",",
"2",
",",
"normalizeWeights",
":",
"true",
")",
";",
"mixer",
".",
"SetInputWeight",
"(",
"inputIndex",
":",
"0",
",",
"weight",
":",
"1",
"-",
"blend",
")",
";",
"mixer",
".",
"SetInputWeight",
"(",
"inputIndex",
":",
"1",
",",
"weight",
":",
"blend",
")",
";",
"var",
"normalStateAcp",
"=",
"AnimationClipPlayable",
".",
"Create",
"(",
"pg",
",",
"normalState",
")",
";",
"var",
"fullyAdaptedStateAcp",
"=",
"AnimationClipPlayable",
".",
"Create",
"(",
"pg",
",",
"fullyAdaptedState",
")",
";",
"pg",
".",
"Connect",
"(",
"normalStateAcp",
",",
"sourceOutputPort",
":",
"0",
",",
"mixer",
",",
"destinationInputPort",
":",
"0",
")",
";",
"pg",
".",
"Connect",
"(",
"fullyAdaptedStateAcp",
",",
"sourceOutputPort",
":",
"0",
",",
"mixer",
",",
"destinationInputPort",
":",
"1",
")",
";",
"var",
"output",
"=",
"AnimationPlayableOutput",
".",
"Create",
"(",
"pg",
",",
"\"",
"AdaptationGraphOutput",
"\"",
",",
"animator",
")",
";",
"output",
".",
"SetSourcePlayable",
"(",
"mixer",
")",
";",
"pg",
".",
"Evaluate",
"(",
")",
";",
"pg",
".",
"Destroy",
"(",
")",
";",
"}",
"}"
] |
Holds 2 .
|
[
"Holds",
"2",
"."
] |
[
"/// <summary>",
"/// Check if both clips are nested on the same controller asset or not.",
"/// </summary>",
"/// <summary>",
"/// Check if all required data are not `null` : the curve, and the 2 <see cref=\"AnimationClip\"/>.",
"/// </summary>",
"/// <summary>",
"/// Use animation Playables API to control keyed values, blended between the first frame of 2 animation clips.",
"/// </summary>",
"/// <param name=\"valueForAdaptationCurve\">A value to evaluate into adaptation curve producing a real blend value for 2 clips.</param>",
"/// <param name=\"animator\">The control target for animation playables. The clips used must be able to control the keyed fields traveling down from this animator component.</param>",
"//Connect up a playable graph, evaluate once, then we're done with them.",
"//Not sure if the mixer should be \"cross fade\" like this, or should we do 0~1 weight over 1 weight?",
"//But I think that's for AnimationLayerMixerPlayable ?"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": [
{
"identifier": "remarks",
"docstring": "It is an \"adaptor\" because it is the one that cause an adaptation.",
"docstring_tokens": [
"It",
"is",
"an",
"\"",
"adaptor",
"\"",
"because",
"it",
"is",
"the",
"one",
"that",
"cause",
"an",
"adaptation",
"."
]
}
]
}
| false
| 14
| 562
| 94
|
1534a4a8eceb369137bdc458e76c6c261f7682fa
|
gsamokovarov/serengeti-pantry
|
cookbooks/cluster_service_discovery/libraries/cluster_service_discovery.rb
|
[
"Apache-2.0"
] |
Ruby
|
ClusterServiceDiscovery
|
#
# ClusterServiceDiscovery --
#
# Allow nodes to discover the location for a given service at runtime, adapting
# when new services register.
#
# Operations:
#
# * provide a service. A timestamp records the last registry.
# * discover all providers for the given service.
# * discover the most recent provider for that service.
# * get the 'public_ip' for a provider -- the address that nodes in the larger
# world should use
# * get the 'public_ip' for a provider -- the address that nodes on the local
# subnet / private cloud should use
#
# Implementation
#
# Nodes register a service by setting the +[:provides_service][service_name]+
# attribute. This attribute is a hash containing at 'timestamp' (the time of
# registry), but the service can pass in an arbitrary hash of values to merge
# in.
#
|
ClusterServiceDiscovery
Allow nodes to discover the location for a given service at runtime, adapting
when new services register.
provide a service. A timestamp records the last registry.
discover all providers for the given service.
discover the most recent provider for that service.
get the 'public_ip' for a provider -- the address that nodes in the larger
world should use
get the 'public_ip' for a provider -- the address that nodes on the local
subnet / private cloud should use
Implementation
Nodes register a service by setting the +[:provides_service][service_name]+
attribute. This attribute is a hash containing at 'timestamp' (the time of
registry), but the service can pass in an arbitrary hash of values to merge
in.
|
[
"ClusterServiceDiscovery",
"Allow",
"nodes",
"to",
"discover",
"the",
"location",
"for",
"a",
"given",
"service",
"at",
"runtime",
"adapting",
"when",
"new",
"services",
"register",
".",
"provide",
"a",
"service",
".",
"A",
"timestamp",
"records",
"the",
"last",
"registry",
".",
"discover",
"all",
"providers",
"for",
"the",
"given",
"service",
".",
"discover",
"the",
"most",
"recent",
"provider",
"for",
"that",
"service",
".",
"get",
"the",
"'",
"public_ip",
"'",
"for",
"a",
"provider",
"--",
"the",
"address",
"that",
"nodes",
"in",
"the",
"larger",
"world",
"should",
"use",
"get",
"the",
"'",
"public_ip",
"'",
"for",
"a",
"provider",
"--",
"the",
"address",
"that",
"nodes",
"on",
"the",
"local",
"subnet",
"/",
"private",
"cloud",
"should",
"use",
"Implementation",
"Nodes",
"register",
"a",
"service",
"by",
"setting",
"the",
"+",
"[",
":",
"provides_service",
"]",
"[",
"service_name",
"]",
"+",
"attribute",
".",
"This",
"attribute",
"is",
"a",
"hash",
"containing",
"at",
"'",
"timestamp",
"'",
"(",
"the",
"time",
"of",
"registry",
")",
"but",
"the",
"service",
"can",
"pass",
"in",
"an",
"arbitrary",
"hash",
"of",
"values",
"to",
"merge",
"in",
"."
] |
module ClusterServiceDiscovery
# Find all nodes that have indicated they provide the given service,
# in descending order of when they registered.
#
def all_providers_for_service service_name
servers = search(:node, "provides_service:#{service_name}").
find_all{|server| server[:provides_service][service_name] && server[:provides_service][service_name]['timestamp'] }.
sort_by{|server| server[:provides_service][service_name]['timestamp'] } rescue []
Chef::Log.info("search(:node, 'provides_service:#{service_name}') returns #{servers.count} nodes.")
servers || []
end
# Find the most recent node that registered to provide the given service
def provider_for_service service_name
all_providers_for_service(service_name).last
end
# Register to provide the given service.
# If you pass in a hash of information, it will be added to
# the registry, and available to clients
def provide_service service_name, service_info={}
Chef::Log.info("Registering to provide service '#{service_name}' with extra info: #{service_info.inspect}")
timestamp = ClusterServiceDiscovery.timestamp
node.set[:provides_service][service_name] = {
:timestamp => timestamp,
}.merge(service_info)
node.save
# Typically when bootstrap the chef node for the first time, the chef node registers itself to provide some service,
# but the Chef Search Server is not faster enough to build index for newly added node property(e.g. 'provides_service'),
# and will return stale results for search(:node, "provides_service:#{service_name}").
# So let's wait for Chef Search Server to generate the search index.
found = false
while !found do
Chef::Log.info("Wait for Chef Solr Server to generate search index for property 'provides_service'")
sleep 5
# a service can be provided by multi nodes, e.g. zookeeper server service
servers = all_providers_for_service(service_name)
servers.each do |server|
if server[:ipaddress] == node[:ipaddress] and server[:provides_service][service_name][:timestamp] == timestamp
found = true
break
end
end
end
Chef::Log.info("service '#{service_name}' is registered successfully.")
end
# given service, get most recent address
# The local-only ip address for the most recent provider for service_name
def provider_private_ip service_name
server = provider_for_service(service_name) or return
private_ip_of(server)
end
# The local-only ip address for the most recent provider for service_name
def provider_fqdn service_name
server = provider_for_service(service_name) or return
# Chef::Log.info("for #{service_name} got #{server.inspect} with #{fqdn_of(server)}")
fqdn_of(server)
end
# The globally-accessable ip address for the most recent provider for service_name
def provider_public_ip service_name
server = provider_for_service(service_name) or return
public_ip_of(server)
end
# given service, get many addresses
# The local-only ip address for all providers for service_name
def all_provider_private_ips service_name
servers = all_providers_for_service(service_name)
servers.map{ |server| private_ip_of(server) }
end
# The globally-accessable ip address for all providers for service_name
def all_provider_public_ips service_name
servers = all_providers_for_service(service_name)
servers.map{ |server| public_ip_of(server) }
end
# given server, get address
# The local-only ip address for the given server
def private_ip_of server
server[:cloud][:private_ips].first rescue server[:ipaddress]
end
# The local-only ip address for the given server
def fqdn_of server
server[:fqdn]
end
# The globally-accessable ip address for the given server
def public_ip_of server
server[:cloud][:public_ips].first rescue server[:ipaddress]
end
# A compact timestamp, to record when services are registered
def self.timestamp
Time.now.utc.strftime("%Y%m%d%H%M%SZ")
end
end
|
[
"module",
"ClusterServiceDiscovery",
"def",
"all_providers_for_service",
"service_name",
"servers",
"=",
"search",
"(",
":node",
",",
"\"provides_service:#{service_name}\"",
")",
".",
"find_all",
"{",
"|",
"server",
"|",
"server",
"[",
":provides_service",
"]",
"[",
"service_name",
"]",
"&&",
"server",
"[",
":provides_service",
"]",
"[",
"service_name",
"]",
"[",
"'timestamp'",
"]",
"}",
".",
"sort_by",
"{",
"|",
"server",
"|",
"server",
"[",
":provides_service",
"]",
"[",
"service_name",
"]",
"[",
"'timestamp'",
"]",
"}",
"rescue",
"[",
"]",
"Chef",
"::",
"Log",
".",
"info",
"(",
"\"search(:node, 'provides_service:#{service_name}') returns #{servers.count} nodes.\"",
")",
"servers",
"||",
"[",
"]",
"end",
"def",
"provider_for_service",
"service_name",
"all_providers_for_service",
"(",
"service_name",
")",
".",
"last",
"end",
"def",
"provide_service",
"service_name",
",",
"service_info",
"=",
"{",
"}",
"Chef",
"::",
"Log",
".",
"info",
"(",
"\"Registering to provide service '#{service_name}' with extra info: #{service_info.inspect}\"",
")",
"timestamp",
"=",
"ClusterServiceDiscovery",
".",
"timestamp",
"node",
".",
"set",
"[",
":provides_service",
"]",
"[",
"service_name",
"]",
"=",
"{",
":timestamp",
"=>",
"timestamp",
",",
"}",
".",
"merge",
"(",
"service_info",
")",
"node",
".",
"save",
"found",
"=",
"false",
"while",
"!",
"found",
"do",
"Chef",
"::",
"Log",
".",
"info",
"(",
"\"Wait for Chef Solr Server to generate search index for property 'provides_service'\"",
")",
"sleep",
"5",
"servers",
"=",
"all_providers_for_service",
"(",
"service_name",
")",
"servers",
".",
"each",
"do",
"|",
"server",
"|",
"if",
"server",
"[",
":ipaddress",
"]",
"==",
"node",
"[",
":ipaddress",
"]",
"and",
"server",
"[",
":provides_service",
"]",
"[",
"service_name",
"]",
"[",
":timestamp",
"]",
"==",
"timestamp",
"found",
"=",
"true",
"break",
"end",
"end",
"end",
"Chef",
"::",
"Log",
".",
"info",
"(",
"\"service '#{service_name}' is registered successfully.\"",
")",
"end",
"def",
"provider_private_ip",
"service_name",
"server",
"=",
"provider_for_service",
"(",
"service_name",
")",
"or",
"return",
"private_ip_of",
"(",
"server",
")",
"end",
"def",
"provider_fqdn",
"service_name",
"server",
"=",
"provider_for_service",
"(",
"service_name",
")",
"or",
"return",
"fqdn_of",
"(",
"server",
")",
"end",
"def",
"provider_public_ip",
"service_name",
"server",
"=",
"provider_for_service",
"(",
"service_name",
")",
"or",
"return",
"public_ip_of",
"(",
"server",
")",
"end",
"def",
"all_provider_private_ips",
"service_name",
"servers",
"=",
"all_providers_for_service",
"(",
"service_name",
")",
"servers",
".",
"map",
"{",
"|",
"server",
"|",
"private_ip_of",
"(",
"server",
")",
"}",
"end",
"def",
"all_provider_public_ips",
"service_name",
"servers",
"=",
"all_providers_for_service",
"(",
"service_name",
")",
"servers",
".",
"map",
"{",
"|",
"server",
"|",
"public_ip_of",
"(",
"server",
")",
"}",
"end",
"def",
"private_ip_of",
"server",
"server",
"[",
":cloud",
"]",
"[",
":private_ips",
"]",
".",
"first",
"rescue",
"server",
"[",
":ipaddress",
"]",
"end",
"def",
"fqdn_of",
"server",
"server",
"[",
":fqdn",
"]",
"end",
"def",
"public_ip_of",
"server",
"server",
"[",
":cloud",
"]",
"[",
":public_ips",
"]",
".",
"first",
"rescue",
"server",
"[",
":ipaddress",
"]",
"end",
"def",
"self",
".",
"timestamp",
"Time",
".",
"now",
".",
"utc",
".",
"strftime",
"(",
"\"%Y%m%d%H%M%SZ\"",
")",
"end",
"end"
] |
ClusterServiceDiscovery
Allow nodes to discover the location for a given service at runtime, adapting
when new services register.
|
[
"ClusterServiceDiscovery",
"Allow",
"nodes",
"to",
"discover",
"the",
"location",
"for",
"a",
"given",
"service",
"at",
"runtime",
"adapting",
"when",
"new",
"services",
"register",
"."
] |
[
"# Find all nodes that have indicated they provide the given service,",
"# in descending order of when they registered.",
"#",
"# Find the most recent node that registered to provide the given service",
"# Register to provide the given service.",
"# If you pass in a hash of information, it will be added to",
"# the registry, and available to clients",
"# Typically when bootstrap the chef node for the first time, the chef node registers itself to provide some service,",
"# but the Chef Search Server is not faster enough to build index for newly added node property(e.g. 'provides_service'),",
"# and will return stale results for search(:node, \"provides_service:#{service_name}\").",
"# So let's wait for Chef Search Server to generate the search index.",
"# a service can be provided by multi nodes, e.g. zookeeper server service",
"# given service, get most recent address",
"# The local-only ip address for the most recent provider for service_name",
"# The local-only ip address for the most recent provider for service_name",
"# Chef::Log.info(\"for #{service_name} got #{server.inspect} with #{fqdn_of(server)}\")",
"# The globally-accessable ip address for the most recent provider for service_name",
"# given service, get many addresses",
"# The local-only ip address for all providers for service_name",
"# The globally-accessable ip address for all providers for service_name",
"# given server, get address",
"# The local-only ip address for the given server",
"# The local-only ip address for the given server",
"# The globally-accessable ip address for the given server",
"# A compact timestamp, to record when services are registered"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 16
| 944
| 185
|
a7c423eb6bdadc2591973569611a104549ecb058
|
RolandCsibrei/yuka
|
src/fuzzy/FuzzyRule.js
|
[
"MIT"
] |
JavaScript
|
FuzzyRule
|
/**
* Class for representing a fuzzy rule. Fuzzy rules are comprised of an antecedent and
* a consequent in the form: IF antecedent THEN consequent.
*
* Compared to ordinary if/else statements with discrete values, the consequent term
* of a fuzzy rule can fire to a matter of degree.
*
* @author {@link https://github.com/Mugen87|Mugen87}
*/
|
Class for representing a fuzzy rule. Fuzzy rules are comprised of an antecedent and
a consequent in the form: IF antecedent THEN consequent.
Compared to ordinary if/else statements with discrete values, the consequent term
of a fuzzy rule can fire to a matter of degree.
|
[
"Class",
"for",
"representing",
"a",
"fuzzy",
"rule",
".",
"Fuzzy",
"rules",
"are",
"comprised",
"of",
"an",
"antecedent",
"and",
"a",
"consequent",
"in",
"the",
"form",
":",
"IF",
"antecedent",
"THEN",
"consequent",
".",
"Compared",
"to",
"ordinary",
"if",
"/",
"else",
"statements",
"with",
"discrete",
"values",
"the",
"consequent",
"term",
"of",
"a",
"fuzzy",
"rule",
"can",
"fire",
"to",
"a",
"matter",
"of",
"degree",
"."
] |
class FuzzyRule {
/**
* Constructs a new fuzzy rule with the given values.
*
* @param {FuzzyTerm} antecedent - Represents the condition of the rule.
* @param {FuzzyTerm} consequence - Describes the consequence if the condition is satisfied.
*/
constructor( antecedent = null, consequence = null ) {
/**
* Represents the condition of the rule.
* @type {?FuzzyTerm}
* @default null
*/
this.antecedent = antecedent;
/**
* Describes the consequence if the condition is satisfied.
* @type {?FuzzyTerm}
* @default null
*/
this.consequence = consequence;
}
/**
* Initializes the consequent term of this fuzzy rule.
*
* @return {FuzzyRule} A reference to this fuzzy rule.
*/
initConsequence() {
this.consequence.clearDegreeOfMembership();
return this;
}
/**
* Evaluates the rule and updates the degree of membership of the consequent term with
* the degree of membership of the antecedent term.
*
* @return {FuzzyRule} A reference to this fuzzy rule.
*/
evaluate() {
this.consequence.updateDegreeOfMembership( this.antecedent.getDegreeOfMembership() );
return this;
}
/**
* Transforms this instance into a JSON object.
*
* @return {Object} The JSON object.
*/
toJSON() {
const json = {};
const antecedent = this.antecedent;
const consequence = this.consequence;
json.type = this.constructor.name;
json.antecedent = ( antecedent instanceof FuzzyCompositeTerm ) ? antecedent.toJSON() : antecedent.uuid;
json.consequence = ( consequence instanceof FuzzyCompositeTerm ) ? consequence.toJSON() : consequence.uuid;
return json;
}
/**
* Restores this instance from the given JSON object.
*
* @param {Object} json - The JSON object.
* @param {Map<String,FuzzySet>} fuzzySets - Maps fuzzy sets to UUIDs.
* @return {FuzzyRule} A reference to this fuzzy rule.
*/
fromJSON( json, fuzzySets ) {
function parseTerm( termJSON ) {
if ( typeof termJSON === 'string' ) {
// atomic term -> FuzzySet
const uuid = termJSON;
return fuzzySets.get( uuid ) || null;
} else {
// composite term
const type = termJSON.type;
let term;
switch ( type ) {
case 'FuzzyAND':
term = new FuzzyAND();
break;
case 'FuzzyOR':
term = new FuzzyOR();
break;
case 'FuzzyVERY':
term = new FuzzyVERY();
break;
case 'FuzzyFAIRLY':
term = new FuzzyFAIRLY();
break;
default:
Logger.error( 'YUKA.FuzzyRule: Unsupported operator type:', type );
return;
}
const termsJSON = termJSON.terms;
for ( let i = 0, l = termsJSON.length; i < l; i ++ ) {
// recursively parse all subordinate terms
term.terms.push( parseTerm( termsJSON[ i ] ) );
}
return term;
}
}
this.antecedent = parseTerm( json.antecedent );
this.consequence = parseTerm( json.consequence );
return this;
}
}
|
[
"class",
"FuzzyRule",
"{",
"constructor",
"(",
"antecedent",
"=",
"null",
",",
"consequence",
"=",
"null",
")",
"{",
"this",
".",
"antecedent",
"=",
"antecedent",
";",
"this",
".",
"consequence",
"=",
"consequence",
";",
"}",
"initConsequence",
"(",
")",
"{",
"this",
".",
"consequence",
".",
"clearDegreeOfMembership",
"(",
")",
";",
"return",
"this",
";",
"}",
"evaluate",
"(",
")",
"{",
"this",
".",
"consequence",
".",
"updateDegreeOfMembership",
"(",
"this",
".",
"antecedent",
".",
"getDegreeOfMembership",
"(",
")",
")",
";",
"return",
"this",
";",
"}",
"toJSON",
"(",
")",
"{",
"const",
"json",
"=",
"{",
"}",
";",
"const",
"antecedent",
"=",
"this",
".",
"antecedent",
";",
"const",
"consequence",
"=",
"this",
".",
"consequence",
";",
"json",
".",
"type",
"=",
"this",
".",
"constructor",
".",
"name",
";",
"json",
".",
"antecedent",
"=",
"(",
"antecedent",
"instanceof",
"FuzzyCompositeTerm",
")",
"?",
"antecedent",
".",
"toJSON",
"(",
")",
":",
"antecedent",
".",
"uuid",
";",
"json",
".",
"consequence",
"=",
"(",
"consequence",
"instanceof",
"FuzzyCompositeTerm",
")",
"?",
"consequence",
".",
"toJSON",
"(",
")",
":",
"consequence",
".",
"uuid",
";",
"return",
"json",
";",
"}",
"fromJSON",
"(",
"json",
",",
"fuzzySets",
")",
"{",
"function",
"parseTerm",
"(",
"termJSON",
")",
"{",
"if",
"(",
"typeof",
"termJSON",
"===",
"'string'",
")",
"{",
"const",
"uuid",
"=",
"termJSON",
";",
"return",
"fuzzySets",
".",
"get",
"(",
"uuid",
")",
"||",
"null",
";",
"}",
"else",
"{",
"const",
"type",
"=",
"termJSON",
".",
"type",
";",
"let",
"term",
";",
"switch",
"(",
"type",
")",
"{",
"case",
"'FuzzyAND'",
":",
"term",
"=",
"new",
"FuzzyAND",
"(",
")",
";",
"break",
";",
"case",
"'FuzzyOR'",
":",
"term",
"=",
"new",
"FuzzyOR",
"(",
")",
";",
"break",
";",
"case",
"'FuzzyVERY'",
":",
"term",
"=",
"new",
"FuzzyVERY",
"(",
")",
";",
"break",
";",
"case",
"'FuzzyFAIRLY'",
":",
"term",
"=",
"new",
"FuzzyFAIRLY",
"(",
")",
";",
"break",
";",
"default",
":",
"Logger",
".",
"error",
"(",
"'YUKA.FuzzyRule: Unsupported operator type:'",
",",
"type",
")",
";",
"return",
";",
"}",
"const",
"termsJSON",
"=",
"termJSON",
".",
"terms",
";",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"l",
"=",
"termsJSON",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"term",
".",
"terms",
".",
"push",
"(",
"parseTerm",
"(",
"termsJSON",
"[",
"i",
"]",
")",
")",
";",
"}",
"return",
"term",
";",
"}",
"}",
"this",
".",
"antecedent",
"=",
"parseTerm",
"(",
"json",
".",
"antecedent",
")",
";",
"this",
".",
"consequence",
"=",
"parseTerm",
"(",
"json",
".",
"consequence",
")",
";",
"return",
"this",
";",
"}",
"}"
] |
Class for representing a fuzzy rule.
|
[
"Class",
"for",
"representing",
"a",
"fuzzy",
"rule",
"."
] |
[
"/**\n\t* Constructs a new fuzzy rule with the given values.\n\t*\n\t* @param {FuzzyTerm} antecedent - Represents the condition of the rule.\n\t* @param {FuzzyTerm} consequence - Describes the consequence if the condition is satisfied.\n\t*/",
"/**\n\t\t* Represents the condition of the rule.\n\t\t* @type {?FuzzyTerm}\n\t\t* @default null\n\t\t*/",
"/**\n\t\t* Describes the consequence if the condition is satisfied.\n\t\t* @type {?FuzzyTerm}\n\t\t* @default null\n\t\t*/",
"/**\n\t* Initializes the consequent term of this fuzzy rule.\n\t*\n\t* @return {FuzzyRule} A reference to this fuzzy rule.\n\t*/",
"/**\n\t* Evaluates the rule and updates the degree of membership of the consequent term with\n\t* the degree of membership of the antecedent term.\n\t*\n\t* @return {FuzzyRule} A reference to this fuzzy rule.\n\t*/",
"/**\n\t* Transforms this instance into a JSON object.\n\t*\n\t* @return {Object} The JSON object.\n\t*/",
"/**\n\t* Restores this instance from the given JSON object.\n\t*\n\t* @param {Object} json - The JSON object.\n\t* @param {Map<String,FuzzySet>} fuzzySets - Maps fuzzy sets to UUIDs.\n\t* @return {FuzzyRule} A reference to this fuzzy rule.\n\t*/",
"// atomic term -> FuzzySet",
"// composite term",
"// recursively parse all subordinate terms"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": [
{
"identifier": "author",
"docstring": null,
"docstring_tokens": [
"None"
]
}
]
}
| false
| 18
| 788
| 88
|
c00b68273b61568031d5e445d1d92374fd1ddd61
|
jaxn/graphql-ruby
|
lib/graphql/analysis/ast/visitor.rb
|
[
"MIT"
] |
Ruby
|
Visitor
|
# Depth first traversal through a query AST, calling AST analyzers
# along the way.
#
# The visitor is a special case of GraphQL::Language::Visitor, visiting
# only the selected operation, providing helpers for common use cases such
# as skipped fields and visiting fragment spreads.
#
# @see {GraphQL::Analysis::AST::Analyzer} AST Analyzers for queries
|
Depth first traversal through a query AST, calling AST analyzers
along the way.
The visitor is a special case of GraphQL::Language::Visitor, visiting
only the selected operation, providing helpers for common use cases such
as skipped fields and visiting fragment spreads.
|
[
"Depth",
"first",
"traversal",
"through",
"a",
"query",
"AST",
"calling",
"AST",
"analyzers",
"along",
"the",
"way",
".",
"The",
"visitor",
"is",
"a",
"special",
"case",
"of",
"GraphQL",
"::",
"Language",
"::",
"Visitor",
"visiting",
"only",
"the",
"selected",
"operation",
"providing",
"helpers",
"for",
"common",
"use",
"cases",
"such",
"as",
"skipped",
"fields",
"and",
"visiting",
"fragment",
"spreads",
"."
] |
class Visitor < GraphQL::Language::Visitor
def initialize(query:, analyzers:)
@analyzers = analyzers
@path = []
@object_types = []
@directives = []
@field_definitions = []
@argument_definitions = []
@directive_definitions = []
@rescued_errors = []
@query = query
@schema = query.schema
@response_path = []
@skip_stack = [false]
super(query.selected_operation)
end
# @return [GraphQL::Query] the query being visited
attr_reader :query
# @return [Array<GraphQL::ObjectType>] Types whose scope we've entered
attr_reader :object_types
# @return [Array<GraphQL::AnalysisError]
attr_reader :rescued_errors
def visit
return unless @document
super
end
# Visit Helpers
# @return [GraphQL::Query::Arguments] Arguments for this node, merging default values, literal values and query variables
# @see {GraphQL::Query#arguments_for}
def arguments_for(ast_node, field_definition)
@query.arguments_for(ast_node, field_definition)
end
# @return [Boolean] If the visitor is currently inside a fragment definition
def visiting_fragment_definition?
@in_fragment_def
end
# @return [Boolean] If the current node should be skipped because of a skip or include directive
def skipping?
@skipping
end
# @return [Array<String>] The path to the response key for the current field
def response_path
@response_path.dup
end
# Visitor Hooks
def on_operation_definition(node, parent)
object_type = @schema.root_type_for_operation(node.operation_type)
@object_types.push(object_type)
@path.push("#{node.operation_type}#{node.name ? " #{node.name}" : ""}")
call_analyzers(:on_enter_operation_definition, node, parent)
super
call_analyzers(:on_leave_operation_definition, node, parent)
@object_types.pop
@path.pop
end
def on_fragment_definition(node, parent)
on_fragment_with_type(node) do
@path.push("fragment #{node.name}")
@in_fragment_def = false
call_analyzers(:on_enter_fragment_definition, node, parent)
super
@in_fragment_def = false
call_analyzers(:on_leave_fragment_definition, node, parent)
end
end
def on_inline_fragment(node, parent)
on_fragment_with_type(node) do
@path.push("...#{node.type ? " on #{node.type.name}" : ""}")
call_analyzers(:on_enter_inline_fragment, node, parent)
super
call_analyzers(:on_leave_inline_fragment, node, parent)
end
end
def on_field(node, parent)
@response_path.push(node.alias || node.name)
parent_type = @object_types.last
field_definition = @schema.get_field(parent_type, node.name)
@field_definitions.push(field_definition)
if !field_definition.nil?
next_object_type = field_definition.type.unwrap
@object_types.push(next_object_type)
else
@object_types.push(nil)
end
@path.push(node.alias || node.name)
@skipping = @skip_stack.last || skip?(node)
@skip_stack << @skipping
call_analyzers(:on_enter_field, node, parent)
super
@skipping = @skip_stack.pop
call_analyzers(:on_leave_field, node, parent)
@response_path.pop
@field_definitions.pop
@object_types.pop
@path.pop
end
def on_directive(node, parent)
directive_defn = @schema.directives[node.name]
@directive_definitions.push(directive_defn)
call_analyzers(:on_enter_directive, node, parent)
super
call_analyzers(:on_leave_directive, node, parent)
@directive_definitions.pop
end
def on_argument(node, parent)
argument_defn = if (arg = @argument_definitions.last)
arg_type = arg.type.unwrap
if arg_type.kind.input_object?
arg_type.arguments[node.name]
else
nil
end
elsif (directive_defn = @directive_definitions.last)
directive_defn.arguments[node.name]
elsif (field_defn = @field_definitions.last)
field_defn.arguments[node.name]
else
nil
end
@argument_definitions.push(argument_defn)
@path.push(node.name)
call_analyzers(:on_enter_argument, node, parent)
super
call_analyzers(:on_leave_argument, node, parent)
@argument_definitions.pop
@path.pop
end
def on_fragment_spread(node, parent)
@path.push("... #{node.name}")
call_analyzers(:on_enter_fragment_spread, node, parent)
enter_fragment_spread_inline(node)
super
leave_fragment_spread_inline(node)
call_analyzers(:on_leave_fragment_spread, node, parent)
@path.pop
end
def on_abstract_node(node, parent)
call_analyzers(:on_enter_abstract_node, node, parent)
super
call_analyzers(:on_leave_abstract_node, node, parent)
end
# @return [GraphQL::BaseType] The current object type
def type_definition
@object_types.last
end
# @return [GraphQL::BaseType] The type which the current type came from
def parent_type_definition
@object_types[-2]
end
# @return [GraphQL::Field, nil] The most-recently-entered GraphQL::Field, if currently inside one
def field_definition
@field_definitions.last
end
# @return [GraphQL::Field, nil] The GraphQL field which returned the object that the current field belongs to
def previous_field_definition
@field_definitions[-2]
end
# @return [GraphQL::Directive, nil] The most-recently-entered GraphQL::Directive, if currently inside one
def directive_definition
@directive_definitions.last
end
# @return [GraphQL::Argument, nil] The most-recently-entered GraphQL::Argument, if currently inside one
def argument_definition
@argument_definitions.last
end
# @return [GraphQL::Argument, nil] The previous GraphQL argument
def previous_argument_definition
@argument_definitions[-2]
end
private
# Visit a fragment spread inline instead of visiting the definition
# by itself.
def enter_fragment_spread_inline(fragment_spread)
fragment_def = query.fragments[fragment_spread.name]
object_type = if fragment_def.type
@query.warden.get_type(fragment_def.type.name)
else
object_types.last
end
object_types << object_type
fragment_def.selections.each do |selection|
visit_node(selection, fragment_def)
end
end
# Visit a fragment spread inline instead of visiting the definition
# by itself.
def leave_fragment_spread_inline(_fragment_spread)
object_types.pop
end
def skip?(ast_node)
dir = ast_node.directives
dir.any? && !GraphQL::Execution::DirectiveChecks.include?(dir, query)
end
def call_analyzers(method, node, parent)
@analyzers.each do |analyzer|
begin
analyzer.public_send(method, node, parent, self)
rescue AnalysisError => err
@rescued_errors << err
end
end
end
def on_fragment_with_type(node)
object_type = if node.type
@query.warden.get_type(node.type.name)
else
@object_types.last
end
@object_types.push(object_type)
yield(node)
@object_types.pop
@path.pop
end
end
|
[
"class",
"Visitor",
"<",
"GraphQL",
"::",
"Language",
"::",
"Visitor",
"def",
"initialize",
"(",
"query",
":",
",",
"analyzers",
":",
")",
"@analyzers",
"=",
"analyzers",
"@path",
"=",
"[",
"]",
"@object_types",
"=",
"[",
"]",
"@directives",
"=",
"[",
"]",
"@field_definitions",
"=",
"[",
"]",
"@argument_definitions",
"=",
"[",
"]",
"@directive_definitions",
"=",
"[",
"]",
"@rescued_errors",
"=",
"[",
"]",
"@query",
"=",
"query",
"@schema",
"=",
"query",
".",
"schema",
"@response_path",
"=",
"[",
"]",
"@skip_stack",
"=",
"[",
"false",
"]",
"super",
"(",
"query",
".",
"selected_operation",
")",
"end",
"attr_reader",
":query",
"attr_reader",
":object_types",
"attr_reader",
":rescued_errors",
"def",
"visit",
"return",
"unless",
"@document",
"super",
"end",
"def",
"arguments_for",
"(",
"ast_node",
",",
"field_definition",
")",
"@query",
".",
"arguments_for",
"(",
"ast_node",
",",
"field_definition",
")",
"end",
"def",
"visiting_fragment_definition?",
"@in_fragment_def",
"end",
"def",
"skipping?",
"@skipping",
"end",
"def",
"response_path",
"@response_path",
".",
"dup",
"end",
"def",
"on_operation_definition",
"(",
"node",
",",
"parent",
")",
"object_type",
"=",
"@schema",
".",
"root_type_for_operation",
"(",
"node",
".",
"operation_type",
")",
"@object_types",
".",
"push",
"(",
"object_type",
")",
"@path",
".",
"push",
"(",
"\"#{node.operation_type}#{node.name ? \" #{node.name}\" : \"\"}\"",
")",
"call_analyzers",
"(",
":on_enter_operation_definition",
",",
"node",
",",
"parent",
")",
"super",
"call_analyzers",
"(",
":on_leave_operation_definition",
",",
"node",
",",
"parent",
")",
"@object_types",
".",
"pop",
"@path",
".",
"pop",
"end",
"def",
"on_fragment_definition",
"(",
"node",
",",
"parent",
")",
"on_fragment_with_type",
"(",
"node",
")",
"do",
"@path",
".",
"push",
"(",
"\"fragment #{node.name}\"",
")",
"@in_fragment_def",
"=",
"false",
"call_analyzers",
"(",
":on_enter_fragment_definition",
",",
"node",
",",
"parent",
")",
"super",
"@in_fragment_def",
"=",
"false",
"call_analyzers",
"(",
":on_leave_fragment_definition",
",",
"node",
",",
"parent",
")",
"end",
"end",
"def",
"on_inline_fragment",
"(",
"node",
",",
"parent",
")",
"on_fragment_with_type",
"(",
"node",
")",
"do",
"@path",
".",
"push",
"(",
"\"...#{node.type ? \" on #{node.type.name}\" : \"\"}\"",
")",
"call_analyzers",
"(",
":on_enter_inline_fragment",
",",
"node",
",",
"parent",
")",
"super",
"call_analyzers",
"(",
":on_leave_inline_fragment",
",",
"node",
",",
"parent",
")",
"end",
"end",
"def",
"on_field",
"(",
"node",
",",
"parent",
")",
"@response_path",
".",
"push",
"(",
"node",
".",
"alias",
"||",
"node",
".",
"name",
")",
"parent_type",
"=",
"@object_types",
".",
"last",
"field_definition",
"=",
"@schema",
".",
"get_field",
"(",
"parent_type",
",",
"node",
".",
"name",
")",
"@field_definitions",
".",
"push",
"(",
"field_definition",
")",
"if",
"!",
"field_definition",
".",
"nil?",
"next_object_type",
"=",
"field_definition",
".",
"type",
".",
"unwrap",
"@object_types",
".",
"push",
"(",
"next_object_type",
")",
"else",
"@object_types",
".",
"push",
"(",
"nil",
")",
"end",
"@path",
".",
"push",
"(",
"node",
".",
"alias",
"||",
"node",
".",
"name",
")",
"@skipping",
"=",
"@skip_stack",
".",
"last",
"||",
"skip?",
"(",
"node",
")",
"@skip_stack",
"<<",
"@skipping",
"call_analyzers",
"(",
":on_enter_field",
",",
"node",
",",
"parent",
")",
"super",
"@skipping",
"=",
"@skip_stack",
".",
"pop",
"call_analyzers",
"(",
":on_leave_field",
",",
"node",
",",
"parent",
")",
"@response_path",
".",
"pop",
"@field_definitions",
".",
"pop",
"@object_types",
".",
"pop",
"@path",
".",
"pop",
"end",
"def",
"on_directive",
"(",
"node",
",",
"parent",
")",
"directive_defn",
"=",
"@schema",
".",
"directives",
"[",
"node",
".",
"name",
"]",
"@directive_definitions",
".",
"push",
"(",
"directive_defn",
")",
"call_analyzers",
"(",
":on_enter_directive",
",",
"node",
",",
"parent",
")",
"super",
"call_analyzers",
"(",
":on_leave_directive",
",",
"node",
",",
"parent",
")",
"@directive_definitions",
".",
"pop",
"end",
"def",
"on_argument",
"(",
"node",
",",
"parent",
")",
"argument_defn",
"=",
"if",
"(",
"arg",
"=",
"@argument_definitions",
".",
"last",
")",
"arg_type",
"=",
"arg",
".",
"type",
".",
"unwrap",
"if",
"arg_type",
".",
"kind",
".",
"input_object?",
"arg_type",
".",
"arguments",
"[",
"node",
".",
"name",
"]",
"else",
"nil",
"end",
"elsif",
"(",
"directive_defn",
"=",
"@directive_definitions",
".",
"last",
")",
"directive_defn",
".",
"arguments",
"[",
"node",
".",
"name",
"]",
"elsif",
"(",
"field_defn",
"=",
"@field_definitions",
".",
"last",
")",
"field_defn",
".",
"arguments",
"[",
"node",
".",
"name",
"]",
"else",
"nil",
"end",
"@argument_definitions",
".",
"push",
"(",
"argument_defn",
")",
"@path",
".",
"push",
"(",
"node",
".",
"name",
")",
"call_analyzers",
"(",
":on_enter_argument",
",",
"node",
",",
"parent",
")",
"super",
"call_analyzers",
"(",
":on_leave_argument",
",",
"node",
",",
"parent",
")",
"@argument_definitions",
".",
"pop",
"@path",
".",
"pop",
"end",
"def",
"on_fragment_spread",
"(",
"node",
",",
"parent",
")",
"@path",
".",
"push",
"(",
"\"... #{node.name}\"",
")",
"call_analyzers",
"(",
":on_enter_fragment_spread",
",",
"node",
",",
"parent",
")",
"enter_fragment_spread_inline",
"(",
"node",
")",
"super",
"leave_fragment_spread_inline",
"(",
"node",
")",
"call_analyzers",
"(",
":on_leave_fragment_spread",
",",
"node",
",",
"parent",
")",
"@path",
".",
"pop",
"end",
"def",
"on_abstract_node",
"(",
"node",
",",
"parent",
")",
"call_analyzers",
"(",
":on_enter_abstract_node",
",",
"node",
",",
"parent",
")",
"super",
"call_analyzers",
"(",
":on_leave_abstract_node",
",",
"node",
",",
"parent",
")",
"end",
"def",
"type_definition",
"@object_types",
".",
"last",
"end",
"def",
"parent_type_definition",
"@object_types",
"[",
"-",
"2",
"]",
"end",
"def",
"field_definition",
"@field_definitions",
".",
"last",
"end",
"def",
"previous_field_definition",
"@field_definitions",
"[",
"-",
"2",
"]",
"end",
"def",
"directive_definition",
"@directive_definitions",
".",
"last",
"end",
"def",
"argument_definition",
"@argument_definitions",
".",
"last",
"end",
"def",
"previous_argument_definition",
"@argument_definitions",
"[",
"-",
"2",
"]",
"end",
"private",
"def",
"enter_fragment_spread_inline",
"(",
"fragment_spread",
")",
"fragment_def",
"=",
"query",
".",
"fragments",
"[",
"fragment_spread",
".",
"name",
"]",
"object_type",
"=",
"if",
"fragment_def",
".",
"type",
"@query",
".",
"warden",
".",
"get_type",
"(",
"fragment_def",
".",
"type",
".",
"name",
")",
"else",
"object_types",
".",
"last",
"end",
"object_types",
"<<",
"object_type",
"fragment_def",
".",
"selections",
".",
"each",
"do",
"|",
"selection",
"|",
"visit_node",
"(",
"selection",
",",
"fragment_def",
")",
"end",
"end",
"def",
"leave_fragment_spread_inline",
"(",
"_fragment_spread",
")",
"object_types",
".",
"pop",
"end",
"def",
"skip?",
"(",
"ast_node",
")",
"dir",
"=",
"ast_node",
".",
"directives",
"dir",
".",
"any?",
"&&",
"!",
"GraphQL",
"::",
"Execution",
"::",
"DirectiveChecks",
".",
"include?",
"(",
"dir",
",",
"query",
")",
"end",
"def",
"call_analyzers",
"(",
"method",
",",
"node",
",",
"parent",
")",
"@analyzers",
".",
"each",
"do",
"|",
"analyzer",
"|",
"begin",
"analyzer",
".",
"public_send",
"(",
"method",
",",
"node",
",",
"parent",
",",
"self",
")",
"rescue",
"AnalysisError",
"=>",
"err",
"@rescued_errors",
"<<",
"err",
"end",
"end",
"end",
"def",
"on_fragment_with_type",
"(",
"node",
")",
"object_type",
"=",
"if",
"node",
".",
"type",
"@query",
".",
"warden",
".",
"get_type",
"(",
"node",
".",
"type",
".",
"name",
")",
"else",
"@object_types",
".",
"last",
"end",
"@object_types",
".",
"push",
"(",
"object_type",
")",
"yield",
"(",
"node",
")",
"@object_types",
".",
"pop",
"@path",
".",
"pop",
"end",
"end"
] |
Depth first traversal through a query AST, calling AST analyzers
along the way.
|
[
"Depth",
"first",
"traversal",
"through",
"a",
"query",
"AST",
"calling",
"AST",
"analyzers",
"along",
"the",
"way",
"."
] |
[
"# @return [GraphQL::Query] the query being visited",
"# @return [Array<GraphQL::ObjectType>] Types whose scope we've entered",
"# @return [Array<GraphQL::AnalysisError]",
"# Visit Helpers",
"# @return [GraphQL::Query::Arguments] Arguments for this node, merging default values, literal values and query variables",
"# @see {GraphQL::Query#arguments_for}",
"# @return [Boolean] If the visitor is currently inside a fragment definition",
"# @return [Boolean] If the current node should be skipped because of a skip or include directive",
"# @return [Array<String>] The path to the response key for the current field",
"# Visitor Hooks",
"# @return [GraphQL::BaseType] The current object type",
"# @return [GraphQL::BaseType] The type which the current type came from",
"# @return [GraphQL::Field, nil] The most-recently-entered GraphQL::Field, if currently inside one",
"# @return [GraphQL::Field, nil] The GraphQL field which returned the object that the current field belongs to",
"# @return [GraphQL::Directive, nil] The most-recently-entered GraphQL::Directive, if currently inside one",
"# @return [GraphQL::Argument, nil] The most-recently-entered GraphQL::Argument, if currently inside one",
"# @return [GraphQL::Argument, nil] The previous GraphQL argument",
"# Visit a fragment spread inline instead of visiting the definition",
"# by itself.",
"# Visit a fragment spread inline instead of visiting the definition",
"# by itself."
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": [
{
"identifier": "see",
"docstring": "{GraphQL::Analysis::AST::Analyzer} AST Analyzers for queries",
"docstring_tokens": [
"{",
"GraphQL",
"::",
"Analysis",
"::",
"AST",
"::",
"Analyzer",
"}",
"AST",
"Analyzers",
"for",
"queries"
]
}
]
}
| false
| 17
| 1,737
| 77
|
80f207bc5600acd4aa6fa26e1d137eb85cfe9564
|
xqt/pwb
|
pywikibot/tools/formatter.py
|
[
"MIT"
] |
Python
|
SequenceOutputter
|
A class formatting a list of items.
It is possible to customize the appearance by changing
``format_string`` which is used by ``str.format`` with ``index``,
``width`` and ``item``. Each line is joined by the separator and the
complete text is surrounded by the prefix and the suffix. All three
are by default a new line. The index starts at 1 and for the width
it's using the width of the sequence's length written as a decimal
number. So a length of 100 will result in a with of 3 and a length
of 99 in a width of 2.
It is iterating over ``self.sequence`` to generate the text. That
sequence can be any iterator but the result is better when it has
an order.
|
A class formatting a list of items.
It is iterating over ``self.sequence`` to generate the text. That
sequence can be any iterator but the result is better when it has
an order.
|
[
"A",
"class",
"formatting",
"a",
"list",
"of",
"items",
".",
"It",
"is",
"iterating",
"over",
"`",
"`",
"self",
".",
"sequence",
"`",
"`",
"to",
"generate",
"the",
"text",
".",
"That",
"sequence",
"can",
"be",
"any",
"iterator",
"but",
"the",
"result",
"is",
"better",
"when",
"it",
"has",
"an",
"order",
"."
] |
class SequenceOutputter:
"""A class formatting a list of items.
It is possible to customize the appearance by changing
``format_string`` which is used by ``str.format`` with ``index``,
``width`` and ``item``. Each line is joined by the separator and the
complete text is surrounded by the prefix and the suffix. All three
are by default a new line. The index starts at 1 and for the width
it's using the width of the sequence's length written as a decimal
number. So a length of 100 will result in a with of 3 and a length
of 99 in a width of 2.
It is iterating over ``self.sequence`` to generate the text. That
sequence can be any iterator but the result is better when it has
an order.
"""
format_string = ' {index:>{width}} - {item}'
separator = '\n'
prefix = '\n'
suffix = '\n'
def __init__(self, sequence) -> None:
"""Create a new instance with a reference to the sequence."""
super().__init__()
self.sequence = sequence
@deprecated('out', since='6.2.0')
def format_list(self):
"""DEPRECATED: Create the text with one item on each line."""
return self.out
@property
def out(self):
"""Create the text with one item on each line."""
if self.sequence:
# Width is only defined when the length is greater 0
width = int(math.log10(len(self.sequence))) + 1
content = self.separator.join(
self.format_string.format(index=i, item=item, width=width)
for i, item in enumerate(self.sequence, start=1))
else:
content = ''
return self.prefix + content + self.suffix
def output(self) -> None:
"""Output the text of the current sequence."""
output(self.out)
|
[
"class",
"SequenceOutputter",
":",
"format_string",
"=",
"' {index:>{width}} - {item}'",
"separator",
"=",
"'\\n'",
"prefix",
"=",
"'\\n'",
"suffix",
"=",
"'\\n'",
"def",
"__init__",
"(",
"self",
",",
"sequence",
")",
"->",
"None",
":",
"\"\"\"Create a new instance with a reference to the sequence.\"\"\"",
"super",
"(",
")",
".",
"__init__",
"(",
")",
"self",
".",
"sequence",
"=",
"sequence",
"@",
"deprecated",
"(",
"'out'",
",",
"since",
"=",
"'6.2.0'",
")",
"def",
"format_list",
"(",
"self",
")",
":",
"\"\"\"DEPRECATED: Create the text with one item on each line.\"\"\"",
"return",
"self",
".",
"out",
"@",
"property",
"def",
"out",
"(",
"self",
")",
":",
"\"\"\"Create the text with one item on each line.\"\"\"",
"if",
"self",
".",
"sequence",
":",
"width",
"=",
"int",
"(",
"math",
".",
"log10",
"(",
"len",
"(",
"self",
".",
"sequence",
")",
")",
")",
"+",
"1",
"content",
"=",
"self",
".",
"separator",
".",
"join",
"(",
"self",
".",
"format_string",
".",
"format",
"(",
"index",
"=",
"i",
",",
"item",
"=",
"item",
",",
"width",
"=",
"width",
")",
"for",
"i",
",",
"item",
"in",
"enumerate",
"(",
"self",
".",
"sequence",
",",
"start",
"=",
"1",
")",
")",
"else",
":",
"content",
"=",
"''",
"return",
"self",
".",
"prefix",
"+",
"content",
"+",
"self",
".",
"suffix",
"def",
"output",
"(",
"self",
")",
"->",
"None",
":",
"\"\"\"Output the text of the current sequence.\"\"\"",
"output",
"(",
"self",
".",
"out",
")"
] |
A class formatting a list of items.
|
[
"A",
"class",
"formatting",
"a",
"list",
"of",
"items",
"."
] |
[
"\"\"\"A class formatting a list of items.\n\n It is possible to customize the appearance by changing\n ``format_string`` which is used by ``str.format`` with ``index``,\n ``width`` and ``item``. Each line is joined by the separator and the\n complete text is surrounded by the prefix and the suffix. All three\n are by default a new line. The index starts at 1 and for the width\n it's using the width of the sequence's length written as a decimal\n number. So a length of 100 will result in a with of 3 and a length\n of 99 in a width of 2.\n\n It is iterating over ``self.sequence`` to generate the text. That\n sequence can be any iterator but the result is better when it has\n an order.\n \"\"\"",
"\"\"\"Create a new instance with a reference to the sequence.\"\"\"",
"\"\"\"DEPRECATED: Create the text with one item on each line.\"\"\"",
"\"\"\"Create the text with one item on each line.\"\"\"",
"# Width is only defined when the length is greater 0",
"\"\"\"Output the text of the current sequence.\"\"\""
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 18
| 428
| 177
|
5a0035410220356081d022a7f8ff6525e587c8ad
|
yusufaytas/leetcode
|
src/main/java/com/yusufaytas/leetcode/FindKPairsWithSmallestSums.java
|
[
"Apache-2.0",
"MIT"
] |
Java
|
FindKPairsWithSmallestSums
|
/*
You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k.
Define a pair (u,v) which consists of one element from the first array and one element from the second array.
Find the k pairs (u1,v1),(u2,v2) ...(uk,vk) with the smallest sums.
Example 1:
Input: nums1 = [1,7,11], nums2 = [2,4,6], k = 3
Output: [[1,2],[1,4],[1,6]]
Explanation: The first 3 pairs are returned from the sequence:
[1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]
Example 2:
Input: nums1 = [1,1,2], nums2 = [1,2,3], k = 2
Output: [1,1],[1,1]
Explanation: The first 2 pairs are returned from the sequence:
[1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]
Example 3:
Input: nums1 = [1,2], nums2 = [3], k = 3
Output: [1,3],[2,3]
Explanation: All possible pairs are returned from the sequence: [1,3],[2,3]
*/
|
You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k.
Define a pair (u,v) which consists of one element from the first array and one element from the second array.
Find the k pairs (u1,v1),(u2,v2) ...(uk,vk) with the smallest sums.
Example 1.
Example 2.
Example 3.
|
[
"You",
"are",
"given",
"two",
"integer",
"arrays",
"nums1",
"and",
"nums2",
"sorted",
"in",
"ascending",
"order",
"and",
"an",
"integer",
"k",
".",
"Define",
"a",
"pair",
"(",
"u",
"v",
")",
"which",
"consists",
"of",
"one",
"element",
"from",
"the",
"first",
"array",
"and",
"one",
"element",
"from",
"the",
"second",
"array",
".",
"Find",
"the",
"k",
"pairs",
"(",
"u1",
"v1",
")",
"(",
"u2",
"v2",
")",
"...",
"(",
"uk",
"vk",
")",
"with",
"the",
"smallest",
"sums",
".",
"Example",
"1",
".",
"Example",
"2",
".",
"Example",
"3",
"."
] |
public class FindKPairsWithSmallestSums {
public List<List<Integer>> kSmallestPairs(final int[] nums1, final int[] nums2, final int k) {
if (nums1 == null || nums2 == null || nums1.length == 0 || nums2.length == 0) {
return Collections.emptyList();
}
final List<List<Integer>> pairs = new ArrayList<>();
for (int i = 0; i < nums1.length; i++) {
for (int j = 0; j < nums2.length; j++) {
pairs.add(Arrays.asList(nums1[i], nums2[j]));
}
}
return pairs.stream()
.sorted(Comparator.comparingInt(o -> o.get(0) + o.get(1)))
.limit(k)
.collect(Collectors.toList());
}
public static void main(String[] args) {
final int[] nums1 = {1, 2, 4};
final int[] nums2 = {-1, 1, 2};
System.out.println(new FindKPairsWithSmallestSums().kSmallestPairs(nums1, nums2, 9));
}
}
|
[
"public",
"class",
"FindKPairsWithSmallestSums",
"{",
"public",
"List",
"<",
"List",
"<",
"Integer",
">",
">",
"kSmallestPairs",
"(",
"final",
"int",
"[",
"]",
"nums1",
",",
"final",
"int",
"[",
"]",
"nums2",
",",
"final",
"int",
"k",
")",
"{",
"if",
"(",
"nums1",
"==",
"null",
"||",
"nums2",
"==",
"null",
"||",
"nums1",
".",
"length",
"==",
"0",
"||",
"nums2",
".",
"length",
"==",
"0",
")",
"{",
"return",
"Collections",
".",
"emptyList",
"(",
")",
";",
"}",
"final",
"List",
"<",
"List",
"<",
"Integer",
">",
">",
"pairs",
"=",
"new",
"ArrayList",
"<",
">",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"nums1",
".",
"length",
";",
"i",
"++",
")",
"{",
"for",
"(",
"int",
"j",
"=",
"0",
";",
"j",
"<",
"nums2",
".",
"length",
";",
"j",
"++",
")",
"{",
"pairs",
".",
"add",
"(",
"Arrays",
".",
"asList",
"(",
"nums1",
"[",
"i",
"]",
",",
"nums2",
"[",
"j",
"]",
")",
")",
";",
"}",
"}",
"return",
"pairs",
".",
"stream",
"(",
")",
".",
"sorted",
"(",
"Comparator",
".",
"comparingInt",
"(",
"o",
"->",
"o",
".",
"get",
"(",
"0",
")",
"+",
"o",
".",
"get",
"(",
"1",
")",
")",
")",
".",
"limit",
"(",
"k",
")",
".",
"collect",
"(",
"Collectors",
".",
"toList",
"(",
")",
")",
";",
"}",
"public",
"static",
"void",
"main",
"(",
"String",
"[",
"]",
"args",
")",
"{",
"final",
"int",
"[",
"]",
"nums1",
"=",
"{",
"1",
",",
"2",
",",
"4",
"}",
";",
"final",
"int",
"[",
"]",
"nums2",
"=",
"{",
"-",
"1",
",",
"1",
",",
"2",
"}",
";",
"System",
".",
"out",
".",
"println",
"(",
"new",
"FindKPairsWithSmallestSums",
"(",
")",
".",
"kSmallestPairs",
"(",
"nums1",
",",
"nums2",
",",
"9",
")",
")",
";",
"}",
"}"
] |
You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k.
Define a pair (u,v) which consists of one element from the first array and one element from the second array.
|
[
"You",
"are",
"given",
"two",
"integer",
"arrays",
"nums1",
"and",
"nums2",
"sorted",
"in",
"ascending",
"order",
"and",
"an",
"integer",
"k",
".",
"Define",
"a",
"pair",
"(",
"u",
"v",
")",
"which",
"consists",
"of",
"one",
"element",
"from",
"the",
"first",
"array",
"and",
"one",
"element",
"from",
"the",
"second",
"array",
"."
] |
[] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 16
| 248
| 321
|
f01cf19c94ed7c271e31308cd37a1724fb3b7efc
|
danpere/binskim
|
src/BinSkim.Sdk/SdkResources.Designer.cs
|
[
"MIT"
] |
C#
|
SdkResources
|
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
|
A strongly-typed resource class, for looking up localized strings, etc.
|
[
"A",
"strongly",
"-",
"typed",
"resource",
"class",
"for",
"looking",
"up",
"localized",
"strings",
"etc",
"."
] |
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class SdkResources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal SdkResources() {
}
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.CodeAnalysis.IL.Sdk.SdkResources", typeof(SdkResources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
internal static string IllegalBinaryCast {
get {
return ResourceManager.GetString("IllegalBinaryCast", resourceCulture);
}
}
internal static string IllegalContextReuse {
get {
return ResourceManager.GetString("IllegalContextReuse", resourceCulture);
}
}
internal static string MetadataCondition_CouldNotLoadPdb {
get {
return ResourceManager.GetString("MetadataCondition_CouldNotLoadPdb", resourceCulture);
}
}
internal static string MetadataCondition_ElfIsCoreNoneOrObject {
get {
return ResourceManager.GetString("MetadataCondition_ElfIsCoreNoneOrObject", resourceCulture);
}
}
internal static string MetadataCondition_ElfNotBuiltWithGCC {
get {
return ResourceManager.GetString("MetadataCondition_ElfNotBuiltWithGCC", resourceCulture);
}
}
internal static string MetadataCondition_ImageCompiledWithOutdatedTools {
get {
return ResourceManager.GetString("MetadataCondition_ImageCompiledWithOutdatedTools", resourceCulture);
}
}
internal static string MetadataCondition_ImageIs64BitBinary {
get {
return ResourceManager.GetString("MetadataCondition_ImageIs64BitBinary", resourceCulture);
}
}
internal static string MetadataCondition_ImageIsBootBinary {
get {
return ResourceManager.GetString("MetadataCondition_ImageIsBootBinary", resourceCulture);
}
}
internal static string MetadataCondition_ImageIsDotNetCoreBootstrapExe {
get {
return ResourceManager.GetString("MetadataCondition_ImageIsDotNetCoreBootstrapExe", resourceCulture);
}
}
internal static string MetadataCondition_ImageIsDotNetCoreEntryPointDll {
get {
return ResourceManager.GetString("MetadataCondition_ImageIsDotNetCoreEntryPointDll", resourceCulture);
}
}
internal static string MetadataCondition_ImageIsDotNetNativeBinary {
get {
return ResourceManager.GetString("MetadataCondition_ImageIsDotNetNativeBinary", resourceCulture);
}
}
internal static string MetadataCondition_ImageIsILLibraryAssembly {
get {
return ResourceManager.GetString("MetadataCondition_ImageIsILLibraryAssembly", resourceCulture);
}
}
internal static string MetadataCondition_ImageIsILOnlyAssembly {
get {
return ResourceManager.GetString("MetadataCondition_ImageIsILOnlyAssembly", resourceCulture);
}
}
internal static string MetadataCondition_ImageIsInteropAssembly {
get {
return ResourceManager.GetString("MetadataCondition_ImageIsInteropAssembly", resourceCulture);
}
}
internal static string MetadataCondition_ImageIsKernelModeAndNot64Bit {
get {
return ResourceManager.GetString("MetadataCondition_ImageIsKernelModeAndNot64Bit", resourceCulture);
}
}
internal static string MetadataCondition_ImageIsKernelModeBinary {
get {
return ResourceManager.GetString("MetadataCondition_ImageIsKernelModeBinary", resourceCulture);
}
}
internal static string MetadataCondition_ImageIsMixedModeBinary {
get {
return ResourceManager.GetString("MetadataCondition_ImageIsMixedModeBinary", resourceCulture);
}
}
internal static string MetadataCondition_ImageIsNativeUniversalWindowsPlatformBinary {
get {
return ResourceManager.GetString("MetadataCondition_ImageIsNativeUniversalWindowsPlatformBinary", resourceCulture);
}
}
internal static string MetadataCondition_ImageIsNot32BitBinary {
get {
return ResourceManager.GetString("MetadataCondition_ImageIsNot32BitBinary", resourceCulture);
}
}
internal static string MetadataCondition_ImageIsNot64BitBinary {
get {
return ResourceManager.GetString("MetadataCondition_ImageIsNot64BitBinary", resourceCulture);
}
}
internal static string MetadataCondition_ImageIsNotElf {
get {
return ResourceManager.GetString("MetadataCondition_ImageIsNotElf", resourceCulture);
}
}
internal static string MetadataCondition_ImageIsNotExe {
get {
return ResourceManager.GetString("MetadataCondition_ImageIsNotExe", resourceCulture);
}
}
internal static string MetadataCondition_ImageIsNotPE {
get {
return ResourceManager.GetString("MetadataCondition_ImageIsNotPE", resourceCulture);
}
}
internal static string MetadataCondition_ImageIsNotSigned {
get {
return ResourceManager.GetString("MetadataCondition_ImageIsNotSigned", resourceCulture);
}
}
internal static string MetadataCondition_ImageIsPreVersion7WindowsCEBinary {
get {
return ResourceManager.GetString("MetadataCondition_ImageIsPreVersion7WindowsCEBinary", resourceCulture);
}
}
internal static string MetadataCondition_ImageIsResourceOnlyAssembly {
get {
return ResourceManager.GetString("MetadataCondition_ImageIsResourceOnlyAssembly", resourceCulture);
}
}
internal static string MetadataCondition_ImageIsResourceOnlyBinary {
get {
return ResourceManager.GetString("MetadataCondition_ImageIsResourceOnlyBinary", resourceCulture);
}
}
internal static string MetadataCondition_ImageIsWixBinary {
get {
return ResourceManager.GetString("MetadataCondition_ImageIsWixBinary", resourceCulture);
}
}
internal static string MetadataCondition_ImageIsXboxBinary {
get {
return ResourceManager.GetString("MetadataCondition_ImageIsXboxBinary", resourceCulture);
}
}
internal static string MetadataCondition_ImageLikelyLoads32BitProcess {
get {
return ResourceManager.GetString("MetadataCondition_ImageLikelyLoads32BitProcess", resourceCulture);
}
}
internal static string RuleWasDisabledDueToMissingPolicy {
get {
return ResourceManager.GetString("RuleWasDisabledDueToMissingPolicy", resourceCulture);
}
}
internal static string TargetNotAnalyzed_NotAPortableExecutable {
get {
return ResourceManager.GetString("TargetNotAnalyzed_NotAPortableExecutable", resourceCulture);
}
}
internal static string TargetNotAnalyzed_NotApplicable {
get {
return ResourceManager.GetString("TargetNotAnalyzed_NotApplicable", resourceCulture);
}
}
}
|
[
"[",
"global",
"::",
"System",
".",
"CodeDom",
".",
"Compiler",
".",
"GeneratedCodeAttribute",
"(",
"\"",
"System.Resources.Tools.StronglyTypedResourceBuilder",
"\"",
",",
"\"",
"16.0.0.0",
"\"",
")",
"]",
"[",
"global",
"::",
"System",
".",
"Diagnostics",
".",
"DebuggerNonUserCodeAttribute",
"(",
")",
"]",
"[",
"global",
"::",
"System",
".",
"Runtime",
".",
"CompilerServices",
".",
"CompilerGeneratedAttribute",
"(",
")",
"]",
"internal",
"class",
"SdkResources",
"{",
"private",
"static",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"resourceMan",
";",
"private",
"static",
"global",
"::",
"System",
".",
"Globalization",
".",
"CultureInfo",
"resourceCulture",
";",
"[",
"global",
"::",
"System",
".",
"Diagnostics",
".",
"CodeAnalysis",
".",
"SuppressMessageAttribute",
"(",
"\"",
"Microsoft.Performance",
"\"",
",",
"\"",
"CA1811:AvoidUncalledPrivateCode",
"\"",
")",
"]",
"internal",
"SdkResources",
"(",
")",
"{",
"}",
"[",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableAttribute",
"(",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableState",
".",
"Advanced",
")",
"]",
"internal",
"static",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"ResourceManager",
"{",
"get",
"{",
"if",
"(",
"object",
".",
"ReferenceEquals",
"(",
"resourceMan",
",",
"null",
")",
")",
"{",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"temp",
"=",
"new",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"(",
"\"",
"Microsoft.CodeAnalysis.IL.Sdk.SdkResources",
"\"",
",",
"typeof",
"(",
"SdkResources",
")",
".",
"Assembly",
")",
";",
"resourceMan",
"=",
"temp",
";",
"}",
"return",
"resourceMan",
";",
"}",
"}",
"[",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableAttribute",
"(",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableState",
".",
"Advanced",
")",
"]",
"internal",
"static",
"global",
"::",
"System",
".",
"Globalization",
".",
"CultureInfo",
"Culture",
"{",
"get",
"{",
"return",
"resourceCulture",
";",
"}",
"set",
"{",
"resourceCulture",
"=",
"value",
";",
"}",
"}",
"internal",
"static",
"string",
"IllegalBinaryCast",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"IllegalBinaryCast",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"IllegalContextReuse",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"IllegalContextReuse",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"MetadataCondition_CouldNotLoadPdb",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"MetadataCondition_CouldNotLoadPdb",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"MetadataCondition_ElfIsCoreNoneOrObject",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"MetadataCondition_ElfIsCoreNoneOrObject",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"MetadataCondition_ElfNotBuiltWithGCC",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"MetadataCondition_ElfNotBuiltWithGCC",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"MetadataCondition_ImageCompiledWithOutdatedTools",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"MetadataCondition_ImageCompiledWithOutdatedTools",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"MetadataCondition_ImageIs64BitBinary",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"MetadataCondition_ImageIs64BitBinary",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"MetadataCondition_ImageIsBootBinary",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"MetadataCondition_ImageIsBootBinary",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"MetadataCondition_ImageIsDotNetCoreBootstrapExe",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"MetadataCondition_ImageIsDotNetCoreBootstrapExe",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"MetadataCondition_ImageIsDotNetCoreEntryPointDll",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"MetadataCondition_ImageIsDotNetCoreEntryPointDll",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"MetadataCondition_ImageIsDotNetNativeBinary",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"MetadataCondition_ImageIsDotNetNativeBinary",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"MetadataCondition_ImageIsILLibraryAssembly",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"MetadataCondition_ImageIsILLibraryAssembly",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"MetadataCondition_ImageIsILOnlyAssembly",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"MetadataCondition_ImageIsILOnlyAssembly",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"MetadataCondition_ImageIsInteropAssembly",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"MetadataCondition_ImageIsInteropAssembly",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"MetadataCondition_ImageIsKernelModeAndNot64Bit",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"MetadataCondition_ImageIsKernelModeAndNot64Bit",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"MetadataCondition_ImageIsKernelModeBinary",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"MetadataCondition_ImageIsKernelModeBinary",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"MetadataCondition_ImageIsMixedModeBinary",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"MetadataCondition_ImageIsMixedModeBinary",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"MetadataCondition_ImageIsNativeUniversalWindowsPlatformBinary",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"MetadataCondition_ImageIsNativeUniversalWindowsPlatformBinary",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"MetadataCondition_ImageIsNot32BitBinary",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"MetadataCondition_ImageIsNot32BitBinary",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"MetadataCondition_ImageIsNot64BitBinary",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"MetadataCondition_ImageIsNot64BitBinary",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"MetadataCondition_ImageIsNotElf",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"MetadataCondition_ImageIsNotElf",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"MetadataCondition_ImageIsNotExe",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"MetadataCondition_ImageIsNotExe",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"MetadataCondition_ImageIsNotPE",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"MetadataCondition_ImageIsNotPE",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"MetadataCondition_ImageIsNotSigned",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"MetadataCondition_ImageIsNotSigned",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"MetadataCondition_ImageIsPreVersion7WindowsCEBinary",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"MetadataCondition_ImageIsPreVersion7WindowsCEBinary",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"MetadataCondition_ImageIsResourceOnlyAssembly",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"MetadataCondition_ImageIsResourceOnlyAssembly",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"MetadataCondition_ImageIsResourceOnlyBinary",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"MetadataCondition_ImageIsResourceOnlyBinary",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"MetadataCondition_ImageIsWixBinary",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"MetadataCondition_ImageIsWixBinary",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"MetadataCondition_ImageIsXboxBinary",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"MetadataCondition_ImageIsXboxBinary",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"MetadataCondition_ImageLikelyLoads32BitProcess",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"MetadataCondition_ImageLikelyLoads32BitProcess",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"RuleWasDisabledDueToMissingPolicy",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"RuleWasDisabledDueToMissingPolicy",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"TargetNotAnalyzed_NotAPortableExecutable",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"TargetNotAnalyzed_NotAPortableExecutable",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"TargetNotAnalyzed_NotApplicable",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"TargetNotAnalyzed_NotApplicable",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"}"
] |
A strongly-typed resource class, for looking up localized strings, etc.
|
[
"A",
"strongly",
"-",
"typed",
"resource",
"class",
"for",
"looking",
"up",
"localized",
"strings",
"etc",
"."
] |
[
"/// <summary>",
"/// Returns the cached ResourceManager instance used by this class.",
"/// </summary>",
"/// <summary>",
"/// Overrides the current thread's CurrentUICulture property for all",
"/// resource lookups using this strongly typed resource class.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to An attempt to cast a binary target to a '{0}' failed. This indicates a programming error in rules evaluating that sort of target..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to A binary context object was re-initialized with a new file path..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to an exception occurred attempting to load its pdb.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to ELF is not a shared object or executable.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to not compiled solely with gcc.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to image was compiled with a toolset version ({0}) that is not sufficiently recent ({1} or newer) to provide relevant settings.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to image is a 64-bit binary.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to image is a boot binary.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to image is a .NET core native bootstrap exe.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to image is a .NET core entry point dll.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to image is a binary built by the .NET native toolset.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to image is a managed IL library (i.e., ahead of time compiled) assembly.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to image is a managed IL-only assembly.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to image is a managed interop assembly.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to image is not 64-bit (the only architecture that enables control flow guard for kernel mode binaries).",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to image is a kernel mode binary.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to image is a mixed mode binary.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to image is a native UWP (Univesal Windows Platform) binary.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to image is not a 32-bit binary.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to image is not a 64-bit binary.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to image is not an ELF binary.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to image is not an executable program.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to image is not a PE binary.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to image is not signed .",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to image is a pre-version 7 Windows CE binary.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to image is a managed resource-only assembly.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to image is a resource-only binary.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to image appears to be a WiX bootstrapper application.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to image is an xbox binary.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to image will likely load as a 32-bit process.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Check '{0}' was disabled for this run as the analysis was not configured with required policy ({1}). To resolve this, configure and provide a policy file on the BinSkim command-line using the --policy argument (recommended), or pass --defaultPolicy to invoke built-in settings. Invoke the BinSkim.exe 'export' command to produce an initial policy file that can be edited if required and passed back into the tool..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to '{0}' was not analyzed as it does not appear to be a valid portable executable..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to '{0}' was not evaluated for check '{1}' as the analysis is not relevant based on observed binary metadata: {2}..",
"/// </summary>"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 17
| 1,463
| 84
|
51c6c07c9c1709842e0a6b9b7786386ea9f55e9e
|
BjoernKellermann/aludratest
|
src/main/java/org/aludratest/util/MostRecentUseCache.java
|
[
"Apache-2.0"
] |
Java
|
MostRecentUseCache
|
/** This class implements a MRU (Most recently used), factory-based cache. When querying for a given key of type <code>K</code> for
* which no value of type <code>V</code> is already stored, the factory of the cache is used to create an object of type
* <code>V</code> (using the key as factory input parameter). In the internal map, the value is stored as value for the <i>Hash
* Value</i> of the used key. The hash value calulcation defaults to {@link Object#hashCode()}, but can be overridden when
* providing an own {@link HashCalculator}. <br>
* After retrieving the object (either an already cached or newly created one), the hash value is inserted as first (or moved to
* first) in the internal MRU list. If the list has more elements than the maximum for the cache, the least recently used value
* (the last element in the list) is removed from the cache. The next query for the key of the removed value will cause the value
* to be newly created using the factory. <br>
* <br>
* This class is fully thread-safe.
*
* @author falbrech
*
* @param <K> Type of the key elements of this cache.
* @param <V> Type of the values being stored in this cache. */
|
This class implements a MRU (Most recently used), factory-based cache. When querying for a given key of type K for
which no value of type V is already stored, the factory of the cache is used to create an object of type
V (using the key as factory input parameter). In the internal map, the value is stored as value for the Hash
Value of the used key. The hash value calulcation defaults to Object#hashCode(), but can be overridden when
providing an own HashCalculator.
After retrieving the object (either an already cached or newly created one), the hash value is inserted as first (or moved to
first) in the internal MRU list. If the list has more elements than the maximum for the cache, the least recently used value
(the last element in the list) is removed from the cache. The next query for the key of the removed value will cause the value
to be newly created using the factory.
This class is fully thread-safe.
@author falbrech
@param Type of the key elements of this cache.
@param Type of the values being stored in this cache.
|
[
"This",
"class",
"implements",
"a",
"MRU",
"(",
"Most",
"recently",
"used",
")",
"factory",
"-",
"based",
"cache",
".",
"When",
"querying",
"for",
"a",
"given",
"key",
"of",
"type",
"K",
"for",
"which",
"no",
"value",
"of",
"type",
"V",
"is",
"already",
"stored",
"the",
"factory",
"of",
"the",
"cache",
"is",
"used",
"to",
"create",
"an",
"object",
"of",
"type",
"V",
"(",
"using",
"the",
"key",
"as",
"factory",
"input",
"parameter",
")",
".",
"In",
"the",
"internal",
"map",
"the",
"value",
"is",
"stored",
"as",
"value",
"for",
"the",
"Hash",
"Value",
"of",
"the",
"used",
"key",
".",
"The",
"hash",
"value",
"calulcation",
"defaults",
"to",
"Object#hashCode",
"()",
"but",
"can",
"be",
"overridden",
"when",
"providing",
"an",
"own",
"HashCalculator",
".",
"After",
"retrieving",
"the",
"object",
"(",
"either",
"an",
"already",
"cached",
"or",
"newly",
"created",
"one",
")",
"the",
"hash",
"value",
"is",
"inserted",
"as",
"first",
"(",
"or",
"moved",
"to",
"first",
")",
"in",
"the",
"internal",
"MRU",
"list",
".",
"If",
"the",
"list",
"has",
"more",
"elements",
"than",
"the",
"maximum",
"for",
"the",
"cache",
"the",
"least",
"recently",
"used",
"value",
"(",
"the",
"last",
"element",
"in",
"the",
"list",
")",
"is",
"removed",
"from",
"the",
"cache",
".",
"The",
"next",
"query",
"for",
"the",
"key",
"of",
"the",
"removed",
"value",
"will",
"cause",
"the",
"value",
"to",
"be",
"newly",
"created",
"using",
"the",
"factory",
".",
"This",
"class",
"is",
"fully",
"thread",
"-",
"safe",
".",
"@author",
"falbrech",
"@param",
"Type",
"of",
"the",
"key",
"elements",
"of",
"this",
"cache",
".",
"@param",
"Type",
"of",
"the",
"values",
"being",
"stored",
"in",
"this",
"cache",
"."
] |
public final class MostRecentUseCache<K, V> {
/** Interface for factories being able to create an object of type <code>O</code> when getting an input object of type
* <code>I</code>.
*
* @author falbrech
*
* @param <I> Type of input objects, being passed to {@link #create(Object)} as parameter.
* @param <O> Type of output objects, the return type of the {@link #create(Object)} method. */
public static interface Factory<I, O> {
/** Creates an object from a given input value.
*
* @param key Input value.
*
* @return Created object. */
public O create(I key);
}
/** Interface for hash value calculators. A hash value is encoded as String to be able to calculate long hashes.
*
* @author falbrech
*
* @param <E> Type of objects this calculator can calculate hash values for. */
public static interface HashCalculator<E> {
/** Calculate the hash value for the given object.
*
* @param object Object to calculate the hash value for.
*
* @return Hash value for the given object. */
public String hash(E object);
}
private Map<String, V> values = new HashMap<String, V>();
private Factory<K, V> factory;
private HashCalculator<K> hashCalculator;
private int maxSize;
private Set<String> lockedHashes = new HashSet<String>();
private List<String> mostRecentUseList = new LinkedList<String>();
/** Creates a new MRU Cache with the given factory and the given maximum capacity. The hashes of used keys are calculated using
* {@link Object#hashCode()}.
*
* @param factory Factory to use to create new values for given keys.
* @param maxSize Maximum size for this cache. */
public MostRecentUseCache(Factory<K, V> factory, int maxSize) {
this(factory, maxSize, new HashCodeCalculator<K>());
}
/** Creates a new MRU Cache with the given factory, the given maximum capacity, and the given calculator for hash values for
* used keys.
*
* @param factory Factory to use to create new values for given keys.
* @param maxSize Maximum size for this cache.
* @param hashCalculator The calculator to use to calculate a hash value for a given key. */
public MostRecentUseCache(Factory<K, V> factory, int maxSize, HashCalculator<K> hashCalculator) {
this.factory = factory;
this.maxSize = maxSize;
this.hashCalculator = hashCalculator;
}
/** Retrieves the value for the given key object. If the key's hash value is not yet (or no more) registered in this cache, the
* factory of the cache is used to create a new object. After creation, the key's hash value is inserted as first (or moved to
* first) in the cache's MRU list. If the MRU list has exceeded maximum size, the value to the last hash value stored in the
* list is removed from the cache.
*
* @param key Key to retrieve the value for.
*
* @return The value for the given key, either reused from cache, or newly created using the factory. */
public V get(K key) {
String hash = hash(key);
acquireLock(hash);
try {
V value = internalGetValue(hash);
if (value != null) {
reused(hash);
return value;
}
value = factory.create(key);
internalSetValue(hash, value);
addUsed(hash);
return value;
}
finally {
releaseLock(hash);
}
}
/** Clears this cache. */
public void clear() {
synchronized (mostRecentUseList) {
mostRecentUseList.clear();
}
synchronized (values) {
values.clear();
}
}
/** Returns the current size of this cache. Once a cache has reached its maximum size, this will always return the same
* (maximum) size, unless {@link #clear()} is invoked to clear the cache.
*
* @return The current size of this cache. */
public int getSize() {
synchronized (values) {
return values.size();
}
}
private String hash(K key) {
return hashCalculator.hash(key);
}
private void acquireLock(String hash) {
synchronized (lockedHashes) {
while (lockedHashes.contains(hash)) {
try {
lockedHashes.wait();
}
catch (InterruptedException e) {
return;
}
}
lockedHashes.add(hash);
}
}
private void releaseLock(String hash) {
synchronized (lockedHashes) {
if (lockedHashes.contains(hash)) {
lockedHashes.remove(hash);
lockedHashes.notifyAll();
}
}
}
private V internalGetValue(String hash) {
synchronized (values) {
return values.get(hash);
}
}
private void internalSetValue(String hash, V value) {
synchronized (values) {
values.put(hash, value);
}
}
private void internalRemoveValue(String hash) {
synchronized (values) {
values.remove(hash);
}
}
private void reused(String hash) {
synchronized (mostRecentUseList) {
mostRecentUseList.remove(hash);
mostRecentUseList.add(0, hash);
}
}
private void addUsed(String hash) {
synchronized (mostRecentUseList) {
mostRecentUseList.add(0, hash);
while (mostRecentUseList.size() > maxSize) {
internalRemoveValue(mostRecentUseList.get(maxSize));
mostRecentUseList.remove(maxSize);
}
}
}
private static class HashCodeCalculator<E> implements HashCalculator<E> {
@Override
public String hash(E object) {
return object == null ? "" : Integer.toHexString(object.hashCode());
}
}
}
|
[
"public",
"final",
"class",
"MostRecentUseCache",
"<",
"K",
",",
"V",
">",
"{",
"/** Interface for factories being able to create an object of type <code>O</code> when getting an input object of type\n * <code>I</code>.\n * \n * @author falbrech\n * \n * @param <I> Type of input objects, being passed to {@link #create(Object)} as parameter.\n * @param <O> Type of output objects, the return type of the {@link #create(Object)} method. */",
"public",
"static",
"interface",
"Factory",
"<",
"I",
",",
"O",
">",
"{",
"/** Creates an object from a given input value.\n * \n * @param key Input value.\n * \n * @return Created object. */",
"public",
"O",
"create",
"(",
"I",
"key",
")",
";",
"}",
"/** Interface for hash value calculators. A hash value is encoded as String to be able to calculate long hashes.\n * \n * @author falbrech\n * \n * @param <E> Type of objects this calculator can calculate hash values for. */",
"public",
"static",
"interface",
"HashCalculator",
"<",
"E",
">",
"{",
"/** Calculate the hash value for the given object.\n * \n * @param object Object to calculate the hash value for.\n * \n * @return Hash value for the given object. */",
"public",
"String",
"hash",
"(",
"E",
"object",
")",
";",
"}",
"private",
"Map",
"<",
"String",
",",
"V",
">",
"values",
"=",
"new",
"HashMap",
"<",
"String",
",",
"V",
">",
"(",
")",
";",
"private",
"Factory",
"<",
"K",
",",
"V",
">",
"factory",
";",
"private",
"HashCalculator",
"<",
"K",
">",
"hashCalculator",
";",
"private",
"int",
"maxSize",
";",
"private",
"Set",
"<",
"String",
">",
"lockedHashes",
"=",
"new",
"HashSet",
"<",
"String",
">",
"(",
")",
";",
"private",
"List",
"<",
"String",
">",
"mostRecentUseList",
"=",
"new",
"LinkedList",
"<",
"String",
">",
"(",
")",
";",
"/** Creates a new MRU Cache with the given factory and the given maximum capacity. The hashes of used keys are calculated using\n * {@link Object#hashCode()}.\n * \n * @param factory Factory to use to create new values for given keys.\n * @param maxSize Maximum size for this cache. */",
"public",
"MostRecentUseCache",
"(",
"Factory",
"<",
"K",
",",
"V",
">",
"factory",
",",
"int",
"maxSize",
")",
"{",
"this",
"(",
"factory",
",",
"maxSize",
",",
"new",
"HashCodeCalculator",
"<",
"K",
">",
"(",
")",
")",
";",
"}",
"/** Creates a new MRU Cache with the given factory, the given maximum capacity, and the given calculator for hash values for\n * used keys.\n * \n * @param factory Factory to use to create new values for given keys.\n * @param maxSize Maximum size for this cache.\n * @param hashCalculator The calculator to use to calculate a hash value for a given key. */",
"public",
"MostRecentUseCache",
"(",
"Factory",
"<",
"K",
",",
"V",
">",
"factory",
",",
"int",
"maxSize",
",",
"HashCalculator",
"<",
"K",
">",
"hashCalculator",
")",
"{",
"this",
".",
"factory",
"=",
"factory",
";",
"this",
".",
"maxSize",
"=",
"maxSize",
";",
"this",
".",
"hashCalculator",
"=",
"hashCalculator",
";",
"}",
"/** Retrieves the value for the given key object. If the key's hash value is not yet (or no more) registered in this cache, the\n * factory of the cache is used to create a new object. After creation, the key's hash value is inserted as first (or moved to\n * first) in the cache's MRU list. If the MRU list has exceeded maximum size, the value to the last hash value stored in the\n * list is removed from the cache.\n * \n * @param key Key to retrieve the value for.\n * \n * @return The value for the given key, either reused from cache, or newly created using the factory. */",
"public",
"V",
"get",
"(",
"K",
"key",
")",
"{",
"String",
"hash",
"=",
"hash",
"(",
"key",
")",
";",
"acquireLock",
"(",
"hash",
")",
";",
"try",
"{",
"V",
"value",
"=",
"internalGetValue",
"(",
"hash",
")",
";",
"if",
"(",
"value",
"!=",
"null",
")",
"{",
"reused",
"(",
"hash",
")",
";",
"return",
"value",
";",
"}",
"value",
"=",
"factory",
".",
"create",
"(",
"key",
")",
";",
"internalSetValue",
"(",
"hash",
",",
"value",
")",
";",
"addUsed",
"(",
"hash",
")",
";",
"return",
"value",
";",
"}",
"finally",
"{",
"releaseLock",
"(",
"hash",
")",
";",
"}",
"}",
"/** Clears this cache. */",
"public",
"void",
"clear",
"(",
")",
"{",
"synchronized",
"(",
"mostRecentUseList",
")",
"{",
"mostRecentUseList",
".",
"clear",
"(",
")",
";",
"}",
"synchronized",
"(",
"values",
")",
"{",
"values",
".",
"clear",
"(",
")",
";",
"}",
"}",
"/** Returns the current size of this cache. Once a cache has reached its maximum size, this will always return the same\n * (maximum) size, unless {@link #clear()} is invoked to clear the cache.\n * \n * @return The current size of this cache. */",
"public",
"int",
"getSize",
"(",
")",
"{",
"synchronized",
"(",
"values",
")",
"{",
"return",
"values",
".",
"size",
"(",
")",
";",
"}",
"}",
"private",
"String",
"hash",
"(",
"K",
"key",
")",
"{",
"return",
"hashCalculator",
".",
"hash",
"(",
"key",
")",
";",
"}",
"private",
"void",
"acquireLock",
"(",
"String",
"hash",
")",
"{",
"synchronized",
"(",
"lockedHashes",
")",
"{",
"while",
"(",
"lockedHashes",
".",
"contains",
"(",
"hash",
")",
")",
"{",
"try",
"{",
"lockedHashes",
".",
"wait",
"(",
")",
";",
"}",
"catch",
"(",
"InterruptedException",
"e",
")",
"{",
"return",
";",
"}",
"}",
"lockedHashes",
".",
"add",
"(",
"hash",
")",
";",
"}",
"}",
"private",
"void",
"releaseLock",
"(",
"String",
"hash",
")",
"{",
"synchronized",
"(",
"lockedHashes",
")",
"{",
"if",
"(",
"lockedHashes",
".",
"contains",
"(",
"hash",
")",
")",
"{",
"lockedHashes",
".",
"remove",
"(",
"hash",
")",
";",
"lockedHashes",
".",
"notifyAll",
"(",
")",
";",
"}",
"}",
"}",
"private",
"V",
"internalGetValue",
"(",
"String",
"hash",
")",
"{",
"synchronized",
"(",
"values",
")",
"{",
"return",
"values",
".",
"get",
"(",
"hash",
")",
";",
"}",
"}",
"private",
"void",
"internalSetValue",
"(",
"String",
"hash",
",",
"V",
"value",
")",
"{",
"synchronized",
"(",
"values",
")",
"{",
"values",
".",
"put",
"(",
"hash",
",",
"value",
")",
";",
"}",
"}",
"private",
"void",
"internalRemoveValue",
"(",
"String",
"hash",
")",
"{",
"synchronized",
"(",
"values",
")",
"{",
"values",
".",
"remove",
"(",
"hash",
")",
";",
"}",
"}",
"private",
"void",
"reused",
"(",
"String",
"hash",
")",
"{",
"synchronized",
"(",
"mostRecentUseList",
")",
"{",
"mostRecentUseList",
".",
"remove",
"(",
"hash",
")",
";",
"mostRecentUseList",
".",
"add",
"(",
"0",
",",
"hash",
")",
";",
"}",
"}",
"private",
"void",
"addUsed",
"(",
"String",
"hash",
")",
"{",
"synchronized",
"(",
"mostRecentUseList",
")",
"{",
"mostRecentUseList",
".",
"add",
"(",
"0",
",",
"hash",
")",
";",
"while",
"(",
"mostRecentUseList",
".",
"size",
"(",
")",
">",
"maxSize",
")",
"{",
"internalRemoveValue",
"(",
"mostRecentUseList",
".",
"get",
"(",
"maxSize",
")",
")",
";",
"mostRecentUseList",
".",
"remove",
"(",
"maxSize",
")",
";",
"}",
"}",
"}",
"private",
"static",
"class",
"HashCodeCalculator",
"<",
"E",
">",
"implements",
"HashCalculator",
"<",
"E",
">",
"{",
"@",
"Override",
"public",
"String",
"hash",
"(",
"E",
"object",
")",
"{",
"return",
"object",
"==",
"null",
"?",
"\"",
"\"",
":",
"Integer",
".",
"toHexString",
"(",
"object",
".",
"hashCode",
"(",
")",
")",
";",
"}",
"}",
"}"
] |
This class implements a MRU (Most recently used), factory-based cache.
|
[
"This",
"class",
"implements",
"a",
"MRU",
"(",
"Most",
"recently",
"used",
")",
"factory",
"-",
"based",
"cache",
"."
] |
[] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 14
| 1,296
| 291
|
a1048a12ac7c8c6196cefc79befb9073c89befd6
|
ianhanniballake/RecipeBook
|
RecipeBook/src/main/java/com/ianhanniballake/recipebook/ui/RecipeDetailActivity.java
|
[
"BSD-3-Clause"
] |
Java
|
RecipeDetailTabsAdapter
|
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to one of the sections/tabs/pages. We use a
* {@link android.support.v4.app.FragmentPagerAdapter} derivative, which will keep every loaded fragment in memory.
* If this becomes too memory intensive, it may be best to switch to a
* {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
|
A FragmentPagerAdapter that returns a fragment corresponding to one of the sections/tabs/pages. We use a
android.support.v4.app.FragmentPagerAdapter derivative, which will keep every loaded fragment in memory.
If this becomes too memory intensive, it may be best to switch to a
android.support.v4.app.FragmentStatePagerAdapter.
|
[
"A",
"FragmentPagerAdapter",
"that",
"returns",
"a",
"fragment",
"corresponding",
"to",
"one",
"of",
"the",
"sections",
"/",
"tabs",
"/",
"pages",
".",
"We",
"use",
"a",
"android",
".",
"support",
".",
"v4",
".",
"app",
".",
"FragmentPagerAdapter",
"derivative",
"which",
"will",
"keep",
"every",
"loaded",
"fragment",
"in",
"memory",
".",
"If",
"this",
"becomes",
"too",
"memory",
"intensive",
"it",
"may",
"be",
"best",
"to",
"switch",
"to",
"a",
"android",
".",
"support",
".",
"v4",
".",
"app",
".",
"FragmentStatePagerAdapter",
"."
] |
public static class RecipeDetailTabsAdapter extends FragmentPagerAdapter implements ActionBar.TabListener,
ViewPager.OnPageChangeListener
{
private final ActionBar actionBar;
private final Context context;
private final ViewPager pager;
/**
* Manages the set of static tabs
*
* @param activity
* Activity showing these swipeable tabs
* @param pager
* Pager displaying the tabs
*/
public RecipeDetailTabsAdapter(final Activity activity, final ViewPager pager)
{
super(activity.getFragmentManager());
context = activity;
actionBar = activity.getActionBar();
this.pager = pager;
}
@Override
public int getCount()
{
// Show 3 total pages.
return 3;
}
@Override
public Fragment getItem(final int position)
{
switch (position)
{
case 0:
return new RecipeDetailSummaryFragment();
case 1:
return new RecipeDetailIngredientFragment();
case 2:
return new RecipeDetailInstructionFragment();
default:
return null;
}
}
@Override
public CharSequence getPageTitle(final int position)
{
final Locale l = Locale.getDefault();
switch (position)
{
case 0:
return context.getString(R.string.title_summary).toUpperCase(l);
case 1:
return context.getString(R.string.title_ingredient_list).toUpperCase(l);
case 2:
return context.getString(R.string.title_instruction_list).toUpperCase(l);
default:
return null;
}
}
@Override
public void onPageScrolled(final int position, final float positionOffset, final int positionOffsetPixels)
{
// Nothing to do
}
@Override
public void onPageScrollStateChanged(final int state)
{
// Nothing to do
}
@Override
public void onPageSelected(final int position)
{
actionBar.setSelectedNavigationItem(position);
}
@Override
public void onTabReselected(final ActionBar.Tab tab, final FragmentTransaction fragmentTransaction)
{
// Nothing to do
}
@Override
public void onTabSelected(final ActionBar.Tab tab, final FragmentTransaction fragmentTransaction)
{
// When the given tab is selected, switch to the corresponding page in the ViewPager.
pager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(final ActionBar.Tab tab, final FragmentTransaction fragmentTransaction)
{
// Nothing to do
}
/**
* Ties the pager and tabs together
*/
public void setup()
{
pager.setAdapter(this);
pager.setOnPageChangeListener(this);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < getCount(); i++)
actionBar.addTab(actionBar.newTab().setText(getPageTitle(i)).setTabListener(this));
}
}
|
[
"public",
"static",
"class",
"RecipeDetailTabsAdapter",
"extends",
"FragmentPagerAdapter",
"implements",
"ActionBar",
".",
"TabListener",
",",
"ViewPager",
".",
"OnPageChangeListener",
"{",
"private",
"final",
"ActionBar",
"actionBar",
";",
"private",
"final",
"Context",
"context",
";",
"private",
"final",
"ViewPager",
"pager",
";",
"/**\n\t\t * Manages the set of static tabs\n\t\t * \n\t\t * @param activity\n\t\t * Activity showing these swipeable tabs\n\t\t * @param pager\n\t\t * Pager displaying the tabs\n\t\t */",
"public",
"RecipeDetailTabsAdapter",
"(",
"final",
"Activity",
"activity",
",",
"final",
"ViewPager",
"pager",
")",
"{",
"super",
"(",
"activity",
".",
"getFragmentManager",
"(",
")",
")",
";",
"context",
"=",
"activity",
";",
"actionBar",
"=",
"activity",
".",
"getActionBar",
"(",
")",
";",
"this",
".",
"pager",
"=",
"pager",
";",
"}",
"@",
"Override",
"public",
"int",
"getCount",
"(",
")",
"{",
"return",
"3",
";",
"}",
"@",
"Override",
"public",
"Fragment",
"getItem",
"(",
"final",
"int",
"position",
")",
"{",
"switch",
"(",
"position",
")",
"{",
"case",
"0",
":",
"return",
"new",
"RecipeDetailSummaryFragment",
"(",
")",
";",
"case",
"1",
":",
"return",
"new",
"RecipeDetailIngredientFragment",
"(",
")",
";",
"case",
"2",
":",
"return",
"new",
"RecipeDetailInstructionFragment",
"(",
")",
";",
"default",
":",
"return",
"null",
";",
"}",
"}",
"@",
"Override",
"public",
"CharSequence",
"getPageTitle",
"(",
"final",
"int",
"position",
")",
"{",
"final",
"Locale",
"l",
"=",
"Locale",
".",
"getDefault",
"(",
")",
";",
"switch",
"(",
"position",
")",
"{",
"case",
"0",
":",
"return",
"context",
".",
"getString",
"(",
"R",
".",
"string",
".",
"title_summary",
")",
".",
"toUpperCase",
"(",
"l",
")",
";",
"case",
"1",
":",
"return",
"context",
".",
"getString",
"(",
"R",
".",
"string",
".",
"title_ingredient_list",
")",
".",
"toUpperCase",
"(",
"l",
")",
";",
"case",
"2",
":",
"return",
"context",
".",
"getString",
"(",
"R",
".",
"string",
".",
"title_instruction_list",
")",
".",
"toUpperCase",
"(",
"l",
")",
";",
"default",
":",
"return",
"null",
";",
"}",
"}",
"@",
"Override",
"public",
"void",
"onPageScrolled",
"(",
"final",
"int",
"position",
",",
"final",
"float",
"positionOffset",
",",
"final",
"int",
"positionOffsetPixels",
")",
"{",
"}",
"@",
"Override",
"public",
"void",
"onPageScrollStateChanged",
"(",
"final",
"int",
"state",
")",
"{",
"}",
"@",
"Override",
"public",
"void",
"onPageSelected",
"(",
"final",
"int",
"position",
")",
"{",
"actionBar",
".",
"setSelectedNavigationItem",
"(",
"position",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"onTabReselected",
"(",
"final",
"ActionBar",
".",
"Tab",
"tab",
",",
"final",
"FragmentTransaction",
"fragmentTransaction",
")",
"{",
"}",
"@",
"Override",
"public",
"void",
"onTabSelected",
"(",
"final",
"ActionBar",
".",
"Tab",
"tab",
",",
"final",
"FragmentTransaction",
"fragmentTransaction",
")",
"{",
"pager",
".",
"setCurrentItem",
"(",
"tab",
".",
"getPosition",
"(",
")",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"onTabUnselected",
"(",
"final",
"ActionBar",
".",
"Tab",
"tab",
",",
"final",
"FragmentTransaction",
"fragmentTransaction",
")",
"{",
"}",
"/**\n\t\t * Ties the pager and tabs together\n\t\t */",
"public",
"void",
"setup",
"(",
")",
"{",
"pager",
".",
"setAdapter",
"(",
"this",
")",
";",
"pager",
".",
"setOnPageChangeListener",
"(",
"this",
")",
";",
"actionBar",
".",
"setNavigationMode",
"(",
"ActionBar",
".",
"NAVIGATION_MODE_TABS",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"getCount",
"(",
")",
";",
"i",
"++",
")",
"actionBar",
".",
"addTab",
"(",
"actionBar",
".",
"newTab",
"(",
")",
".",
"setText",
"(",
"getPageTitle",
"(",
"i",
")",
")",
".",
"setTabListener",
"(",
"this",
")",
")",
";",
"}",
"}"
] |
A {@link FragmentPagerAdapter} that returns a fragment corresponding to one of the sections/tabs/pages.
|
[
"A",
"{",
"@link",
"FragmentPagerAdapter",
"}",
"that",
"returns",
"a",
"fragment",
"corresponding",
"to",
"one",
"of",
"the",
"sections",
"/",
"tabs",
"/",
"pages",
"."
] |
[
"// Show 3 total pages.",
"// Nothing to do",
"// Nothing to do",
"// Nothing to do",
"// When the given tab is selected, switch to the corresponding page in the ViewPager.",
"// Nothing to do",
"// For each of the sections in the app, add a tab to the action bar."
] |
[
{
"param": "FragmentPagerAdapter",
"type": null
},
{
"param": "ActionBar.TabListener,\n\t\t\tViewPager.OnPageChangeListener",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "FragmentPagerAdapter",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "ActionBar.TabListener,\n\t\t\tViewPager.OnPageChangeListener",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 14
| 668
| 83
|
8942a6df493997830121b4399bd25d02e06ac7b9
|
thiagoritto/ross
|
ross/results.py
|
[
"MIT"
] |
Python
|
OrbitResponseResults
|
Class used to store results and provide plots for Orbit Response
Analysis.
This class takes the results from orbit response analysis and creates a
plot (2D or 3D) given a force array and a time array.
Parameters
----------
t: array
Time values for the output.
yout: array
System response.
xout: array
Time evolution of the state vector.
nodes_list: array
list with nodes from a rotor model
nodes_pos: array
Rotor nodes axial positions
Returns
-------
ax : matplotlib.axes
Matplotlib axes with orbit response plot.
if plot_type == "3d"
bk_ax : bokeh axes
Bokeh axes with orbit response plot
if plot_type == "2d"
|
Class used to store results and provide plots for Orbit Response
Analysis.
This class takes the results from orbit response analysis and creates a
plot (2D or 3D) given a force array and a time array.
Parameters
array
Time values for the output.
yout: array
System response.
xout: array
Time evolution of the state vector.
nodes_list: array
list with nodes from a rotor model
nodes_pos: array
Rotor nodes axial positions
Returns
ax : matplotlib.axes
Matplotlib axes with orbit response plot.
if plot_type == "3d"
bk_ax : bokeh axes
Bokeh axes with orbit response plot
if plot_type == "2d"
|
[
"Class",
"used",
"to",
"store",
"results",
"and",
"provide",
"plots",
"for",
"Orbit",
"Response",
"Analysis",
".",
"This",
"class",
"takes",
"the",
"results",
"from",
"orbit",
"response",
"analysis",
"and",
"creates",
"a",
"plot",
"(",
"2D",
"or",
"3D",
")",
"given",
"a",
"force",
"array",
"and",
"a",
"time",
"array",
".",
"Parameters",
"array",
"Time",
"values",
"for",
"the",
"output",
".",
"yout",
":",
"array",
"System",
"response",
".",
"xout",
":",
"array",
"Time",
"evolution",
"of",
"the",
"state",
"vector",
".",
"nodes_list",
":",
"array",
"list",
"with",
"nodes",
"from",
"a",
"rotor",
"model",
"nodes_pos",
":",
"array",
"Rotor",
"nodes",
"axial",
"positions",
"Returns",
"ax",
":",
"matplotlib",
".",
"axes",
"Matplotlib",
"axes",
"with",
"orbit",
"response",
"plot",
".",
"if",
"plot_type",
"==",
"\"",
"3d",
"\"",
"bk_ax",
":",
"bokeh",
"axes",
"Bokeh",
"axes",
"with",
"orbit",
"response",
"plot",
"if",
"plot_type",
"==",
"\"",
"2d",
"\""
] |
class OrbitResponseResults:
"""Class used to store results and provide plots for Orbit Response
Analysis.
This class takes the results from orbit response analysis and creates a
plot (2D or 3D) given a force array and a time array.
Parameters
----------
t: array
Time values for the output.
yout: array
System response.
xout: array
Time evolution of the state vector.
nodes_list: array
list with nodes from a rotor model
nodes_pos: array
Rotor nodes axial positions
Returns
-------
ax : matplotlib.axes
Matplotlib axes with orbit response plot.
if plot_type == "3d"
bk_ax : bokeh axes
Bokeh axes with orbit response plot
if plot_type == "2d"
"""
def __init__(self, t, yout, xout, nodes_list, nodes_pos):
self.t = t
self.yout = yout
self.xout = xout
self.nodes_pos = nodes_pos
self.nodes_list = nodes_list
def _plot3d(self, fig=None, ax=None):
"""Plot orbit response.
This function will take a rotor object and plot its orbit response
using Matplotlib
Parameters
----------
fig : matplotlib figure
The figure object with the plot.
if None, creates a new one
ax : matplotlib.axes
Matplotlib axes where orbit response will be plotted.
if None, creates a new one
Returns
-------
ax : matplotlib.axes
Matplotlib axes with orbit response plot.
"""
if ax is None:
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.gca(projection="3d")
for n in self.nodes_list:
z_pos = np.ones(self.yout.shape[0]) * self.nodes_pos[n]
ax.plot(
self.yout[200:, 4 * n],
self.yout[200:, 4 * n + 1],
z_pos[200:],
zdir="x",
color="k"
)
# plot center line
line = np.zeros(len(self.nodes_pos))
ax.plot(line, line, self.nodes_pos, "k-.", linewidth=1.5, zdir="x")
ax.set_xlabel("Rotor length (m)", labelpad=20, fontsize=18)
ax.set_ylabel("Amplitude - X direction (m)", labelpad=20, fontsize=18)
ax.set_zlabel("Amplitude - Y direction (m)", labelpad=20, fontsize=18)
ax.set_title("Rotor Orbits", fontsize=18)
ax.tick_params(axis='both', which='major', labelsize=18)
ax.tick_params(axis='both', which='minor', labelsize=18)
return ax
def _plot2d(self, node):
"""Plot orbit response.
This function will take a rotor object and plot its orbit response
using Bokeh
Parameters
----------
node: int, optional
Selected node to plot orbit.
Returns
-------
bk_ax : bokeh axes
Bokeh axes with orbit response plot
if plot_type == "bokeh"
"""
# bokeh plot - create a new plot
bk_ax = figure(
tools="pan, box_zoom, wheel_zoom, reset, save",
width=640,
height=480,
title="Response for node %s" % (node),
x_axis_label="Amplitude - X direction (m)",
y_axis_label="Amplitude - Y direction (m)"
)
bk_ax.xaxis.axis_label_text_font_size = "20pt"
bk_ax.yaxis.axis_label_text_font_size = "20pt"
bk_ax.title.text_font_size = "14pt"
bk_ax.line(
self.yout[:, 4 * node],
self.yout[:, 4 * node + 1],
line_width=3,
line_color=bokeh_colors[0],
)
return bk_ax
def plot(self, plot_type="3d", node=None, **kwargs):
"""Plot orbit response.
This function will take a rotor object and plot its orbit response
Parameters
----------
plot_type: str
3d or 2d.
Choose between plotting orbit for all nodes (3d plot) and
plotting orbit for a single node (2d plot).
Default is 3d.
node: int, optional
Selected node to plot orbit.
Fill this attribute only when selection plot_type = "2d".
Detault is None
kwargs : optional
Additional key word arguments can be passed to change
the plot (e.g. linestyle='--')
Returns
-------
ax : matplotlib.axes
Matplotlib axes with time response plot.
if plot_type == "3d"
bk_ax : bokeh axes
Bokeh axes with time response plot
if plot_type == "2d"
"""
if plot_type == "3d":
return self._plot3d(**kwargs)
elif plot_type == "2d":
if node is None:
raise Exception("Select a node to plot orbit when plotting 2D")
elif node not in self.nodes_list:
raise Exception("Select a valid node to plot 2D orbit")
return self._plot2d(node=node, **kwargs)
else:
raise ValueError(f"{plot_type} is not a valid plot type.")
|
[
"class",
"OrbitResponseResults",
":",
"def",
"__init__",
"(",
"self",
",",
"t",
",",
"yout",
",",
"xout",
",",
"nodes_list",
",",
"nodes_pos",
")",
":",
"self",
".",
"t",
"=",
"t",
"self",
".",
"yout",
"=",
"yout",
"self",
".",
"xout",
"=",
"xout",
"self",
".",
"nodes_pos",
"=",
"nodes_pos",
"self",
".",
"nodes_list",
"=",
"nodes_list",
"def",
"_plot3d",
"(",
"self",
",",
"fig",
"=",
"None",
",",
"ax",
"=",
"None",
")",
":",
"\"\"\"Plot orbit response.\n\n This function will take a rotor object and plot its orbit response\n using Matplotlib\n\n Parameters\n ----------\n fig : matplotlib figure\n The figure object with the plot.\n if None, creates a new one\n ax : matplotlib.axes\n Matplotlib axes where orbit response will be plotted.\n if None, creates a new one\n\n Returns\n -------\n ax : matplotlib.axes\n Matplotlib axes with orbit response plot.\n \"\"\"",
"if",
"ax",
"is",
"None",
":",
"from",
"mpl_toolkits",
".",
"mplot3d",
"import",
"Axes3D",
"fig",
"=",
"plt",
".",
"figure",
"(",
")",
"ax",
"=",
"fig",
".",
"gca",
"(",
"projection",
"=",
"\"3d\"",
")",
"for",
"n",
"in",
"self",
".",
"nodes_list",
":",
"z_pos",
"=",
"np",
".",
"ones",
"(",
"self",
".",
"yout",
".",
"shape",
"[",
"0",
"]",
")",
"*",
"self",
".",
"nodes_pos",
"[",
"n",
"]",
"ax",
".",
"plot",
"(",
"self",
".",
"yout",
"[",
"200",
":",
",",
"4",
"*",
"n",
"]",
",",
"self",
".",
"yout",
"[",
"200",
":",
",",
"4",
"*",
"n",
"+",
"1",
"]",
",",
"z_pos",
"[",
"200",
":",
"]",
",",
"zdir",
"=",
"\"x\"",
",",
"color",
"=",
"\"k\"",
")",
"line",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"self",
".",
"nodes_pos",
")",
")",
"ax",
".",
"plot",
"(",
"line",
",",
"line",
",",
"self",
".",
"nodes_pos",
",",
"\"k-.\"",
",",
"linewidth",
"=",
"1.5",
",",
"zdir",
"=",
"\"x\"",
")",
"ax",
".",
"set_xlabel",
"(",
"\"Rotor length (m)\"",
",",
"labelpad",
"=",
"20",
",",
"fontsize",
"=",
"18",
")",
"ax",
".",
"set_ylabel",
"(",
"\"Amplitude - X direction (m)\"",
",",
"labelpad",
"=",
"20",
",",
"fontsize",
"=",
"18",
")",
"ax",
".",
"set_zlabel",
"(",
"\"Amplitude - Y direction (m)\"",
",",
"labelpad",
"=",
"20",
",",
"fontsize",
"=",
"18",
")",
"ax",
".",
"set_title",
"(",
"\"Rotor Orbits\"",
",",
"fontsize",
"=",
"18",
")",
"ax",
".",
"tick_params",
"(",
"axis",
"=",
"'both'",
",",
"which",
"=",
"'major'",
",",
"labelsize",
"=",
"18",
")",
"ax",
".",
"tick_params",
"(",
"axis",
"=",
"'both'",
",",
"which",
"=",
"'minor'",
",",
"labelsize",
"=",
"18",
")",
"return",
"ax",
"def",
"_plot2d",
"(",
"self",
",",
"node",
")",
":",
"\"\"\"Plot orbit response.\n\n This function will take a rotor object and plot its orbit response\n using Bokeh\n\n Parameters\n ----------\n node: int, optional\n Selected node to plot orbit.\n\n Returns\n -------\n bk_ax : bokeh axes\n Bokeh axes with orbit response plot\n if plot_type == \"bokeh\"\n \"\"\"",
"bk_ax",
"=",
"figure",
"(",
"tools",
"=",
"\"pan, box_zoom, wheel_zoom, reset, save\"",
",",
"width",
"=",
"640",
",",
"height",
"=",
"480",
",",
"title",
"=",
"\"Response for node %s\"",
"%",
"(",
"node",
")",
",",
"x_axis_label",
"=",
"\"Amplitude - X direction (m)\"",
",",
"y_axis_label",
"=",
"\"Amplitude - Y direction (m)\"",
")",
"bk_ax",
".",
"xaxis",
".",
"axis_label_text_font_size",
"=",
"\"20pt\"",
"bk_ax",
".",
"yaxis",
".",
"axis_label_text_font_size",
"=",
"\"20pt\"",
"bk_ax",
".",
"title",
".",
"text_font_size",
"=",
"\"14pt\"",
"bk_ax",
".",
"line",
"(",
"self",
".",
"yout",
"[",
":",
",",
"4",
"*",
"node",
"]",
",",
"self",
".",
"yout",
"[",
":",
",",
"4",
"*",
"node",
"+",
"1",
"]",
",",
"line_width",
"=",
"3",
",",
"line_color",
"=",
"bokeh_colors",
"[",
"0",
"]",
",",
")",
"return",
"bk_ax",
"def",
"plot",
"(",
"self",
",",
"plot_type",
"=",
"\"3d\"",
",",
"node",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"\"\"\"Plot orbit response.\n\n This function will take a rotor object and plot its orbit response\n\n Parameters\n ----------\n plot_type: str\n 3d or 2d.\n Choose between plotting orbit for all nodes (3d plot) and\n plotting orbit for a single node (2d plot).\n Default is 3d.\n node: int, optional\n Selected node to plot orbit.\n Fill this attribute only when selection plot_type = \"2d\".\n Detault is None\n kwargs : optional\n Additional key word arguments can be passed to change\n the plot (e.g. linestyle='--')\n\n Returns\n -------\n ax : matplotlib.axes\n Matplotlib axes with time response plot.\n if plot_type == \"3d\"\n bk_ax : bokeh axes\n Bokeh axes with time response plot\n if plot_type == \"2d\"\n \"\"\"",
"if",
"plot_type",
"==",
"\"3d\"",
":",
"return",
"self",
".",
"_plot3d",
"(",
"**",
"kwargs",
")",
"elif",
"plot_type",
"==",
"\"2d\"",
":",
"if",
"node",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"Select a node to plot orbit when plotting 2D\"",
")",
"elif",
"node",
"not",
"in",
"self",
".",
"nodes_list",
":",
"raise",
"Exception",
"(",
"\"Select a valid node to plot 2D orbit\"",
")",
"return",
"self",
".",
"_plot2d",
"(",
"node",
"=",
"node",
",",
"**",
"kwargs",
")",
"else",
":",
"raise",
"ValueError",
"(",
"f\"{plot_type} is not a valid plot type.\"",
")"
] |
Class used to store results and provide plots for Orbit Response
Analysis.
|
[
"Class",
"used",
"to",
"store",
"results",
"and",
"provide",
"plots",
"for",
"Orbit",
"Response",
"Analysis",
"."
] |
[
"\"\"\"Class used to store results and provide plots for Orbit Response\n Analysis.\n\n This class takes the results from orbit response analysis and creates a\n plot (2D or 3D) given a force array and a time array.\n\n Parameters\n ----------\n t: array\n Time values for the output.\n yout: array\n System response.\n xout: array\n Time evolution of the state vector.\n nodes_list: array\n list with nodes from a rotor model\n nodes_pos: array\n Rotor nodes axial positions\n\n Returns\n -------\n ax : matplotlib.axes\n Matplotlib axes with orbit response plot.\n if plot_type == \"3d\"\n bk_ax : bokeh axes\n Bokeh axes with orbit response plot\n if plot_type == \"2d\"\n \"\"\"",
"\"\"\"Plot orbit response.\n\n This function will take a rotor object and plot its orbit response\n using Matplotlib\n\n Parameters\n ----------\n fig : matplotlib figure\n The figure object with the plot.\n if None, creates a new one\n ax : matplotlib.axes\n Matplotlib axes where orbit response will be plotted.\n if None, creates a new one\n\n Returns\n -------\n ax : matplotlib.axes\n Matplotlib axes with orbit response plot.\n \"\"\"",
"# plot center line",
"\"\"\"Plot orbit response.\n\n This function will take a rotor object and plot its orbit response\n using Bokeh\n\n Parameters\n ----------\n node: int, optional\n Selected node to plot orbit.\n\n Returns\n -------\n bk_ax : bokeh axes\n Bokeh axes with orbit response plot\n if plot_type == \"bokeh\"\n \"\"\"",
"# bokeh plot - create a new plot",
"\"\"\"Plot orbit response.\n\n This function will take a rotor object and plot its orbit response\n\n Parameters\n ----------\n plot_type: str\n 3d or 2d.\n Choose between plotting orbit for all nodes (3d plot) and\n plotting orbit for a single node (2d plot).\n Default is 3d.\n node: int, optional\n Selected node to plot orbit.\n Fill this attribute only when selection plot_type = \"2d\".\n Detault is None\n kwargs : optional\n Additional key word arguments can be passed to change\n the plot (e.g. linestyle='--')\n\n Returns\n -------\n ax : matplotlib.axes\n Matplotlib axes with time response plot.\n if plot_type == \"3d\"\n bk_ax : bokeh axes\n Bokeh axes with time response plot\n if plot_type == \"2d\"\n \"\"\""
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 15
| 1,225
| 173
|
96763d273d30ea6874451978a305f778d8c5a801
|
7dev7urandom/mcblend
|
mcblend/operator_func/model.py
|
[
"MIT"
] |
Python
|
BoneExport
|
Object that represents a Bone during model export.
# Properties
- `model: ModelExport` - a model that contains this bone.
- `name: str` - the name of the bone.
- `parent: Optional[str]` - the name of a parent of this bone
- `rotation: np.ndarray` - rotation of the bone.
- `pivot: np.ndarray` - pivot of the bone.
- `cubes: List[CubeExport]` - list of cubes to export.
- `locators: Dict[str, LocatorExport]` - list of locators to export.
(if exists) or None
|
Object that represents a Bone during model export.
Properties
`model: ModelExport` - a model that contains this bone.
`name: str` - the name of the bone.
`parent: Optional[str]` - the name of a parent of this bone
`rotation: np.ndarray` - rotation of the bone.
`pivot: np.ndarray` - pivot of the bone.
`cubes: List[CubeExport]` - list of cubes to export.
`locators: Dict[str, LocatorExport]` - list of locators to export.
(if exists) or None
|
[
"Object",
"that",
"represents",
"a",
"Bone",
"during",
"model",
"export",
".",
"Properties",
"`",
"model",
":",
"ModelExport",
"`",
"-",
"a",
"model",
"that",
"contains",
"this",
"bone",
".",
"`",
"name",
":",
"str",
"`",
"-",
"the",
"name",
"of",
"the",
"bone",
".",
"`",
"parent",
":",
"Optional",
"[",
"str",
"]",
"`",
"-",
"the",
"name",
"of",
"a",
"parent",
"of",
"this",
"bone",
"`",
"rotation",
":",
"np",
".",
"ndarray",
"`",
"-",
"rotation",
"of",
"the",
"bone",
".",
"`",
"pivot",
":",
"np",
".",
"ndarray",
"`",
"-",
"pivot",
"of",
"the",
"bone",
".",
"`",
"cubes",
":",
"List",
"[",
"CubeExport",
"]",
"`",
"-",
"list",
"of",
"cubes",
"to",
"export",
".",
"`",
"locators",
":",
"Dict",
"[",
"str",
"LocatorExport",
"]",
"`",
"-",
"list",
"of",
"locators",
"to",
"export",
".",
"(",
"if",
"exists",
")",
"or",
"None"
] |
class BoneExport:
'''
Object that represents a Bone during model export.
# Properties
- `model: ModelExport` - a model that contains this bone.
- `name: str` - the name of the bone.
- `parent: Optional[str]` - the name of a parent of this bone
- `rotation: np.ndarray` - rotation of the bone.
- `pivot: np.ndarray` - pivot of the bone.
- `cubes: List[CubeExport]` - list of cubes to export.
- `locators: Dict[str, LocatorExport]` - list of locators to export.
(if exists) or None
'''
def __init__(self, bone: McblendObject, model: ModelExport):
'''
Creates BoneExport. If the input value of BONE or BOTH McObjectType
than ValueError is raised.
'''
self.model = model
# Test if bone is valid input object
if bone.mctype not in [MCObjType.BONE, MCObjType.BOTH]:
raise ValueError('Input object is not a bone.')
# Create cubes and locators list
cubes: List[McblendObject] = []
if bone.mctype == MCObjType.BOTH: # Else MCObjType == BOTH
cubes.append(bone)
locators: List[McblendObject] = []
# Add children cubes if they are MCObjType.CUBE type
for child in bone.children:
if child.mctype is MCObjType.CUBE:
cubes.append(child)
elif child.mctype is MCObjType.LOCATOR:
locators.append(child)
self.name: str = bone.obj_name
self.parent: Optional[str] = (
None if bone.parent is None else bone.parent.obj_name)
self.rotation: np.ndarray = bone.get_mcrotation(bone.parent)
self.pivot: np.ndarray = bone.mcpivot * MINECRAFT_SCALE_FACTOR
self.cubes: List[CubeExport] = []
self.poly_mesh: PolyMesh = PolyMesh()
self.locators: Dict[str, LocatorExport] = {}
self.load(bone, cubes, locators)
def load(
self, thisobj: McblendObject, cube_objs: List[McblendObject],
locator_objs: List[McblendObject]):
'''
Used in constructor to cubes and locators.
'''
uv_factory = UvExportFactory(
(self.model.texture_width, self.model.texture_height)
)
def _scale(objprop: McblendObject) -> np.ndarray:
'''Scale of a bone'''
_, _, scale = objprop.obj_matrix_world.decompose()
return np.array(scale.xzy)
# Set locators
for locatorprop in locator_objs:
_l_scale = _scale(locatorprop)
l_pivot = locatorprop.mcpivot * MINECRAFT_SCALE_FACTOR
l_origin = l_pivot + (
locatorprop.mccube_position *
_l_scale * MINECRAFT_SCALE_FACTOR
)
self.locators[locatorprop.obj_name] = LocatorExport(l_origin)
# Set cubes
for cubeprop in cube_objs:
if cubeprop.mesh_type is MeshType.CUBE:
_c_scale = _scale(cubeprop)
c_size = cubeprop.mcube_size * _c_scale * MINECRAFT_SCALE_FACTOR
c_pivot = cubeprop.mcpivot * MINECRAFT_SCALE_FACTOR
c_origin = c_pivot + (
cubeprop.mccube_position * _c_scale * MINECRAFT_SCALE_FACTOR
)
c_rot = cubeprop.get_mcrotation(thisobj)
if cubeprop.inflate != 0:
c_size = c_size - cubeprop.inflate*2
c_origin = c_origin + cubeprop.inflate
uv = uv_factory.get_uv_export(cubeprop, c_size)
cube = CubeExport(
size=c_size, pivot=c_pivot, origin=c_origin,
rotation=c_rot, inflate=cubeprop.inflate, uv=uv)
self.cubes.append(cube)
elif cubeprop.mesh_type is MeshType.POLY_MESH:
cubeprop.obj_data.calc_normals_split()
polygons = cubeprop.obj_data.polygons # loop ids and vertices
vertices = cubeprop.obj_data.vertices # crds
loops = cubeprop.obj_data.loops # normals
uv_data = cubeprop.obj_data.uv_layers.active.data # uv
inv_bone_matrix = cubeprop.get_local_matrix(thisobj)
positions: List[List[float]] = []
normals: List[List[float]] = []
polys: List[List[Tuple[int, int, int]]] = []
uvs: List[List[int]] = [list(i.uv) for i in uv_data]
for vertex in vertices:
transformed_vertex = inv_bone_matrix @ vertex.co
transformed_vertex = (
np.array(transformed_vertex) * MINECRAFT_SCALE_FACTOR *
np.array(thisobj.obj_matrix_world.to_scale())
)[[0, 2, 1]] + self.pivot
positions.append(list(transformed_vertex))
for loop in loops:
transformed_normal = mathutils.Vector(
np.array(loop.normal)[[0, 2, 1]]
).normalized()
normals.append(list(transformed_normal))
for poly in polygons:
# vertex data -> List[(positions, normals, uvs)]
curr_poly: List[Tuple[int, int, int]] = []
for loop_id, vertex_id in zip(
poly.loop_indices, poly.vertices):
curr_poly.append((vertex_id, loop_id, loop_id))
if len(curr_poly) == 3:
curr_poly.append(copy(curr_poly[2]))
polys.append(curr_poly)
self.poly_mesh.extend_mesh_data(positions, normals, polys, uvs)
def json(self) -> Dict:
'''
Returns the dictionary that represents a single mcbone in json file
of model.
# Returns:
`Dict` - the single bone from Minecraft model.
'''
# Basic bone properties
mcbone: Dict = {'name': self.name}
if self.parent is not None:
mcbone['parent'] = self.parent
mcbone['pivot'] = get_vect_json(self.pivot)
mcbone['rotation'] = get_vect_json(self.rotation)
# Locators
if len(self.locators) > 0:
mcbone['locators'] = {}
for name, locator in self.locators.items():
mcbone['locators'][name] = locator.json()
# Cubess
if len(self.cubes) > 0:
mcbone['cubes'] = []
for cube in self.cubes:
mcbone['cubes'].append(cube.json())
if not self.poly_mesh.is_empty:
mcbone['poly_mesh'] = self.poly_mesh.json()
return mcbone
|
[
"class",
"BoneExport",
":",
"def",
"__init__",
"(",
"self",
",",
"bone",
":",
"McblendObject",
",",
"model",
":",
"ModelExport",
")",
":",
"'''\n Creates BoneExport. If the input value of BONE or BOTH McObjectType\n than ValueError is raised.\n '''",
"self",
".",
"model",
"=",
"model",
"if",
"bone",
".",
"mctype",
"not",
"in",
"[",
"MCObjType",
".",
"BONE",
",",
"MCObjType",
".",
"BOTH",
"]",
":",
"raise",
"ValueError",
"(",
"'Input object is not a bone.'",
")",
"cubes",
":",
"List",
"[",
"McblendObject",
"]",
"=",
"[",
"]",
"if",
"bone",
".",
"mctype",
"==",
"MCObjType",
".",
"BOTH",
":",
"cubes",
".",
"append",
"(",
"bone",
")",
"locators",
":",
"List",
"[",
"McblendObject",
"]",
"=",
"[",
"]",
"for",
"child",
"in",
"bone",
".",
"children",
":",
"if",
"child",
".",
"mctype",
"is",
"MCObjType",
".",
"CUBE",
":",
"cubes",
".",
"append",
"(",
"child",
")",
"elif",
"child",
".",
"mctype",
"is",
"MCObjType",
".",
"LOCATOR",
":",
"locators",
".",
"append",
"(",
"child",
")",
"self",
".",
"name",
":",
"str",
"=",
"bone",
".",
"obj_name",
"self",
".",
"parent",
":",
"Optional",
"[",
"str",
"]",
"=",
"(",
"None",
"if",
"bone",
".",
"parent",
"is",
"None",
"else",
"bone",
".",
"parent",
".",
"obj_name",
")",
"self",
".",
"rotation",
":",
"np",
".",
"ndarray",
"=",
"bone",
".",
"get_mcrotation",
"(",
"bone",
".",
"parent",
")",
"self",
".",
"pivot",
":",
"np",
".",
"ndarray",
"=",
"bone",
".",
"mcpivot",
"*",
"MINECRAFT_SCALE_FACTOR",
"self",
".",
"cubes",
":",
"List",
"[",
"CubeExport",
"]",
"=",
"[",
"]",
"self",
".",
"poly_mesh",
":",
"PolyMesh",
"=",
"PolyMesh",
"(",
")",
"self",
".",
"locators",
":",
"Dict",
"[",
"str",
",",
"LocatorExport",
"]",
"=",
"{",
"}",
"self",
".",
"load",
"(",
"bone",
",",
"cubes",
",",
"locators",
")",
"def",
"load",
"(",
"self",
",",
"thisobj",
":",
"McblendObject",
",",
"cube_objs",
":",
"List",
"[",
"McblendObject",
"]",
",",
"locator_objs",
":",
"List",
"[",
"McblendObject",
"]",
")",
":",
"'''\n Used in constructor to cubes and locators.\n '''",
"uv_factory",
"=",
"UvExportFactory",
"(",
"(",
"self",
".",
"model",
".",
"texture_width",
",",
"self",
".",
"model",
".",
"texture_height",
")",
")",
"def",
"_scale",
"(",
"objprop",
":",
"McblendObject",
")",
"->",
"np",
".",
"ndarray",
":",
"'''Scale of a bone'''",
"_",
",",
"_",
",",
"scale",
"=",
"objprop",
".",
"obj_matrix_world",
".",
"decompose",
"(",
")",
"return",
"np",
".",
"array",
"(",
"scale",
".",
"xzy",
")",
"for",
"locatorprop",
"in",
"locator_objs",
":",
"_l_scale",
"=",
"_scale",
"(",
"locatorprop",
")",
"l_pivot",
"=",
"locatorprop",
".",
"mcpivot",
"*",
"MINECRAFT_SCALE_FACTOR",
"l_origin",
"=",
"l_pivot",
"+",
"(",
"locatorprop",
".",
"mccube_position",
"*",
"_l_scale",
"*",
"MINECRAFT_SCALE_FACTOR",
")",
"self",
".",
"locators",
"[",
"locatorprop",
".",
"obj_name",
"]",
"=",
"LocatorExport",
"(",
"l_origin",
")",
"for",
"cubeprop",
"in",
"cube_objs",
":",
"if",
"cubeprop",
".",
"mesh_type",
"is",
"MeshType",
".",
"CUBE",
":",
"_c_scale",
"=",
"_scale",
"(",
"cubeprop",
")",
"c_size",
"=",
"cubeprop",
".",
"mcube_size",
"*",
"_c_scale",
"*",
"MINECRAFT_SCALE_FACTOR",
"c_pivot",
"=",
"cubeprop",
".",
"mcpivot",
"*",
"MINECRAFT_SCALE_FACTOR",
"c_origin",
"=",
"c_pivot",
"+",
"(",
"cubeprop",
".",
"mccube_position",
"*",
"_c_scale",
"*",
"MINECRAFT_SCALE_FACTOR",
")",
"c_rot",
"=",
"cubeprop",
".",
"get_mcrotation",
"(",
"thisobj",
")",
"if",
"cubeprop",
".",
"inflate",
"!=",
"0",
":",
"c_size",
"=",
"c_size",
"-",
"cubeprop",
".",
"inflate",
"*",
"2",
"c_origin",
"=",
"c_origin",
"+",
"cubeprop",
".",
"inflate",
"uv",
"=",
"uv_factory",
".",
"get_uv_export",
"(",
"cubeprop",
",",
"c_size",
")",
"cube",
"=",
"CubeExport",
"(",
"size",
"=",
"c_size",
",",
"pivot",
"=",
"c_pivot",
",",
"origin",
"=",
"c_origin",
",",
"rotation",
"=",
"c_rot",
",",
"inflate",
"=",
"cubeprop",
".",
"inflate",
",",
"uv",
"=",
"uv",
")",
"self",
".",
"cubes",
".",
"append",
"(",
"cube",
")",
"elif",
"cubeprop",
".",
"mesh_type",
"is",
"MeshType",
".",
"POLY_MESH",
":",
"cubeprop",
".",
"obj_data",
".",
"calc_normals_split",
"(",
")",
"polygons",
"=",
"cubeprop",
".",
"obj_data",
".",
"polygons",
"vertices",
"=",
"cubeprop",
".",
"obj_data",
".",
"vertices",
"loops",
"=",
"cubeprop",
".",
"obj_data",
".",
"loops",
"uv_data",
"=",
"cubeprop",
".",
"obj_data",
".",
"uv_layers",
".",
"active",
".",
"data",
"inv_bone_matrix",
"=",
"cubeprop",
".",
"get_local_matrix",
"(",
"thisobj",
")",
"positions",
":",
"List",
"[",
"List",
"[",
"float",
"]",
"]",
"=",
"[",
"]",
"normals",
":",
"List",
"[",
"List",
"[",
"float",
"]",
"]",
"=",
"[",
"]",
"polys",
":",
"List",
"[",
"List",
"[",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
"]",
"]",
"]",
"=",
"[",
"]",
"uvs",
":",
"List",
"[",
"List",
"[",
"int",
"]",
"]",
"=",
"[",
"list",
"(",
"i",
".",
"uv",
")",
"for",
"i",
"in",
"uv_data",
"]",
"for",
"vertex",
"in",
"vertices",
":",
"transformed_vertex",
"=",
"inv_bone_matrix",
"@",
"vertex",
".",
"co",
"transformed_vertex",
"=",
"(",
"np",
".",
"array",
"(",
"transformed_vertex",
")",
"*",
"MINECRAFT_SCALE_FACTOR",
"*",
"np",
".",
"array",
"(",
"thisobj",
".",
"obj_matrix_world",
".",
"to_scale",
"(",
")",
")",
")",
"[",
"[",
"0",
",",
"2",
",",
"1",
"]",
"]",
"+",
"self",
".",
"pivot",
"positions",
".",
"append",
"(",
"list",
"(",
"transformed_vertex",
")",
")",
"for",
"loop",
"in",
"loops",
":",
"transformed_normal",
"=",
"mathutils",
".",
"Vector",
"(",
"np",
".",
"array",
"(",
"loop",
".",
"normal",
")",
"[",
"[",
"0",
",",
"2",
",",
"1",
"]",
"]",
")",
".",
"normalized",
"(",
")",
"normals",
".",
"append",
"(",
"list",
"(",
"transformed_normal",
")",
")",
"for",
"poly",
"in",
"polygons",
":",
"curr_poly",
":",
"List",
"[",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
"]",
"]",
"=",
"[",
"]",
"for",
"loop_id",
",",
"vertex_id",
"in",
"zip",
"(",
"poly",
".",
"loop_indices",
",",
"poly",
".",
"vertices",
")",
":",
"curr_poly",
".",
"append",
"(",
"(",
"vertex_id",
",",
"loop_id",
",",
"loop_id",
")",
")",
"if",
"len",
"(",
"curr_poly",
")",
"==",
"3",
":",
"curr_poly",
".",
"append",
"(",
"copy",
"(",
"curr_poly",
"[",
"2",
"]",
")",
")",
"polys",
".",
"append",
"(",
"curr_poly",
")",
"self",
".",
"poly_mesh",
".",
"extend_mesh_data",
"(",
"positions",
",",
"normals",
",",
"polys",
",",
"uvs",
")",
"def",
"json",
"(",
"self",
")",
"->",
"Dict",
":",
"'''\n Returns the dictionary that represents a single mcbone in json file\n of model.\n\n # Returns:\n `Dict` - the single bone from Minecraft model.\n '''",
"mcbone",
":",
"Dict",
"=",
"{",
"'name'",
":",
"self",
".",
"name",
"}",
"if",
"self",
".",
"parent",
"is",
"not",
"None",
":",
"mcbone",
"[",
"'parent'",
"]",
"=",
"self",
".",
"parent",
"mcbone",
"[",
"'pivot'",
"]",
"=",
"get_vect_json",
"(",
"self",
".",
"pivot",
")",
"mcbone",
"[",
"'rotation'",
"]",
"=",
"get_vect_json",
"(",
"self",
".",
"rotation",
")",
"if",
"len",
"(",
"self",
".",
"locators",
")",
">",
"0",
":",
"mcbone",
"[",
"'locators'",
"]",
"=",
"{",
"}",
"for",
"name",
",",
"locator",
"in",
"self",
".",
"locators",
".",
"items",
"(",
")",
":",
"mcbone",
"[",
"'locators'",
"]",
"[",
"name",
"]",
"=",
"locator",
".",
"json",
"(",
")",
"if",
"len",
"(",
"self",
".",
"cubes",
")",
">",
"0",
":",
"mcbone",
"[",
"'cubes'",
"]",
"=",
"[",
"]",
"for",
"cube",
"in",
"self",
".",
"cubes",
":",
"mcbone",
"[",
"'cubes'",
"]",
".",
"append",
"(",
"cube",
".",
"json",
"(",
")",
")",
"if",
"not",
"self",
".",
"poly_mesh",
".",
"is_empty",
":",
"mcbone",
"[",
"'poly_mesh'",
"]",
"=",
"self",
".",
"poly_mesh",
".",
"json",
"(",
")",
"return",
"mcbone"
] |
Object that represents a Bone during model export.
|
[
"Object",
"that",
"represents",
"a",
"Bone",
"during",
"model",
"export",
"."
] |
[
"'''\n Object that represents a Bone during model export.\n\n # Properties\n - `model: ModelExport` - a model that contains this bone.\n - `name: str` - the name of the bone.\n - `parent: Optional[str]` - the name of a parent of this bone\n - `rotation: np.ndarray` - rotation of the bone.\n - `pivot: np.ndarray` - pivot of the bone.\n - `cubes: List[CubeExport]` - list of cubes to export.\n - `locators: Dict[str, LocatorExport]` - list of locators to export.\n (if exists) or None\n\n '''",
"'''\n Creates BoneExport. If the input value of BONE or BOTH McObjectType\n than ValueError is raised.\n '''",
"# Test if bone is valid input object",
"# Create cubes and locators list",
"# Else MCObjType == BOTH",
"# Add children cubes if they are MCObjType.CUBE type",
"'''\n Used in constructor to cubes and locators.\n '''",
"'''Scale of a bone'''",
"# Set locators",
"# Set cubes",
"# loop ids and vertices",
"# crds",
"# normals",
"# uv",
"# vertex data -> List[(positions, normals, uvs)]",
"'''\n Returns the dictionary that represents a single mcbone in json file\n of model.\n\n # Returns:\n `Dict` - the single bone from Minecraft model.\n '''",
"# Basic bone properties",
"# Locators",
"# Cubess"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 23
| 1,509
| 141
|
e910c911be9e003ffad5997e52f66f5ae6e26c03
|
SofianeBoumedine/lobsters
|
vendor/cache/ruby/2.7.0/gems/svg-graph-2.2.1/lib/SVG/Graph/BarHorizontal.rb
|
[
"BSD-3-Clause"
] |
Ruby
|
BarHorizontal
|
# === Create presentation quality SVG horitonzal bar graphs easily
#
# = Synopsis
#
# require 'SVG/Graph/BarHorizontal'
#
# fields = %w(Jan Feb Mar)
# data_sales_02 = [12, 45, 21]
#
# graph = SVG::Graph::BarHorizontal.new({
# :height => 500,
# :width => 300,
# :fields => fields,
# })
#
# graph.add_data({
# :data => data_sales_02,
# :title => 'Sales 2002',
# })
#
# print "Content-type: image/svg+xml\r\n\r\n"
# print graph.burn
#
# = Description
#
# This object aims to allow you to easily create high quality
# SVG horitonzal bar graphs. You can either use the default style sheet
# or supply your own. Either way there are many options which can
# be configured to give you control over how the graph is
# generated - with or without a key, data elements at each point,
# title, subtitle etc.
#
# = Examples
#
# * http://germane-software.com/repositories/public/SVG/test/test.rb
#
# = See also
#
# * SVG::Graph::Graph
# * SVG::Graph::Bar
# * SVG::Graph::Line
# * SVG::Graph::Pie
# * SVG::Graph::Plot
# * SVG::Graph::TimeSeries
#
# == Author
#
# Sean E. Russell <serATgermaneHYPHENsoftwareDOTcom>
#
# Copyright 2004 Sean E. Russell
# This software is available under the Ruby license[LICENSE.txt]
#
|
Create presentation quality SVG horitonzal bar graphs easily
Synopsis
print "Content-type: image/svg+xml\r\n\r\n"
print graph.burn
Description
This object aims to allow you to easily create high quality
SVG horitonzal bar graphs. You can either use the default style sheet
or supply your own. Either way there are many options which can
be configured to give you control over how the graph is
generated - with or without a key, data elements at each point,
title, subtitle etc.
Examples
See also
Author
Sean E. Russell
|
[
"Create",
"presentation",
"quality",
"SVG",
"horitonzal",
"bar",
"graphs",
"easily",
"Synopsis",
"print",
"\"",
"Content",
"-",
"type",
":",
"image",
"/",
"svg",
"+",
"xml",
"\\",
"r",
"\\",
"n",
"\\",
"r",
"\\",
"n",
"\"",
"print",
"graph",
".",
"burn",
"Description",
"This",
"object",
"aims",
"to",
"allow",
"you",
"to",
"easily",
"create",
"high",
"quality",
"SVG",
"horitonzal",
"bar",
"graphs",
".",
"You",
"can",
"either",
"use",
"the",
"default",
"style",
"sheet",
"or",
"supply",
"your",
"own",
".",
"Either",
"way",
"there",
"are",
"many",
"options",
"which",
"can",
"be",
"configured",
"to",
"give",
"you",
"control",
"over",
"how",
"the",
"graph",
"is",
"generated",
"-",
"with",
"or",
"without",
"a",
"key",
"data",
"elements",
"at",
"each",
"point",
"title",
"subtitle",
"etc",
".",
"Examples",
"See",
"also",
"Author",
"Sean",
"E",
".",
"Russell"
] |
class BarHorizontal < BarBase
# In addition to the defaults set in BarBase::set_defaults, sets
# [rotate_y_labels] true
# [show_x_guidelines] true
# [show_y_guidelines] false
def set_defaults
super
init_with(
:rotate_y_labels => true,
:show_x_guidelines => true,
:show_y_guidelines => false
)
# self.right_align = self.right_font = 1
end
protected
def get_x_labels
maxvalue = max_value
minvalue = min_value
range = maxvalue - minvalue
top_pad = range == 0 ? 10 : range / 20.0
scale_range = (maxvalue + top_pad) - minvalue
@x_scale_division = scale_divisions || (scale_range / 10.0)
if scale_integers
@x_scale_division = @x_scale_division < 1 ? 1 : @x_scale_division.round
end
rv = []
#if maxvalue%@x_scale_division != 0
# maxvalue = maxvalue + @x_scale_division
#end
minvalue.step( maxvalue, @x_scale_division ) {|v| rv << v}
return rv
end
def get_y_labels
@config[:fields]
end
def y_label_offset( height )
height / -2.0
end
def draw_data
minvalue = min_value
fieldheight = field_height
bargap = bar_gap ? (fieldheight < 10 ? fieldheight / 2 : 10) : 0
bar_height = fieldheight - bargap
bar_height /= @data.length if stack == :side
y_mod = (bar_height / 2) + (font_size / 2)
field_count = 1
@config[:fields].each_index { |i|
dataset_count = 0
for dataset in @data
total = 0
dataset[:data].each {|x|
total += x
}
value = dataset[:data][i]
top = @graph_height - (fieldheight * field_count) + (bargap/2)
top += (bar_height * dataset_count) if stack == :side
# cases (assume 0 = +ve):
# value min length left
# +ve +ve value.abs - min minvalue.abs
# +ve -ve value.abs - 0 minvalue.abs
# -ve -ve value.abs - 0 minvalue.abs + value
length = (value.abs - (minvalue > 0 ? minvalue : 0))/@x_scale_division.to_f * field_width
left = (minvalue.abs + (value < 0 ? value : 0))/@x_scale_division.to_f * field_width
@graph.add_element( "rect", {
"x" => left.to_s,
"y" => top.to_s,
"width" => length.to_s,
"height" => bar_height.to_s,
"class" => "fill#{dataset_count+1}"
})
value_string = ""
value_string += (@number_format % dataset[:data][i]) if show_actual_values
percent = 100.0 * dataset[:data][i] / total
value_string += " (" + percent.round.to_s + "%)" if show_percent
make_datapoint_text(left+length+5, top+y_mod, value_string, "text-anchor: start; ")
# number format shall not apply to popup (use .to_s conversion)
add_popup(left+length, top+y_mod , value_string)
dataset_count += 1
end
field_count += 1
}
end
end
|
[
"class",
"BarHorizontal",
"<",
"BarBase",
"def",
"set_defaults",
"super",
"init_with",
"(",
":rotate_y_labels",
"=>",
"true",
",",
":show_x_guidelines",
"=>",
"true",
",",
":show_y_guidelines",
"=>",
"false",
")",
"end",
"protected",
"def",
"get_x_labels",
"maxvalue",
"=",
"max_value",
"minvalue",
"=",
"min_value",
"range",
"=",
"maxvalue",
"-",
"minvalue",
"top_pad",
"=",
"range",
"==",
"0",
"?",
"10",
":",
"range",
"/",
"20.0",
"scale_range",
"=",
"(",
"maxvalue",
"+",
"top_pad",
")",
"-",
"minvalue",
"@x_scale_division",
"=",
"scale_divisions",
"||",
"(",
"scale_range",
"/",
"10.0",
")",
"if",
"scale_integers",
"@x_scale_division",
"=",
"@x_scale_division",
"<",
"1",
"?",
"1",
":",
"@x_scale_division",
".",
"round",
"end",
"rv",
"=",
"[",
"]",
"minvalue",
".",
"step",
"(",
"maxvalue",
",",
"@x_scale_division",
")",
"{",
"|",
"v",
"|",
"rv",
"<<",
"v",
"}",
"return",
"rv",
"end",
"def",
"get_y_labels",
"@config",
"[",
":fields",
"]",
"end",
"def",
"y_label_offset",
"(",
"height",
")",
"height",
"/",
"-",
"2.0",
"end",
"def",
"draw_data",
"minvalue",
"=",
"min_value",
"fieldheight",
"=",
"field_height",
"bargap",
"=",
"bar_gap",
"?",
"(",
"fieldheight",
"<",
"10",
"?",
"fieldheight",
"/",
"2",
":",
"10",
")",
":",
"0",
"bar_height",
"=",
"fieldheight",
"-",
"bargap",
"bar_height",
"/=",
"@data",
".",
"length",
"if",
"stack",
"==",
":side",
"y_mod",
"=",
"(",
"bar_height",
"/",
"2",
")",
"+",
"(",
"font_size",
"/",
"2",
")",
"field_count",
"=",
"1",
"@config",
"[",
":fields",
"]",
".",
"each_index",
"{",
"|",
"i",
"|",
"dataset_count",
"=",
"0",
"for",
"dataset",
"in",
"@data",
"total",
"=",
"0",
"dataset",
"[",
":data",
"]",
".",
"each",
"{",
"|",
"x",
"|",
"total",
"+=",
"x",
"}",
"value",
"=",
"dataset",
"[",
":data",
"]",
"[",
"i",
"]",
"top",
"=",
"@graph_height",
"-",
"(",
"fieldheight",
"*",
"field_count",
")",
"+",
"(",
"bargap",
"/",
"2",
")",
"top",
"+=",
"(",
"bar_height",
"*",
"dataset_count",
")",
"if",
"stack",
"==",
":side",
"length",
"=",
"(",
"value",
".",
"abs",
"-",
"(",
"minvalue",
">",
"0",
"?",
"minvalue",
":",
"0",
")",
")",
"/",
"@x_scale_division",
".",
"to_f",
"*",
"field_width",
"left",
"=",
"(",
"minvalue",
".",
"abs",
"+",
"(",
"value",
"<",
"0",
"?",
"value",
":",
"0",
")",
")",
"/",
"@x_scale_division",
".",
"to_f",
"*",
"field_width",
"@graph",
".",
"add_element",
"(",
"\"rect\"",
",",
"{",
"\"x\"",
"=>",
"left",
".",
"to_s",
",",
"\"y\"",
"=>",
"top",
".",
"to_s",
",",
"\"width\"",
"=>",
"length",
".",
"to_s",
",",
"\"height\"",
"=>",
"bar_height",
".",
"to_s",
",",
"\"class\"",
"=>",
"\"fill#{dataset_count+1}\"",
"}",
")",
"value_string",
"=",
"\"\"",
"value_string",
"+=",
"(",
"@number_format",
"%",
"dataset",
"[",
":data",
"]",
"[",
"i",
"]",
")",
"if",
"show_actual_values",
"percent",
"=",
"100.0",
"*",
"dataset",
"[",
":data",
"]",
"[",
"i",
"]",
"/",
"total",
"value_string",
"+=",
"\" (\"",
"+",
"percent",
".",
"round",
".",
"to_s",
"+",
"\"%)\"",
"if",
"show_percent",
"make_datapoint_text",
"(",
"left",
"+",
"length",
"+",
"5",
",",
"top",
"+",
"y_mod",
",",
"value_string",
",",
"\"text-anchor: start; \"",
")",
"add_popup",
"(",
"left",
"+",
"length",
",",
"top",
"+",
"y_mod",
",",
"value_string",
")",
"dataset_count",
"+=",
"1",
"end",
"field_count",
"+=",
"1",
"}",
"end",
"end"
] |
Create presentation quality SVG horitonzal bar graphs easily
Synopsis
|
[
"Create",
"presentation",
"quality",
"SVG",
"horitonzal",
"bar",
"graphs",
"easily",
"Synopsis"
] |
[
"# In addition to the defaults set in BarBase::set_defaults, sets",
"# [rotate_y_labels] true",
"# [show_x_guidelines] true",
"# [show_y_guidelines] false",
"# self.right_align = self.right_font = 1",
"#if maxvalue%@x_scale_division != 0",
"# maxvalue = maxvalue + @x_scale_division",
"#end",
"# cases (assume 0 = +ve):",
"# value min length left",
"# +ve +ve value.abs - min minvalue.abs",
"# +ve -ve value.abs - 0 minvalue.abs",
"# -ve -ve value.abs - 0 minvalue.abs + value",
"# number format shall not apply to popup (use .to_s conversion)"
] |
[
{
"param": "BarBase",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "BarBase",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 18
| 870
| 381
|
9fc304d750e2a0432734f5c1645df63294704e82
|
nnthienbao/javasimon
|
core/src/main/java/org/javasimon/callback/quantiles/QuantilesCallback.java
|
[
"BSD-3-Clause"
] |
Java
|
QuantilesCallback
|
/**
* Callback which stores data in buckets to compute quantiles.
* The {@link #createBuckets(org.javasimon.Stopwatch)} should be
* implemented to configure the width and resolution of buckets.
* Then {@link Buckets} are stored among Simon attributes.
* There are 2 implementations:
* <ul>
* <li>{@link AutoQuantilesCallback} tries to determine the best configuration for each Stopwatch.</li>
* <li>{@link FixedQuantilesCallback} uses a fixed configuration for all Stopwatches.</li>
* </ul>
*
* @author gquintana
* @see Buckets
* @since 3.2
*/
|
Callback which stores data in buckets to compute quantiles.
The #createBuckets(org.javasimon.Stopwatch) should be
implemented to configure the width and resolution of buckets.
Then Buckets are stored among Simon attributes.
There are 2 implementations:
AutoQuantilesCallback tries to determine the best configuration for each Stopwatch.
FixedQuantilesCallback uses a fixed configuration for all Stopwatches.
@author gquintana
@see Buckets
@since 3.2
|
[
"Callback",
"which",
"stores",
"data",
"in",
"buckets",
"to",
"compute",
"quantiles",
".",
"The",
"#createBuckets",
"(",
"org",
".",
"javasimon",
".",
"Stopwatch",
")",
"should",
"be",
"implemented",
"to",
"configure",
"the",
"width",
"and",
"resolution",
"of",
"buckets",
".",
"Then",
"Buckets",
"are",
"stored",
"among",
"Simon",
"attributes",
".",
"There",
"are",
"2",
"implementations",
":",
"AutoQuantilesCallback",
"tries",
"to",
"determine",
"the",
"best",
"configuration",
"for",
"each",
"Stopwatch",
".",
"FixedQuantilesCallback",
"uses",
"a",
"fixed",
"configuration",
"for",
"all",
"Stopwatches",
".",
"@author",
"gquintana",
"@see",
"Buckets",
"@since",
"3",
".",
"2"
] |
@SuppressWarnings("UnusedDeclaration")
public abstract class QuantilesCallback extends CallbackSkeleton {
/** Simon attribute name of the buckets stored in Simons after warmup time. */
public static final String ATTR_NAME_BUCKETS = "buckets";
/** SLF4J log template shared by all stopwatches. */
private final LogTemplate<Split> enabledStopwatchLogTemplate = toSLF4J(getClass().getName(), "debug");
/** Global flag indicating whether last splits should be logged once in a while. */
private boolean logEnabled = false;
/** Type of the buckets: linear or exponential. */
private BucketsType bucketsType;
/** Default constructor. */
protected QuantilesCallback() {
bucketsType = BucketsType.LINEAR;
}
/**
* Constructor with buckets type.
*
* @param bucketsType Type of buckets
*/
protected QuantilesCallback(BucketsType bucketsType) {
this.bucketsType = bucketsType;
}
/**
* Returns buckets type.
*
* @return Buckets type
*/
public BucketsType getBucketsType() {
return bucketsType;
}
public boolean isLogEnabled() {
return logEnabled;
}
public void setLogEnabled(boolean logEnabled) {
this.logEnabled = logEnabled;
}
/**
* Create log template for given stopwatch.
* This method can be overridden to tune logging strategy.
* By default, when enabled, quantiles are logged at most once per minute
*
* @param stopwatch Stopwatch
* @return Logger
*/
@SuppressWarnings("UnusedParameters")
protected LogTemplate<Split> createLogTemplate(Stopwatch stopwatch) {
LogTemplate<Split> logTemplate;
if (logEnabled) {
logTemplate = everyNSeconds(enabledStopwatchLogTemplate, 60);
} else {
logTemplate = disabled();
}
return logTemplate;
}
/** Returns the buckets attribute. */
public static Buckets getBuckets(Stopwatch stopwatch) {
return (Buckets) stopwatch.getAttribute(ATTR_NAME_BUCKETS);
}
/**
* Factory method to create a Buckets object using given configuration.
*
* @param stopwatch Target Stopwatch
* @param min Min bound
* @param max Max bound
* @param bucketNb Number of buckets between min and max
* @return Buckets
*/
protected final Buckets createBuckets(Stopwatch stopwatch, long min, long max, int bucketNb) {
Buckets buckets = bucketsType.createBuckets(stopwatch, min, max, bucketNb);
buckets.setLogTemplate(createLogTemplate(stopwatch));
return buckets;
}
/**
* Create Buckets for given stopwatch.
* Call {@link #createBuckets(org.javasimon.Stopwatch, long, long, int)} to create a new buckets object.
*
* @param stopwatch Stopwatch
* @return Buckets
*/
protected abstract Buckets createBuckets(Stopwatch stopwatch);
/** Returns the buckets attribute or create it if it does not exist. */
@SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
protected final Buckets getOrCreateBuckets(Stopwatch stopwatch) {
synchronized (stopwatch) {
Buckets buckets = getBuckets(stopwatch);
if (buckets == null) {
buckets = createBuckets(stopwatch);
stopwatch.setAttribute(ATTR_NAME_BUCKETS, buckets);
}
return buckets;
}
}
/** Returns the buckets attribute and sample them. */
public static BucketsSample sampleBuckets(Stopwatch stopwatch) {
final Buckets buckets = getBuckets(stopwatch);
return buckets == null ? null : buckets.sample();
}
/**
* Called when there is a new split on a Stopwatch, either
* {@link #onStopwatchStop} or {@link #onStopwatchAdd}.
* If buckets have been initialized, the value is added to appropriate bucket.
*/
protected void onStopwatchSplit(Stopwatch stopwatch, Split split) {
Buckets buckets = getOrCreateBuckets(stopwatch);
if (buckets != null) {
buckets.addValue(split.runningFor());
buckets.log(split);
}
}
/**
* When a split is stopped, if buckets have been initialized, the value
* is added to appropriate bucket.
*/
@Override
public void onStopwatchStop(Split split, StopwatchSample sample) {
onStopwatchSplit(split.getStopwatch(), split);
}
/** When a split is added, if buckets have been initialized, the value is added to appropriate bucket. */
@Override
public void onStopwatchAdd(Stopwatch stopwatch, Split split, StopwatchSample sample) {
onStopwatchSplit(split.getStopwatch(), split);
}
}
|
[
"@",
"SuppressWarnings",
"(",
"\"",
"UnusedDeclaration",
"\"",
")",
"public",
"abstract",
"class",
"QuantilesCallback",
"extends",
"CallbackSkeleton",
"{",
"/** Simon attribute name of the buckets stored in Simons after warmup time. */",
"public",
"static",
"final",
"String",
"ATTR_NAME_BUCKETS",
"=",
"\"",
"buckets",
"\"",
";",
"/** SLF4J log template shared by all stopwatches. */",
"private",
"final",
"LogTemplate",
"<",
"Split",
">",
"enabledStopwatchLogTemplate",
"=",
"toSLF4J",
"(",
"getClass",
"(",
")",
".",
"getName",
"(",
")",
",",
"\"",
"debug",
"\"",
")",
";",
"/** Global flag indicating whether last splits should be logged once in a while. */",
"private",
"boolean",
"logEnabled",
"=",
"false",
";",
"/** Type of the buckets: linear or exponential. */",
"private",
"BucketsType",
"bucketsType",
";",
"/** Default constructor. */",
"protected",
"QuantilesCallback",
"(",
")",
"{",
"bucketsType",
"=",
"BucketsType",
".",
"LINEAR",
";",
"}",
"/**\r\n\t * Constructor with buckets type.\r\n\t *\r\n\t * @param bucketsType Type of buckets\r\n\t */",
"protected",
"QuantilesCallback",
"(",
"BucketsType",
"bucketsType",
")",
"{",
"this",
".",
"bucketsType",
"=",
"bucketsType",
";",
"}",
"/**\r\n\t * Returns buckets type.\r\n\t *\r\n\t * @return Buckets type\r\n\t */",
"public",
"BucketsType",
"getBucketsType",
"(",
")",
"{",
"return",
"bucketsType",
";",
"}",
"public",
"boolean",
"isLogEnabled",
"(",
")",
"{",
"return",
"logEnabled",
";",
"}",
"public",
"void",
"setLogEnabled",
"(",
"boolean",
"logEnabled",
")",
"{",
"this",
".",
"logEnabled",
"=",
"logEnabled",
";",
"}",
"/**\r\n\t * Create log template for given stopwatch.\r\n\t * This method can be overridden to tune logging strategy.\r\n\t * By default, when enabled, quantiles are logged at most once per minute\r\n\t *\r\n\t * @param stopwatch Stopwatch\r\n\t * @return Logger\r\n\t */",
"@",
"SuppressWarnings",
"(",
"\"",
"UnusedParameters",
"\"",
")",
"protected",
"LogTemplate",
"<",
"Split",
">",
"createLogTemplate",
"(",
"Stopwatch",
"stopwatch",
")",
"{",
"LogTemplate",
"<",
"Split",
">",
"logTemplate",
";",
"if",
"(",
"logEnabled",
")",
"{",
"logTemplate",
"=",
"everyNSeconds",
"(",
"enabledStopwatchLogTemplate",
",",
"60",
")",
";",
"}",
"else",
"{",
"logTemplate",
"=",
"disabled",
"(",
")",
";",
"}",
"return",
"logTemplate",
";",
"}",
"/** Returns the buckets attribute. */",
"public",
"static",
"Buckets",
"getBuckets",
"(",
"Stopwatch",
"stopwatch",
")",
"{",
"return",
"(",
"Buckets",
")",
"stopwatch",
".",
"getAttribute",
"(",
"ATTR_NAME_BUCKETS",
")",
";",
"}",
"/**\r\n\t * Factory method to create a Buckets object using given configuration.\r\n\t *\r\n\t * @param stopwatch Target Stopwatch\r\n\t * @param min Min bound\r\n\t * @param max Max bound\r\n\t * @param bucketNb Number of buckets between min and max\r\n\t * @return Buckets\r\n\t */",
"protected",
"final",
"Buckets",
"createBuckets",
"(",
"Stopwatch",
"stopwatch",
",",
"long",
"min",
",",
"long",
"max",
",",
"int",
"bucketNb",
")",
"{",
"Buckets",
"buckets",
"=",
"bucketsType",
".",
"createBuckets",
"(",
"stopwatch",
",",
"min",
",",
"max",
",",
"bucketNb",
")",
";",
"buckets",
".",
"setLogTemplate",
"(",
"createLogTemplate",
"(",
"stopwatch",
")",
")",
";",
"return",
"buckets",
";",
"}",
"/**\r\n\t * Create Buckets for given stopwatch.\r\n\t * Call {@link #createBuckets(org.javasimon.Stopwatch, long, long, int)} to create a new buckets object.\r\n\t *\r\n\t * @param stopwatch Stopwatch\r\n\t * @return Buckets\r\n\t */",
"protected",
"abstract",
"Buckets",
"createBuckets",
"(",
"Stopwatch",
"stopwatch",
")",
";",
"/** Returns the buckets attribute or create it if it does not exist. */",
"@",
"SuppressWarnings",
"(",
"\"",
"SynchronizationOnLocalVariableOrMethodParameter",
"\"",
")",
"protected",
"final",
"Buckets",
"getOrCreateBuckets",
"(",
"Stopwatch",
"stopwatch",
")",
"{",
"synchronized",
"(",
"stopwatch",
")",
"{",
"Buckets",
"buckets",
"=",
"getBuckets",
"(",
"stopwatch",
")",
";",
"if",
"(",
"buckets",
"==",
"null",
")",
"{",
"buckets",
"=",
"createBuckets",
"(",
"stopwatch",
")",
";",
"stopwatch",
".",
"setAttribute",
"(",
"ATTR_NAME_BUCKETS",
",",
"buckets",
")",
";",
"}",
"return",
"buckets",
";",
"}",
"}",
"/** Returns the buckets attribute and sample them. */",
"public",
"static",
"BucketsSample",
"sampleBuckets",
"(",
"Stopwatch",
"stopwatch",
")",
"{",
"final",
"Buckets",
"buckets",
"=",
"getBuckets",
"(",
"stopwatch",
")",
";",
"return",
"buckets",
"==",
"null",
"?",
"null",
":",
"buckets",
".",
"sample",
"(",
")",
";",
"}",
"/**\r\n\t * Called when there is a new split on a Stopwatch, either\r\n\t * {@link #onStopwatchStop} or {@link #onStopwatchAdd}.\r\n\t * If buckets have been initialized, the value is added to appropriate bucket.\r\n\t */",
"protected",
"void",
"onStopwatchSplit",
"(",
"Stopwatch",
"stopwatch",
",",
"Split",
"split",
")",
"{",
"Buckets",
"buckets",
"=",
"getOrCreateBuckets",
"(",
"stopwatch",
")",
";",
"if",
"(",
"buckets",
"!=",
"null",
")",
"{",
"buckets",
".",
"addValue",
"(",
"split",
".",
"runningFor",
"(",
")",
")",
";",
"buckets",
".",
"log",
"(",
"split",
")",
";",
"}",
"}",
"/**\r\n\t * When a split is stopped, if buckets have been initialized, the value\r\n\t * is added to appropriate bucket.\r\n\t */",
"@",
"Override",
"public",
"void",
"onStopwatchStop",
"(",
"Split",
"split",
",",
"StopwatchSample",
"sample",
")",
"{",
"onStopwatchSplit",
"(",
"split",
".",
"getStopwatch",
"(",
")",
",",
"split",
")",
";",
"}",
"/** When a split is added, if buckets have been initialized, the value is added to appropriate bucket. */",
"@",
"Override",
"public",
"void",
"onStopwatchAdd",
"(",
"Stopwatch",
"stopwatch",
",",
"Split",
"split",
",",
"StopwatchSample",
"sample",
")",
"{",
"onStopwatchSplit",
"(",
"split",
".",
"getStopwatch",
"(",
")",
",",
"split",
")",
";",
"}",
"}"
] |
Callback which stores data in buckets to compute quantiles.
|
[
"Callback",
"which",
"stores",
"data",
"in",
"buckets",
"to",
"compute",
"quantiles",
"."
] |
[] |
[
{
"param": "CallbackSkeleton",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "CallbackSkeleton",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 13
| 1,018
| 138
|
6479b79f29cfb4447519138536761ca986f5cac7
|
neos-sdi/adfsmfa
|
Neos.IdentityServer 3.1/Neos.IdentityServer.MultiFactor.Cmdlets/Neos.IdentityServer.MultiFactor.Admin.Cmdlets.cs
|
[
"MIT"
] |
C#
|
SetMFATemplateMode
|
/// <summary>
/// <para type="synopsis">Set Policy Template.</para>
/// <para type="description">Set Policy template, for managing security features like ChangePassword, Auto-registration and more.</para>
/// </summary>
/// <example>
/// <para>Set-MFAPolicyTemplate -Template Strict</para>
/// <para>Change policy template for MFA configuration</para>
/// </example>
|
Set Policy Template.Set Policy template, for managing security features like ChangePassword, Auto-registration and more.
|
[
"Set",
"Policy",
"Template",
".",
"Set",
"Policy",
"template",
"for",
"managing",
"security",
"features",
"like",
"ChangePassword",
"Auto",
"-",
"registration",
"and",
"more",
"."
] |
[Cmdlet(VerbsCommon.Set, "MFAPolicyTemplate", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.High, RemotingCapability = RemotingCapability.None, DefaultParameterSetName = "Data")]
[PrimaryServerRequired, AdministratorsRightsRequired, NotRemotable, AdministrationPin]
public sealed class SetMFATemplateMode : MFACmdlet
{
private PSTemplateMode _template;
private FlatTemplateMode _target;
private FlatConfig _config;
[Parameter(Mandatory = true, Position = 0, ParameterSetName = "Data", ValueFromPipeline = false)]
[ValidateNotNullOrEmpty()]
public PSTemplateMode Template
{
get { return _template; }
set { _template = value; }
}
protected override void BeginProcessing()
{
base.BeginProcessing();
try
{
ManagementService.Initialize(this.Host, true);
_config = new FlatConfig();
_config.Load(this.Host);
_target = (FlatTemplateMode)_template;
}
catch (Exception ex)
{
this.ThrowTerminatingError(new ErrorRecord(ex, "3023", ErrorCategory.OperationStopped, this));
}
}
protected override void ProcessRecord()
{
if (ShouldProcess("Set MFA Template Configuration"))
{
try
{
_config.SetPolicyTemplate(this.Host, _target);
this.WriteVerbose(infos_strings.InfosConfigUpdated);
}
catch (Exception ex)
{
this.ThrowTerminatingError(new ErrorRecord(ex, "3024", ErrorCategory.OperationStopped, this));
}
}
}
protected override void StopProcessing()
{
_config = null;
base.StopProcessing();
}
}
|
[
"[",
"Cmdlet",
"(",
"VerbsCommon",
".",
"Set",
",",
"\"",
"MFAPolicyTemplate",
"\"",
",",
"SupportsShouldProcess",
"=",
"true",
",",
"ConfirmImpact",
"=",
"ConfirmImpact",
".",
"High",
",",
"RemotingCapability",
"=",
"RemotingCapability",
".",
"None",
",",
"DefaultParameterSetName",
"=",
"\"",
"Data",
"\"",
")",
"]",
"[",
"PrimaryServerRequired",
",",
"AdministratorsRightsRequired",
",",
"NotRemotable",
",",
"AdministrationPin",
"]",
"public",
"sealed",
"class",
"SetMFATemplateMode",
":",
"MFACmdlet",
"{",
"private",
"PSTemplateMode",
"_template",
";",
"private",
"FlatTemplateMode",
"_target",
";",
"private",
"FlatConfig",
"_config",
";",
"[",
"Parameter",
"(",
"Mandatory",
"=",
"true",
",",
"Position",
"=",
"0",
",",
"ParameterSetName",
"=",
"\"",
"Data",
"\"",
",",
"ValueFromPipeline",
"=",
"false",
")",
"]",
"[",
"ValidateNotNullOrEmpty",
"(",
")",
"]",
"public",
"PSTemplateMode",
"Template",
"{",
"get",
"{",
"return",
"_template",
";",
"}",
"set",
"{",
"_template",
"=",
"value",
";",
"}",
"}",
"protected",
"override",
"void",
"BeginProcessing",
"(",
")",
"{",
"base",
".",
"BeginProcessing",
"(",
")",
";",
"try",
"{",
"ManagementService",
".",
"Initialize",
"(",
"this",
".",
"Host",
",",
"true",
")",
";",
"_config",
"=",
"new",
"FlatConfig",
"(",
")",
";",
"_config",
".",
"Load",
"(",
"this",
".",
"Host",
")",
";",
"_target",
"=",
"(",
"FlatTemplateMode",
")",
"_template",
";",
"}",
"catch",
"(",
"Exception",
"ex",
")",
"{",
"this",
".",
"ThrowTerminatingError",
"(",
"new",
"ErrorRecord",
"(",
"ex",
",",
"\"",
"3023",
"\"",
",",
"ErrorCategory",
".",
"OperationStopped",
",",
"this",
")",
")",
";",
"}",
"}",
"protected",
"override",
"void",
"ProcessRecord",
"(",
")",
"{",
"if",
"(",
"ShouldProcess",
"(",
"\"",
"Set MFA Template Configuration",
"\"",
")",
")",
"{",
"try",
"{",
"_config",
".",
"SetPolicyTemplate",
"(",
"this",
".",
"Host",
",",
"_target",
")",
";",
"this",
".",
"WriteVerbose",
"(",
"infos_strings",
".",
"InfosConfigUpdated",
")",
";",
"}",
"catch",
"(",
"Exception",
"ex",
")",
"{",
"this",
".",
"ThrowTerminatingError",
"(",
"new",
"ErrorRecord",
"(",
"ex",
",",
"\"",
"3024",
"\"",
",",
"ErrorCategory",
".",
"OperationStopped",
",",
"this",
")",
")",
";",
"}",
"}",
"}",
"protected",
"override",
"void",
"StopProcessing",
"(",
")",
"{",
"_config",
"=",
"null",
";",
"base",
".",
"StopProcessing",
"(",
")",
";",
"}",
"}"
] |
Set Policy Template.Set Policy template, for managing security features like ChangePassword, Auto-registration and more.
|
[
"Set",
"Policy",
"Template",
".",
"Set",
"Policy",
"template",
"for",
"managing",
"security",
"features",
"like",
"ChangePassword",
"Auto",
"-",
"registration",
"and",
"more",
"."
] |
[
"/// <summary>",
"/// <para type=\"description\">Template enumeration member. </para>",
"/// </summary>",
"/// <summary>",
"/// BeginProcessing method implementation",
"/// </summary>",
"/// <summary>",
"/// ProcessRecord method override",
"/// </summary>",
"/// <summary>",
"/// StopProcessing method implementation",
"/// </summary>"
] |
[
{
"param": "MFACmdlet",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "MFACmdlet",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": [
{
"identifier": "example",
"docstring": "Set-MFAPolicyTemplate -Template StrictChange policy template for MFA configuration",
"docstring_tokens": [
"Set",
"-",
"MFAPolicyTemplate",
"-",
"Template",
"StrictChange",
"policy",
"template",
"for",
"MFA",
"configuration"
]
}
]
}
| false
| 18
| 371
| 88
|
27d462fe0a3b03094571bd73b460e435bfc9cf1f
|
sous-chefs/nexus
|
libraries/chef_nexus.rb
|
[
"Apache-2.0"
] |
Ruby
|
Chef
|
#
# Cookbook:: nexus
# Library:: chef_nexus
#
# Author:: Kyle Allan (<[email protected]>)
# Author:: Heavy Water Operations LLC (<[email protected]>)
# Copyright:: 2013, Riot Games
#
# 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.
#
#
|
: nexus
Library:: chef_nexus
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
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.
|
[
":",
"nexus",
"Library",
"::",
"chef_nexus",
"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",
"Unless",
"required",
"by",
"applicable",
"law",
"or",
"agreed",
"to",
"in",
"writing",
"software",
"distributed",
"under",
"the",
"License",
"is",
"distributed",
"on",
"an",
"\"",
"AS",
"IS",
"\"",
"BASIS",
"WITHOUT",
"WARRANTIES",
"OR",
"CONDITIONS",
"OF",
"ANY",
"KIND",
"either",
"express",
"or",
"implied",
".",
"See",
"the",
"License",
"for",
"the",
"specific",
"language",
"governing",
"permissions",
"and",
"limitations",
"under",
"the",
"License",
"."
] |
class Chef
module Nexus
class << self
# Creates and returns an instance of a NexusCli::RemoteFactory that
# will be authenticated with the info inside the credentials data bag
# item.
#
# @param config [Hash] a configuration hash for the connection
#
# @return [NexusCli::RemoteFactory] a connection to a Nexus server
def nexus(config)
require 'nexus_cli'
connection_config = {
'url' => config['url'],
'repository' => config['repository'],
'username' => config['username'],
'password' => config['password'],
}
NexusCli::RemoteFactory.create(connection_config, config['ssl_verify'])
end
# Generates the URL for a nexus instance
# @param override_config [Hash]
# @param node [Chef::Node]
#
# @return [String]
def default_url(node, override_config = {})
require 'uri'
url = {
scheme: 'http',
host: 'localhost',
port: node['nexus']['port'],
path: node['nexus']['context_path'],
}
url.merge!(override_config)
URI::Generic.build(url).to_s
end
# Merges provided configuration with defaults, returning the config
# as a Mash.
# @param override_config a hash of default configuration overrides
#
# @return [Mash] hash of configuration values for the nexus connection
def merge_config(node, override_config = {})
default_config = Mash.new(
url: default_url(node, override_config),
username: 'admin',
password: 'admin123',
retries: 10,
retry_delay: 10
)
default_config.merge(override_config)
end
# Checks to ensure the Nexus server is available. When
# it is unavailable, the Chef run is failed. Otherwise
# the Chef run continues.
#
# @param config [Hash] a configuration hash for the connection
#
# @return [NilClass]
def ensure_service_available(config)
raise('Could not connect to Nexus. Please ensure Nexus is running.') unless Chef::Nexus.service_available?(config)
end
# Attempts to connect to the Nexus and retries if a connection
# cannot be made.
#
# @param config [Hash] a configuration hash for the connection
#
# @return [Boolean] true if a connection could be made, false otherwise
def service_available?(config)
retries = config['retries']
retry_delay = config['retry_delay']
begin
remote = anonymous_nexus_remote(config)
remote.status['state'] == 'STARTED'
rescue Errno::ECONNREFUSED, NexusCli::CouldNotConnectToNexusException, \
NexusCli::UnexpectedStatusCodeException => e
if retries > 0
retries -= 1
Chef::Log.info "Could not connect to Nexus, #{retries} attempt(s) left"
Chef::Log.info "Nexus error: #{e.inspect}"
sleep retry_delay
retry
end
false
end
end
# Returns a 'safe-for-Nexus' identifier by replacing
# spaces with underscores and downcasing the entire
# String.
#
# @param nexus_identifier [String] a Nexus identifier
#
# @example
# Chef::Nexus.parse_identifier("Artifacts Repository") => "artifacts_repository"
#
# @return [String] a safe-for-Nexus version of the identifier
def parse_identifier(nexus_identifier)
nexus_identifier.tr(' ', '_').downcase
end
def decode(value)
require 'base64'
Base64.decode64(value)
end
private
# Creates a new instance of a Nexus connection using only
# the URL to the local server. This connection is anonymous.
#
# @param config [Hash] a configuration hash for the connection
#
# @return [NexusCli::BaseRemote] a NexusCli remote class
def anonymous_nexus_remote(config)
require 'nexus_cli'
NexusCli::RemoteFactory.create(
{ 'url' => config['url'] },
config['ssl_verify']
)
end
end
end
end
|
[
"class",
"Chef",
"module",
"Nexus",
"class",
"<<",
"self",
"def",
"nexus",
"(",
"config",
")",
"require",
"'nexus_cli'",
"connection_config",
"=",
"{",
"'url'",
"=>",
"config",
"[",
"'url'",
"]",
",",
"'repository'",
"=>",
"config",
"[",
"'repository'",
"]",
",",
"'username'",
"=>",
"config",
"[",
"'username'",
"]",
",",
"'password'",
"=>",
"config",
"[",
"'password'",
"]",
",",
"}",
"NexusCli",
"::",
"RemoteFactory",
".",
"create",
"(",
"connection_config",
",",
"config",
"[",
"'ssl_verify'",
"]",
")",
"end",
"def",
"default_url",
"(",
"node",
",",
"override_config",
"=",
"{",
"}",
")",
"require",
"'uri'",
"url",
"=",
"{",
"scheme",
":",
"'http'",
",",
"host",
":",
"'localhost'",
",",
"port",
":",
"node",
"[",
"'nexus'",
"]",
"[",
"'port'",
"]",
",",
"path",
":",
"node",
"[",
"'nexus'",
"]",
"[",
"'context_path'",
"]",
",",
"}",
"url",
".",
"merge!",
"(",
"override_config",
")",
"URI",
"::",
"Generic",
".",
"build",
"(",
"url",
")",
".",
"to_s",
"end",
"def",
"merge_config",
"(",
"node",
",",
"override_config",
"=",
"{",
"}",
")",
"default_config",
"=",
"Mash",
".",
"new",
"(",
"url",
":",
"default_url",
"(",
"node",
",",
"override_config",
")",
",",
"username",
":",
"'admin'",
",",
"password",
":",
"'admin123'",
",",
"retries",
":",
"10",
",",
"retry_delay",
":",
"10",
")",
"default_config",
".",
"merge",
"(",
"override_config",
")",
"end",
"def",
"ensure_service_available",
"(",
"config",
")",
"raise",
"(",
"'Could not connect to Nexus. Please ensure Nexus is running.'",
")",
"unless",
"Chef",
"::",
"Nexus",
".",
"service_available?",
"(",
"config",
")",
"end",
"def",
"service_available?",
"(",
"config",
")",
"retries",
"=",
"config",
"[",
"'retries'",
"]",
"retry_delay",
"=",
"config",
"[",
"'retry_delay'",
"]",
"begin",
"remote",
"=",
"anonymous_nexus_remote",
"(",
"config",
")",
"remote",
".",
"status",
"[",
"'state'",
"]",
"==",
"'STARTED'",
"rescue",
"Errno",
"::",
"ECONNREFUSED",
",",
"NexusCli",
"::",
"CouldNotConnectToNexusException",
",",
"NexusCli",
"::",
"UnexpectedStatusCodeException",
"=>",
"e",
"if",
"retries",
">",
"0",
"retries",
"-=",
"1",
"Chef",
"::",
"Log",
".",
"info",
"\"Could not connect to Nexus, #{retries} attempt(s) left\"",
"Chef",
"::",
"Log",
".",
"info",
"\"Nexus error: #{e.inspect}\"",
"sleep",
"retry_delay",
"retry",
"end",
"false",
"end",
"end",
"def",
"parse_identifier",
"(",
"nexus_identifier",
")",
"nexus_identifier",
".",
"tr",
"(",
"' '",
",",
"'_'",
")",
".",
"downcase",
"end",
"def",
"decode",
"(",
"value",
")",
"require",
"'base64'",
"Base64",
".",
"decode64",
"(",
"value",
")",
"end",
"private",
"def",
"anonymous_nexus_remote",
"(",
"config",
")",
"require",
"'nexus_cli'",
"NexusCli",
"::",
"RemoteFactory",
".",
"create",
"(",
"{",
"'url'",
"=>",
"config",
"[",
"'url'",
"]",
"}",
",",
"config",
"[",
"'ssl_verify'",
"]",
")",
"end",
"end",
"end",
"end"
] |
Cookbook:: nexus
Library:: chef_nexus
|
[
"Cookbook",
"::",
"nexus",
"Library",
"::",
"chef_nexus"
] |
[
"# Creates and returns an instance of a NexusCli::RemoteFactory that",
"# will be authenticated with the info inside the credentials data bag",
"# item.",
"#",
"# @param config [Hash] a configuration hash for the connection",
"#",
"# @return [NexusCli::RemoteFactory] a connection to a Nexus server",
"# Generates the URL for a nexus instance",
"# @param override_config [Hash]",
"# @param node [Chef::Node]",
"#",
"# @return [String]",
"# Merges provided configuration with defaults, returning the config",
"# as a Mash.",
"# @param override_config a hash of default configuration overrides",
"#",
"# @return [Mash] hash of configuration values for the nexus connection",
"# Checks to ensure the Nexus server is available. When",
"# it is unavailable, the Chef run is failed. Otherwise",
"# the Chef run continues.",
"#",
"# @param config [Hash] a configuration hash for the connection",
"#",
"# @return [NilClass]",
"# Attempts to connect to the Nexus and retries if a connection",
"# cannot be made.",
"#",
"# @param config [Hash] a configuration hash for the connection",
"#",
"# @return [Boolean] true if a connection could be made, false otherwise",
"# Returns a 'safe-for-Nexus' identifier by replacing",
"# spaces with underscores and downcasing the entire",
"# String.",
"#",
"# @param nexus_identifier [String] a Nexus identifier",
"#",
"# @example",
"# Chef::Nexus.parse_identifier(\"Artifacts Repository\") => \"artifacts_repository\"",
"#",
"# @return [String] a safe-for-Nexus version of the identifier",
"# Creates a new instance of a Nexus connection using only",
"# the URL to the local server. This connection is anonymous.",
"#",
"# @param config [Hash] a configuration hash for the connection",
"#",
"# @return [NexusCli::BaseRemote] a NexusCli remote class"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 19
| 951
| 177
|
04b601094a3516c6ed76f574b61b6aa03f635758
|
n0x00/beef
|
extensions/customhook/handler.rb
|
[
"Apache-2.0"
] |
Ruby
|
BeEF
|
#
# Copyright 2012 Wade Alcorn [email protected]
#
# 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.
#
|
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.
|
[
"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",
"."
] |
module BeEF
module Extension
module Customhook
class Handler
def call(env)
@body = ''
@request = Rack::Request.new(env)
@params = @request.query_string
@response = Rack::Response.new(body=[], 200, header={})
config = BeEF::Core::Configuration.instance
eruby = Erubis::FastEruby.new(File.read(File.dirname(__FILE__)+'/html/index.html'))
@body << eruby.evaluate({'customhook_target' => config.get("beef.extension.customhook.customhook_target"),
'customhook_title' => config.get("beef.extension.customhook.customhook_title")})
@response = Rack::Response.new(
body = [@body],
status = 200,
header = {
'Pragma' => 'no-cache',
'Cache-Control' => 'no-cache',
'Expires' => '0',
'Content-Type' => 'text/html',
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'POST, GET'
}
)
end
private
# @note Object representing the HTTP request
@request
# @note Object representing the HTTP response
@response
end
end
end
end
|
[
"module",
"BeEF",
"module",
"Extension",
"module",
"Customhook",
"class",
"Handler",
"def",
"call",
"(",
"env",
")",
"@body",
"=",
"''",
"@request",
"=",
"Rack",
"::",
"Request",
".",
"new",
"(",
"env",
")",
"@params",
"=",
"@request",
".",
"query_string",
"@response",
"=",
"Rack",
"::",
"Response",
".",
"new",
"(",
"body",
"=",
"[",
"]",
",",
"200",
",",
"header",
"=",
"{",
"}",
")",
"config",
"=",
"BeEF",
"::",
"Core",
"::",
"Configuration",
".",
"instance",
"eruby",
"=",
"Erubis",
"::",
"FastEruby",
".",
"new",
"(",
"File",
".",
"read",
"(",
"File",
".",
"dirname",
"(",
"__FILE__",
")",
"+",
"'/html/index.html'",
")",
")",
"@body",
"<<",
"eruby",
".",
"evaluate",
"(",
"{",
"'customhook_target'",
"=>",
"config",
".",
"get",
"(",
"\"beef.extension.customhook.customhook_target\"",
")",
",",
"'customhook_title'",
"=>",
"config",
".",
"get",
"(",
"\"beef.extension.customhook.customhook_title\"",
")",
"}",
")",
"@response",
"=",
"Rack",
"::",
"Response",
".",
"new",
"(",
"body",
"=",
"[",
"@body",
"]",
",",
"status",
"=",
"200",
",",
"header",
"=",
"{",
"'Pragma'",
"=>",
"'no-cache'",
",",
"'Cache-Control'",
"=>",
"'no-cache'",
",",
"'Expires'",
"=>",
"'0'",
",",
"'Content-Type'",
"=>",
"'text/html'",
",",
"'Access-Control-Allow-Origin'",
"=>",
"'*'",
",",
"'Access-Control-Allow-Methods'",
"=>",
"'POST, GET'",
"}",
")",
"end",
"private",
"@request",
"@response",
"end",
"end",
"end",
"end"
] |
Copyright 2012 Wade Alcorn [email protected]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
|
[
"Copyright",
"2012",
"Wade",
"Alcorn",
"wade@bindshell",
".",
"net",
"Licensed",
"under",
"the",
"Apache",
"License",
"Version",
"2",
".",
"0",
"(",
"the",
"\"",
"License",
"\"",
")",
";",
"you",
"may",
"not",
"use",
"this",
"file",
"except",
"in",
"compliance",
"with",
"the",
"License",
"."
] |
[
"# @note Object representing the HTTP request",
"# @note Object representing the HTTP response"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 19
| 277
| 148
|
9922b10fd9c9a186123a2f7eadc624fc6f9c19a8
|
infoverload/crate
|
server/src/main/java/io/crate/execution/engine/join/HashInnerJoinBatchIterator.java
|
[
"Apache-2.0"
] |
Java
|
HashInnerJoinBatchIterator
|
/**
* <pre>
* Build Phase:
* for (leftRow in left) {
* calculate hash and put in Buffer (HashMap) until the blockSize is reached
* }
*
* Probe Phase:
* // We iterate on the right until we find a matching row or the right side needs to be loaded a next batch of data
* for (rightRow in right) {
* if (hash(rightRow) found in Buffer {
* for (row in matchedInBuffer) { // Handle duplicate values from left and hash collisions
* if (joinCondition matches) {
* // We need to check that the joinCondition matches as we can have a hash collision
* // or the join condition can contain more operators.
* //
* // Row-lookup-by-hash-code can only work by the EQ operators of a join condition,
* // all other possible operators must be checked afterwards.
* emmit(combinedRow)
* }
* }
* }
* }
*
* When the right side is all loaded, we reset the right iterator to start, clear the buffer and switch back to
* iterate the next elements in the left side and re-build the buffer based on the next items in the left until we
* reach the blockSize again.
*
* Repeat until both sides are all loaded and processed.
* </pre>
* <p>
* The caller of the constructor needs to pass two functions {@link #hashBuilderForLeft} and {@link #hashBuilderForRight}.
* Those functions are called on each row of the left and right side respectively and they return the hash value of
* the relevant columns of the row.
* <p>
* This information is not available for the {@link HashInnerJoinBatchIterator}, so it's the responsibility of the
* caller to provide those two functions that operate on the left and right rows accordingly and return the hash values.
*/
|
Build Phase:
for (leftRow in left) {
calculate hash and put in Buffer (HashMap) until the blockSize is reached
}
Probe Phase:
We iterate on the right until we find a matching row or the right side needs to be loaded a next batch of data
for (rightRow in right) {
if (hash(rightRow) found in Buffer {
for (row in matchedInBuffer) { // Handle duplicate values from left and hash collisions
if (joinCondition matches) {
We need to check that the joinCondition matches as we can have a hash collision
or the join condition can contain more operators.
Row-lookup-by-hash-code can only work by the EQ operators of a join condition,
all other possible operators must be checked afterwards.
emmit(combinedRow)
}
}
}
}
When the right side is all loaded, we reset the right iterator to start, clear the buffer and switch back to
iterate the next elements in the left side and re-build the buffer based on the next items in the left until we
reach the blockSize again.
Repeat until both sides are all loaded and processed.
The caller of the constructor needs to pass two functions #hashBuilderForLeft and #hashBuilderForRight.
Those functions are called on each row of the left and right side respectively and they return the hash value of
the relevant columns of the row.
This information is not available for the HashInnerJoinBatchIterator, so it's the responsibility of the
caller to provide those two functions that operate on the left and right rows accordingly and return the hash values.
|
[
"Build",
"Phase",
":",
"for",
"(",
"leftRow",
"in",
"left",
")",
"{",
"calculate",
"hash",
"and",
"put",
"in",
"Buffer",
"(",
"HashMap",
")",
"until",
"the",
"blockSize",
"is",
"reached",
"}",
"Probe",
"Phase",
":",
"We",
"iterate",
"on",
"the",
"right",
"until",
"we",
"find",
"a",
"matching",
"row",
"or",
"the",
"right",
"side",
"needs",
"to",
"be",
"loaded",
"a",
"next",
"batch",
"of",
"data",
"for",
"(",
"rightRow",
"in",
"right",
")",
"{",
"if",
"(",
"hash",
"(",
"rightRow",
")",
"found",
"in",
"Buffer",
"{",
"for",
"(",
"row",
"in",
"matchedInBuffer",
")",
"{",
"//",
"Handle",
"duplicate",
"values",
"from",
"left",
"and",
"hash",
"collisions",
"if",
"(",
"joinCondition",
"matches",
")",
"{",
"We",
"need",
"to",
"check",
"that",
"the",
"joinCondition",
"matches",
"as",
"we",
"can",
"have",
"a",
"hash",
"collision",
"or",
"the",
"join",
"condition",
"can",
"contain",
"more",
"operators",
".",
"Row",
"-",
"lookup",
"-",
"by",
"-",
"hash",
"-",
"code",
"can",
"only",
"work",
"by",
"the",
"EQ",
"operators",
"of",
"a",
"join",
"condition",
"all",
"other",
"possible",
"operators",
"must",
"be",
"checked",
"afterwards",
".",
"emmit",
"(",
"combinedRow",
")",
"}",
"}",
"}",
"}",
"When",
"the",
"right",
"side",
"is",
"all",
"loaded",
"we",
"reset",
"the",
"right",
"iterator",
"to",
"start",
"clear",
"the",
"buffer",
"and",
"switch",
"back",
"to",
"iterate",
"the",
"next",
"elements",
"in",
"the",
"left",
"side",
"and",
"re",
"-",
"build",
"the",
"buffer",
"based",
"on",
"the",
"next",
"items",
"in",
"the",
"left",
"until",
"we",
"reach",
"the",
"blockSize",
"again",
".",
"Repeat",
"until",
"both",
"sides",
"are",
"all",
"loaded",
"and",
"processed",
".",
"The",
"caller",
"of",
"the",
"constructor",
"needs",
"to",
"pass",
"two",
"functions",
"#hashBuilderForLeft",
"and",
"#hashBuilderForRight",
".",
"Those",
"functions",
"are",
"called",
"on",
"each",
"row",
"of",
"the",
"left",
"and",
"right",
"side",
"respectively",
"and",
"they",
"return",
"the",
"hash",
"value",
"of",
"the",
"relevant",
"columns",
"of",
"the",
"row",
".",
"This",
"information",
"is",
"not",
"available",
"for",
"the",
"HashInnerJoinBatchIterator",
"so",
"it",
"'",
"s",
"the",
"responsibility",
"of",
"the",
"caller",
"to",
"provide",
"those",
"two",
"functions",
"that",
"operate",
"on",
"the",
"left",
"and",
"right",
"rows",
"accordingly",
"and",
"return",
"the",
"hash",
"values",
"."
] |
public class HashInnerJoinBatchIterator extends JoinBatchIterator<Row, Row, Row> {
private final RowAccounting<Object[]> leftRowAccounting;
private final Predicate<Row> joinCondition;
/**
* Used to avoid instantiating multiple times RowN in {@link #findMatchingRows()}
*/
private final UnsafeArrayRow leftRow = new UnsafeArrayRow();
private final ToIntFunction<Row> hashBuilderForLeft;
private final ToIntFunction<Row> hashBuilderForRight;
private final IntSupplier calculateBlockSize;
private final IntObjectHashMap<List<Object[]>> buffer;
private final UnsafeArrayRow unsafeArrayRow = new UnsafeArrayRow();
private int blockSize;
private int numberOfRowsInBuffer = 0;
private boolean leftBatchHasItems = false;
private int numberOfLeftBatchesForBlock;
private int numberOfLeftBatchesLoadedForBlock;
private Iterator<Object[]> leftMatchingRowsIterator;
public HashInnerJoinBatchIterator(BatchIterator<Row> left,
BatchIterator<Row> right,
RowAccounting<Object[]> leftRowAccounting,
CombinedRow combiner,
Predicate<Row> joinCondition,
ToIntFunction<Row> hashBuilderForLeft,
ToIntFunction<Row> hashBuilderForRight,
IntSupplier calculateBlockSize) {
super(left, right, combiner);
this.leftRowAccounting = leftRowAccounting;
this.joinCondition = joinCondition;
this.hashBuilderForLeft = hashBuilderForLeft;
this.hashBuilderForRight = hashBuilderForRight;
this.calculateBlockSize = calculateBlockSize;
// resized upon block size calculation
this.buffer = new IntObjectHashMap<>();
resetBuffer();
numberOfLeftBatchesLoadedForBlock = 0;
this.activeIt = left;
}
@Override
public Row currentElement() {
return combiner.currentElement();
}
@Override
public void moveToStart() {
left.moveToStart();
right.moveToStart();
activeIt = left;
resetBuffer();
leftMatchingRowsIterator = null;
}
@Override
public CompletionStage<?> loadNextBatch() throws Exception {
if (activeIt == left) {
numberOfLeftBatchesLoadedForBlock++;
}
return super.loadNextBatch();
}
@Override
public boolean moveNext() {
while (buildBufferAndMatchRight() == false) {
if (right.allLoaded() && leftBatchHasItems == false && left.allLoaded()) {
// both sides are fully loaded, we're done here
return false;
} else if (activeIt == left) {
// left needs the next batch loaded
return false;
} else if (right.allLoaded()) {
right.moveToStart();
activeIt = left;
resetBuffer();
} else {
return false;
}
}
// match found
return true;
}
private void resetBuffer() {
blockSize = calculateBlockSize.getAsInt();
buffer.clear();
numberOfRowsInBuffer = 0;
leftRowAccounting.release();
// A batch is not guaranteed to deliver PAGE_SIZE number of rows. It could be more or less.
// So we cannot rely on that to decide if processing 1 block is done, we must also know and track how much
// batches should be required for processing 1 block.
numberOfLeftBatchesForBlock = Math.max(1, (int) Math.ceil((double) blockSize / Paging.PAGE_SIZE));
numberOfLeftBatchesLoadedForBlock = leftBatchHasItems ? 1 : 0;
}
private boolean buildBufferAndMatchRight() {
if (activeIt == left) {
while (leftBatchHasItems = left.moveNext()) {
Object[] leftRow = left.currentElement().materialize();
leftRowAccounting.accountForAndMaybeBreak(leftRow);
int hash = hashBuilderForLeft.applyAsInt(unsafeArrayRow.cells(leftRow));
addToBuffer(leftRow, hash);
if (numberOfRowsInBuffer == blockSize) {
break;
}
}
if (mustLoadLeftNextBatch()) {
// we should load the left side
return false;
}
if (mustSwitchToRight()) {
activeIt = right;
}
}
// In case of multiple matches on the left side (duplicate values or hash collisions)
if (leftMatchingRowsIterator != null && findMatchingRows()) {
return true;
}
leftMatchingRowsIterator = null;
while (right.moveNext()) {
int rightHash = hashBuilderForRight.applyAsInt(right.currentElement());
List<Object[]> leftMatchingRows = buffer.get(rightHash);
if (leftMatchingRows != null) {
leftMatchingRowsIterator = leftMatchingRows.iterator();
combiner.setRight(right.currentElement());
if (findMatchingRows()) {
return true;
}
}
}
// need to load the next batch of the right relation
return false;
}
private void addToBuffer(Object[] currentRow, int hash) {
List<Object[]> existingRows = buffer.get(hash);
if (existingRows == null) {
existingRows = new ArrayList<>();
buffer.put(hash, existingRows);
}
existingRows.add(currentRow);
numberOfRowsInBuffer++;
}
private boolean findMatchingRows() {
while (leftMatchingRowsIterator.hasNext()) {
leftRow.cells(leftMatchingRowsIterator.next());
combiner.setLeft(leftRow);
if (joinCondition.test(combiner.currentElement())) {
return true;
}
}
return false;
}
private boolean mustSwitchToRight() {
return left.allLoaded()
|| numberOfRowsInBuffer == blockSize
|| (leftBatchHasItems == false && numberOfLeftBatchesLoadedForBlock == numberOfLeftBatchesForBlock);
}
private boolean mustLoadLeftNextBatch() {
return leftBatchHasItems == false
&& left.allLoaded() == false
&& numberOfRowsInBuffer < blockSize
&& numberOfLeftBatchesLoadedForBlock < numberOfLeftBatchesForBlock;
}
}
|
[
"public",
"class",
"HashInnerJoinBatchIterator",
"extends",
"JoinBatchIterator",
"<",
"Row",
",",
"Row",
",",
"Row",
">",
"{",
"private",
"final",
"RowAccounting",
"<",
"Object",
"[",
"]",
">",
"leftRowAccounting",
";",
"private",
"final",
"Predicate",
"<",
"Row",
">",
"joinCondition",
";",
"/**\n * Used to avoid instantiating multiple times RowN in {@link #findMatchingRows()}\n */",
"private",
"final",
"UnsafeArrayRow",
"leftRow",
"=",
"new",
"UnsafeArrayRow",
"(",
")",
";",
"private",
"final",
"ToIntFunction",
"<",
"Row",
">",
"hashBuilderForLeft",
";",
"private",
"final",
"ToIntFunction",
"<",
"Row",
">",
"hashBuilderForRight",
";",
"private",
"final",
"IntSupplier",
"calculateBlockSize",
";",
"private",
"final",
"IntObjectHashMap",
"<",
"List",
"<",
"Object",
"[",
"]",
">",
">",
"buffer",
";",
"private",
"final",
"UnsafeArrayRow",
"unsafeArrayRow",
"=",
"new",
"UnsafeArrayRow",
"(",
")",
";",
"private",
"int",
"blockSize",
";",
"private",
"int",
"numberOfRowsInBuffer",
"=",
"0",
";",
"private",
"boolean",
"leftBatchHasItems",
"=",
"false",
";",
"private",
"int",
"numberOfLeftBatchesForBlock",
";",
"private",
"int",
"numberOfLeftBatchesLoadedForBlock",
";",
"private",
"Iterator",
"<",
"Object",
"[",
"]",
">",
"leftMatchingRowsIterator",
";",
"public",
"HashInnerJoinBatchIterator",
"(",
"BatchIterator",
"<",
"Row",
">",
"left",
",",
"BatchIterator",
"<",
"Row",
">",
"right",
",",
"RowAccounting",
"<",
"Object",
"[",
"]",
">",
"leftRowAccounting",
",",
"CombinedRow",
"combiner",
",",
"Predicate",
"<",
"Row",
">",
"joinCondition",
",",
"ToIntFunction",
"<",
"Row",
">",
"hashBuilderForLeft",
",",
"ToIntFunction",
"<",
"Row",
">",
"hashBuilderForRight",
",",
"IntSupplier",
"calculateBlockSize",
")",
"{",
"super",
"(",
"left",
",",
"right",
",",
"combiner",
")",
";",
"this",
".",
"leftRowAccounting",
"=",
"leftRowAccounting",
";",
"this",
".",
"joinCondition",
"=",
"joinCondition",
";",
"this",
".",
"hashBuilderForLeft",
"=",
"hashBuilderForLeft",
";",
"this",
".",
"hashBuilderForRight",
"=",
"hashBuilderForRight",
";",
"this",
".",
"calculateBlockSize",
"=",
"calculateBlockSize",
";",
"this",
".",
"buffer",
"=",
"new",
"IntObjectHashMap",
"<",
">",
"(",
")",
";",
"resetBuffer",
"(",
")",
";",
"numberOfLeftBatchesLoadedForBlock",
"=",
"0",
";",
"this",
".",
"activeIt",
"=",
"left",
";",
"}",
"@",
"Override",
"public",
"Row",
"currentElement",
"(",
")",
"{",
"return",
"combiner",
".",
"currentElement",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"moveToStart",
"(",
")",
"{",
"left",
".",
"moveToStart",
"(",
")",
";",
"right",
".",
"moveToStart",
"(",
")",
";",
"activeIt",
"=",
"left",
";",
"resetBuffer",
"(",
")",
";",
"leftMatchingRowsIterator",
"=",
"null",
";",
"}",
"@",
"Override",
"public",
"CompletionStage",
"<",
"?",
">",
"loadNextBatch",
"(",
")",
"throws",
"Exception",
"{",
"if",
"(",
"activeIt",
"==",
"left",
")",
"{",
"numberOfLeftBatchesLoadedForBlock",
"++",
";",
"}",
"return",
"super",
".",
"loadNextBatch",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"boolean",
"moveNext",
"(",
")",
"{",
"while",
"(",
"buildBufferAndMatchRight",
"(",
")",
"==",
"false",
")",
"{",
"if",
"(",
"right",
".",
"allLoaded",
"(",
")",
"&&",
"leftBatchHasItems",
"==",
"false",
"&&",
"left",
".",
"allLoaded",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"else",
"if",
"(",
"activeIt",
"==",
"left",
")",
"{",
"return",
"false",
";",
"}",
"else",
"if",
"(",
"right",
".",
"allLoaded",
"(",
")",
")",
"{",
"right",
".",
"moveToStart",
"(",
")",
";",
"activeIt",
"=",
"left",
";",
"resetBuffer",
"(",
")",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}",
"private",
"void",
"resetBuffer",
"(",
")",
"{",
"blockSize",
"=",
"calculateBlockSize",
".",
"getAsInt",
"(",
")",
";",
"buffer",
".",
"clear",
"(",
")",
";",
"numberOfRowsInBuffer",
"=",
"0",
";",
"leftRowAccounting",
".",
"release",
"(",
")",
";",
"numberOfLeftBatchesForBlock",
"=",
"Math",
".",
"max",
"(",
"1",
",",
"(",
"int",
")",
"Math",
".",
"ceil",
"(",
"(",
"double",
")",
"blockSize",
"/",
"Paging",
".",
"PAGE_SIZE",
")",
")",
";",
"numberOfLeftBatchesLoadedForBlock",
"=",
"leftBatchHasItems",
"?",
"1",
":",
"0",
";",
"}",
"private",
"boolean",
"buildBufferAndMatchRight",
"(",
")",
"{",
"if",
"(",
"activeIt",
"==",
"left",
")",
"{",
"while",
"(",
"leftBatchHasItems",
"=",
"left",
".",
"moveNext",
"(",
")",
")",
"{",
"Object",
"[",
"]",
"leftRow",
"=",
"left",
".",
"currentElement",
"(",
")",
".",
"materialize",
"(",
")",
";",
"leftRowAccounting",
".",
"accountForAndMaybeBreak",
"(",
"leftRow",
")",
";",
"int",
"hash",
"=",
"hashBuilderForLeft",
".",
"applyAsInt",
"(",
"unsafeArrayRow",
".",
"cells",
"(",
"leftRow",
")",
")",
";",
"addToBuffer",
"(",
"leftRow",
",",
"hash",
")",
";",
"if",
"(",
"numberOfRowsInBuffer",
"==",
"blockSize",
")",
"{",
"break",
";",
"}",
"}",
"if",
"(",
"mustLoadLeftNextBatch",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"mustSwitchToRight",
"(",
")",
")",
"{",
"activeIt",
"=",
"right",
";",
"}",
"}",
"if",
"(",
"leftMatchingRowsIterator",
"!=",
"null",
"&&",
"findMatchingRows",
"(",
")",
")",
"{",
"return",
"true",
";",
"}",
"leftMatchingRowsIterator",
"=",
"null",
";",
"while",
"(",
"right",
".",
"moveNext",
"(",
")",
")",
"{",
"int",
"rightHash",
"=",
"hashBuilderForRight",
".",
"applyAsInt",
"(",
"right",
".",
"currentElement",
"(",
")",
")",
";",
"List",
"<",
"Object",
"[",
"]",
">",
"leftMatchingRows",
"=",
"buffer",
".",
"get",
"(",
"rightHash",
")",
";",
"if",
"(",
"leftMatchingRows",
"!=",
"null",
")",
"{",
"leftMatchingRowsIterator",
"=",
"leftMatchingRows",
".",
"iterator",
"(",
")",
";",
"combiner",
".",
"setRight",
"(",
"right",
".",
"currentElement",
"(",
")",
")",
";",
"if",
"(",
"findMatchingRows",
"(",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"}",
"return",
"false",
";",
"}",
"private",
"void",
"addToBuffer",
"(",
"Object",
"[",
"]",
"currentRow",
",",
"int",
"hash",
")",
"{",
"List",
"<",
"Object",
"[",
"]",
">",
"existingRows",
"=",
"buffer",
".",
"get",
"(",
"hash",
")",
";",
"if",
"(",
"existingRows",
"==",
"null",
")",
"{",
"existingRows",
"=",
"new",
"ArrayList",
"<",
">",
"(",
")",
";",
"buffer",
".",
"put",
"(",
"hash",
",",
"existingRows",
")",
";",
"}",
"existingRows",
".",
"add",
"(",
"currentRow",
")",
";",
"numberOfRowsInBuffer",
"++",
";",
"}",
"private",
"boolean",
"findMatchingRows",
"(",
")",
"{",
"while",
"(",
"leftMatchingRowsIterator",
".",
"hasNext",
"(",
")",
")",
"{",
"leftRow",
".",
"cells",
"(",
"leftMatchingRowsIterator",
".",
"next",
"(",
")",
")",
";",
"combiner",
".",
"setLeft",
"(",
"leftRow",
")",
";",
"if",
"(",
"joinCondition",
".",
"test",
"(",
"combiner",
".",
"currentElement",
"(",
")",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}",
"private",
"boolean",
"mustSwitchToRight",
"(",
")",
"{",
"return",
"left",
".",
"allLoaded",
"(",
")",
"||",
"numberOfRowsInBuffer",
"==",
"blockSize",
"||",
"(",
"leftBatchHasItems",
"==",
"false",
"&&",
"numberOfLeftBatchesLoadedForBlock",
"==",
"numberOfLeftBatchesForBlock",
")",
";",
"}",
"private",
"boolean",
"mustLoadLeftNextBatch",
"(",
")",
"{",
"return",
"leftBatchHasItems",
"==",
"false",
"&&",
"left",
".",
"allLoaded",
"(",
")",
"==",
"false",
"&&",
"numberOfRowsInBuffer",
"<",
"blockSize",
"&&",
"numberOfLeftBatchesLoadedForBlock",
"<",
"numberOfLeftBatchesForBlock",
";",
"}",
"}"
] |
<pre>
Build Phase:
for (leftRow in left) {
calculate hash and put in Buffer (HashMap) until the blockSize is reached
}
|
[
"<pre",
">",
"Build",
"Phase",
":",
"for",
"(",
"leftRow",
"in",
"left",
")",
"{",
"calculate",
"hash",
"and",
"put",
"in",
"Buffer",
"(",
"HashMap",
")",
"until",
"the",
"blockSize",
"is",
"reached",
"}"
] |
[
"// resized upon block size calculation",
"// both sides are fully loaded, we're done here",
"// left needs the next batch loaded",
"// match found",
"// A batch is not guaranteed to deliver PAGE_SIZE number of rows. It could be more or less.",
"// So we cannot rely on that to decide if processing 1 block is done, we must also know and track how much",
"// batches should be required for processing 1 block.",
"// we should load the left side",
"// In case of multiple matches on the left side (duplicate values or hash collisions)",
"// need to load the next batch of the right relation"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 15
| 1,296
| 405
|
d9333c3aa1f59cf2c55ff4fc8d971bff718fa00c
|
gravitee-io/gravitee-ui-components
|
src/organisms/gv-tabs.js
|
[
"ECL-2.0",
"Apache-2.0"
] |
JavaScript
|
GvTabs
|
/**
* Tabs component
*
* * ## Details
* * This component use gv-option component to generate tabs.
*
* @attr {Array<id: string | {id, title?, icon?, active?, description?, label?}>} options - An array of options for gv-option sub component
* @slot content - List of elements for tabs content. Should have an id related to options.
*
* @attr {String} value - the opened tab id
* @attr {Boolean} disabled - true if disabled
* @attr {Boolean} small - true if you want display tabs below of title
* @attr {Boolean} truncate - true if you want truncate tabs title
* @attr {Function} validator - a function that's calls when user change tab, this is useful to validate tab change.
*
* @cssprop {Length} [--gv-tabs-options--m=0] - Tabs options margin
*/
|
Tabs component
Details
This component use gv-option component to generate tabs.
@attr {Array} options - An array of options for gv-option sub component
@slot content - List of elements for tabs content. Should have an id related to options.
|
[
"Tabs",
"component",
"Details",
"This",
"component",
"use",
"gv",
"-",
"option",
"component",
"to",
"generate",
"tabs",
".",
"@attr",
"{",
"Array",
"}",
"options",
"-",
"An",
"array",
"of",
"options",
"for",
"gv",
"-",
"option",
"sub",
"component",
"@slot",
"content",
"-",
"List",
"of",
"elements",
"for",
"tabs",
"content",
".",
"Should",
"have",
"an",
"id",
"related",
"to",
"options",
"."
] |
class GvTabs extends LitElement {
static get properties() {
return {
options: { type: Array },
_options: { type: Array, attribute: false },
value: { type: String, reflect: true },
validator: { type: Function },
disabled: { type: Boolean },
small: { type: Boolean },
truncate: { type: Boolean },
};
}
static get styles() {
return [
// language=css
css`
:host {
box-sizing: border-box;
}
::slotted([slot='content']) {
opacity: 0;
box-sizing: border-box;
transition: opacity 350ms ease-in-out;
visibility: hidden;
position: absolute;
left: -9999px;
top: -9999px;
}
::slotted([slot='content'].current) {
opacity: 1;
visibility: visible;
position: relative;
left: auto;
top: auto;
}
.header {
display: flex;
border-bottom: 1px solid #d9d9d9;
box-sizing: border-box;
}
.title {
flex: 1;
display: flex;
align-items: center;
}
.actions {
display: flex;
align-items: center;
}
.tabs {
flex: 1;
display: flex;
justify-content: flex-end;
--gv-option--bdrs: 0;
}
:host([small]) .tabs {
flex-direction: column;
}
:host([small]) gv-option {
align-self: flex-end;
}
gv-option {
margin: var(--gv-tabs-options--m, 0);
}
::slotted(gv-button) {
padding-bottom: 2px;
}
`,
];
}
_getContent() {
const content = this.shadowRoot.querySelector('slot[name="content"]');
return content.assignedNodes();
}
firstUpdated() {
if (this.value == null && this.options != null && this.options.length > 0) {
this.value = this.options[0].id;
}
}
set options(options) {
if (options && Array.isArray(options)) {
this._options = options.map((option) => {
if (typeof option === 'string') {
return { id: option, title: option };
} else if (typeof option === 'object' && option.title == null) {
return { id: option.id, title: option.id };
}
return option;
});
}
}
get options() {
return this._options;
}
updated() {
const content = this._getContent();
content.forEach((c) => c.classList.remove('current'));
if (this.value) {
const target = this.querySelector(`#${this.value}`);
if (target) {
target.classList.add('current');
}
} else {
content[0].classList.add('current');
}
}
_changeTab(from, content, value) {
from.classList.remove('current');
content.classList.add('current');
this.value = value;
dispatchCustomEvent(this, 'change', { value, from: from.id, to: content.id });
}
_onClick({ detail }) {
if (!this.disabled) {
const from = this._getContent().find((e) => e.classList.contains('current'));
const content = this.querySelector(`#${detail.id}`);
this.shadowRoot.querySelector('gv-option').value = from.id;
if (this.validator) {
this.validator({ from: from.id, to: content.id })
.then(() => {
this._changeTab(from, content, detail.id);
})
.catch(() => {});
} else {
this._changeTab(from, content, detail.id);
}
}
}
get _contextualOptions() {
if (this.truncate) {
return this.options.map((option) => {
if (this.value !== option.id) {
const label = option.label || option.title;
return { ...option, label: label.substring(0, 1) };
}
return option;
});
}
return this.options;
}
render() {
return html`<div>
<div class="header">
<div class="tabs">
<slot name="title" class="title"></slot>
<gv-option small .options="${this._contextualOptions}" @gv-option:select="${this._onClick}" .value="${this.value}"></gv-option>
</div>
</div>
<slot name="content"></slot>
</div>`;
}
}
|
[
"class",
"GvTabs",
"extends",
"LitElement",
"{",
"static",
"get",
"properties",
"(",
")",
"{",
"return",
"{",
"options",
":",
"{",
"type",
":",
"Array",
"}",
",",
"_options",
":",
"{",
"type",
":",
"Array",
",",
"attribute",
":",
"false",
"}",
",",
"value",
":",
"{",
"type",
":",
"String",
",",
"reflect",
":",
"true",
"}",
",",
"validator",
":",
"{",
"type",
":",
"Function",
"}",
",",
"disabled",
":",
"{",
"type",
":",
"Boolean",
"}",
",",
"small",
":",
"{",
"type",
":",
"Boolean",
"}",
",",
"truncate",
":",
"{",
"type",
":",
"Boolean",
"}",
",",
"}",
";",
"}",
"static",
"get",
"styles",
"(",
")",
"{",
"return",
"[",
"css",
"`",
"`",
",",
"]",
";",
"}",
"_getContent",
"(",
")",
"{",
"const",
"content",
"=",
"this",
".",
"shadowRoot",
".",
"querySelector",
"(",
"'slot[name=\"content\"]'",
")",
";",
"return",
"content",
".",
"assignedNodes",
"(",
")",
";",
"}",
"firstUpdated",
"(",
")",
"{",
"if",
"(",
"this",
".",
"value",
"==",
"null",
"&&",
"this",
".",
"options",
"!=",
"null",
"&&",
"this",
".",
"options",
".",
"length",
">",
"0",
")",
"{",
"this",
".",
"value",
"=",
"this",
".",
"options",
"[",
"0",
"]",
".",
"id",
";",
"}",
"}",
"set",
"options",
"(",
"options",
")",
"{",
"if",
"(",
"options",
"&&",
"Array",
".",
"isArray",
"(",
"options",
")",
")",
"{",
"this",
".",
"_options",
"=",
"options",
".",
"map",
"(",
"(",
"option",
")",
"=>",
"{",
"if",
"(",
"typeof",
"option",
"===",
"'string'",
")",
"{",
"return",
"{",
"id",
":",
"option",
",",
"title",
":",
"option",
"}",
";",
"}",
"else",
"if",
"(",
"typeof",
"option",
"===",
"'object'",
"&&",
"option",
".",
"title",
"==",
"null",
")",
"{",
"return",
"{",
"id",
":",
"option",
".",
"id",
",",
"title",
":",
"option",
".",
"id",
"}",
";",
"}",
"return",
"option",
";",
"}",
")",
";",
"}",
"}",
"get",
"options",
"(",
")",
"{",
"return",
"this",
".",
"_options",
";",
"}",
"updated",
"(",
")",
"{",
"const",
"content",
"=",
"this",
".",
"_getContent",
"(",
")",
";",
"content",
".",
"forEach",
"(",
"(",
"c",
")",
"=>",
"c",
".",
"classList",
".",
"remove",
"(",
"'current'",
")",
")",
";",
"if",
"(",
"this",
".",
"value",
")",
"{",
"const",
"target",
"=",
"this",
".",
"querySelector",
"(",
"`",
"${",
"this",
".",
"value",
"}",
"`",
")",
";",
"if",
"(",
"target",
")",
"{",
"target",
".",
"classList",
".",
"add",
"(",
"'current'",
")",
";",
"}",
"}",
"else",
"{",
"content",
"[",
"0",
"]",
".",
"classList",
".",
"add",
"(",
"'current'",
")",
";",
"}",
"}",
"_changeTab",
"(",
"from",
",",
"content",
",",
"value",
")",
"{",
"from",
".",
"classList",
".",
"remove",
"(",
"'current'",
")",
";",
"content",
".",
"classList",
".",
"add",
"(",
"'current'",
")",
";",
"this",
".",
"value",
"=",
"value",
";",
"dispatchCustomEvent",
"(",
"this",
",",
"'change'",
",",
"{",
"value",
",",
"from",
":",
"from",
".",
"id",
",",
"to",
":",
"content",
".",
"id",
"}",
")",
";",
"}",
"_onClick",
"(",
"{",
"detail",
"}",
")",
"{",
"if",
"(",
"!",
"this",
".",
"disabled",
")",
"{",
"const",
"from",
"=",
"this",
".",
"_getContent",
"(",
")",
".",
"find",
"(",
"(",
"e",
")",
"=>",
"e",
".",
"classList",
".",
"contains",
"(",
"'current'",
")",
")",
";",
"const",
"content",
"=",
"this",
".",
"querySelector",
"(",
"`",
"${",
"detail",
".",
"id",
"}",
"`",
")",
";",
"this",
".",
"shadowRoot",
".",
"querySelector",
"(",
"'gv-option'",
")",
".",
"value",
"=",
"from",
".",
"id",
";",
"if",
"(",
"this",
".",
"validator",
")",
"{",
"this",
".",
"validator",
"(",
"{",
"from",
":",
"from",
".",
"id",
",",
"to",
":",
"content",
".",
"id",
"}",
")",
".",
"then",
"(",
"(",
")",
"=>",
"{",
"this",
".",
"_changeTab",
"(",
"from",
",",
"content",
",",
"detail",
".",
"id",
")",
";",
"}",
")",
".",
"catch",
"(",
"(",
")",
"=>",
"{",
"}",
")",
";",
"}",
"else",
"{",
"this",
".",
"_changeTab",
"(",
"from",
",",
"content",
",",
"detail",
".",
"id",
")",
";",
"}",
"}",
"}",
"get",
"_contextualOptions",
"(",
")",
"{",
"if",
"(",
"this",
".",
"truncate",
")",
"{",
"return",
"this",
".",
"options",
".",
"map",
"(",
"(",
"option",
")",
"=>",
"{",
"if",
"(",
"this",
".",
"value",
"!==",
"option",
".",
"id",
")",
"{",
"const",
"label",
"=",
"option",
".",
"label",
"||",
"option",
".",
"title",
";",
"return",
"{",
"...",
"option",
",",
"label",
":",
"label",
".",
"substring",
"(",
"0",
",",
"1",
")",
"}",
";",
"}",
"return",
"option",
";",
"}",
")",
";",
"}",
"return",
"this",
".",
"options",
";",
"}",
"render",
"(",
")",
"{",
"return",
"html",
"`",
"${",
"this",
".",
"_contextualOptions",
"}",
"${",
"this",
".",
"_onClick",
"}",
"${",
"this",
".",
"value",
"}",
"`",
";",
"}",
"}"
] |
Tabs component
* ## Details
* This component use gv-option component to generate tabs.
|
[
"Tabs",
"component",
"*",
"##",
"Details",
"*",
"This",
"component",
"use",
"gv",
"-",
"option",
"component",
"to",
"generate",
"tabs",
"."
] |
[
"// language=css"
] |
[
{
"param": "LitElement",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "LitElement",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 21
| 1,022
| 190
|
b5a6b7f4d072b43c98803eb9bcf90bcf186fba96
|
GidLev/cepy
|
cepy/ce.py
|
[
"MIT"
] |
Python
|
Weights
|
Stores the trained weight (W and W' matrices) of all fitting permutations.
Extract the weights with ``get_w_permut(index, norm_flag)`` and ``get_w_mean(norm_flag)``
or ``get_w_apos_permut(index, norm_flag)`` and ``get_w_apos_mean(norm_flag)``. If norm_flag
is set to True l2 normalization would apply on each vector before extraction.
|
Stores the trained weight (W and W' matrices) of all fitting permutations.
|
[
"Stores",
"the",
"trained",
"weight",
"(",
"W",
"and",
"W",
"'",
"matrices",
")",
"of",
"all",
"fitting",
"permutations",
"."
] |
class Weights:
'''
Stores the trained weight (W and W' matrices) of all fitting permutations.
Extract the weights with ``get_w_permut(index, norm_flag)`` and ``get_w_mean(norm_flag)``
or ``get_w_apos_permut(index, norm_flag)`` and ``get_w_apos_mean(norm_flag)``. If norm_flag
is set to True l2 normalization would apply on each vector before extraction.
'''
def __init__(self):
self.w = []
self.w_apos = []
def get_w_permut(self, index=0, norm=True):
if norm: # L2 norm
return self.w[index] / np.linalg.norm(self.w[index], axis=1)[:, np.newaxis]
else:
return self.w[index]
def get_w_mean(self, norm=True):
all_w = [self.get_w_permut(i, norm=norm) for i in np.arange(len(self.w))]
return np.mean(all_w, axis=0)
def get_w_apos_permut(self, index=0, norm=True):
if norm: # L2 norm
return self.w_apos[index] / np.linalg.norm(self.w_apos[index], axis=0)[np.newaxis, :]
else:
return self.w_apos[index]
def get_w_apos_mean(self, norm=True):
all_w_apos = [self.get_w_apos_permut(i, norm=norm) for i in np.arange(len(self.w_apos))]
return np.mean(all_w_apos, axis=0)
|
[
"class",
"Weights",
":",
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"w",
"=",
"[",
"]",
"self",
".",
"w_apos",
"=",
"[",
"]",
"def",
"get_w_permut",
"(",
"self",
",",
"index",
"=",
"0",
",",
"norm",
"=",
"True",
")",
":",
"if",
"norm",
":",
"return",
"self",
".",
"w",
"[",
"index",
"]",
"/",
"np",
".",
"linalg",
".",
"norm",
"(",
"self",
".",
"w",
"[",
"index",
"]",
",",
"axis",
"=",
"1",
")",
"[",
":",
",",
"np",
".",
"newaxis",
"]",
"else",
":",
"return",
"self",
".",
"w",
"[",
"index",
"]",
"def",
"get_w_mean",
"(",
"self",
",",
"norm",
"=",
"True",
")",
":",
"all_w",
"=",
"[",
"self",
".",
"get_w_permut",
"(",
"i",
",",
"norm",
"=",
"norm",
")",
"for",
"i",
"in",
"np",
".",
"arange",
"(",
"len",
"(",
"self",
".",
"w",
")",
")",
"]",
"return",
"np",
".",
"mean",
"(",
"all_w",
",",
"axis",
"=",
"0",
")",
"def",
"get_w_apos_permut",
"(",
"self",
",",
"index",
"=",
"0",
",",
"norm",
"=",
"True",
")",
":",
"if",
"norm",
":",
"return",
"self",
".",
"w_apos",
"[",
"index",
"]",
"/",
"np",
".",
"linalg",
".",
"norm",
"(",
"self",
".",
"w_apos",
"[",
"index",
"]",
",",
"axis",
"=",
"0",
")",
"[",
"np",
".",
"newaxis",
",",
":",
"]",
"else",
":",
"return",
"self",
".",
"w_apos",
"[",
"index",
"]",
"def",
"get_w_apos_mean",
"(",
"self",
",",
"norm",
"=",
"True",
")",
":",
"all_w_apos",
"=",
"[",
"self",
".",
"get_w_apos_permut",
"(",
"i",
",",
"norm",
"=",
"norm",
")",
"for",
"i",
"in",
"np",
".",
"arange",
"(",
"len",
"(",
"self",
".",
"w_apos",
")",
")",
"]",
"return",
"np",
".",
"mean",
"(",
"all_w_apos",
",",
"axis",
"=",
"0",
")"
] |
Stores the trained weight (W and W' matrices) of all fitting permutations.
|
[
"Stores",
"the",
"trained",
"weight",
"(",
"W",
"and",
"W",
"'",
"matrices",
")",
"of",
"all",
"fitting",
"permutations",
"."
] |
[
"'''\n Stores the trained weight (W and W' matrices) of all fitting permutations.\n\n Extract the weights with ``get_w_permut(index, norm_flag)`` and ``get_w_mean(norm_flag)``\n or ``get_w_apos_permut(index, norm_flag)`` and ``get_w_apos_mean(norm_flag)``. If norm_flag\n is set to True l2 normalization would apply on each vector before extraction.\n\n '''",
"# L2 norm",
"# L2 norm"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 14
| 338
| 91
|
85aabdf791de0d97f725c0b7a42168917c77ef24
|
igorpeshansky/getting-started-ruby
|
bookshelf/app/models/book.rb
|
[
"Apache-2.0"
] |
Ruby
|
Book
|
# Copyright 2019 Google LLC.
# 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.
|
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.
|
[
"Unless",
"required",
"by",
"applicable",
"law",
"or",
"agreed",
"to",
"in",
"writing",
"software",
"distributed",
"under",
"the",
"License",
"is",
"distributed",
"on",
"an",
"\"",
"AS",
"IS",
"\"",
"BASIS",
"WITHOUT",
"WARRANTIES",
"OR",
"CONDITIONS",
"OF",
"ANY",
"KIND",
"either",
"express",
"or",
"implied",
".",
"See",
"the",
"License",
"for",
"the",
"specific",
"language",
"governing",
"permissions",
"and",
"limitations",
"under",
"the",
"License",
"."
] |
class Book
# Add Active Model support.
# Provides constructor that takes a Hash of attribute values.
include ActiveModel::Model
# Add Active Model validation support to Book class.
include ActiveModel::Validations
validates :title, presence: true
attr_accessor :id, :title, :author, :published_on, :description, :image_url, :cover_image
# Return a Google::Cloud::Firestore::Dataset for the configured collection.
# The collection is used to create, read, update, and delete entity objects.
def self.collection
project_id = ENV["GOOGLE_CLOUD_PROJECT"]
raise "Set the GOOGLE_CLOUD_PROJECT environment variable" if project_id.nil?
# [START bookshelf_firestore_client]
require "google/cloud/firestore"
firestore = Google::Cloud::Firestore.new project_id: project_id
@collection = firestore.col "books"
# [END bookshelf_firestore_client]
end
def self.storage_bucket
project_id = ENV["GOOGLE_CLOUD_PROJECT"]
raise "Set the GOOGLE_CLOUD_PROJECT environment variable" if project_id.nil?
@storage_bucket = begin
config = Rails.application.config.x.settings
# [START bookshelf_cloud_storage_client]
require "google/cloud/storage"
bucket_id = project_id + "_bucket"
storage = Google::Cloud::Storage.new project_id: config["project_id"],
credentials: config["keyfile"]
bucket = storage.bucket bucket_id
# [END bookshelf_cloud_storage_client]
raise "bucket does not exist" if bucket.nil?
bucket
end
end
# Query Book entities from Cloud Firestore.
#
# returns an array of Book query results and the last book title
# that can be used to query for additional results.
def self.query options = {}
query = collection.order :title
query = query.limit options[:limit] if options[:limit]
query = query.start_after options[:last_title] if options[:last_title]
books = []
begin
query.get do |book|
books << Book.from_snapspot(book)
end
rescue
end
books
end
def self.requires_pagination last_title
if last_title
collection
.order(:title)
.limit(1)
.start_after(last_title)
.get.count > 0
end
end
def self.from_snapspot book_snapshot
book = Book.new
book.id = book_snapshot.document_id
book_snapshot.data.each do |name, value|
book.send "#{name}=", value if book.respond_to? "#{name}="
end
book
end
# Lookup Book by ID. Returns Book or nil.
def self.find id
# [START bookshelf_firestore_client_get_book]
book_snapshot = collection.doc(id).get
Book.from_snapspot book_snapshot if book_snapshot.data
# [END bookshelf_firestore_client_get_book]
end
# Save the book to Firestore.
# @return true if valid and saved successfully, otherwise false.
def save
if valid?
book_ref = Book.collection.doc id
book_ref.set \
title: title,
author: author,
published_on: published_on,
description: description,
image_url: image_url
self.id = book_ref.document_id
true
else
false
end
end
def create
upload_image if cover_image
save
end
# Set attribute values from provided Hash and save to Firestore.
def update attributes
attributes.each do |name, value|
send "#{name}=", value if respond_to? "#{name}="
end
update_image if cover_image
save
end
def update_image
delete_image if image_url
upload_image
end
def upload_image
file = Book.storage_bucket.create_file \
cover_image.tempfile,
"cover_images/#{id}/#{cover_image.original_filename}",
content_type: cover_image.content_type,
acl: "public"
@image_url = file.public_url
end
def destroy
delete_image if image_url
book_ref = Book.collection.doc id
book_ref.delete if book_ref
end
def delete_image
image_uri = URI.parse image_url
if image_uri.host == "#{Book.storage_bucket.name}.storage.googleapis.com"
# Remove leading forward slash from image path
# The result will be the image key, eg. "cover_images/:id/:filename"
image_path = image_uri.path.sub "/", ""
file = Book.storage_bucket.file image_path
file.delete
end
end
##################
def persisted?
id.present?
end
end
|
[
"class",
"Book",
"include",
"ActiveModel",
"::",
"Model",
"include",
"ActiveModel",
"::",
"Validations",
"validates",
":title",
",",
"presence",
":",
"true",
"attr_accessor",
":id",
",",
":title",
",",
":author",
",",
":published_on",
",",
":description",
",",
":image_url",
",",
":cover_image",
"def",
"self",
".",
"collection",
"project_id",
"=",
"ENV",
"[",
"\"GOOGLE_CLOUD_PROJECT\"",
"]",
"raise",
"\"Set the GOOGLE_CLOUD_PROJECT environment variable\"",
"if",
"project_id",
".",
"nil?",
"require",
"\"google/cloud/firestore\"",
"firestore",
"=",
"Google",
"::",
"Cloud",
"::",
"Firestore",
".",
"new",
"project_id",
":",
"project_id",
"@collection",
"=",
"firestore",
".",
"col",
"\"books\"",
"end",
"def",
"self",
".",
"storage_bucket",
"project_id",
"=",
"ENV",
"[",
"\"GOOGLE_CLOUD_PROJECT\"",
"]",
"raise",
"\"Set the GOOGLE_CLOUD_PROJECT environment variable\"",
"if",
"project_id",
".",
"nil?",
"@storage_bucket",
"=",
"begin",
"config",
"=",
"Rails",
".",
"application",
".",
"config",
".",
"x",
".",
"settings",
"require",
"\"google/cloud/storage\"",
"bucket_id",
"=",
"project_id",
"+",
"\"_bucket\"",
"storage",
"=",
"Google",
"::",
"Cloud",
"::",
"Storage",
".",
"new",
"project_id",
":",
"config",
"[",
"\"project_id\"",
"]",
",",
"credentials",
":",
"config",
"[",
"\"keyfile\"",
"]",
"bucket",
"=",
"storage",
".",
"bucket",
"bucket_id",
"raise",
"\"bucket does not exist\"",
"if",
"bucket",
".",
"nil?",
"bucket",
"end",
"end",
"def",
"self",
".",
"query",
"options",
"=",
"{",
"}",
"query",
"=",
"collection",
".",
"order",
":title",
"query",
"=",
"query",
".",
"limit",
"options",
"[",
":limit",
"]",
"if",
"options",
"[",
":limit",
"]",
"query",
"=",
"query",
".",
"start_after",
"options",
"[",
":last_title",
"]",
"if",
"options",
"[",
":last_title",
"]",
"books",
"=",
"[",
"]",
"begin",
"query",
".",
"get",
"do",
"|",
"book",
"|",
"books",
"<<",
"Book",
".",
"from_snapspot",
"(",
"book",
")",
"end",
"rescue",
"end",
"books",
"end",
"def",
"self",
".",
"requires_pagination",
"last_title",
"if",
"last_title",
"collection",
".",
"order",
"(",
":title",
")",
".",
"limit",
"(",
"1",
")",
".",
"start_after",
"(",
"last_title",
")",
".",
"get",
".",
"count",
">",
"0",
"end",
"end",
"def",
"self",
".",
"from_snapspot",
"book_snapshot",
"book",
"=",
"Book",
".",
"new",
"book",
".",
"id",
"=",
"book_snapshot",
".",
"document_id",
"book_snapshot",
".",
"data",
".",
"each",
"do",
"|",
"name",
",",
"value",
"|",
"book",
".",
"send",
"\"#{name}=\"",
",",
"value",
"if",
"book",
".",
"respond_to?",
"\"#{name}=\"",
"end",
"book",
"end",
"def",
"self",
".",
"find",
"id",
"book_snapshot",
"=",
"collection",
".",
"doc",
"(",
"id",
")",
".",
"get",
"Book",
".",
"from_snapspot",
"book_snapshot",
"if",
"book_snapshot",
".",
"data",
"end",
"def",
"save",
"if",
"valid?",
"book_ref",
"=",
"Book",
".",
"collection",
".",
"doc",
"id",
"book_ref",
".",
"set",
"title",
":",
"title",
",",
"author",
":",
"author",
",",
"published_on",
":",
"published_on",
",",
"description",
":",
"description",
",",
"image_url",
":",
"image_url",
"self",
".",
"id",
"=",
"book_ref",
".",
"document_id",
"true",
"else",
"false",
"end",
"end",
"def",
"create",
"upload_image",
"if",
"cover_image",
"save",
"end",
"def",
"update",
"attributes",
"attributes",
".",
"each",
"do",
"|",
"name",
",",
"value",
"|",
"send",
"\"#{name}=\"",
",",
"value",
"if",
"respond_to?",
"\"#{name}=\"",
"end",
"update_image",
"if",
"cover_image",
"save",
"end",
"def",
"update_image",
"delete_image",
"if",
"image_url",
"upload_image",
"end",
"def",
"upload_image",
"file",
"=",
"Book",
".",
"storage_bucket",
".",
"create_file",
"cover_image",
".",
"tempfile",
",",
"\"cover_images/#{id}/#{cover_image.original_filename}\"",
",",
"content_type",
":",
"cover_image",
".",
"content_type",
",",
"acl",
":",
"\"public\"",
"@image_url",
"=",
"file",
".",
"public_url",
"end",
"def",
"destroy",
"delete_image",
"if",
"image_url",
"book_ref",
"=",
"Book",
".",
"collection",
".",
"doc",
"id",
"book_ref",
".",
"delete",
"if",
"book_ref",
"end",
"def",
"delete_image",
"image_uri",
"=",
"URI",
".",
"parse",
"image_url",
"if",
"image_uri",
".",
"host",
"==",
"\"#{Book.storage_bucket.name}.storage.googleapis.com\"",
"image_path",
"=",
"image_uri",
".",
"path",
".",
"sub",
"\"/\"",
",",
"\"\"",
"file",
"=",
"Book",
".",
"storage_bucket",
".",
"file",
"image_path",
"file",
".",
"delete",
"end",
"end",
"def",
"persisted?",
"id",
".",
"present?",
"end",
"end"
] |
Copyright 2019 Google LLC.
|
[
"Copyright",
"2019",
"Google",
"LLC",
"."
] |
[
"# Add Active Model support.",
"# Provides constructor that takes a Hash of attribute values.",
"# Add Active Model validation support to Book class.",
"# Return a Google::Cloud::Firestore::Dataset for the configured collection.",
"# The collection is used to create, read, update, and delete entity objects.",
"# [START bookshelf_firestore_client]",
"# [END bookshelf_firestore_client]",
"# [START bookshelf_cloud_storage_client]",
"# [END bookshelf_cloud_storage_client]",
"# Query Book entities from Cloud Firestore.",
"#",
"# returns an array of Book query results and the last book title",
"# that can be used to query for additional results.",
"# Lookup Book by ID. Returns Book or nil.",
"# [START bookshelf_firestore_client_get_book]",
"# [END bookshelf_firestore_client_get_book]",
"# Save the book to Firestore.",
"# @return true if valid and saved successfully, otherwise false.",
"# Set attribute values from provided Hash and save to Firestore.",
"# Remove leading forward slash from image path",
"# The result will be the image key, eg. \"cover_images/:id/:filename\"",
"##################"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 14
| 1,034
| 129
|
7b3d4e06886ca572ef49d8c196d25d41fcb80063
|
IndoorAtlas/unity-plugin
|
Plugins/IndoorAtlas/IndoorAtlasWGSConversion.cs
|
[
"Apache-2.0"
] |
C#
|
WGSConversion
|
/// <summary>
/// A utility class which converts IndoorAtlas SDK's location coordinates to metric
/// (east, north) coordinates. This is achieved with a linear approximation around
/// a fixed "linearization point" (origin). This point can be any fixed point
/// in the 3D world whose (latitude, longitude) and (x, y, z) relation can be
/// determined accurately.
/// The origin has to be updated if the movement is "great" with respect to Earth's
/// curvature (e.g. moving to another side of the world in a simulated environment).
/// </summary>
|
A utility class which converts IndoorAtlas SDK's location coordinates to metric
(east, north) coordinates. This is achieved with a linear approximation around
a fixed "linearization point" (origin). This point can be any fixed point
in the 3D world whose (latitude, longitude) and (x, y, z) relation can be
determined accurately.
The origin has to be updated if the movement is "great" with respect to Earth's
curvature .
|
[
"A",
"utility",
"class",
"which",
"converts",
"IndoorAtlas",
"SDK",
"'",
"s",
"location",
"coordinates",
"to",
"metric",
"(",
"east",
"north",
")",
"coordinates",
".",
"This",
"is",
"achieved",
"with",
"a",
"linear",
"approximation",
"around",
"a",
"fixed",
"\"",
"linearization",
"point",
"\"",
"(",
"origin",
")",
".",
"This",
"point",
"can",
"be",
"any",
"fixed",
"point",
"in",
"the",
"3D",
"world",
"whose",
"(",
"latitude",
"longitude",
")",
"and",
"(",
"x",
"y",
"z",
")",
"relation",
"can",
"be",
"determined",
"accurately",
".",
"The",
"origin",
"has",
"to",
"be",
"updated",
"if",
"the",
"movement",
"is",
"\"",
"great",
"\"",
"with",
"respect",
"to",
"Earth",
"'",
"s",
"curvature",
"."
] |
public class WGSConversion {
private double lat0;
private double lon0;
private double deltaX;
private double deltaY;
private bool hasLinearizationPoint = false;
public void SetOrigin(double latitude, double longitude) {
lat0 = latitude;
lon0 = longitude;
const double a = 6378137.0;
const double f = 1.0 / 298.257223563;
const double b = a * (1.0 - f);
const double a2 = a * a;
const double b2 = b * b;
double sinlat = System.Math.Sin(System.Math.PI / 180.0 * latitude);
double coslat = System.Math.Cos(System.Math.PI / 180.0 * latitude);
double tmp = System.Math.Sqrt(a2 * coslat * coslat + b2 * sinlat * sinlat);
deltaX = (System.Math.PI / 180.0) * (a2 / tmp) * coslat;
deltaY = (System.Math.PI / 180.0) * (a2 * b2 / (tmp * tmp * tmp));
hasLinearizationPoint = true;
}
public Vector2 WGStoEN(double latitude, double longitude) {
if (!hasLinearizationPoint) throw new System.InvalidOperationException("Origin hasn't been set before the conversion.");
return new Vector2((float)(deltaX * (longitude - lon0)), (float)(deltaY * (latitude - lat0)));
}
public bool IsReady() {
return hasLinearizationPoint;
}
}
|
[
"public",
"class",
"WGSConversion",
"{",
"private",
"double",
"lat0",
";",
"private",
"double",
"lon0",
";",
"private",
"double",
"deltaX",
";",
"private",
"double",
"deltaY",
";",
"private",
"bool",
"hasLinearizationPoint",
"=",
"false",
";",
"public",
"void",
"SetOrigin",
"(",
"double",
"latitude",
",",
"double",
"longitude",
")",
"{",
"lat0",
"=",
"latitude",
";",
"lon0",
"=",
"longitude",
";",
"const",
"double",
"a",
"=",
"6378137.0",
";",
"const",
"double",
"f",
"=",
"1.0",
"/",
"298.257223563",
";",
"const",
"double",
"b",
"=",
"a",
"*",
"(",
"1.0",
"-",
"f",
")",
";",
"const",
"double",
"a2",
"=",
"a",
"*",
"a",
";",
"const",
"double",
"b2",
"=",
"b",
"*",
"b",
";",
"double",
"sinlat",
"=",
"System",
".",
"Math",
".",
"Sin",
"(",
"System",
".",
"Math",
".",
"PI",
"/",
"180.0",
"*",
"latitude",
")",
";",
"double",
"coslat",
"=",
"System",
".",
"Math",
".",
"Cos",
"(",
"System",
".",
"Math",
".",
"PI",
"/",
"180.0",
"*",
"latitude",
")",
";",
"double",
"tmp",
"=",
"System",
".",
"Math",
".",
"Sqrt",
"(",
"a2",
"*",
"coslat",
"*",
"coslat",
"+",
"b2",
"*",
"sinlat",
"*",
"sinlat",
")",
";",
"deltaX",
"=",
"(",
"System",
".",
"Math",
".",
"PI",
"/",
"180.0",
")",
"*",
"(",
"a2",
"/",
"tmp",
")",
"*",
"coslat",
";",
"deltaY",
"=",
"(",
"System",
".",
"Math",
".",
"PI",
"/",
"180.0",
")",
"*",
"(",
"a2",
"*",
"b2",
"/",
"(",
"tmp",
"*",
"tmp",
"*",
"tmp",
")",
")",
";",
"hasLinearizationPoint",
"=",
"true",
";",
"}",
"public",
"Vector2",
"WGStoEN",
"(",
"double",
"latitude",
",",
"double",
"longitude",
")",
"{",
"if",
"(",
"!",
"hasLinearizationPoint",
")",
"throw",
"new",
"System",
".",
"InvalidOperationException",
"(",
"\"",
"Origin hasn't been set before the conversion.",
"\"",
")",
";",
"return",
"new",
"Vector2",
"(",
"(",
"float",
")",
"(",
"deltaX",
"*",
"(",
"longitude",
"-",
"lon0",
")",
")",
",",
"(",
"float",
")",
"(",
"deltaY",
"*",
"(",
"latitude",
"-",
"lat0",
")",
")",
")",
";",
"}",
"public",
"bool",
"IsReady",
"(",
")",
"{",
"return",
"hasLinearizationPoint",
";",
"}",
"}"
] |
A utility class which converts IndoorAtlas SDK's location coordinates to metric
(east, north) coordinates.
|
[
"A",
"utility",
"class",
"which",
"converts",
"IndoorAtlas",
"SDK",
"'",
"s",
"location",
"coordinates",
"to",
"metric",
"(",
"east",
"north",
")",
"coordinates",
"."
] |
[
"/// <summary>",
"/// Sets the origin in metric coordinates to (latitude, longitude) location.",
"/// </summary>",
"/// <param name=\"latitude\">The latitude of origin in degrees</param>",
"/// <param name=\"longitude\">The longitude of origin in degrees</param>",
"// Earth's semimajor axis in meters in WGS84",
"// Earth's flattening in WGS84",
"/// <summary>",
"/// Converts a (latitude, longitude) pair to (east, north) metric coordinates",
"/// with respect to the (previously set) origin. That is, what is the translation",
"/// to east and north respectively from the origin to reach (latitude, longitude).",
"/// </summary>",
"/// <param name=\"latitude\">Latitude in degrees</param>",
"/// <param name=\"longitude\">Longitude in degrees</param>",
"/// <returns>Metric coordinates in a local (east, north) coordinate system.</returns>",
"/// <exception cref=\"System.InvalidOperationException\">",
"/// Thrown if setOrigin hasn't been called before this function call.",
"/// </exception>",
"/// <summary>",
"/// Checks if origin has been set successfully.",
"/// </summary>",
"/// <returns>True if converter has origin, false otherwise.</returns>"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 15
| 358
| 126
|
10d33e9a5a8788ee555274a3bb733180a62deb89
|
Veok/eshoe-shop
|
eshoe-shop/admin123/themes/new-theme/js/components/form-submit-button.js
|
[
"MIT"
] |
JavaScript
|
FormSubmitButton
|
/**
* Component which allows submitting very simple forms without having to use <form> element.
*
* Useful when performing actions on resource where URL contains all needed data.
* For example, to toggle category status via "POST /categories/2/toggle-status)"
* or delete cover image via "POST /categories/2/delete-cover-image".
*
* Usage example in template:
*
* <button class="js-form-submit-btn"
* data-form-submit-url="/my-custom-url" // (required) URL to which form will be submitted
* data-form-csrf-token="my-generated-csrf-token" // (optional) to increase security
* data-form-confirm-message="Are you sure?" // (optional) to confirm action before submit
* type="button" // make sure its simple button
* // so we can avoid submitting actual form
* // when our button is defined inside form
* >
* Click me to submit form
* </button>
*
* In page specific JS you have to enable this feature:
*
* new FormSubmitButton();
*/
|
Component which allows submitting very simple forms without having to use element.
Useful when performing actions on resource where URL contains all needed data.
Usage example in template.
Click me to submit form
In page specific JS you have to enable this feature.
|
[
"Component",
"which",
"allows",
"submitting",
"very",
"simple",
"forms",
"without",
"having",
"to",
"use",
"element",
".",
"Useful",
"when",
"performing",
"actions",
"on",
"resource",
"where",
"URL",
"contains",
"all",
"needed",
"data",
".",
"Usage",
"example",
"in",
"template",
".",
"Click",
"me",
"to",
"submit",
"form",
"In",
"page",
"specific",
"JS",
"you",
"have",
"to",
"enable",
"this",
"feature",
"."
] |
class FormSubmitButton {
constructor() {
$(document).on('click', '.js-form-submit-btn', function (event) {
event.preventDefault();
const $btn = $(this);
if ($btn.data('form-confirm-message') && false === confirm($btn.data('form-confirm-message'))) {
return;
}
const $form = $('<form>', {
'action': $btn.data('form-submit-url'),
'method': 'POST',
});
if ($btn.data('form-csrf-token')) {
$form.append($('<input>', {
'type': '_hidden',
'name': '_csrf_token',
'value': $btn.data('form-csrf-token')
}));
}
$form.appendTo('body').submit();
});
}
}
|
[
"class",
"FormSubmitButton",
"{",
"constructor",
"(",
")",
"{",
"$",
"(",
"document",
")",
".",
"on",
"(",
"'click'",
",",
"'.js-form-submit-btn'",
",",
"function",
"(",
"event",
")",
"{",
"event",
".",
"preventDefault",
"(",
")",
";",
"const",
"$btn",
"=",
"$",
"(",
"this",
")",
";",
"if",
"(",
"$btn",
".",
"data",
"(",
"'form-confirm-message'",
")",
"&&",
"false",
"===",
"confirm",
"(",
"$btn",
".",
"data",
"(",
"'form-confirm-message'",
")",
")",
")",
"{",
"return",
";",
"}",
"const",
"$form",
"=",
"$",
"(",
"'<form>'",
",",
"{",
"'action'",
":",
"$btn",
".",
"data",
"(",
"'form-submit-url'",
")",
",",
"'method'",
":",
"'POST'",
",",
"}",
")",
";",
"if",
"(",
"$btn",
".",
"data",
"(",
"'form-csrf-token'",
")",
")",
"{",
"$form",
".",
"append",
"(",
"$",
"(",
"'<input>'",
",",
"{",
"'type'",
":",
"'_hidden'",
",",
"'name'",
":",
"'_csrf_token'",
",",
"'value'",
":",
"$btn",
".",
"data",
"(",
"'form-csrf-token'",
")",
"}",
")",
")",
";",
"}",
"$form",
".",
"appendTo",
"(",
"'body'",
")",
".",
"submit",
"(",
")",
";",
"}",
")",
";",
"}",
"}"
] |
Component which allows submitting very simple forms without having to use <form> element.
|
[
"Component",
"which",
"allows",
"submitting",
"very",
"simple",
"forms",
"without",
"having",
"to",
"use",
"<form",
">",
"element",
"."
] |
[] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 22
| 166
| 227
|
319595c7497f211e445f7585be922c7fd89a3898
|
EmbryoPhenomics/vuba
|
vuba/ops.py
|
[
"MIT"
] |
Python
|
Solidity
|
Filter contours by solidity based on a lower or upper limit, or both.
Parameters
----------
min : int or float
Lower solidity limit to filter contours.
max: int or float
Upper solidity limit to filter contours.
Returns
-------
filter : Solidity
Class object with ``__call__`` method that filters contours based on
the pre-defined solidity limits provided at initiation.
Notes
-----
Note that here the solidity of a contour is based on its area relative
to its corresponding convex hull.
See Also
--------
smallest
largest
parents
Area
Eccentricity
|
Filter contours by solidity based on a lower or upper limit, or both.
Parameters
min : int or float
Lower solidity limit to filter contours.
max: int or float
Upper solidity limit to filter contours.
Returns
filter : Solidity
Class object with ``__call__`` method that filters contours based on
the pre-defined solidity limits provided at initiation.
Notes
Note that here the solidity of a contour is based on its area relative
to its corresponding convex hull.
See Also
smallest
largest
parents
Area
Eccentricity
|
[
"Filter",
"contours",
"by",
"solidity",
"based",
"on",
"a",
"lower",
"or",
"upper",
"limit",
"or",
"both",
".",
"Parameters",
"min",
":",
"int",
"or",
"float",
"Lower",
"solidity",
"limit",
"to",
"filter",
"contours",
".",
"max",
":",
"int",
"or",
"float",
"Upper",
"solidity",
"limit",
"to",
"filter",
"contours",
".",
"Returns",
"filter",
":",
"Solidity",
"Class",
"object",
"with",
"`",
"`",
"__call__",
"`",
"`",
"method",
"that",
"filters",
"contours",
"based",
"on",
"the",
"pre",
"-",
"defined",
"solidity",
"limits",
"provided",
"at",
"initiation",
".",
"Notes",
"Note",
"that",
"here",
"the",
"solidity",
"of",
"a",
"contour",
"is",
"based",
"on",
"its",
"area",
"relative",
"to",
"its",
"corresponding",
"convex",
"hull",
".",
"See",
"Also",
"smallest",
"largest",
"parents",
"Area",
"Eccentricity"
] |
class Solidity:
"""
Filter contours by solidity based on a lower or upper limit, or both.
Parameters
----------
min : int or float
Lower solidity limit to filter contours.
max: int or float
Upper solidity limit to filter contours.
Returns
-------
filter : Solidity
Class object with ``__call__`` method that filters contours based on
the pre-defined solidity limits provided at initiation.
Notes
-----
Note that here the solidity of a contour is based on its area relative
to its corresponding convex hull.
See Also
--------
smallest
largest
parents
Area
Eccentricity
"""
def __init__(self, min=None, max=None):
self._filter = _ByLimit(min, max)
def _solidity(self, contours):
"""Convenience method for computing the solidity of contours. """
for i, c in enumerate(contours):
c_area = cv2.contourArea(c)
hull = cv2.convexHull(c)
hullarea = cv2.contourArea(hull)
try:
yield (i, c_area / hullarea)
except ZeroDivisionError:
pass
def __call__(self, contours) -> "Solidity":
"""
Filter contours by solidity based on pre-defined limits.
Parameters
----------
contours : list
List of contours to filter.
Returns
-------
contours : list
Filtered contours.
"""
_filtered = []
for i, s in self._solidity(contours):
if self._filter(s):
_filtered.append(contours[i])
return _filtered
|
[
"class",
"Solidity",
":",
"def",
"__init__",
"(",
"self",
",",
"min",
"=",
"None",
",",
"max",
"=",
"None",
")",
":",
"self",
".",
"_filter",
"=",
"_ByLimit",
"(",
"min",
",",
"max",
")",
"def",
"_solidity",
"(",
"self",
",",
"contours",
")",
":",
"\"\"\"Convenience method for computing the solidity of contours. \"\"\"",
"for",
"i",
",",
"c",
"in",
"enumerate",
"(",
"contours",
")",
":",
"c_area",
"=",
"cv2",
".",
"contourArea",
"(",
"c",
")",
"hull",
"=",
"cv2",
".",
"convexHull",
"(",
"c",
")",
"hullarea",
"=",
"cv2",
".",
"contourArea",
"(",
"hull",
")",
"try",
":",
"yield",
"(",
"i",
",",
"c_area",
"/",
"hullarea",
")",
"except",
"ZeroDivisionError",
":",
"pass",
"def",
"__call__",
"(",
"self",
",",
"contours",
")",
"->",
"\"Solidity\"",
":",
"\"\"\"\n Filter contours by solidity based on pre-defined limits.\n\n Parameters\n ----------\n contours : list\n List of contours to filter.\n\n Returns\n -------\n contours : list\n Filtered contours.\n\n \"\"\"",
"_filtered",
"=",
"[",
"]",
"for",
"i",
",",
"s",
"in",
"self",
".",
"_solidity",
"(",
"contours",
")",
":",
"if",
"self",
".",
"_filter",
"(",
"s",
")",
":",
"_filtered",
".",
"append",
"(",
"contours",
"[",
"i",
"]",
")",
"return",
"_filtered"
] |
Filter contours by solidity based on a lower or upper limit, or both.
|
[
"Filter",
"contours",
"by",
"solidity",
"based",
"on",
"a",
"lower",
"or",
"upper",
"limit",
"or",
"both",
"."
] |
[
"\"\"\"\n Filter contours by solidity based on a lower or upper limit, or both.\n\n Parameters\n ----------\n min : int or float\n Lower solidity limit to filter contours.\n max: int or float\n Upper solidity limit to filter contours.\n\n Returns\n -------\n filter : Solidity\n Class object with ``__call__`` method that filters contours based on\n the pre-defined solidity limits provided at initiation.\n\n Notes\n -----\n Note that here the solidity of a contour is based on its area relative\n to its corresponding convex hull.\n\n See Also\n --------\n smallest\n largest\n parents\n Area\n Eccentricity\n\n \"\"\"",
"\"\"\"Convenience method for computing the solidity of contours. \"\"\"",
"\"\"\"\n Filter contours by solidity based on pre-defined limits.\n\n Parameters\n ----------\n contours : list\n List of contours to filter.\n\n Returns\n -------\n contours : list\n Filtered contours.\n\n \"\"\""
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 13
| 359
| 141
|
2bf0bf1e1ef9ae9048b1b411646e71547bcd867a
|
YYTVicky/kafka
|
runners/flink/runner/src/main/java/org/apache/beam/runners/flink/translation/wrappers/streaming/state/FlinkSplitStateInternals.java
|
[
"Apache-2.0"
] |
Java
|
FlinkSplitStateInternals
|
/**
* {@link StateInternals} that uses a Flink {@link OperatorStateBackend}
* to manage the split-distribute state.
*
* <p>Elements in ListState will be redistributed in round robin fashion
* to operators when restarting with a different parallelism.
*
* <p>Note:
* Ignore index of key and namespace.
* Just implement BagState.
*/
|
StateInternals that uses a Flink OperatorStateBackend
to manage the split-distribute state.
Elements in ListState will be redistributed in round robin fashion
to operators when restarting with a different parallelism.
Note:
Ignore index of key and namespace.
|
[
"StateInternals",
"that",
"uses",
"a",
"Flink",
"OperatorStateBackend",
"to",
"manage",
"the",
"split",
"-",
"distribute",
"state",
".",
"Elements",
"in",
"ListState",
"will",
"be",
"redistributed",
"in",
"round",
"robin",
"fashion",
"to",
"operators",
"when",
"restarting",
"with",
"a",
"different",
"parallelism",
".",
"Note",
":",
"Ignore",
"index",
"of",
"key",
"and",
"namespace",
"."
] |
public class FlinkSplitStateInternals<K> implements StateInternals<K> {
private final OperatorStateBackend stateBackend;
public FlinkSplitStateInternals(OperatorStateBackend stateBackend) {
this.stateBackend = stateBackend;
}
@Override
public K getKey() {
return null;
}
@Override
public <T extends State> T state(
final StateNamespace namespace,
StateTag<? super K, T> address) {
return state(namespace, address, StateContexts.nullContext());
}
@Override
public <T extends State> T state(
final StateNamespace namespace,
StateTag<? super K, T> address,
final StateContext<?> context) {
return address.bind(new StateTag.StateBinder<K>() {
@Override
public <T> ValueState<T> bindValue(
StateTag<? super K, ValueState<T>> address,
Coder<T> coder) {
throw new UnsupportedOperationException(
String.format("%s is not supported", ValueState.class.getSimpleName()));
}
@Override
public <T> BagState<T> bindBag(
StateTag<? super K, BagState<T>> address,
Coder<T> elemCoder) {
return new FlinkSplitBagState<>(stateBackend, address, namespace, elemCoder);
}
@Override
public <T> SetState<T> bindSet(
StateTag<? super K, SetState<T>> address,
Coder<T> elemCoder) {
throw new UnsupportedOperationException(
String.format("%s is not supported", SetState.class.getSimpleName()));
}
@Override
public <KeyT, ValueT> MapState<KeyT, ValueT> bindMap(
StateTag<? super K, MapState<KeyT, ValueT>> spec,
Coder<KeyT> mapKeyCoder, Coder<ValueT> mapValueCoder) {
throw new UnsupportedOperationException(
String.format("%s is not supported", MapState.class.getSimpleName()));
}
@Override
public <InputT, AccumT, OutputT>
CombiningState<InputT, AccumT, OutputT>
bindCombiningValue(
StateTag<? super K, CombiningState<InputT, AccumT, OutputT>> address,
Coder<AccumT> accumCoder,
Combine.CombineFn<InputT, AccumT, OutputT> combineFn) {
throw new UnsupportedOperationException("bindCombiningValue is not supported.");
}
@Override
public <InputT, AccumT, OutputT>
CombiningState<InputT, AccumT, OutputT> bindKeyedCombiningValue(
StateTag<? super K, CombiningState<InputT, AccumT, OutputT>> address,
Coder<AccumT> accumCoder,
final Combine.KeyedCombineFn<? super K, InputT, AccumT, OutputT> combineFn) {
throw new UnsupportedOperationException("bindKeyedCombiningValue is not supported.");
}
@Override
public <InputT, AccumT, OutputT>
CombiningState<InputT, AccumT, OutputT> bindKeyedCombiningValueWithContext(
StateTag<? super K, CombiningState<InputT, AccumT, OutputT>> address,
Coder<AccumT> accumCoder,
CombineWithContext.KeyedCombineFnWithContext<
? super K, InputT, AccumT, OutputT> combineFn) {
throw new UnsupportedOperationException(
"bindKeyedCombiningValueWithContext is not supported.");
}
@Override
public <W extends BoundedWindow> WatermarkHoldState<W> bindWatermark(
StateTag<? super K, WatermarkHoldState<W>> address,
OutputTimeFn<? super W> outputTimeFn) {
throw new UnsupportedOperationException(
String.format("%s is not supported", CombiningState.class.getSimpleName()));
}
});
}
private static class FlinkSplitBagState<K, T> implements BagState<T> {
private final ListStateDescriptor<T> descriptor;
private OperatorStateBackend flinkStateBackend;
private final StateNamespace namespace;
private final StateTag<? super K, BagState<T>> address;
FlinkSplitBagState(
OperatorStateBackend flinkStateBackend,
StateTag<? super K, BagState<T>> address,
StateNamespace namespace,
Coder<T> coder) {
this.flinkStateBackend = flinkStateBackend;
this.namespace = namespace;
this.address = address;
CoderTypeInformation<T> typeInfo =
new CoderTypeInformation<>(coder);
descriptor = new ListStateDescriptor<>(address.getId(),
typeInfo.createSerializer(new ExecutionConfig()));
}
@Override
public void add(T input) {
try {
flinkStateBackend.getOperatorState(descriptor).add(input);
} catch (Exception e) {
throw new RuntimeException("Error updating state.", e);
}
}
@Override
public BagState<T> readLater() {
return this;
}
@Override
public Iterable<T> read() {
try {
Iterable<T> result = flinkStateBackend.getOperatorState(descriptor).get();
return result != null ? result : Collections.<T>emptyList();
} catch (Exception e) {
throw new RuntimeException("Error updating state.", e);
}
}
@Override
public ReadableState<Boolean> isEmpty() {
return new ReadableState<Boolean>() {
@Override
public Boolean read() {
try {
Iterable<T> result = flinkStateBackend.getOperatorState(descriptor).get();
// PartitionableListState.get() return empty collection When there is no element,
// KeyedListState different. (return null)
return result == null || Iterators.size(result.iterator()) == 0;
} catch (Exception e) {
throw new RuntimeException("Error reading state.", e);
}
}
@Override
public ReadableState<Boolean> readLater() {
return this;
}
};
}
@Override
public void clear() {
try {
flinkStateBackend.getOperatorState(descriptor).clear();
} catch (Exception e) {
throw new RuntimeException("Error reading state.", e);
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FlinkSplitBagState<?, ?> that = (FlinkSplitBagState<?, ?>) o;
return namespace.equals(that.namespace) && address.equals(that.address);
}
@Override
public int hashCode() {
int result = namespace.hashCode();
result = 31 * result + address.hashCode();
return result;
}
}
}
|
[
"public",
"class",
"FlinkSplitStateInternals",
"<",
"K",
">",
"implements",
"StateInternals",
"<",
"K",
">",
"{",
"private",
"final",
"OperatorStateBackend",
"stateBackend",
";",
"public",
"FlinkSplitStateInternals",
"(",
"OperatorStateBackend",
"stateBackend",
")",
"{",
"this",
".",
"stateBackend",
"=",
"stateBackend",
";",
"}",
"@",
"Override",
"public",
"K",
"getKey",
"(",
")",
"{",
"return",
"null",
";",
"}",
"@",
"Override",
"public",
"<",
"T",
"extends",
"State",
">",
"T",
"state",
"(",
"final",
"StateNamespace",
"namespace",
",",
"StateTag",
"<",
"?",
"super",
"K",
",",
"T",
">",
"address",
")",
"{",
"return",
"state",
"(",
"namespace",
",",
"address",
",",
"StateContexts",
".",
"nullContext",
"(",
")",
")",
";",
"}",
"@",
"Override",
"public",
"<",
"T",
"extends",
"State",
">",
"T",
"state",
"(",
"final",
"StateNamespace",
"namespace",
",",
"StateTag",
"<",
"?",
"super",
"K",
",",
"T",
">",
"address",
",",
"final",
"StateContext",
"<",
"?",
">",
"context",
")",
"{",
"return",
"address",
".",
"bind",
"(",
"new",
"StateTag",
".",
"StateBinder",
"<",
"K",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"<",
"T",
">",
"ValueState",
"<",
"T",
">",
"bindValue",
"(",
"StateTag",
"<",
"?",
"super",
"K",
",",
"ValueState",
"<",
"T",
">",
">",
"address",
",",
"Coder",
"<",
"T",
">",
"coder",
")",
"{",
"throw",
"new",
"UnsupportedOperationException",
"(",
"String",
".",
"format",
"(",
"\"",
"%s is not supported",
"\"",
",",
"ValueState",
".",
"class",
".",
"getSimpleName",
"(",
")",
")",
")",
";",
"}",
"@",
"Override",
"public",
"<",
"T",
">",
"BagState",
"<",
"T",
">",
"bindBag",
"(",
"StateTag",
"<",
"?",
"super",
"K",
",",
"BagState",
"<",
"T",
">",
">",
"address",
",",
"Coder",
"<",
"T",
">",
"elemCoder",
")",
"{",
"return",
"new",
"FlinkSplitBagState",
"<",
">",
"(",
"stateBackend",
",",
"address",
",",
"namespace",
",",
"elemCoder",
")",
";",
"}",
"@",
"Override",
"public",
"<",
"T",
">",
"SetState",
"<",
"T",
">",
"bindSet",
"(",
"StateTag",
"<",
"?",
"super",
"K",
",",
"SetState",
"<",
"T",
">",
">",
"address",
",",
"Coder",
"<",
"T",
">",
"elemCoder",
")",
"{",
"throw",
"new",
"UnsupportedOperationException",
"(",
"String",
".",
"format",
"(",
"\"",
"%s is not supported",
"\"",
",",
"SetState",
".",
"class",
".",
"getSimpleName",
"(",
")",
")",
")",
";",
"}",
"@",
"Override",
"public",
"<",
"KeyT",
",",
"ValueT",
">",
"MapState",
"<",
"KeyT",
",",
"ValueT",
">",
"bindMap",
"(",
"StateTag",
"<",
"?",
"super",
"K",
",",
"MapState",
"<",
"KeyT",
",",
"ValueT",
">",
">",
"spec",
",",
"Coder",
"<",
"KeyT",
">",
"mapKeyCoder",
",",
"Coder",
"<",
"ValueT",
">",
"mapValueCoder",
")",
"{",
"throw",
"new",
"UnsupportedOperationException",
"(",
"String",
".",
"format",
"(",
"\"",
"%s is not supported",
"\"",
",",
"MapState",
".",
"class",
".",
"getSimpleName",
"(",
")",
")",
")",
";",
"}",
"@",
"Override",
"public",
"<",
"InputT",
",",
"AccumT",
",",
"OutputT",
">",
"CombiningState",
"<",
"InputT",
",",
"AccumT",
",",
"OutputT",
">",
"bindCombiningValue",
"(",
"StateTag",
"<",
"?",
"super",
"K",
",",
"CombiningState",
"<",
"InputT",
",",
"AccumT",
",",
"OutputT",
">",
">",
"address",
",",
"Coder",
"<",
"AccumT",
">",
"accumCoder",
",",
"Combine",
".",
"CombineFn",
"<",
"InputT",
",",
"AccumT",
",",
"OutputT",
">",
"combineFn",
")",
"{",
"throw",
"new",
"UnsupportedOperationException",
"(",
"\"",
"bindCombiningValue is not supported.",
"\"",
")",
";",
"}",
"@",
"Override",
"public",
"<",
"InputT",
",",
"AccumT",
",",
"OutputT",
">",
"CombiningState",
"<",
"InputT",
",",
"AccumT",
",",
"OutputT",
">",
"bindKeyedCombiningValue",
"(",
"StateTag",
"<",
"?",
"super",
"K",
",",
"CombiningState",
"<",
"InputT",
",",
"AccumT",
",",
"OutputT",
">",
">",
"address",
",",
"Coder",
"<",
"AccumT",
">",
"accumCoder",
",",
"final",
"Combine",
".",
"KeyedCombineFn",
"<",
"?",
"super",
"K",
",",
"InputT",
",",
"AccumT",
",",
"OutputT",
">",
"combineFn",
")",
"{",
"throw",
"new",
"UnsupportedOperationException",
"(",
"\"",
"bindKeyedCombiningValue is not supported.",
"\"",
")",
";",
"}",
"@",
"Override",
"public",
"<",
"InputT",
",",
"AccumT",
",",
"OutputT",
">",
"CombiningState",
"<",
"InputT",
",",
"AccumT",
",",
"OutputT",
">",
"bindKeyedCombiningValueWithContext",
"(",
"StateTag",
"<",
"?",
"super",
"K",
",",
"CombiningState",
"<",
"InputT",
",",
"AccumT",
",",
"OutputT",
">",
">",
"address",
",",
"Coder",
"<",
"AccumT",
">",
"accumCoder",
",",
"CombineWithContext",
".",
"KeyedCombineFnWithContext",
"<",
"?",
"super",
"K",
",",
"InputT",
",",
"AccumT",
",",
"OutputT",
">",
"combineFn",
")",
"{",
"throw",
"new",
"UnsupportedOperationException",
"(",
"\"",
"bindKeyedCombiningValueWithContext is not supported.",
"\"",
")",
";",
"}",
"@",
"Override",
"public",
"<",
"W",
"extends",
"BoundedWindow",
">",
"WatermarkHoldState",
"<",
"W",
">",
"bindWatermark",
"(",
"StateTag",
"<",
"?",
"super",
"K",
",",
"WatermarkHoldState",
"<",
"W",
">",
">",
"address",
",",
"OutputTimeFn",
"<",
"?",
"super",
"W",
">",
"outputTimeFn",
")",
"{",
"throw",
"new",
"UnsupportedOperationException",
"(",
"String",
".",
"format",
"(",
"\"",
"%s is not supported",
"\"",
",",
"CombiningState",
".",
"class",
".",
"getSimpleName",
"(",
")",
")",
")",
";",
"}",
"}",
")",
";",
"}",
"private",
"static",
"class",
"FlinkSplitBagState",
"<",
"K",
",",
"T",
">",
"implements",
"BagState",
"<",
"T",
">",
"{",
"private",
"final",
"ListStateDescriptor",
"<",
"T",
">",
"descriptor",
";",
"private",
"OperatorStateBackend",
"flinkStateBackend",
";",
"private",
"final",
"StateNamespace",
"namespace",
";",
"private",
"final",
"StateTag",
"<",
"?",
"super",
"K",
",",
"BagState",
"<",
"T",
">",
">",
"address",
";",
"FlinkSplitBagState",
"(",
"OperatorStateBackend",
"flinkStateBackend",
",",
"StateTag",
"<",
"?",
"super",
"K",
",",
"BagState",
"<",
"T",
">",
">",
"address",
",",
"StateNamespace",
"namespace",
",",
"Coder",
"<",
"T",
">",
"coder",
")",
"{",
"this",
".",
"flinkStateBackend",
"=",
"flinkStateBackend",
";",
"this",
".",
"namespace",
"=",
"namespace",
";",
"this",
".",
"address",
"=",
"address",
";",
"CoderTypeInformation",
"<",
"T",
">",
"typeInfo",
"=",
"new",
"CoderTypeInformation",
"<",
">",
"(",
"coder",
")",
";",
"descriptor",
"=",
"new",
"ListStateDescriptor",
"<",
">",
"(",
"address",
".",
"getId",
"(",
")",
",",
"typeInfo",
".",
"createSerializer",
"(",
"new",
"ExecutionConfig",
"(",
")",
")",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"add",
"(",
"T",
"input",
")",
"{",
"try",
"{",
"flinkStateBackend",
".",
"getOperatorState",
"(",
"descriptor",
")",
".",
"add",
"(",
"input",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"",
"Error updating state.",
"\"",
",",
"e",
")",
";",
"}",
"}",
"@",
"Override",
"public",
"BagState",
"<",
"T",
">",
"readLater",
"(",
")",
"{",
"return",
"this",
";",
"}",
"@",
"Override",
"public",
"Iterable",
"<",
"T",
">",
"read",
"(",
")",
"{",
"try",
"{",
"Iterable",
"<",
"T",
">",
"result",
"=",
"flinkStateBackend",
".",
"getOperatorState",
"(",
"descriptor",
")",
".",
"get",
"(",
")",
";",
"return",
"result",
"!=",
"null",
"?",
"result",
":",
"Collections",
".",
"<",
"T",
">",
"emptyList",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"",
"Error updating state.",
"\"",
",",
"e",
")",
";",
"}",
"}",
"@",
"Override",
"public",
"ReadableState",
"<",
"Boolean",
">",
"isEmpty",
"(",
")",
"{",
"return",
"new",
"ReadableState",
"<",
"Boolean",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"Boolean",
"read",
"(",
")",
"{",
"try",
"{",
"Iterable",
"<",
"T",
">",
"result",
"=",
"flinkStateBackend",
".",
"getOperatorState",
"(",
"descriptor",
")",
".",
"get",
"(",
")",
";",
"return",
"result",
"==",
"null",
"||",
"Iterators",
".",
"size",
"(",
"result",
".",
"iterator",
"(",
")",
")",
"==",
"0",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"",
"Error reading state.",
"\"",
",",
"e",
")",
";",
"}",
"}",
"@",
"Override",
"public",
"ReadableState",
"<",
"Boolean",
">",
"readLater",
"(",
")",
"{",
"return",
"this",
";",
"}",
"}",
";",
"}",
"@",
"Override",
"public",
"void",
"clear",
"(",
")",
"{",
"try",
"{",
"flinkStateBackend",
".",
"getOperatorState",
"(",
"descriptor",
")",
".",
"clear",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"",
"Error reading state.",
"\"",
",",
"e",
")",
";",
"}",
"}",
"@",
"Override",
"public",
"boolean",
"equals",
"(",
"Object",
"o",
")",
"{",
"if",
"(",
"this",
"==",
"o",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"o",
"==",
"null",
"||",
"getClass",
"(",
")",
"!=",
"o",
".",
"getClass",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"FlinkSplitBagState",
"<",
"?",
",",
"?",
">",
"that",
"=",
"(",
"FlinkSplitBagState",
"<",
"?",
",",
"?",
">",
")",
"o",
";",
"return",
"namespace",
".",
"equals",
"(",
"that",
".",
"namespace",
")",
"&&",
"address",
".",
"equals",
"(",
"that",
".",
"address",
")",
";",
"}",
"@",
"Override",
"public",
"int",
"hashCode",
"(",
")",
"{",
"int",
"result",
"=",
"namespace",
".",
"hashCode",
"(",
")",
";",
"result",
"=",
"31",
"*",
"result",
"+",
"address",
".",
"hashCode",
"(",
")",
";",
"return",
"result",
";",
"}",
"}",
"}"
] |
{@link StateInternals} that uses a Flink {@link OperatorStateBackend}
to manage the split-distribute state.
|
[
"{",
"@link",
"StateInternals",
"}",
"that",
"uses",
"a",
"Flink",
"{",
"@link",
"OperatorStateBackend",
"}",
"to",
"manage",
"the",
"split",
"-",
"distribute",
"state",
"."
] |
[
"// PartitionableListState.get() return empty collection When there is no element,",
"// KeyedListState different. (return null)"
] |
[
{
"param": "StateInternals<K>",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "StateInternals<K>",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 21
| 1,446
| 80
|
8d0f6c03f881489ed990207abbfa735594394d84
|
KeyBridge/lib-javax-usb3
|
src/main/java/javax/usb3/ri/UsbIrpQueue.java
|
[
"Apache-2.0"
] |
Java
|
UsbIrpQueue
|
/**
* A concurrent queue manager for USB I/O Request packets.
* <p>
* An IrpQueue contains a thread safe FIFO queue and a threaded
* processUsbIrpQueueor to handle each IRP that is placed into the queue.
* <p>
* Developer note: The default operation of an IrpQueue is to support
* Asynchronous operation (e.g. processUsbIrpQueue in a separate thread.) To
* implement synchronous IRP queue handling implement a WAIT lock on the
* {@link IUsbIrp.isComplete() isComplete} method IUsbIrp.isComplete().
*
* @author Klaus Reimer
* @author Jesse Caulfield
*/
|
A concurrent queue manager for USB I/O Request packets.
An IrpQueue contains a thread safe FIFO queue and a threaded
processUsbIrpQueueor to handle each IRP that is placed into the queue.
Developer note: The default operation of an IrpQueue is to support
Asynchronous operation To
implement synchronous IRP queue handling implement a WAIT lock on the
IUsbIrp.isComplete() isComplete method IUsbIrp.isComplete().
@author Klaus Reimer
@author Jesse Caulfield
|
[
"A",
"concurrent",
"queue",
"manager",
"for",
"USB",
"I",
"/",
"O",
"Request",
"packets",
".",
"An",
"IrpQueue",
"contains",
"a",
"thread",
"safe",
"FIFO",
"queue",
"and",
"a",
"threaded",
"processUsbIrpQueueor",
"to",
"handle",
"each",
"IRP",
"that",
"is",
"placed",
"into",
"the",
"queue",
".",
"Developer",
"note",
":",
"The",
"default",
"operation",
"of",
"an",
"IrpQueue",
"is",
"to",
"support",
"Asynchronous",
"operation",
"To",
"implement",
"synchronous",
"IRP",
"queue",
"handling",
"implement",
"a",
"WAIT",
"lock",
"on",
"the",
"IUsbIrp",
".",
"isComplete",
"()",
"isComplete",
"method",
"IUsbIrp",
".",
"isComplete",
"()",
".",
"@author",
"Klaus",
"Reimer",
"@author",
"Jesse",
"Caulfield"
] |
public final class UsbIrpQueue extends AUsbIrpQueue<IUsbIrp> {
/**
* The USB pipe.
*/
private final IUsbPipe pipe;
/**
* The PIPE end point direction. [IN, OUT]. This is set upon instantiation and
* proxied in a class-level field to speed up do/while loops buried within.
*/
private final EEndpointDirection endPointDirection;
/**
* The PIPE end point transfer type. This is set upon instantiation and
* proxied in a class-level field to speed up do/while loops buried within.
*/
private final EDataFlowtype endpointTransferType;
/**
* The PIPE end point descriptor. This is set upon instantiation and proxied
* in a class-level field to speed up do/while loops buried within.
*/
private final IUsbEndpointDescriptor endpointDescriptor;
/**
* Constructor.
*
* @param pipe The USB pipe
*/
public UsbIrpQueue(final UsbPipe pipe) {
super(pipe.getDevice());
this.pipe = pipe;
this.endPointDirection = pipe.getUsbEndpoint().getDirection();
this.endpointTransferType = pipe.getUsbEndpoint().getType();
this.endpointDescriptor = this.pipe.getUsbEndpoint().getUsbEndpointDescriptor();
}
/**
* Processes the IRP.
*
* @param irp The IRP to processUsbIrpQueue.
* @throws UsbException When processUsbIrpQueueing the IRP fails.
*/
@Override
protected void processIrp(final IUsbIrp irp) throws UsbException {
final IUsbEndpoint endpoint = this.pipe.getUsbEndpoint();
if (EDataFlowtype.CONTROL.equals(endpoint.getType())) {
processControlIrp((IUsbControlIrp) irp);
return;
}
switch (endpoint.getDirection()) {
case OUT:
case HOST_TO_DEVICE:
writeUsbIrp(irp);
// irp.setActualLength(write(irp.getData(), irp.getOffset(), irp.getLength()));
if (irp.getActualLength() < irp.getLength() && !irp.getAcceptShortPacket()) {
throw new UsbShortPacketException();
}
break;
case IN:
case DEVICE_TO_HOST:
readUsbIrp(irp);
// irp.setActualLength(read(irp.getData(), irp.getOffset(), irp.getLength()));
if (irp.getActualLength() < irp.getLength() && !irp.getAcceptShortPacket()) {
throw new UsbShortPacketException();
}
break;
default:
throw new UsbException("Invalid direction: " + endpoint.getDirection());
}
}
/**
* Called after IRP has finished. This can be implemented to send events for
* example.
*
* @param irp The IRP which has been finished.
*/
@Override
protected void finishIrp(final IUsbIrp irp) {
((UsbPipe) this.pipe).sendEvent(irp);
}
/**
* Reads bytes from an interrupt endpoint into the specified I/O Request
* Packet.
*
* @param irp A USB I/O Request Packet (IRP) instance
* @throws UsbException if the Device cannot be opened or cannot be read from
*/
private void readUsbIrp(final IUsbIrp irp) throws UsbException {
/**
* Open the USB device and returns the USB device handle. If device was
* already open then the old handle is returned.
*/
final DeviceHandle deviceHandle = this.usbDevice.open();
int read = 0;
while (read < irp.getLength()) {
final int size = Math.min(irp.getLength() - read, endpointDescriptor.wMaxPacketSize() & 0xffff);
final ByteBuffer buffer = ByteBuffer.allocateDirect(size);
final int result = transfer(deviceHandle, endpointDescriptor, buffer);
buffer.rewind();
buffer.get(irp.getData(), irp.getOffset() + read, result);
read += result;
/**
* Short packet detected, abort the WHILE loop.
*/
if (result < size) {
break;
}
}
irp.setActualLength(read);
}
/**
* Write an I/O Request Packet to an interrupt endpoint.
*
* @param irp A USB I/O Request Packet (IRP) instance
* @throws UsbException if the Device cannot be opened or cannot be written to
*/
private void writeUsbIrp(final IUsbIrp irp) throws UsbException {
final DeviceHandle handle = this.usbDevice.open();
int written = 0;
while (written < irp.getLength()) {
final int size = Math.min(irp.getLength() - written, endpointDescriptor.wMaxPacketSize() & 0xffff);
final ByteBuffer buffer = ByteBuffer.allocateDirect(size);
buffer.put(irp.getData(), irp.getOffset() + written, size);
buffer.rewind();
final int result = transfer(handle, endpointDescriptor, buffer);
written += result;
// Short packet detected, aborting
if (result < size) {
break;
}
}
irp.setActualLength(written);
}
/**
* Transfers data from or to the device.
*
* @param handle The device handle.
* @param descriptor The endpoint descriptor.
* @param type The endpoint type.
* @param buffer The data buffer.
* @return The number of transferred bytes.
* @throws UsbException When data transfer fails.
*/
private int transfer(final DeviceHandle handle,
final IUsbEndpointDescriptor descriptor,
final ByteBuffer buffer) throws UsbException {
switch (endpointTransferType) {
case BULK:
return transferBulk(handle, descriptor.endpointAddress(), buffer);
case INTERRUPT:
return transferInterrupt(handle, descriptor.endpointAddress(), buffer);
case CONTROL:
throw new UsbException("Unsupported endpoint type: " + endpointTransferType + ": Control transfers require a Control-Type IRP.");
case ISOCHRONOUS:
throw new UsbException("Unsupported endpoint type: " + endpointTransferType + ". libusb asynchronous (non-blocking) API for USB device I/O not yet implemented.");
default:
throw new AssertionError(endpointTransferType.name());
}
}
/**
* Transfers bulk data from or to the device.
*
* @param handle The device handle.
* @param address The endpoint address.
* @param buffer The data buffer.
* @return The number of transferred bytes.
* @throws UsbException When data transfer fails.
*/
private int transferBulk(final DeviceHandle handle,
final BEndpointAddress address,
final ByteBuffer buffer) throws UsbException {
final IntBuffer transferred = IntBuffer.allocate(1);
int result;
do {
result = LibUsb.bulkTransfer(handle, address.getByteCode(), buffer, transferred, UsbServiceInstanceConfiguration.TIMEOUT);
if (result == LibUsb.ERROR_TIMEOUT && isAborting()) {
throw new UsbAbortException();
}
} while (EEndpointDirection.DEVICE_TO_HOST.equals(endPointDirection) && result == LibUsb.ERROR_TIMEOUT);
if (result < 0) {
throw UsbExceptionFactory.createPlatformException("Transfer error on bulk endpoint", result);
}
return transferred.get(0);
}
/**
* Transfers interrupt data from or to the device.
*
* @param handle The device handle.
* @param address The endpoint address.
* @param buffer The data buffer.
* @return The number of transferred bytes.
* @throws UsbException When data transfer fails.
*/
private int transferInterrupt(final DeviceHandle handle,
final BEndpointAddress address,
final ByteBuffer buffer) throws UsbException {
final IntBuffer transferred = IntBuffer.allocate(1);
int result;
do {
result = LibUsb.interruptTransfer(handle, address.getByteCode(), buffer, transferred, UsbServiceInstanceConfiguration.TIMEOUT);
if (result == LibUsb.ERROR_TIMEOUT && isAborting()) {
throw new UsbAbortException();
}
} while (EEndpointDirection.DEVICE_TO_HOST.equals(endPointDirection) && result == LibUsb.ERROR_TIMEOUT);
if (result < 0) {
throw UsbExceptionFactory.createPlatformException("Transfer error on interrupt endpoint", result);
}
return transferred.get(0);
}
}
|
[
"public",
"final",
"class",
"UsbIrpQueue",
"extends",
"AUsbIrpQueue",
"<",
"IUsbIrp",
">",
"{",
"/**\n * The USB pipe.\n */",
"private",
"final",
"IUsbPipe",
"pipe",
";",
"/**\n * The PIPE end point direction. [IN, OUT]. This is set upon instantiation and\n * proxied in a class-level field to speed up do/while loops buried within.\n */",
"private",
"final",
"EEndpointDirection",
"endPointDirection",
";",
"/**\n * The PIPE end point transfer type. This is set upon instantiation and\n * proxied in a class-level field to speed up do/while loops buried within.\n */",
"private",
"final",
"EDataFlowtype",
"endpointTransferType",
";",
"/**\n * The PIPE end point descriptor. This is set upon instantiation and proxied\n * in a class-level field to speed up do/while loops buried within.\n */",
"private",
"final",
"IUsbEndpointDescriptor",
"endpointDescriptor",
";",
"/**\n * Constructor.\n *\n * @param pipe The USB pipe\n */",
"public",
"UsbIrpQueue",
"(",
"final",
"UsbPipe",
"pipe",
")",
"{",
"super",
"(",
"pipe",
".",
"getDevice",
"(",
")",
")",
";",
"this",
".",
"pipe",
"=",
"pipe",
";",
"this",
".",
"endPointDirection",
"=",
"pipe",
".",
"getUsbEndpoint",
"(",
")",
".",
"getDirection",
"(",
")",
";",
"this",
".",
"endpointTransferType",
"=",
"pipe",
".",
"getUsbEndpoint",
"(",
")",
".",
"getType",
"(",
")",
";",
"this",
".",
"endpointDescriptor",
"=",
"this",
".",
"pipe",
".",
"getUsbEndpoint",
"(",
")",
".",
"getUsbEndpointDescriptor",
"(",
")",
";",
"}",
"/**\n * Processes the IRP.\n *\n * @param irp The IRP to processUsbIrpQueue.\n * @throws UsbException When processUsbIrpQueueing the IRP fails.\n */",
"@",
"Override",
"protected",
"void",
"processIrp",
"(",
"final",
"IUsbIrp",
"irp",
")",
"throws",
"UsbException",
"{",
"final",
"IUsbEndpoint",
"endpoint",
"=",
"this",
".",
"pipe",
".",
"getUsbEndpoint",
"(",
")",
";",
"if",
"(",
"EDataFlowtype",
".",
"CONTROL",
".",
"equals",
"(",
"endpoint",
".",
"getType",
"(",
")",
")",
")",
"{",
"processControlIrp",
"(",
"(",
"IUsbControlIrp",
")",
"irp",
")",
";",
"return",
";",
"}",
"switch",
"(",
"endpoint",
".",
"getDirection",
"(",
")",
")",
"{",
"case",
"OUT",
":",
"case",
"HOST_TO_DEVICE",
":",
"writeUsbIrp",
"(",
"irp",
")",
";",
"if",
"(",
"irp",
".",
"getActualLength",
"(",
")",
"<",
"irp",
".",
"getLength",
"(",
")",
"&&",
"!",
"irp",
".",
"getAcceptShortPacket",
"(",
")",
")",
"{",
"throw",
"new",
"UsbShortPacketException",
"(",
")",
";",
"}",
"break",
";",
"case",
"IN",
":",
"case",
"DEVICE_TO_HOST",
":",
"readUsbIrp",
"(",
"irp",
")",
";",
"if",
"(",
"irp",
".",
"getActualLength",
"(",
")",
"<",
"irp",
".",
"getLength",
"(",
")",
"&&",
"!",
"irp",
".",
"getAcceptShortPacket",
"(",
")",
")",
"{",
"throw",
"new",
"UsbShortPacketException",
"(",
")",
";",
"}",
"break",
";",
"default",
":",
"throw",
"new",
"UsbException",
"(",
"\"",
"Invalid direction: ",
"\"",
"+",
"endpoint",
".",
"getDirection",
"(",
")",
")",
";",
"}",
"}",
"/**\n * Called after IRP has finished. This can be implemented to send events for\n * example.\n *\n * @param irp The IRP which has been finished.\n */",
"@",
"Override",
"protected",
"void",
"finishIrp",
"(",
"final",
"IUsbIrp",
"irp",
")",
"{",
"(",
"(",
"UsbPipe",
")",
"this",
".",
"pipe",
")",
".",
"sendEvent",
"(",
"irp",
")",
";",
"}",
"/**\n * Reads bytes from an interrupt endpoint into the specified I/O Request\n * Packet.\n *\n * @param irp A USB I/O Request Packet (IRP) instance\n * @throws UsbException if the Device cannot be opened or cannot be read from\n */",
"private",
"void",
"readUsbIrp",
"(",
"final",
"IUsbIrp",
"irp",
")",
"throws",
"UsbException",
"{",
"/**\n * Open the USB device and returns the USB device handle. If device was\n * already open then the old handle is returned.\n */",
"final",
"DeviceHandle",
"deviceHandle",
"=",
"this",
".",
"usbDevice",
".",
"open",
"(",
")",
";",
"int",
"read",
"=",
"0",
";",
"while",
"(",
"read",
"<",
"irp",
".",
"getLength",
"(",
")",
")",
"{",
"final",
"int",
"size",
"=",
"Math",
".",
"min",
"(",
"irp",
".",
"getLength",
"(",
")",
"-",
"read",
",",
"endpointDescriptor",
".",
"wMaxPacketSize",
"(",
")",
"&",
"0xffff",
")",
";",
"final",
"ByteBuffer",
"buffer",
"=",
"ByteBuffer",
".",
"allocateDirect",
"(",
"size",
")",
";",
"final",
"int",
"result",
"=",
"transfer",
"(",
"deviceHandle",
",",
"endpointDescriptor",
",",
"buffer",
")",
";",
"buffer",
".",
"rewind",
"(",
")",
";",
"buffer",
".",
"get",
"(",
"irp",
".",
"getData",
"(",
")",
",",
"irp",
".",
"getOffset",
"(",
")",
"+",
"read",
",",
"result",
")",
";",
"read",
"+=",
"result",
";",
"/**\n * Short packet detected, abort the WHILE loop.\n */",
"if",
"(",
"result",
"<",
"size",
")",
"{",
"break",
";",
"}",
"}",
"irp",
".",
"setActualLength",
"(",
"read",
")",
";",
"}",
"/**\n * Write an I/O Request Packet to an interrupt endpoint.\n *\n * @param irp A USB I/O Request Packet (IRP) instance\n * @throws UsbException if the Device cannot be opened or cannot be written to\n */",
"private",
"void",
"writeUsbIrp",
"(",
"final",
"IUsbIrp",
"irp",
")",
"throws",
"UsbException",
"{",
"final",
"DeviceHandle",
"handle",
"=",
"this",
".",
"usbDevice",
".",
"open",
"(",
")",
";",
"int",
"written",
"=",
"0",
";",
"while",
"(",
"written",
"<",
"irp",
".",
"getLength",
"(",
")",
")",
"{",
"final",
"int",
"size",
"=",
"Math",
".",
"min",
"(",
"irp",
".",
"getLength",
"(",
")",
"-",
"written",
",",
"endpointDescriptor",
".",
"wMaxPacketSize",
"(",
")",
"&",
"0xffff",
")",
";",
"final",
"ByteBuffer",
"buffer",
"=",
"ByteBuffer",
".",
"allocateDirect",
"(",
"size",
")",
";",
"buffer",
".",
"put",
"(",
"irp",
".",
"getData",
"(",
")",
",",
"irp",
".",
"getOffset",
"(",
")",
"+",
"written",
",",
"size",
")",
";",
"buffer",
".",
"rewind",
"(",
")",
";",
"final",
"int",
"result",
"=",
"transfer",
"(",
"handle",
",",
"endpointDescriptor",
",",
"buffer",
")",
";",
"written",
"+=",
"result",
";",
"if",
"(",
"result",
"<",
"size",
")",
"{",
"break",
";",
"}",
"}",
"irp",
".",
"setActualLength",
"(",
"written",
")",
";",
"}",
"/**\n * Transfers data from or to the device.\n *\n * @param handle The device handle.\n * @param descriptor The endpoint descriptor.\n * @param type The endpoint type.\n * @param buffer The data buffer.\n * @return The number of transferred bytes.\n * @throws UsbException When data transfer fails.\n */",
"private",
"int",
"transfer",
"(",
"final",
"DeviceHandle",
"handle",
",",
"final",
"IUsbEndpointDescriptor",
"descriptor",
",",
"final",
"ByteBuffer",
"buffer",
")",
"throws",
"UsbException",
"{",
"switch",
"(",
"endpointTransferType",
")",
"{",
"case",
"BULK",
":",
"return",
"transferBulk",
"(",
"handle",
",",
"descriptor",
".",
"endpointAddress",
"(",
")",
",",
"buffer",
")",
";",
"case",
"INTERRUPT",
":",
"return",
"transferInterrupt",
"(",
"handle",
",",
"descriptor",
".",
"endpointAddress",
"(",
")",
",",
"buffer",
")",
";",
"case",
"CONTROL",
":",
"throw",
"new",
"UsbException",
"(",
"\"",
"Unsupported endpoint type: ",
"\"",
"+",
"endpointTransferType",
"+",
"\"",
": Control transfers require a Control-Type IRP.",
"\"",
")",
";",
"case",
"ISOCHRONOUS",
":",
"throw",
"new",
"UsbException",
"(",
"\"",
"Unsupported endpoint type: ",
"\"",
"+",
"endpointTransferType",
"+",
"\"",
". libusb asynchronous (non-blocking) API for USB device I/O not yet implemented.",
"\"",
")",
";",
"default",
":",
"throw",
"new",
"AssertionError",
"(",
"endpointTransferType",
".",
"name",
"(",
")",
")",
";",
"}",
"}",
"/**\n * Transfers bulk data from or to the device.\n *\n * @param handle The device handle.\n * @param address The endpoint address.\n * @param buffer The data buffer.\n * @return The number of transferred bytes.\n * @throws UsbException When data transfer fails.\n */",
"private",
"int",
"transferBulk",
"(",
"final",
"DeviceHandle",
"handle",
",",
"final",
"BEndpointAddress",
"address",
",",
"final",
"ByteBuffer",
"buffer",
")",
"throws",
"UsbException",
"{",
"final",
"IntBuffer",
"transferred",
"=",
"IntBuffer",
".",
"allocate",
"(",
"1",
")",
";",
"int",
"result",
";",
"do",
"{",
"result",
"=",
"LibUsb",
".",
"bulkTransfer",
"(",
"handle",
",",
"address",
".",
"getByteCode",
"(",
")",
",",
"buffer",
",",
"transferred",
",",
"UsbServiceInstanceConfiguration",
".",
"TIMEOUT",
")",
";",
"if",
"(",
"result",
"==",
"LibUsb",
".",
"ERROR_TIMEOUT",
"&&",
"isAborting",
"(",
")",
")",
"{",
"throw",
"new",
"UsbAbortException",
"(",
")",
";",
"}",
"}",
"while",
"(",
"EEndpointDirection",
".",
"DEVICE_TO_HOST",
".",
"equals",
"(",
"endPointDirection",
")",
"&&",
"result",
"==",
"LibUsb",
".",
"ERROR_TIMEOUT",
")",
";",
"if",
"(",
"result",
"<",
"0",
")",
"{",
"throw",
"UsbExceptionFactory",
".",
"createPlatformException",
"(",
"\"",
"Transfer error on bulk endpoint",
"\"",
",",
"result",
")",
";",
"}",
"return",
"transferred",
".",
"get",
"(",
"0",
")",
";",
"}",
"/**\n * Transfers interrupt data from or to the device.\n *\n * @param handle The device handle.\n * @param address The endpoint address.\n * @param buffer The data buffer.\n * @return The number of transferred bytes.\n * @throws UsbException When data transfer fails.\n */",
"private",
"int",
"transferInterrupt",
"(",
"final",
"DeviceHandle",
"handle",
",",
"final",
"BEndpointAddress",
"address",
",",
"final",
"ByteBuffer",
"buffer",
")",
"throws",
"UsbException",
"{",
"final",
"IntBuffer",
"transferred",
"=",
"IntBuffer",
".",
"allocate",
"(",
"1",
")",
";",
"int",
"result",
";",
"do",
"{",
"result",
"=",
"LibUsb",
".",
"interruptTransfer",
"(",
"handle",
",",
"address",
".",
"getByteCode",
"(",
")",
",",
"buffer",
",",
"transferred",
",",
"UsbServiceInstanceConfiguration",
".",
"TIMEOUT",
")",
";",
"if",
"(",
"result",
"==",
"LibUsb",
".",
"ERROR_TIMEOUT",
"&&",
"isAborting",
"(",
")",
")",
"{",
"throw",
"new",
"UsbAbortException",
"(",
")",
";",
"}",
"}",
"while",
"(",
"EEndpointDirection",
".",
"DEVICE_TO_HOST",
".",
"equals",
"(",
"endPointDirection",
")",
"&&",
"result",
"==",
"LibUsb",
".",
"ERROR_TIMEOUT",
")",
";",
"if",
"(",
"result",
"<",
"0",
")",
"{",
"throw",
"UsbExceptionFactory",
".",
"createPlatformException",
"(",
"\"",
"Transfer error on interrupt endpoint",
"\"",
",",
"result",
")",
";",
"}",
"return",
"transferred",
".",
"get",
"(",
"0",
")",
";",
"}",
"}"
] |
A concurrent queue manager for USB I/O Request packets.
|
[
"A",
"concurrent",
"queue",
"manager",
"for",
"USB",
"I",
"/",
"O",
"Request",
"packets",
"."
] |
[
"// irp.setActualLength(write(irp.getData(), irp.getOffset(), irp.getLength()));",
"// irp.setActualLength(read(irp.getData(), irp.getOffset(), irp.getLength()));",
"// Short packet detected, aborting"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 14
| 1,857
| 146
|
8e060ba83551925501c4272effa64351f6e28aca
|
Samsung/xamarin-forms-samples
|
WorkingWithListviewNative/WorkingWithListviewNative/D/NativeListViewPage2.cs
|
[
"Apache-2.0"
] |
C#
|
NativeListViewPage2
|
/// <summary>
/// This page uses a custom renderer that wraps native list controls:
/// iOS : UITableView
/// Android : ListView (do not confuse with Xamarin.Forms ListView)
/// Windows Phone : ListView
/// Tizen : Native.ListView
///
/// It uses a CUSTOM row/cell class that is defined natively which
/// is still faster than a Xamarin.Forms-defined ViewCell subclass.
/// </summary>
|
It uses a CUSTOM row/cell class that is defined natively which
is still faster than a Xamarin.Forms-defined ViewCell subclass.
|
[
"It",
"uses",
"a",
"CUSTOM",
"row",
"/",
"cell",
"class",
"that",
"is",
"defined",
"natively",
"which",
"is",
"still",
"faster",
"than",
"a",
"Xamarin",
".",
"Forms",
"-",
"defined",
"ViewCell",
"subclass",
"."
] |
public class NativeListViewPage2 : ContentPage
{
public NativeListViewPage2 ()
{
var nativeListView2 = new NativeListView2 ();
nativeListView2.VerticalOptions = LayoutOptions.FillAndExpand;
nativeListView2.Items = DataSource2.GetList ();
nativeListView2.ItemSelected += async (sender, e) => {
await DisplayAlert ("clicked", "one of the rows was clicked", "ok");
};
Content = new StackLayout {
Padding = new Thickness(0, Device.RuntimePlatform == Device.iOS ? 20 : 0, 0, 0),
Children = {
new Label {
HorizontalTextAlignment = TextAlignment.Center,
Text = Device.RuntimePlatform == Device.iOS ? "Custom UITableView+UICell" :
Device.RuntimePlatform == Device.Android ? "Custom ListView+Cell" : "Custom renderer ListView+DataTemplate"
},
nativeListView2
}
};
}
}
|
[
"public",
"class",
"NativeListViewPage2",
":",
"ContentPage",
"{",
"public",
"NativeListViewPage2",
"(",
")",
"{",
"var",
"nativeListView2",
"=",
"new",
"NativeListView2",
"(",
")",
";",
"nativeListView2",
".",
"VerticalOptions",
"=",
"LayoutOptions",
".",
"FillAndExpand",
";",
"nativeListView2",
".",
"Items",
"=",
"DataSource2",
".",
"GetList",
"(",
")",
";",
"nativeListView2",
".",
"ItemSelected",
"+=",
"async",
"(",
"sender",
",",
"e",
")",
"=>",
"{",
"await",
"DisplayAlert",
"(",
"\"",
"clicked",
"\"",
",",
"\"",
"one of the rows was clicked",
"\"",
",",
"\"",
"ok",
"\"",
")",
";",
"}",
";",
"Content",
"=",
"new",
"StackLayout",
"{",
"Padding",
"=",
"new",
"Thickness",
"(",
"0",
",",
"Device",
".",
"RuntimePlatform",
"==",
"Device",
".",
"iOS",
"?",
"20",
":",
"0",
",",
"0",
",",
"0",
")",
",",
"Children",
"=",
"{",
"new",
"Label",
"{",
"HorizontalTextAlignment",
"=",
"TextAlignment",
".",
"Center",
",",
"Text",
"=",
"Device",
".",
"RuntimePlatform",
"==",
"Device",
".",
"iOS",
"?",
"\"",
"Custom UITableView+UICell",
"\"",
":",
"Device",
".",
"RuntimePlatform",
"==",
"Device",
".",
"Android",
"?",
"\"",
"Custom ListView+Cell",
"\"",
":",
"\"",
"Custom renderer ListView+DataTemplate",
"\"",
"}",
",",
"nativeListView2",
"}",
"}",
";",
"}",
"}"
] |
This page uses a custom renderer that wraps native list controls:
iOS : UITableView
Android : ListView (do not confuse with Xamarin.Forms ListView)
Windows Phone : ListView
Tizen : Native.ListView
|
[
"This",
"page",
"uses",
"a",
"custom",
"renderer",
"that",
"wraps",
"native",
"list",
"controls",
":",
"iOS",
":",
"UITableView",
"Android",
":",
"ListView",
"(",
"do",
"not",
"confuse",
"with",
"Xamarin",
".",
"Forms",
"ListView",
")",
"Windows",
"Phone",
":",
"ListView",
"Tizen",
":",
"Native",
".",
"ListView"
] |
[
"// CUSTOM RENDERER using a native control",
"// REQUIRED: To share a scrollable view with other views in a StackLayout, it should have a VerticalOptions of FillAndExpand.",
"//await Navigation.PushModalAsync (new DetailPage(e.SelectedItem));",
"// The root page of your application"
] |
[
{
"param": "ContentPage",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "ContentPage",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 18
| 216
| 90
|
8b564169b3694eff03fa485fd3fc64cc64cb1fdc
|
intj-t/openvmsft
|
WRK-V1.2/PUBLIC/INTERNAL/WIN/psi/Sources/Audio/Microsoft.Psi.Audio.Windows/AudioCapture.cs
|
[
"Intel"
] |
C#
|
AudioCapture
|
/// <summary>
/// Component that captures and streams audio from an input device such as a microphone.
/// </summary>
/// <remarks>
/// This sensor component produces an audio output stream of type <see cref="AudioBuffer"/> which may be piped to
/// downstream components for further processing and optionally saved to a data store. The audio input device from
/// which to capture may be specified via the <see cref="AudioCaptureConfiguration.DeviceName"/> configuration
/// parameter. The <see cref="GetAvailableDevices"/> static method may be used to enumerate the names of audio
/// input devices currently available on the system.
/// <br/>
/// **Please note**: This component uses Audio APIs that are available on Windows only.
/// </remarks>
|
Component that captures and streams audio from an input device such as a microphone.
|
[
"Component",
"that",
"captures",
"and",
"streams",
"audio",
"from",
"an",
"input",
"device",
"such",
"as",
"a",
"microphone",
"."
] |
public sealed class AudioCapture : IProducer<AudioBuffer>, ISourceComponent, IDisposable
{
private readonly Pipeline pipeline;
private readonly AudioCaptureConfiguration configuration;
private readonly Emitter<AudioBuffer> audioBuffers;
private WasapiCapture wasapiCapture;
private AudioBuffer buffer;
private WaveFormat sourceFormat = null;
private DateTime lastPostedAudioTime = DateTime.MinValue;
public AudioCapture(Pipeline pipeline, AudioCaptureConfiguration configuration)
{
this.pipeline = pipeline;
this.configuration = configuration;
this.audioBuffers = pipeline.CreateEmitter<AudioBuffer>(this, "AudioBuffers");
this.AudioLevelInput = pipeline.CreateReceiver<double>(this, this.SetAudioLevel, nameof(this.AudioLevelInput), true);
this.AudioLevel = pipeline.CreateEmitter<double>(this, nameof(this.AudioLevel));
this.wasapiCapture = new WasapiCapture();
this.wasapiCapture.Initialize(this.Configuration.DeviceName);
if (this.Configuration.AudioLevel >= 0)
{
this.wasapiCapture.AudioLevel = this.Configuration.AudioLevel;
}
}
public AudioCapture(Pipeline pipeline, string configurationFilename = null)
: this(
pipeline,
(configurationFilename == null) ? new AudioCaptureConfiguration() : new ConfigurationHelper<AudioCaptureConfiguration>(configurationFilename).Configuration)
{
}
public AudioCapture(Pipeline pipeline, WaveFormat outputFormat, string deviceName = null)
: this(pipeline, new AudioCaptureConfiguration() { Format = outputFormat, DeviceName = deviceName })
{
}
public Emitter<AudioBuffer> Out
{
get { return this.audioBuffers; }
}
public Receiver<double> AudioLevelInput { get; }
public Emitter<double> AudioLevel { get; }
public string AudioDeviceName
{
get { return this.wasapiCapture.Name; }
}
private AudioCaptureConfiguration Configuration
{
get { return this.configuration; }
}
public static string[] GetAvailableDevices()
{
return WasapiCapture.GetAvailableCaptureDevices();
}
public void SetAudioLevel(Message<double> level)
{
if (this.wasapiCapture != null)
{
this.wasapiCapture.AudioLevel = level.Data;
}
}
public void Dispose()
{
if (this.wasapiCapture != null)
{
this.wasapiCapture.Dispose();
this.wasapiCapture = null;
}
}
public void Start(Action<DateTime> notifyCompletionTime)
{
notifyCompletionTime(DateTime.MaxValue);
this.AudioLevel.Post(this.wasapiCapture.AudioLevel, this.pipeline.GetCurrentTime());
this.wasapiCapture.AudioDataAvailableEvent += this.HandleAudioDataAvailableEvent;
this.wasapiCapture.AudioVolumeNotification += this.HandleAudioVolumeNotification;
this.wasapiCapture.StartCapture(this.Configuration.TargetLatencyInMs, this.Configuration.AudioEngineBufferInMs, this.Configuration.Gain, this.Configuration.Format, this.Configuration.OptimizeForSpeech, this.Configuration.UseEventDrivenCapture);
this.sourceFormat = this.Configuration.Format ?? this.wasapiCapture.MixFormat;
}
public void Stop(DateTime finalOriginatingTime, Action notifyCompleted)
{
notifyCompleted();
this.sourceFormat = null;
}
private void HandleAudioDataAvailableEvent(object sender, AudioDataEventArgs e)
{
if ((e.Length > 0) && (this.sourceFormat != null))
{
DateTime originatingTime = this.pipeline.GetCurrentTimeFromElapsedTicks(e.Timestamp +
(10000000L * e.Length / this.sourceFormat.AvgBytesPerSec));
if (originatingTime < this.lastPostedAudioTime)
{
if (this.configuration.DropOutOfOrderPackets)
{
return;
}
else
{
throw new InvalidOperationException(
$"The most recently captured audio buffer has a timestamp ({originatingTime.TimeOfDay}) which is before " +
$"that of the last posted audio buffer ({this.lastPostedAudioTime.TimeOfDay}), as reported by the driver. This could " +
$"be due to a timing glitch in the audio stream. Set the 'DropOutOfOrderPackets' " +
$"{nameof(AudioCaptureConfiguration)} flag to true to handle this condition by dropping " +
$"packets with out of order timestamps.");
}
}
this.lastPostedAudioTime = originatingTime;
if ((this.buffer.Data == null) || (this.buffer.Length != e.Length))
{
this.buffer = new AudioBuffer(e.Length, this.sourceFormat);
}
Marshal.Copy(e.Data, this.buffer.Data, 0, e.Length);
this.audioBuffers.Post(this.buffer, originatingTime);
}
}
private void HandleAudioVolumeNotification(object sender, AudioVolumeEventArgs e)
{
this.AudioLevel.Post(e.MasterVolume, this.pipeline.GetCurrentTime());
}
}
|
[
"public",
"sealed",
"class",
"AudioCapture",
":",
"IProducer",
"<",
"AudioBuffer",
">",
",",
"ISourceComponent",
",",
"IDisposable",
"{",
"private",
"readonly",
"Pipeline",
"pipeline",
";",
"private",
"readonly",
"AudioCaptureConfiguration",
"configuration",
";",
"private",
"readonly",
"Emitter",
"<",
"AudioBuffer",
">",
"audioBuffers",
";",
"private",
"WasapiCapture",
"wasapiCapture",
";",
"private",
"AudioBuffer",
"buffer",
";",
"private",
"WaveFormat",
"sourceFormat",
"=",
"null",
";",
"private",
"DateTime",
"lastPostedAudioTime",
"=",
"DateTime",
".",
"MinValue",
";",
"public",
"AudioCapture",
"(",
"Pipeline",
"pipeline",
",",
"AudioCaptureConfiguration",
"configuration",
")",
"{",
"this",
".",
"pipeline",
"=",
"pipeline",
";",
"this",
".",
"configuration",
"=",
"configuration",
";",
"this",
".",
"audioBuffers",
"=",
"pipeline",
".",
"CreateEmitter",
"<",
"AudioBuffer",
">",
"(",
"this",
",",
"\"",
"AudioBuffers",
"\"",
")",
";",
"this",
".",
"AudioLevelInput",
"=",
"pipeline",
".",
"CreateReceiver",
"<",
"double",
">",
"(",
"this",
",",
"this",
".",
"SetAudioLevel",
",",
"nameof",
"(",
"this",
".",
"AudioLevelInput",
")",
",",
"true",
")",
";",
"this",
".",
"AudioLevel",
"=",
"pipeline",
".",
"CreateEmitter",
"<",
"double",
">",
"(",
"this",
",",
"nameof",
"(",
"this",
".",
"AudioLevel",
")",
")",
";",
"this",
".",
"wasapiCapture",
"=",
"new",
"WasapiCapture",
"(",
")",
";",
"this",
".",
"wasapiCapture",
".",
"Initialize",
"(",
"this",
".",
"Configuration",
".",
"DeviceName",
")",
";",
"if",
"(",
"this",
".",
"Configuration",
".",
"AudioLevel",
">=",
"0",
")",
"{",
"this",
".",
"wasapiCapture",
".",
"AudioLevel",
"=",
"this",
".",
"Configuration",
".",
"AudioLevel",
";",
"}",
"}",
"public",
"AudioCapture",
"(",
"Pipeline",
"pipeline",
",",
"string",
"configurationFilename",
"=",
"null",
")",
":",
"this",
"(",
"pipeline",
",",
"(",
"configurationFilename",
"==",
"null",
")",
"?",
"new",
"AudioCaptureConfiguration",
"(",
")",
":",
"new",
"ConfigurationHelper",
"<",
"AudioCaptureConfiguration",
">",
"(",
"configurationFilename",
")",
".",
"Configuration",
")",
"{",
"}",
"public",
"AudioCapture",
"(",
"Pipeline",
"pipeline",
",",
"WaveFormat",
"outputFormat",
",",
"string",
"deviceName",
"=",
"null",
")",
":",
"this",
"(",
"pipeline",
",",
"new",
"AudioCaptureConfiguration",
"(",
")",
"{",
"Format",
"=",
"outputFormat",
",",
"DeviceName",
"=",
"deviceName",
"}",
")",
"{",
"}",
"public",
"Emitter",
"<",
"AudioBuffer",
">",
"Out",
"{",
"get",
"{",
"return",
"this",
".",
"audioBuffers",
";",
"}",
"}",
"public",
"Receiver",
"<",
"double",
">",
"AudioLevelInput",
"{",
"get",
";",
"}",
"public",
"Emitter",
"<",
"double",
">",
"AudioLevel",
"{",
"get",
";",
"}",
"public",
"string",
"AudioDeviceName",
"{",
"get",
"{",
"return",
"this",
".",
"wasapiCapture",
".",
"Name",
";",
"}",
"}",
"private",
"AudioCaptureConfiguration",
"Configuration",
"{",
"get",
"{",
"return",
"this",
".",
"configuration",
";",
"}",
"}",
"public",
"static",
"string",
"[",
"]",
"GetAvailableDevices",
"(",
")",
"{",
"return",
"WasapiCapture",
".",
"GetAvailableCaptureDevices",
"(",
")",
";",
"}",
"public",
"void",
"SetAudioLevel",
"(",
"Message",
"<",
"double",
">",
"level",
")",
"{",
"if",
"(",
"this",
".",
"wasapiCapture",
"!=",
"null",
")",
"{",
"this",
".",
"wasapiCapture",
".",
"AudioLevel",
"=",
"level",
".",
"Data",
";",
"}",
"}",
"public",
"void",
"Dispose",
"(",
")",
"{",
"if",
"(",
"this",
".",
"wasapiCapture",
"!=",
"null",
")",
"{",
"this",
".",
"wasapiCapture",
".",
"Dispose",
"(",
")",
";",
"this",
".",
"wasapiCapture",
"=",
"null",
";",
"}",
"}",
"public",
"void",
"Start",
"(",
"Action",
"<",
"DateTime",
">",
"notifyCompletionTime",
")",
"{",
"notifyCompletionTime",
"(",
"DateTime",
".",
"MaxValue",
")",
";",
"this",
".",
"AudioLevel",
".",
"Post",
"(",
"this",
".",
"wasapiCapture",
".",
"AudioLevel",
",",
"this",
".",
"pipeline",
".",
"GetCurrentTime",
"(",
")",
")",
";",
"this",
".",
"wasapiCapture",
".",
"AudioDataAvailableEvent",
"+=",
"this",
".",
"HandleAudioDataAvailableEvent",
";",
"this",
".",
"wasapiCapture",
".",
"AudioVolumeNotification",
"+=",
"this",
".",
"HandleAudioVolumeNotification",
";",
"this",
".",
"wasapiCapture",
".",
"StartCapture",
"(",
"this",
".",
"Configuration",
".",
"TargetLatencyInMs",
",",
"this",
".",
"Configuration",
".",
"AudioEngineBufferInMs",
",",
"this",
".",
"Configuration",
".",
"Gain",
",",
"this",
".",
"Configuration",
".",
"Format",
",",
"this",
".",
"Configuration",
".",
"OptimizeForSpeech",
",",
"this",
".",
"Configuration",
".",
"UseEventDrivenCapture",
")",
";",
"this",
".",
"sourceFormat",
"=",
"this",
".",
"Configuration",
".",
"Format",
"??",
"this",
".",
"wasapiCapture",
".",
"MixFormat",
";",
"}",
"public",
"void",
"Stop",
"(",
"DateTime",
"finalOriginatingTime",
",",
"Action",
"notifyCompleted",
")",
"{",
"notifyCompleted",
"(",
")",
";",
"this",
".",
"sourceFormat",
"=",
"null",
";",
"}",
"private",
"void",
"HandleAudioDataAvailableEvent",
"(",
"object",
"sender",
",",
"AudioDataEventArgs",
"e",
")",
"{",
"if",
"(",
"(",
"e",
".",
"Length",
">",
"0",
")",
"&&",
"(",
"this",
".",
"sourceFormat",
"!=",
"null",
")",
")",
"{",
"DateTime",
"originatingTime",
"=",
"this",
".",
"pipeline",
".",
"GetCurrentTimeFromElapsedTicks",
"(",
"e",
".",
"Timestamp",
"+",
"(",
"10000000L",
"*",
"e",
".",
"Length",
"/",
"this",
".",
"sourceFormat",
".",
"AvgBytesPerSec",
")",
")",
";",
"if",
"(",
"originatingTime",
"<",
"this",
".",
"lastPostedAudioTime",
")",
"{",
"if",
"(",
"this",
".",
"configuration",
".",
"DropOutOfOrderPackets",
")",
"{",
"return",
";",
"}",
"else",
"{",
"throw",
"new",
"InvalidOperationException",
"(",
"$\"",
"The most recently captured audio buffer has a timestamp (",
"{",
"originatingTime",
".",
"TimeOfDay",
"}",
") which is before ",
"\"",
"+",
"$\"",
"that of the last posted audio buffer (",
"{",
"this",
".",
"lastPostedAudioTime",
".",
"TimeOfDay",
"}",
"), as reported by the driver. This could ",
"\"",
"+",
"$\"",
"be due to a timing glitch in the audio stream. Set the 'DropOutOfOrderPackets' ",
"\"",
"+",
"$\"",
"{",
"nameof",
"(",
"AudioCaptureConfiguration",
")",
"}",
" flag to true to handle this condition by dropping ",
"\"",
"+",
"$\"",
"packets with out of order timestamps.",
"\"",
")",
";",
"}",
"}",
"this",
".",
"lastPostedAudioTime",
"=",
"originatingTime",
";",
"if",
"(",
"(",
"this",
".",
"buffer",
".",
"Data",
"==",
"null",
")",
"||",
"(",
"this",
".",
"buffer",
".",
"Length",
"!=",
"e",
".",
"Length",
")",
")",
"{",
"this",
".",
"buffer",
"=",
"new",
"AudioBuffer",
"(",
"e",
".",
"Length",
",",
"this",
".",
"sourceFormat",
")",
";",
"}",
"Marshal",
".",
"Copy",
"(",
"e",
".",
"Data",
",",
"this",
".",
"buffer",
".",
"Data",
",",
"0",
",",
"e",
".",
"Length",
")",
";",
"this",
".",
"audioBuffers",
".",
"Post",
"(",
"this",
".",
"buffer",
",",
"originatingTime",
")",
";",
"}",
"}",
"private",
"void",
"HandleAudioVolumeNotification",
"(",
"object",
"sender",
",",
"AudioVolumeEventArgs",
"e",
")",
"{",
"this",
".",
"AudioLevel",
".",
"Post",
"(",
"e",
".",
"MasterVolume",
",",
"this",
".",
"pipeline",
".",
"GetCurrentTime",
"(",
")",
")",
";",
"}",
"}"
] |
Component that captures and streams audio from an input device such as a microphone.
|
[
"Component",
"that",
"captures",
"and",
"streams",
"audio",
"from",
"an",
"input",
"device",
"such",
"as",
"a",
"microphone",
"."
] |
[
"/// <summary>",
"/// The configuration for this component.",
"/// </summary>",
"/// <summary>",
"/// The output stream of audio buffers.",
"/// </summary>",
"/// <summary>",
"/// The audio capture device.",
"/// </summary>",
"/// <summary>",
"/// The current audio capture buffer.",
"/// </summary>",
"/// <summary>",
"/// The current source audio format.",
"/// </summary>",
"/// <summary>",
"/// Keep track of the timestamp of the last audio buffer (computed from the value reported to us by the capture driver).",
"/// </summary>",
"/// <summary>",
"/// Initializes a new instance of the <see cref=\"AudioCapture\"/> class.",
"/// </summary>",
"/// <param name=\"pipeline\">The pipeline to add the component to.</param>",
"/// <param name=\"configuration\">The component configuration.</param>",
"/// <summary>",
"/// Initializes a new instance of the <see cref=\"AudioCapture\"/> class.",
"/// </summary>",
"/// <param name=\"pipeline\">The pipeline to add the component to.</param>",
"/// <param name=\"configurationFilename\">The component configuration file.</param>",
"/// <summary>",
"/// Initializes a new instance of the <see cref=\"AudioCapture\"/> class with a specified output format and device name.",
"/// </summary>",
"/// <param name=\"pipeline\">The pipeline to add the component to.</param>",
"/// <param name=\"outputFormat\">The output format to use.</param>",
"/// <param name=\"deviceName\">The name of the audio device.</param>",
"/// <summary>",
"/// Gets the output stream of audio buffers.",
"/// </summary>",
"/// <summary>",
"/// Gets the level control input.",
"/// </summary>",
"/// <summary>",
"/// Gets the output stream of audio level data.",
"/// </summary>",
"/// <summary>",
"/// Gets the name of the audio device.",
"/// </summary>",
"/// <summary>",
"/// Gets the configuration for this component.",
"/// </summary>",
"/// <summary>",
"/// Static method to get the available audio capture devices.",
"/// </summary>",
"/// <returns>",
"/// An array of available capture device names.",
"/// </returns>",
"/// <summary>",
"/// Sets the audio level.",
"/// </summary>",
"/// <param name=\"level\">The audio level.</param>",
"/// <summary>",
"/// Dispose method.",
"/// </summary>",
"/// <inheritdoc/>",
"// notify that this is an infinite source component",
"// publish initial values at startup",
"// register the event handler which will post new captured samples on the output stream",
"// register the volume notification event handler",
"// tell the audio device to start capturing audio",
"// Get the actual capture format. This should normally match the configured output format,",
"// unless that was null in which case the native device capture format is returned.",
"/// <inheritdoc/>",
"/// <summary>",
"/// The event handler that processes new audio data packets.",
"/// </summary>",
"/// <param name=\"sender\">The source of the event.</param>",
"/// <param name=\"e\">A <see cref=\"AudioDataEventArgs\"/> that contains the event data.</param>",
"// use the end of the last sample in the packet as the originating time",
"// Detect out of order originating times",
"// Ignore this packet with an out of order timestamp and return.",
"// Only create a new buffer if necessary.",
"// Copy the data.",
"// post the data to the output stream",
"/// <summary>",
"/// Handles volume notifications.",
"/// </summary>",
"/// <param name=\"sender\">The source of the event.</param>",
"/// <param name=\"e\">A <see cref=\"AudioVolumeEventArgs\"/> that contains the event data.</param>"
] |
[
{
"param": "ISourceComponent",
"type": null
},
{
"param": "IDisposable",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "ISourceComponent",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "IDisposable",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": [
{
"identifier": "remarks",
"docstring": "This sensor component produces an audio output stream of type which may be piped to\ndownstream components for further processing and optionally saved to a data store. The audio input device from\nwhich to capture may be specified via the configuration\nparameter. The static method may be used to enumerate the names of audio\ninput devices currently available on the system.\n\nPlease note**: This component uses Audio APIs that are available on Windows only.",
"docstring_tokens": [
"This",
"sensor",
"component",
"produces",
"an",
"audio",
"output",
"stream",
"of",
"type",
"which",
"may",
"be",
"piped",
"to",
"downstream",
"components",
"for",
"further",
"processing",
"and",
"optionally",
"saved",
"to",
"a",
"data",
"store",
".",
"The",
"audio",
"input",
"device",
"from",
"which",
"to",
"capture",
"may",
"be",
"specified",
"via",
"the",
"configuration",
"parameter",
".",
"The",
"static",
"method",
"may",
"be",
"used",
"to",
"enumerate",
"the",
"names",
"of",
"audio",
"input",
"devices",
"currently",
"available",
"on",
"the",
"system",
".",
"Please",
"note",
"**",
":",
"This",
"component",
"uses",
"Audio",
"APIs",
"that",
"are",
"available",
"on",
"Windows",
"only",
"."
]
}
]
}
| false
| 23
| 1,019
| 152
|
be2c83a9467635d8cf5b88bf19d152994d665d23
|
sorah/aws-sdk-ruby
|
lib/aws/ec2/dhcp_options_collection.rb
|
[
"Apache-2.0"
] |
Ruby
|
AWS
|
# Copyright 2011-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
|
or in the "license" file accompanying this file.
|
[
"or",
"in",
"the",
"\"",
"license",
"\"",
"file",
"accompanying",
"this",
"file",
"."
] |
module AWS
class EC2
class DHCPOptionsCollection < Collection
include TaggedCollection
include Core::Collection::Simple
# @param [Hash] options
#
# @option options [required,String] :domain_name A domain name of your
# choice (e.g., example.com).
#
# @option options [Array<String>] :domain_name_servers
# The IP addresses of domain name servers. You can specify up to
# four addresses.
#
# @option options [Array<String>] :ntp_servers
# The IP addresses of Network Time Protocol (NTP) servers. You can
# specify up to four addresses.
#
# @option options [Array<String>] :netbios_name_servers
# The IP addresses of NetBIOS name servers. You can specify up to
# four addresses.
#
# @option options [String] :netbios_node_type Value indicating the
# NetBIOS node type (1, 2, 4, or 8). For more information about the
# values, go to RFC 2132. We recommend you only use 2 at this time
# (broadcast and multicast are currently not supported).
#
def create options = {}
configurations = []
options.each_pair do |opt,values|
opt = opt.to_s.gsub(/_/, '-')
values = values.is_a?(Array) ? values : [values]
configurations << { :key => opt, :values => values.map(&:to_s) }
end
client_opts = {}
client_opts[:dhcp_configurations] = configurations
resp = client.create_dhcp_options(client_opts)
DHCPOptions.new_from(:create_dhcp_options,
resp.dhcp_options,
resp.dhcp_options.dhcp_options_id,
:config => config)
end
# @param [String] dhcp_options_id
# @return [DHCPOptions]
def [] dhcp_options_id
DHCPOptions.new(dhcp_options_id, :config => config)
end
protected
def _each_item options = {}, &block
response = filtered_request(:describe_dhcp_options, options, &block)
response.dhcp_options_set.each do |opts|
options = DHCPOptions.new_from(:describe_dhcp_options, opts,
opts.dhcp_options_id, :config => config)
yield(options)
end
end
end
end
end
|
[
"module",
"AWS",
"class",
"EC2",
"class",
"DHCPOptionsCollection",
"<",
"Collection",
"include",
"TaggedCollection",
"include",
"Core",
"::",
"Collection",
"::",
"Simple",
"def",
"create",
"options",
"=",
"{",
"}",
"configurations",
"=",
"[",
"]",
"options",
".",
"each_pair",
"do",
"|",
"opt",
",",
"values",
"|",
"opt",
"=",
"opt",
".",
"to_s",
".",
"gsub",
"(",
"/",
"_",
"/",
",",
"'-'",
")",
"values",
"=",
"values",
".",
"is_a?",
"(",
"Array",
")",
"?",
"values",
":",
"[",
"values",
"]",
"configurations",
"<<",
"{",
":key",
"=>",
"opt",
",",
":values",
"=>",
"values",
".",
"map",
"(",
"&",
":to_s",
")",
"}",
"end",
"client_opts",
"=",
"{",
"}",
"client_opts",
"[",
":dhcp_configurations",
"]",
"=",
"configurations",
"resp",
"=",
"client",
".",
"create_dhcp_options",
"(",
"client_opts",
")",
"DHCPOptions",
".",
"new_from",
"(",
":create_dhcp_options",
",",
"resp",
".",
"dhcp_options",
",",
"resp",
".",
"dhcp_options",
".",
"dhcp_options_id",
",",
":config",
"=>",
"config",
")",
"end",
"def",
"[]",
"dhcp_options_id",
"DHCPOptions",
".",
"new",
"(",
"dhcp_options_id",
",",
":config",
"=>",
"config",
")",
"end",
"protected",
"def",
"_each_item",
"options",
"=",
"{",
"}",
",",
"&",
"block",
"response",
"=",
"filtered_request",
"(",
":describe_dhcp_options",
",",
"options",
",",
"&",
"block",
")",
"response",
".",
"dhcp_options_set",
".",
"each",
"do",
"|",
"opts",
"|",
"options",
"=",
"DHCPOptions",
".",
"new_from",
"(",
":describe_dhcp_options",
",",
"opts",
",",
"opts",
".",
"dhcp_options_id",
",",
":config",
"=>",
"config",
")",
"yield",
"(",
"options",
")",
"end",
"end",
"end",
"end",
"end"
] |
Copyright 2011-2013 Amazon.com, Inc. or its affiliates.
|
[
"Copyright",
"2011",
"-",
"2013",
"Amazon",
".",
"com",
"Inc",
".",
"or",
"its",
"affiliates",
"."
] |
[
"# @param [Hash] options",
"#",
"# @option options [required,String] :domain_name A domain name of your",
"# choice (e.g., example.com).",
"#",
"# @option options [Array<String>] :domain_name_servers",
"# The IP addresses of domain name servers. You can specify up to",
"# four addresses.",
"#",
"# @option options [Array<String>] :ntp_servers",
"# The IP addresses of Network Time Protocol (NTP) servers. You can",
"# specify up to four addresses.",
"#",
"# @option options [Array<String>] :netbios_name_servers",
"# The IP addresses of NetBIOS name servers. You can specify up to",
"# four addresses.",
"#",
"# @option options [String] :netbios_node_type Value indicating the",
"# NetBIOS node type (1, 2, 4, or 8). For more information about the",
"# values, go to RFC 2132. We recommend you only use 2 at this time",
"# (broadcast and multicast are currently not supported).",
"#",
"# @param [String] dhcp_options_id",
"# @return [DHCPOptions]"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 18
| 548
| 141
|
fd89ac12d9c503acc4395f94c9053f584aa64d27
|
gjy5885/azure-sdk-for-net
|
sdk/core/Microsoft.Azure.Core.Spatial/src/Serialization/LevelTwoGeoJsonCoordinateReader.cs
|
[
"MIT"
] |
C#
|
LevelTwoGeoJsonCoordinateReader
|
/// <summary>
/// Advances a Utf8JsonReader identified to contain either a Polygon or MultiLineString.
/// </summary>
/// <remarks>
/// Both Polygon and MultiLineString are an array of an array of points. When Process is called,
/// depending on the positioning of the GeoJson properties, the GeoJson 'type' property may not
/// have been read, so the reader processes the GeoJson coordinates property and creates a list of
/// a List of GeographyPoints. Once both the type and coordinates properties have been read,
/// GetGeography will be called, and the reader will either create a Polygon or MultiLineString,
/// or raise an exception if the type argument is not Polygon or MultiLineString.
/// </remarks>
|
Advances a Utf8JsonReader identified to contain either a Polygon or MultiLineString.
|
[
"Advances",
"a",
"Utf8JsonReader",
"identified",
"to",
"contain",
"either",
"a",
"Polygon",
"or",
"MultiLineString",
"."
] |
internal class LevelTwoGeoJsonCoordinateReader : GeoJsonCoordinateReader
{
protected List<List<GeographyPoint>> Points { get; set; }
public override Geography GetGeography(string type)
{
if (type == GeoJsonConstants.PolygonTypeName)
{
return GeographyFactory.Polygon().Create(Points);
}
else if (type == GeoJsonConstants.MultiLineStringTypeName)
{
return GeographyFactory.MultiLineString().Create(Points);
}
else
{
throw new JsonException($"Invalid GeoJson: type '{type}' does not match coordinates provided.");
}
}
public override void Process(ref Utf8JsonReader reader)
{
Points = reader.ReadPolygonOrMultiLineString();
}
}
|
[
"internal",
"class",
"LevelTwoGeoJsonCoordinateReader",
":",
"GeoJsonCoordinateReader",
"{",
"protected",
"List",
"<",
"List",
"<",
"GeographyPoint",
">",
">",
"Points",
"{",
"get",
";",
"set",
";",
"}",
"public",
"override",
"Geography",
"GetGeography",
"(",
"string",
"type",
")",
"{",
"if",
"(",
"type",
"==",
"GeoJsonConstants",
".",
"PolygonTypeName",
")",
"{",
"return",
"GeographyFactory",
".",
"Polygon",
"(",
")",
".",
"Create",
"(",
"Points",
")",
";",
"}",
"else",
"if",
"(",
"type",
"==",
"GeoJsonConstants",
".",
"MultiLineStringTypeName",
")",
"{",
"return",
"GeographyFactory",
".",
"MultiLineString",
"(",
")",
".",
"Create",
"(",
"Points",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"JsonException",
"(",
"$\"",
"Invalid GeoJson: type '",
"{",
"type",
"}",
"' does not match coordinates provided.",
"\"",
")",
";",
"}",
"}",
"public",
"override",
"void",
"Process",
"(",
"ref",
"Utf8JsonReader",
"reader",
")",
"{",
"Points",
"=",
"reader",
".",
"ReadPolygonOrMultiLineString",
"(",
")",
";",
"}",
"}"
] |
Advances a Utf8JsonReader identified to contain either a Polygon or MultiLineString.
|
[
"Advances",
"a",
"Utf8JsonReader",
"identified",
"to",
"contain",
"either",
"a",
"Polygon",
"or",
"MultiLineString",
"."
] |
[
"/// <summary>",
"/// Converts the Points array of an array into either a Polygon or MultiLineString",
"/// </summary>",
"/// <param name=\"type\">The GeoJson type read from the 'type' property</param>",
"/// <returns>The Geography created from the Points array of an array</returns>",
"/// <exception cref=\"JsonException\">Invalid GeoJson, e.g. 'type' property specifies Polygon",
"/// where as the coordinates property contains a LineString</exception>",
"/// <summary>",
"/// Extracts an array of an array of points from a Utf8JsonReader",
"/// </summary>",
"/// <param name=\"reader\">A Utf8JsonReader positioned at the first number in the first array</param>"
] |
[
{
"param": "GeoJsonCoordinateReader",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "GeoJsonCoordinateReader",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": [
{
"identifier": "remarks",
"docstring": "Both Polygon and MultiLineString are an array of an array of points. When Process is called,\ndepending on the positioning of the GeoJson properties, the GeoJson 'type' property may not\nhave been read, so the reader processes the GeoJson coordinates property and creates a list of\na List of GeographyPoints. Once both the type and coordinates properties have been read,\nGetGeography will be called, and the reader will either create a Polygon or MultiLineString,\nor raise an exception if the type argument is not Polygon or MultiLineString.",
"docstring_tokens": [
"Both",
"Polygon",
"and",
"MultiLineString",
"are",
"an",
"array",
"of",
"an",
"array",
"of",
"points",
".",
"When",
"Process",
"is",
"called",
"depending",
"on",
"the",
"positioning",
"of",
"the",
"GeoJson",
"properties",
"the",
"GeoJson",
"'",
"type",
"'",
"property",
"may",
"not",
"have",
"been",
"read",
"so",
"the",
"reader",
"processes",
"the",
"GeoJson",
"coordinates",
"property",
"and",
"creates",
"a",
"list",
"of",
"a",
"List",
"of",
"GeographyPoints",
".",
"Once",
"both",
"the",
"type",
"and",
"coordinates",
"properties",
"have",
"been",
"read",
"GetGeography",
"will",
"be",
"called",
"and",
"the",
"reader",
"will",
"either",
"create",
"a",
"Polygon",
"or",
"MultiLineString",
"or",
"raise",
"an",
"exception",
"if",
"the",
"type",
"argument",
"is",
"not",
"Polygon",
"or",
"MultiLineString",
"."
]
}
]
}
| false
| 14
| 159
| 152
|
71636458c905d09b6eb8c6b8f371c12ad3a787a0
|
bubdm/TypePipe
|
Core/MutableReflection/Generics/TypeInstantiation.cs
|
[
"ECL-2.0",
"Apache-2.0"
] |
C#
|
TypeInstantiation
|
/// <summary>
/// Represents a constructed generic <see cref="Type"/>, i.e., a generic type definition that was instantiated with type arguments.
/// This class is needed because the the original reflection classes do not work in combination with <see cref="CustomType"/> instances.
/// </summary>
/// <remarks>Instances of this class are returned by <see cref="TypeExtensions.MakeTypePipeGenericType"/> and implement value equality.</remarks>
|
Represents a constructed generic , i.e., a generic type definition that was instantiated with type arguments.
This class is needed because the the original reflection classes do not work in combination with instances.
|
[
"Represents",
"a",
"constructed",
"generic",
"i",
".",
"e",
".",
"a",
"generic",
"type",
"definition",
"that",
"was",
"instantiated",
"with",
"type",
"arguments",
".",
"This",
"class",
"is",
"needed",
"because",
"the",
"the",
"original",
"reflection",
"classes",
"do",
"not",
"work",
"in",
"combination",
"with",
"instances",
"."
] |
public class TypeInstantiation : CustomType
{
private const BindingFlags c_allMembers = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance;
private readonly TypeInstantiationInfo _instantiationInfo;
private readonly TypeInstantiationContext _instantiationContext;
private readonly IDictionary<Type, Type> _parametersToArguments;
private readonly Lazy<IReadOnlyCollection<Type>> _nestedTypes;
private readonly Lazy<IReadOnlyCollection<Type>> _interfaces;
private readonly Lazy<IReadOnlyCollection<FieldInfo>> _fields;
private readonly Lazy<IReadOnlyCollection<ConstructorInfo>> _constructors;
private readonly Lazy<IReadOnlyCollection<MethodOnTypeInstantiation>> _methods;
private readonly Lazy<IReadOnlyCollection<PropertyInfo>> _properties;
private readonly Lazy<IReadOnlyCollection<EventInfo>> _events;
public TypeInstantiation (TypeInstantiationInfo instantiationInfo, TypeInstantiationContext instantiationContext)
: base (
ArgumentUtility.CheckNotNull ("instantiationInfo", instantiationInfo).GenericTypeDefinition.Name,
instantiationInfo.GenericTypeDefinition.Namespace,
instantiationInfo.GenericTypeDefinition.Attributes,
genericTypeDefinition: instantiationInfo.GenericTypeDefinition,
typeArguments: instantiationInfo.TypeArguments)
{
ArgumentUtility.CheckNotNull ("instantiationContext", instantiationContext);
_instantiationInfo = instantiationInfo;
_instantiationContext = instantiationContext;
var genericTypeDefinition = instantiationInfo.GenericTypeDefinition;
var declaringType = genericTypeDefinition.DeclaringType;
var outerMapping = declaringType != null
? declaringType.GetGenericArguments().Zip (instantiationInfo.TypeArguments, Tuple.Create)
: new Tuple<Type, Type>[0];
var mapping = genericTypeDefinition.GetGenericArguments().Zip (instantiationInfo.TypeArguments, Tuple.Create);
_parametersToArguments = outerMapping.Concat (mapping).ToDictionary (t => t.Item1, t => t.Item2);
instantiationContext.Add (instantiationInfo, this);
if (declaringType != null)
SetDeclaringType (SubstituteGenericParameters (declaringType));
if (genericTypeDefinition.BaseType != null)
SetBaseType (SubstituteGenericParameters (genericTypeDefinition.BaseType));
_nestedTypes = new Lazy<IReadOnlyCollection<Type>> (() => CreateNestedType().ToList().AsReadOnly());
_interfaces = new Lazy<IReadOnlyCollection<Type>> (() => CreateInterfaces().ToList().AsReadOnly());
_fields = new Lazy<IReadOnlyCollection<FieldInfo>> (() => CreateFields().Cast<FieldInfo>().ToList().AsReadOnly());
_constructors = new Lazy<IReadOnlyCollection<ConstructorInfo>> (() => CreateConstructors().Cast<ConstructorInfo>().ToList().AsReadOnly());
_methods = new Lazy<IReadOnlyCollection<MethodOnTypeInstantiation>> (() => CreateMethods().ToList().AsReadOnly());
_properties = new Lazy<IReadOnlyCollection<PropertyInfo>> (() => CreateProperties().Cast<PropertyInfo>().ToList().AsReadOnly());
_events = new Lazy<IReadOnlyCollection<EventInfo>> (() => CreateEvents().Cast<EventInfo>().ToList().AsReadOnly());
}
public Type SubstituteGenericParameters (Type type)
{
ArgumentUtility.CheckNotNull ("type", type);
return _instantiationContext.SubstituteGenericParameters (type, _parametersToArguments);
}
public override bool Equals (object obj)
{
return Equals (obj as Type);
}
public override bool Equals (Type type)
{
var other = type as TypeInstantiation;
if (other == null)
return false;
return _instantiationInfo.Equals (other._instantiationInfo);
}
public override int GetHashCode ()
{
return _instantiationInfo.GetHashCode();
}
public override IEnumerable<ICustomAttributeData> GetCustomAttributeData ()
{
return TypePipeCustomAttributeData.GetCustomAttributes (GetGenericTypeDefinition());
}
public override IEnumerable<Type> GetAllNestedTypes ()
{
return _nestedTypes.Value;
}
public override IEnumerable<Type> GetAllInterfaces ()
{
return _interfaces.Value;
}
public override IEnumerable<FieldInfo> GetAllFields ()
{
return _fields.Value;
}
public override IEnumerable<ConstructorInfo> GetAllConstructors ()
{
return _constructors.Value;
}
public override IEnumerable<MethodInfo> GetAllMethods ()
{
return _methods.Value;
}
public override IEnumerable<PropertyInfo> GetAllProperties ()
{
return _properties.Value;
}
public override IEnumerable<EventInfo> GetAllEvents ()
{
return _events.Value;
}
private IEnumerable<Type> CreateNestedType ()
{
throw new NotImplementedException ("TODO 5816");
}
private IEnumerable<Type> CreateInterfaces ()
{
return _instantiationInfo.GenericTypeDefinition.GetInterfaces().Select (SubstituteGenericParameters);
}
private IEnumerable<FieldOnTypeInstantiation> CreateFields ()
{
return _instantiationInfo.GenericTypeDefinition.GetFields (c_allMembers).Select (f => new FieldOnTypeInstantiation (this, f));
}
private IEnumerable<ConstructorOnTypeInstantiation> CreateConstructors ()
{
return _instantiationInfo.GenericTypeDefinition.GetConstructors (c_allMembers).Select (c => new ConstructorOnTypeInstantiation (this, c));
}
private IEnumerable<MethodOnTypeInstantiation> CreateMethods ()
{
return _instantiationInfo.GenericTypeDefinition.GetMethods (c_allMembers).Select (m => new MethodOnTypeInstantiation (this, m));
}
private IEnumerable<PropertyOnTypeInstantiation> CreateProperties ()
{
return _instantiationInfo.GenericTypeDefinition.GetProperties (c_allMembers).Select (CreateProperty);
}
private IEnumerable<EventOnTypeInstantiation> CreateEvents ()
{
return _instantiationInfo.GenericTypeDefinition.GetEvents (c_allMembers).Select (CreateEvent);
}
private PropertyOnTypeInstantiation CreateProperty (PropertyInfo genericProperty)
{
var mapping = GetGenericMethodToInstantiationMapping();
var getMethod = GetMethodOrNull (mapping, genericProperty.GetGetMethod (true));
var setMethod = GetMethodOrNull (mapping, genericProperty.GetSetMethod (true));
return new PropertyOnTypeInstantiation (this, genericProperty, getMethod, setMethod);
}
private EventOnTypeInstantiation CreateEvent (EventInfo genericEvent)
{
var mapping = GetGenericMethodToInstantiationMapping();
var addMethod = GetMethodOrNull (mapping, genericEvent.GetAddMethod (true));
var removeMethod = GetMethodOrNull (mapping, genericEvent.GetRemoveMethod (true));
var raiseMethod = GetMethodOrNull (mapping, genericEvent.GetRaiseMethod (true));
return new EventOnTypeInstantiation (this, genericEvent, addMethod, removeMethod, raiseMethod);
}
private Dictionary<MethodInfo, MethodOnTypeInstantiation> GetGenericMethodToInstantiationMapping ()
{
return _methods.Value.ToDictionary (m => m.MethodOnGenericType);
}
private MethodOnTypeInstantiation GetMethodOrNull (Dictionary<MethodInfo, MethodOnTypeInstantiation> methodMapping, MethodInfo genericMethod)
{
return genericMethod != null ? methodMapping[genericMethod] : null;
}
}
|
[
"public",
"class",
"TypeInstantiation",
":",
"CustomType",
"{",
"private",
"const",
"BindingFlags",
"c_allMembers",
"=",
"BindingFlags",
".",
"Public",
"|",
"BindingFlags",
".",
"NonPublic",
"|",
"BindingFlags",
".",
"Static",
"|",
"BindingFlags",
".",
"Instance",
";",
"private",
"readonly",
"TypeInstantiationInfo",
"_instantiationInfo",
";",
"private",
"readonly",
"TypeInstantiationContext",
"_instantiationContext",
";",
"private",
"readonly",
"IDictionary",
"<",
"Type",
",",
"Type",
">",
"_parametersToArguments",
";",
"private",
"readonly",
"Lazy",
"<",
"IReadOnlyCollection",
"<",
"Type",
">",
">",
"_nestedTypes",
";",
"private",
"readonly",
"Lazy",
"<",
"IReadOnlyCollection",
"<",
"Type",
">",
">",
"_interfaces",
";",
"private",
"readonly",
"Lazy",
"<",
"IReadOnlyCollection",
"<",
"FieldInfo",
">",
">",
"_fields",
";",
"private",
"readonly",
"Lazy",
"<",
"IReadOnlyCollection",
"<",
"ConstructorInfo",
">",
">",
"_constructors",
";",
"private",
"readonly",
"Lazy",
"<",
"IReadOnlyCollection",
"<",
"MethodOnTypeInstantiation",
">",
">",
"_methods",
";",
"private",
"readonly",
"Lazy",
"<",
"IReadOnlyCollection",
"<",
"PropertyInfo",
">",
">",
"_properties",
";",
"private",
"readonly",
"Lazy",
"<",
"IReadOnlyCollection",
"<",
"EventInfo",
">",
">",
"_events",
";",
"public",
"TypeInstantiation",
"(",
"TypeInstantiationInfo",
"instantiationInfo",
",",
"TypeInstantiationContext",
"instantiationContext",
")",
":",
"base",
"(",
"ArgumentUtility",
".",
"CheckNotNull",
"(",
"\"",
"instantiationInfo",
"\"",
",",
"instantiationInfo",
")",
".",
"GenericTypeDefinition",
".",
"Name",
",",
"instantiationInfo",
".",
"GenericTypeDefinition",
".",
"Namespace",
",",
"instantiationInfo",
".",
"GenericTypeDefinition",
".",
"Attributes",
",",
"genericTypeDefinition",
":",
"instantiationInfo",
".",
"GenericTypeDefinition",
",",
"typeArguments",
":",
"instantiationInfo",
".",
"TypeArguments",
")",
"{",
"ArgumentUtility",
".",
"CheckNotNull",
"(",
"\"",
"instantiationContext",
"\"",
",",
"instantiationContext",
")",
";",
"_instantiationInfo",
"=",
"instantiationInfo",
";",
"_instantiationContext",
"=",
"instantiationContext",
";",
"var",
"genericTypeDefinition",
"=",
"instantiationInfo",
".",
"GenericTypeDefinition",
";",
"var",
"declaringType",
"=",
"genericTypeDefinition",
".",
"DeclaringType",
";",
"var",
"outerMapping",
"=",
"declaringType",
"!=",
"null",
"?",
"declaringType",
".",
"GetGenericArguments",
"(",
")",
".",
"Zip",
"(",
"instantiationInfo",
".",
"TypeArguments",
",",
"Tuple",
".",
"Create",
")",
":",
"new",
"Tuple",
"<",
"Type",
",",
"Type",
">",
"[",
"0",
"]",
";",
"var",
"mapping",
"=",
"genericTypeDefinition",
".",
"GetGenericArguments",
"(",
")",
".",
"Zip",
"(",
"instantiationInfo",
".",
"TypeArguments",
",",
"Tuple",
".",
"Create",
")",
";",
"_parametersToArguments",
"=",
"outerMapping",
".",
"Concat",
"(",
"mapping",
")",
".",
"ToDictionary",
"(",
"t",
"=>",
"t",
".",
"Item1",
",",
"t",
"=>",
"t",
".",
"Item2",
")",
";",
"instantiationContext",
".",
"Add",
"(",
"instantiationInfo",
",",
"this",
")",
";",
"if",
"(",
"declaringType",
"!=",
"null",
")",
"SetDeclaringType",
"(",
"SubstituteGenericParameters",
"(",
"declaringType",
")",
")",
";",
"if",
"(",
"genericTypeDefinition",
".",
"BaseType",
"!=",
"null",
")",
"SetBaseType",
"(",
"SubstituteGenericParameters",
"(",
"genericTypeDefinition",
".",
"BaseType",
")",
")",
";",
"_nestedTypes",
"=",
"new",
"Lazy",
"<",
"IReadOnlyCollection",
"<",
"Type",
">",
">",
"(",
"(",
")",
"=>",
"CreateNestedType",
"(",
")",
".",
"ToList",
"(",
")",
".",
"AsReadOnly",
"(",
")",
")",
";",
"_interfaces",
"=",
"new",
"Lazy",
"<",
"IReadOnlyCollection",
"<",
"Type",
">",
">",
"(",
"(",
")",
"=>",
"CreateInterfaces",
"(",
")",
".",
"ToList",
"(",
")",
".",
"AsReadOnly",
"(",
")",
")",
";",
"_fields",
"=",
"new",
"Lazy",
"<",
"IReadOnlyCollection",
"<",
"FieldInfo",
">",
">",
"(",
"(",
")",
"=>",
"CreateFields",
"(",
")",
".",
"Cast",
"<",
"FieldInfo",
">",
"(",
")",
".",
"ToList",
"(",
")",
".",
"AsReadOnly",
"(",
")",
")",
";",
"_constructors",
"=",
"new",
"Lazy",
"<",
"IReadOnlyCollection",
"<",
"ConstructorInfo",
">",
">",
"(",
"(",
")",
"=>",
"CreateConstructors",
"(",
")",
".",
"Cast",
"<",
"ConstructorInfo",
">",
"(",
")",
".",
"ToList",
"(",
")",
".",
"AsReadOnly",
"(",
")",
")",
";",
"_methods",
"=",
"new",
"Lazy",
"<",
"IReadOnlyCollection",
"<",
"MethodOnTypeInstantiation",
">",
">",
"(",
"(",
")",
"=>",
"CreateMethods",
"(",
")",
".",
"ToList",
"(",
")",
".",
"AsReadOnly",
"(",
")",
")",
";",
"_properties",
"=",
"new",
"Lazy",
"<",
"IReadOnlyCollection",
"<",
"PropertyInfo",
">",
">",
"(",
"(",
")",
"=>",
"CreateProperties",
"(",
")",
".",
"Cast",
"<",
"PropertyInfo",
">",
"(",
")",
".",
"ToList",
"(",
")",
".",
"AsReadOnly",
"(",
")",
")",
";",
"_events",
"=",
"new",
"Lazy",
"<",
"IReadOnlyCollection",
"<",
"EventInfo",
">",
">",
"(",
"(",
")",
"=>",
"CreateEvents",
"(",
")",
".",
"Cast",
"<",
"EventInfo",
">",
"(",
")",
".",
"ToList",
"(",
")",
".",
"AsReadOnly",
"(",
")",
")",
";",
"}",
"public",
"Type",
"SubstituteGenericParameters",
"(",
"Type",
"type",
")",
"{",
"ArgumentUtility",
".",
"CheckNotNull",
"(",
"\"",
"type",
"\"",
",",
"type",
")",
";",
"return",
"_instantiationContext",
".",
"SubstituteGenericParameters",
"(",
"type",
",",
"_parametersToArguments",
")",
";",
"}",
"public",
"override",
"bool",
"Equals",
"(",
"object",
"obj",
")",
"{",
"return",
"Equals",
"(",
"obj",
"as",
"Type",
")",
";",
"}",
"public",
"override",
"bool",
"Equals",
"(",
"Type",
"type",
")",
"{",
"var",
"other",
"=",
"type",
"as",
"TypeInstantiation",
";",
"if",
"(",
"other",
"==",
"null",
")",
"return",
"false",
";",
"return",
"_instantiationInfo",
".",
"Equals",
"(",
"other",
".",
"_instantiationInfo",
")",
";",
"}",
"public",
"override",
"int",
"GetHashCode",
"(",
")",
"{",
"return",
"_instantiationInfo",
".",
"GetHashCode",
"(",
")",
";",
"}",
"public",
"override",
"IEnumerable",
"<",
"ICustomAttributeData",
">",
"GetCustomAttributeData",
"(",
")",
"{",
"return",
"TypePipeCustomAttributeData",
".",
"GetCustomAttributes",
"(",
"GetGenericTypeDefinition",
"(",
")",
")",
";",
"}",
"public",
"override",
"IEnumerable",
"<",
"Type",
">",
"GetAllNestedTypes",
"(",
")",
"{",
"return",
"_nestedTypes",
".",
"Value",
";",
"}",
"public",
"override",
"IEnumerable",
"<",
"Type",
">",
"GetAllInterfaces",
"(",
")",
"{",
"return",
"_interfaces",
".",
"Value",
";",
"}",
"public",
"override",
"IEnumerable",
"<",
"FieldInfo",
">",
"GetAllFields",
"(",
")",
"{",
"return",
"_fields",
".",
"Value",
";",
"}",
"public",
"override",
"IEnumerable",
"<",
"ConstructorInfo",
">",
"GetAllConstructors",
"(",
")",
"{",
"return",
"_constructors",
".",
"Value",
";",
"}",
"public",
"override",
"IEnumerable",
"<",
"MethodInfo",
">",
"GetAllMethods",
"(",
")",
"{",
"return",
"_methods",
".",
"Value",
";",
"}",
"public",
"override",
"IEnumerable",
"<",
"PropertyInfo",
">",
"GetAllProperties",
"(",
")",
"{",
"return",
"_properties",
".",
"Value",
";",
"}",
"public",
"override",
"IEnumerable",
"<",
"EventInfo",
">",
"GetAllEvents",
"(",
")",
"{",
"return",
"_events",
".",
"Value",
";",
"}",
"private",
"IEnumerable",
"<",
"Type",
">",
"CreateNestedType",
"(",
")",
"{",
"throw",
"new",
"NotImplementedException",
"(",
"\"",
"TODO 5816",
"\"",
")",
";",
"}",
"private",
"IEnumerable",
"<",
"Type",
">",
"CreateInterfaces",
"(",
")",
"{",
"return",
"_instantiationInfo",
".",
"GenericTypeDefinition",
".",
"GetInterfaces",
"(",
")",
".",
"Select",
"(",
"SubstituteGenericParameters",
")",
";",
"}",
"private",
"IEnumerable",
"<",
"FieldOnTypeInstantiation",
">",
"CreateFields",
"(",
")",
"{",
"return",
"_instantiationInfo",
".",
"GenericTypeDefinition",
".",
"GetFields",
"(",
"c_allMembers",
")",
".",
"Select",
"(",
"f",
"=>",
"new",
"FieldOnTypeInstantiation",
"(",
"this",
",",
"f",
")",
")",
";",
"}",
"private",
"IEnumerable",
"<",
"ConstructorOnTypeInstantiation",
">",
"CreateConstructors",
"(",
")",
"{",
"return",
"_instantiationInfo",
".",
"GenericTypeDefinition",
".",
"GetConstructors",
"(",
"c_allMembers",
")",
".",
"Select",
"(",
"c",
"=>",
"new",
"ConstructorOnTypeInstantiation",
"(",
"this",
",",
"c",
")",
")",
";",
"}",
"private",
"IEnumerable",
"<",
"MethodOnTypeInstantiation",
">",
"CreateMethods",
"(",
")",
"{",
"return",
"_instantiationInfo",
".",
"GenericTypeDefinition",
".",
"GetMethods",
"(",
"c_allMembers",
")",
".",
"Select",
"(",
"m",
"=>",
"new",
"MethodOnTypeInstantiation",
"(",
"this",
",",
"m",
")",
")",
";",
"}",
"private",
"IEnumerable",
"<",
"PropertyOnTypeInstantiation",
">",
"CreateProperties",
"(",
")",
"{",
"return",
"_instantiationInfo",
".",
"GenericTypeDefinition",
".",
"GetProperties",
"(",
"c_allMembers",
")",
".",
"Select",
"(",
"CreateProperty",
")",
";",
"}",
"private",
"IEnumerable",
"<",
"EventOnTypeInstantiation",
">",
"CreateEvents",
"(",
")",
"{",
"return",
"_instantiationInfo",
".",
"GenericTypeDefinition",
".",
"GetEvents",
"(",
"c_allMembers",
")",
".",
"Select",
"(",
"CreateEvent",
")",
";",
"}",
"private",
"PropertyOnTypeInstantiation",
"CreateProperty",
"(",
"PropertyInfo",
"genericProperty",
")",
"{",
"var",
"mapping",
"=",
"GetGenericMethodToInstantiationMapping",
"(",
")",
";",
"var",
"getMethod",
"=",
"GetMethodOrNull",
"(",
"mapping",
",",
"genericProperty",
".",
"GetGetMethod",
"(",
"true",
")",
")",
";",
"var",
"setMethod",
"=",
"GetMethodOrNull",
"(",
"mapping",
",",
"genericProperty",
".",
"GetSetMethod",
"(",
"true",
")",
")",
";",
"return",
"new",
"PropertyOnTypeInstantiation",
"(",
"this",
",",
"genericProperty",
",",
"getMethod",
",",
"setMethod",
")",
";",
"}",
"private",
"EventOnTypeInstantiation",
"CreateEvent",
"(",
"EventInfo",
"genericEvent",
")",
"{",
"var",
"mapping",
"=",
"GetGenericMethodToInstantiationMapping",
"(",
")",
";",
"var",
"addMethod",
"=",
"GetMethodOrNull",
"(",
"mapping",
",",
"genericEvent",
".",
"GetAddMethod",
"(",
"true",
")",
")",
";",
"var",
"removeMethod",
"=",
"GetMethodOrNull",
"(",
"mapping",
",",
"genericEvent",
".",
"GetRemoveMethod",
"(",
"true",
")",
")",
";",
"var",
"raiseMethod",
"=",
"GetMethodOrNull",
"(",
"mapping",
",",
"genericEvent",
".",
"GetRaiseMethod",
"(",
"true",
")",
")",
";",
"return",
"new",
"EventOnTypeInstantiation",
"(",
"this",
",",
"genericEvent",
",",
"addMethod",
",",
"removeMethod",
",",
"raiseMethod",
")",
";",
"}",
"private",
"Dictionary",
"<",
"MethodInfo",
",",
"MethodOnTypeInstantiation",
">",
"GetGenericMethodToInstantiationMapping",
"(",
")",
"{",
"return",
"_methods",
".",
"Value",
".",
"ToDictionary",
"(",
"m",
"=>",
"m",
".",
"MethodOnGenericType",
")",
";",
"}",
"private",
"MethodOnTypeInstantiation",
"GetMethodOrNull",
"(",
"Dictionary",
"<",
"MethodInfo",
",",
"MethodOnTypeInstantiation",
">",
"methodMapping",
",",
"MethodInfo",
"genericMethod",
")",
"{",
"return",
"genericMethod",
"!=",
"null",
"?",
"methodMapping",
"[",
"genericMethod",
"]",
":",
"null",
";",
"}",
"}"
] |
Represents a constructed generic , i.e., a generic type definition that was instantiated with type arguments.
|
[
"Represents",
"a",
"constructed",
"generic",
"i",
".",
"e",
".",
"a",
"generic",
"type",
"definition",
"that",
"was",
"instantiated",
"with",
"type",
"arguments",
"."
] |
[
"// TODO 5452: Use type unification.",
"// Even though the _genericTypeDefinition includes the type parameters of the enclosing type(s) (if any), declaringType.GetGenericArguments() ",
"// will return objects not equal to this type's generic parameters. Since the call to SetDeclaringType below needs to replace the those type ",
"// parameters with type arguments, add a mapping for the declaring type's generic parameters in addition to this type's generic parameters.",
"// ReSharper disable ConditionIsAlwaysTrueOrFalse // ReSharper is wrong here, declaringType can be null.",
"// ReSharper restore ConditionIsAlwaysTrueOrFalse",
"// Add own instantation to context before substituting any generic parameters. ",
"// ReSharper disable ConditionIsAlwaysTrueOrFalse // ReSharper is wrong here, declaringType can be null.",
"// ReSharper restore ConditionIsAlwaysTrueOrFalse"
] |
[
{
"param": "CustomType",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "CustomType",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": [
{
"identifier": "remarks",
"docstring": "Instances of this class are returned by and implement value equality.",
"docstring_tokens": [
"Instances",
"of",
"this",
"class",
"are",
"returned",
"by",
"and",
"implement",
"value",
"equality",
"."
]
}
]
}
| false
| 19
| 1,501
| 89
|
dcf56e779c16e2a309b9c1e1719c4a57bea1f895
|
blavalla/stetho
|
stetho/src/main/java/com/facebook/stetho/server/ProtocolDetectingSocketHandler.java
|
[
"BSD-3-Clause"
] |
Java
|
ProtocolDetectingSocketHandler
|
/**
* Socket handler which is designed to detect a difference in protocol signatures very early on
* in the connection to figure out which real handler to route to. This is used for performance
* and backwards compatibility reasons to maintain Stetho having just one actual socket
* connection despite dumpapp and DevTools now diverging in protocol.
* <p />
* Note this trick is only possible if the protocol requires that the client initiate the
* conversation. Otherwise, the server would be expected to say something before we know what
* protocol the client is speaking.
*/
|
Socket handler which is designed to detect a difference in protocol signatures very early on
in the connection to figure out which real handler to route to. This is used for performance
and backwards compatibility reasons to maintain Stetho having just one actual socket
connection despite dumpapp and DevTools now diverging in protocol.
Note this trick is only possible if the protocol requires that the client initiate the
conversation. Otherwise, the server would be expected to say something before we know what
protocol the client is speaking.
|
[
"Socket",
"handler",
"which",
"is",
"designed",
"to",
"detect",
"a",
"difference",
"in",
"protocol",
"signatures",
"very",
"early",
"on",
"in",
"the",
"connection",
"to",
"figure",
"out",
"which",
"real",
"handler",
"to",
"route",
"to",
".",
"This",
"is",
"used",
"for",
"performance",
"and",
"backwards",
"compatibility",
"reasons",
"to",
"maintain",
"Stetho",
"having",
"just",
"one",
"actual",
"socket",
"connection",
"despite",
"dumpapp",
"and",
"DevTools",
"now",
"diverging",
"in",
"protocol",
".",
"Note",
"this",
"trick",
"is",
"only",
"possible",
"if",
"the",
"protocol",
"requires",
"that",
"the",
"client",
"initiate",
"the",
"conversation",
".",
"Otherwise",
"the",
"server",
"would",
"be",
"expected",
"to",
"say",
"something",
"before",
"we",
"know",
"what",
"protocol",
"the",
"client",
"is",
"speaking",
"."
] |
public class ProtocolDetectingSocketHandler extends SecureSocketHandler {
private static final int SENSING_BUFFER_SIZE = 256;
private final ArrayList<HandlerInfo> mHandlers = new ArrayList<>(2);
public ProtocolDetectingSocketHandler(Context context) {
super(context);
}
public void addHandler(MagicMatcher magicMatcher, SocketLikeHandler handler) {
mHandlers.add(new HandlerInfo(magicMatcher, handler));
}
@Override
protected void onSecured(LocalSocket socket) throws IOException {
LeakyBufferedInputStream leakyIn = new LeakyBufferedInputStream(
socket.getInputStream(),
SENSING_BUFFER_SIZE);
if (mHandlers.isEmpty()) {
throw new IllegalStateException("No handlers added");
}
for (int i = 0, N = mHandlers.size(); i < N; i++) {
HandlerInfo handlerInfo = mHandlers.get(i);
leakyIn.mark(SENSING_BUFFER_SIZE);
boolean matches = handlerInfo.magicMatcher.matches(leakyIn);
leakyIn.reset();
if (matches) {
SocketLike socketLike = new SocketLike(socket, leakyIn);
handlerInfo.handler.onAccepted(socketLike);
return;
}
}
throw new IOException("No matching handler, firstByte=" + leakyIn.read());
}
public interface MagicMatcher {
boolean matches(InputStream in) throws IOException;
}
public static class ExactMagicMatcher implements MagicMatcher {
private final byte[] mMagic;
public ExactMagicMatcher(byte[] magic) {
mMagic = magic;
}
@Override
public boolean matches(InputStream in) throws IOException {
byte[] buf = new byte[mMagic.length];
int n = in.read(buf);
return n == buf.length && Arrays.equals(buf, mMagic);
}
}
public static class AlwaysMatchMatcher implements MagicMatcher {
@Override
public boolean matches(InputStream in) throws IOException {
return true;
}
}
private static class HandlerInfo {
public final MagicMatcher magicMatcher;
public final SocketLikeHandler handler;
private HandlerInfo(MagicMatcher magicMatcher, SocketLikeHandler handler) {
this.magicMatcher = magicMatcher;
this.handler = handler;
}
}
}
|
[
"public",
"class",
"ProtocolDetectingSocketHandler",
"extends",
"SecureSocketHandler",
"{",
"private",
"static",
"final",
"int",
"SENSING_BUFFER_SIZE",
"=",
"256",
";",
"private",
"final",
"ArrayList",
"<",
"HandlerInfo",
">",
"mHandlers",
"=",
"new",
"ArrayList",
"<",
">",
"(",
"2",
")",
";",
"public",
"ProtocolDetectingSocketHandler",
"(",
"Context",
"context",
")",
"{",
"super",
"(",
"context",
")",
";",
"}",
"public",
"void",
"addHandler",
"(",
"MagicMatcher",
"magicMatcher",
",",
"SocketLikeHandler",
"handler",
")",
"{",
"mHandlers",
".",
"add",
"(",
"new",
"HandlerInfo",
"(",
"magicMatcher",
",",
"handler",
")",
")",
";",
"}",
"@",
"Override",
"protected",
"void",
"onSecured",
"(",
"LocalSocket",
"socket",
")",
"throws",
"IOException",
"{",
"LeakyBufferedInputStream",
"leakyIn",
"=",
"new",
"LeakyBufferedInputStream",
"(",
"socket",
".",
"getInputStream",
"(",
")",
",",
"SENSING_BUFFER_SIZE",
")",
";",
"if",
"(",
"mHandlers",
".",
"isEmpty",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"",
"No handlers added",
"\"",
")",
";",
"}",
"for",
"(",
"int",
"i",
"=",
"0",
",",
"N",
"=",
"mHandlers",
".",
"size",
"(",
")",
";",
"i",
"<",
"N",
";",
"i",
"++",
")",
"{",
"HandlerInfo",
"handlerInfo",
"=",
"mHandlers",
".",
"get",
"(",
"i",
")",
";",
"leakyIn",
".",
"mark",
"(",
"SENSING_BUFFER_SIZE",
")",
";",
"boolean",
"matches",
"=",
"handlerInfo",
".",
"magicMatcher",
".",
"matches",
"(",
"leakyIn",
")",
";",
"leakyIn",
".",
"reset",
"(",
")",
";",
"if",
"(",
"matches",
")",
"{",
"SocketLike",
"socketLike",
"=",
"new",
"SocketLike",
"(",
"socket",
",",
"leakyIn",
")",
";",
"handlerInfo",
".",
"handler",
".",
"onAccepted",
"(",
"socketLike",
")",
";",
"return",
";",
"}",
"}",
"throw",
"new",
"IOException",
"(",
"\"",
"No matching handler, firstByte=",
"\"",
"+",
"leakyIn",
".",
"read",
"(",
")",
")",
";",
"}",
"public",
"interface",
"MagicMatcher",
"{",
"boolean",
"matches",
"(",
"InputStream",
"in",
")",
"throws",
"IOException",
";",
"}",
"public",
"static",
"class",
"ExactMagicMatcher",
"implements",
"MagicMatcher",
"{",
"private",
"final",
"byte",
"[",
"]",
"mMagic",
";",
"public",
"ExactMagicMatcher",
"(",
"byte",
"[",
"]",
"magic",
")",
"{",
"mMagic",
"=",
"magic",
";",
"}",
"@",
"Override",
"public",
"boolean",
"matches",
"(",
"InputStream",
"in",
")",
"throws",
"IOException",
"{",
"byte",
"[",
"]",
"buf",
"=",
"new",
"byte",
"[",
"mMagic",
".",
"length",
"]",
";",
"int",
"n",
"=",
"in",
".",
"read",
"(",
"buf",
")",
";",
"return",
"n",
"==",
"buf",
".",
"length",
"&&",
"Arrays",
".",
"equals",
"(",
"buf",
",",
"mMagic",
")",
";",
"}",
"}",
"public",
"static",
"class",
"AlwaysMatchMatcher",
"implements",
"MagicMatcher",
"{",
"@",
"Override",
"public",
"boolean",
"matches",
"(",
"InputStream",
"in",
")",
"throws",
"IOException",
"{",
"return",
"true",
";",
"}",
"}",
"private",
"static",
"class",
"HandlerInfo",
"{",
"public",
"final",
"MagicMatcher",
"magicMatcher",
";",
"public",
"final",
"SocketLikeHandler",
"handler",
";",
"private",
"HandlerInfo",
"(",
"MagicMatcher",
"magicMatcher",
",",
"SocketLikeHandler",
"handler",
")",
"{",
"this",
".",
"magicMatcher",
"=",
"magicMatcher",
";",
"this",
".",
"handler",
"=",
"handler",
";",
"}",
"}",
"}"
] |
Socket handler which is designed to detect a difference in protocol signatures very early on
in the connection to figure out which real handler to route to.
|
[
"Socket",
"handler",
"which",
"is",
"designed",
"to",
"detect",
"a",
"difference",
"in",
"protocol",
"signatures",
"very",
"early",
"on",
"in",
"the",
"connection",
"to",
"figure",
"out",
"which",
"real",
"handler",
"to",
"route",
"to",
"."
] |
[] |
[
{
"param": "SecureSocketHandler",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "SecureSocketHandler",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 13
| 473
| 117
|
db5c765a625adac6886103517ffbfd3cd04397be
|
PotosnakW/auton-survival
|
auton_survival/models/cph/__init__.py
|
[
"MIT"
] |
Python
|
DeepCoxPH
|
A Deep Cox Proportional Hazards model.
This is the main interface to a Deep Cox Proportional Hazards model.
A model is instantiated with approporiate set of hyperparameters and
fit on numpy arrays consisting of the features, event/censoring times
and the event/censoring indicators.
For full details on Deep Cox Proportional Hazards, refer [1], [2].
References
----------
[1] <a href="https://arxiv.org/abs/1606.00931">DeepSurv: personalized
treatment recommender system using a Cox proportional hazards
deep neural network. BMC medical research methodology (2018)</a>
[2] <a href="https://onlinelibrary.wiley.com/doi/pdf/10.1002/sim.4780140108">
A neural network model for survival data. Statistics in medicine (1995)</a>
Parameters
----------
k: int
The number of underlying Cox distributions.
layers: list
A list of integers consisting of the number of neurons in each
hidden layer.
random_seed: int
Controls the reproducibility of called functions.
Example
-------
>>> from auton_survival import DeepCoxPH
>>> model = DeepCoxPH()
>>> model.fit(x, t, e)
|
A Deep Cox Proportional Hazards model.
This is the main interface to a Deep Cox Proportional Hazards model.
A model is instantiated with approporiate set of hyperparameters and
fit on numpy arrays consisting of the features, event/censoring times
and the event/censoring indicators.
For full details on Deep Cox Proportional Hazards, refer [1], [2].
References
[1] DeepSurv: personalized
treatment recommender system using a Cox proportional hazards
deep neural network. BMC medical research methodology (2018)
[2]
A neural network model for survival data. Statistics in medicine (1995)
Parameters
int
The number of underlying Cox distributions.
layers: list
A list of integers consisting of the number of neurons in each
hidden layer.
random_seed: int
Controls the reproducibility of called functions.
Example
|
[
"A",
"Deep",
"Cox",
"Proportional",
"Hazards",
"model",
".",
"This",
"is",
"the",
"main",
"interface",
"to",
"a",
"Deep",
"Cox",
"Proportional",
"Hazards",
"model",
".",
"A",
"model",
"is",
"instantiated",
"with",
"approporiate",
"set",
"of",
"hyperparameters",
"and",
"fit",
"on",
"numpy",
"arrays",
"consisting",
"of",
"the",
"features",
"event",
"/",
"censoring",
"times",
"and",
"the",
"event",
"/",
"censoring",
"indicators",
".",
"For",
"full",
"details",
"on",
"Deep",
"Cox",
"Proportional",
"Hazards",
"refer",
"[",
"1",
"]",
"[",
"2",
"]",
".",
"References",
"[",
"1",
"]",
"DeepSurv",
":",
"personalized",
"treatment",
"recommender",
"system",
"using",
"a",
"Cox",
"proportional",
"hazards",
"deep",
"neural",
"network",
".",
"BMC",
"medical",
"research",
"methodology",
"(",
"2018",
")",
"[",
"2",
"]",
"A",
"neural",
"network",
"model",
"for",
"survival",
"data",
".",
"Statistics",
"in",
"medicine",
"(",
"1995",
")",
"Parameters",
"int",
"The",
"number",
"of",
"underlying",
"Cox",
"distributions",
".",
"layers",
":",
"list",
"A",
"list",
"of",
"integers",
"consisting",
"of",
"the",
"number",
"of",
"neurons",
"in",
"each",
"hidden",
"layer",
".",
"random_seed",
":",
"int",
"Controls",
"the",
"reproducibility",
"of",
"called",
"functions",
".",
"Example"
] |
class DeepCoxPH:
"""A Deep Cox Proportional Hazards model.
This is the main interface to a Deep Cox Proportional Hazards model.
A model is instantiated with approporiate set of hyperparameters and
fit on numpy arrays consisting of the features, event/censoring times
and the event/censoring indicators.
For full details on Deep Cox Proportional Hazards, refer [1], [2].
References
----------
[1] <a href="https://arxiv.org/abs/1606.00931">DeepSurv: personalized
treatment recommender system using a Cox proportional hazards
deep neural network. BMC medical research methodology (2018)</a>
[2] <a href="https://onlinelibrary.wiley.com/doi/pdf/10.1002/sim.4780140108">
A neural network model for survival data. Statistics in medicine (1995)</a>
Parameters
----------
k: int
The number of underlying Cox distributions.
layers: list
A list of integers consisting of the number of neurons in each
hidden layer.
random_seed: int
Controls the reproducibility of called functions.
Example
-------
>>> from auton_survival import DeepCoxPH
>>> model = DeepCoxPH()
>>> model.fit(x, t, e)
"""
def __init__(self, layers=None, random_seed=0):
self.layers = layers
self.fitted = False
self.random_seed = random_seed
def __call__(self):
if self.fitted:
print("A fitted instance of the Deep Cox PH model")
else:
print("An unfitted instance of the Deep Cox PH model")
print("Hidden Layers:", self.layers)
def _preprocess_test_data(self, x):
return torch.from_numpy(x).float()
def _preprocess_training_data(self, x, t, e, vsize, val_data, random_seed):
idx = list(range(x.shape[0]))
np.random.seed(random_seed)
np.random.shuffle(idx)
x_train, t_train, e_train = x[idx], t[idx], e[idx]
x_train = torch.from_numpy(x_train).float()
t_train = torch.from_numpy(t_train).float()
e_train = torch.from_numpy(e_train).float()
if val_data is None:
vsize = int(vsize*x_train.shape[0])
x_val, t_val, e_val = x_train[-vsize:], t_train[-vsize:], e_train[-vsize:]
x_train = x_train[:-vsize]
t_train = t_train[:-vsize]
e_train = e_train[:-vsize]
else:
x_val, t_val, e_val = val_data
x_val = torch.from_numpy(x_val).float()
t_val = torch.from_numpy(t_val).float()
e_val = torch.from_numpy(e_val).float()
return (x_train, t_train, e_train, x_val, t_val, e_val)
def _gen_torch_model(self, inputdim, optimizer):
"""Helper function to return a torch model."""
# Add random seed to get the same results like in dcm __init__.py
np.random.seed(self.random_seed)
torch.manual_seed(self.random_seed)
return DeepCoxPHTorch(inputdim, layers=self.layers,
optimizer=optimizer)
def fit(self, x, t, e, vsize=0.15, val_data=None,
iters=1, learning_rate=1e-3, batch_size=100,
optimizer="Adam"):
r"""This method is used to train an instance of the DSM model.
Parameters
----------
x: np.ndarray
A numpy array of the input features, \( x \).
t: np.ndarray
A numpy array of the event/censoring times, \( t \).
e: np.ndarray
A numpy array of the event/censoring indicators, \( \delta \).
\( \delta = 1 \) means the event took place.
vsize: float
Amount of data to set aside as the validation set.
val_data: tuple
A tuple of the validation dataset. If passed vsize is ignored.
iters: int
The maximum number of training iterations on the training dataset.
learning_rate: float
The learning rate for the `Adam` optimizer.
batch_size: int
learning is performed on mini-batches of input data. this parameter
specifies the size of each mini-batch.
optimizer: str
The choice of the gradient based optimization method. One of
'Adam', 'RMSProp' or 'SGD'.
"""
processed_data = self._preprocess_training_data(x, t, e,
vsize, val_data,
self.random_seed)
x_train, t_train, e_train, x_val, t_val, e_val = processed_data
#Todo: Change this somehow. The base design shouldn't depend on child
inputdim = x_train.shape[-1]
model = self._gen_torch_model(inputdim, optimizer)
model, _ = train_dcph(model,
(x_train, t_train, e_train),
(x_val, t_val, e_val),
epochs=iters,
lr=learning_rate,
bs=batch_size,
return_losses=True,
random_seed=self.random_seed)
self.torch_model = (model[0].eval(), model[1])
self.fitted = True
return self
def predict_risk(self, x, t=None):
if self.fitted:
return 1-self.predict_survival(x, t)
else:
raise Exception("The model has not been fitted yet. Please fit the " +
"model using the `fit` method on some training data " +
"before calling `predict_risk`.")
def predict_survival(self, x, t=None):
r"""Returns the estimated survival probability at time \( t \),
\( \widehat{\mathbb{P}}(T > t|X) \) for some input data \( x \).
Parameters
----------
x: np.ndarray
A numpy array of the input features, \( x \).
t: list or float
a list or float of the times at which survival probability is
to be computed
Returns:
np.array: numpy array of the survival probabilites at each time in t.
"""
if not self.fitted:
raise Exception("The model has not been fitted yet. Please fit the " +
"model using the `fit` method on some training data " +
"before calling `predict_survival`.")
x = self._preprocess_test_data(x)
if t is not None:
if not isinstance(t, list):
t = [t]
scores = predict_survival(self.torch_model, x, t)
return scores
|
[
"class",
"DeepCoxPH",
":",
"def",
"__init__",
"(",
"self",
",",
"layers",
"=",
"None",
",",
"random_seed",
"=",
"0",
")",
":",
"self",
".",
"layers",
"=",
"layers",
"self",
".",
"fitted",
"=",
"False",
"self",
".",
"random_seed",
"=",
"random_seed",
"def",
"__call__",
"(",
"self",
")",
":",
"if",
"self",
".",
"fitted",
":",
"print",
"(",
"\"A fitted instance of the Deep Cox PH model\"",
")",
"else",
":",
"print",
"(",
"\"An unfitted instance of the Deep Cox PH model\"",
")",
"print",
"(",
"\"Hidden Layers:\"",
",",
"self",
".",
"layers",
")",
"def",
"_preprocess_test_data",
"(",
"self",
",",
"x",
")",
":",
"return",
"torch",
".",
"from_numpy",
"(",
"x",
")",
".",
"float",
"(",
")",
"def",
"_preprocess_training_data",
"(",
"self",
",",
"x",
",",
"t",
",",
"e",
",",
"vsize",
",",
"val_data",
",",
"random_seed",
")",
":",
"idx",
"=",
"list",
"(",
"range",
"(",
"x",
".",
"shape",
"[",
"0",
"]",
")",
")",
"np",
".",
"random",
".",
"seed",
"(",
"random_seed",
")",
"np",
".",
"random",
".",
"shuffle",
"(",
"idx",
")",
"x_train",
",",
"t_train",
",",
"e_train",
"=",
"x",
"[",
"idx",
"]",
",",
"t",
"[",
"idx",
"]",
",",
"e",
"[",
"idx",
"]",
"x_train",
"=",
"torch",
".",
"from_numpy",
"(",
"x_train",
")",
".",
"float",
"(",
")",
"t_train",
"=",
"torch",
".",
"from_numpy",
"(",
"t_train",
")",
".",
"float",
"(",
")",
"e_train",
"=",
"torch",
".",
"from_numpy",
"(",
"e_train",
")",
".",
"float",
"(",
")",
"if",
"val_data",
"is",
"None",
":",
"vsize",
"=",
"int",
"(",
"vsize",
"*",
"x_train",
".",
"shape",
"[",
"0",
"]",
")",
"x_val",
",",
"t_val",
",",
"e_val",
"=",
"x_train",
"[",
"-",
"vsize",
":",
"]",
",",
"t_train",
"[",
"-",
"vsize",
":",
"]",
",",
"e_train",
"[",
"-",
"vsize",
":",
"]",
"x_train",
"=",
"x_train",
"[",
":",
"-",
"vsize",
"]",
"t_train",
"=",
"t_train",
"[",
":",
"-",
"vsize",
"]",
"e_train",
"=",
"e_train",
"[",
":",
"-",
"vsize",
"]",
"else",
":",
"x_val",
",",
"t_val",
",",
"e_val",
"=",
"val_data",
"x_val",
"=",
"torch",
".",
"from_numpy",
"(",
"x_val",
")",
".",
"float",
"(",
")",
"t_val",
"=",
"torch",
".",
"from_numpy",
"(",
"t_val",
")",
".",
"float",
"(",
")",
"e_val",
"=",
"torch",
".",
"from_numpy",
"(",
"e_val",
")",
".",
"float",
"(",
")",
"return",
"(",
"x_train",
",",
"t_train",
",",
"e_train",
",",
"x_val",
",",
"t_val",
",",
"e_val",
")",
"def",
"_gen_torch_model",
"(",
"self",
",",
"inputdim",
",",
"optimizer",
")",
":",
"\"\"\"Helper function to return a torch model.\"\"\"",
"np",
".",
"random",
".",
"seed",
"(",
"self",
".",
"random_seed",
")",
"torch",
".",
"manual_seed",
"(",
"self",
".",
"random_seed",
")",
"return",
"DeepCoxPHTorch",
"(",
"inputdim",
",",
"layers",
"=",
"self",
".",
"layers",
",",
"optimizer",
"=",
"optimizer",
")",
"def",
"fit",
"(",
"self",
",",
"x",
",",
"t",
",",
"e",
",",
"vsize",
"=",
"0.15",
",",
"val_data",
"=",
"None",
",",
"iters",
"=",
"1",
",",
"learning_rate",
"=",
"1e-3",
",",
"batch_size",
"=",
"100",
",",
"optimizer",
"=",
"\"Adam\"",
")",
":",
"r\"\"\"This method is used to train an instance of the DSM model.\n\n Parameters\n ----------\n x: np.ndarray\n A numpy array of the input features, \\( x \\).\n t: np.ndarray\n A numpy array of the event/censoring times, \\( t \\).\n e: np.ndarray\n A numpy array of the event/censoring indicators, \\( \\delta \\).\n \\( \\delta = 1 \\) means the event took place.\n vsize: float\n Amount of data to set aside as the validation set.\n val_data: tuple\n A tuple of the validation dataset. If passed vsize is ignored.\n iters: int\n The maximum number of training iterations on the training dataset.\n learning_rate: float\n The learning rate for the `Adam` optimizer.\n batch_size: int\n learning is performed on mini-batches of input data. this parameter\n specifies the size of each mini-batch.\n optimizer: str\n The choice of the gradient based optimization method. One of\n 'Adam', 'RMSProp' or 'SGD'.\n \n \"\"\"",
"processed_data",
"=",
"self",
".",
"_preprocess_training_data",
"(",
"x",
",",
"t",
",",
"e",
",",
"vsize",
",",
"val_data",
",",
"self",
".",
"random_seed",
")",
"x_train",
",",
"t_train",
",",
"e_train",
",",
"x_val",
",",
"t_val",
",",
"e_val",
"=",
"processed_data",
"inputdim",
"=",
"x_train",
".",
"shape",
"[",
"-",
"1",
"]",
"model",
"=",
"self",
".",
"_gen_torch_model",
"(",
"inputdim",
",",
"optimizer",
")",
"model",
",",
"_",
"=",
"train_dcph",
"(",
"model",
",",
"(",
"x_train",
",",
"t_train",
",",
"e_train",
")",
",",
"(",
"x_val",
",",
"t_val",
",",
"e_val",
")",
",",
"epochs",
"=",
"iters",
",",
"lr",
"=",
"learning_rate",
",",
"bs",
"=",
"batch_size",
",",
"return_losses",
"=",
"True",
",",
"random_seed",
"=",
"self",
".",
"random_seed",
")",
"self",
".",
"torch_model",
"=",
"(",
"model",
"[",
"0",
"]",
".",
"eval",
"(",
")",
",",
"model",
"[",
"1",
"]",
")",
"self",
".",
"fitted",
"=",
"True",
"return",
"self",
"def",
"predict_risk",
"(",
"self",
",",
"x",
",",
"t",
"=",
"None",
")",
":",
"if",
"self",
".",
"fitted",
":",
"return",
"1",
"-",
"self",
".",
"predict_survival",
"(",
"x",
",",
"t",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"The model has not been fitted yet. Please fit the \"",
"+",
"\"model using the `fit` method on some training data \"",
"+",
"\"before calling `predict_risk`.\"",
")",
"def",
"predict_survival",
"(",
"self",
",",
"x",
",",
"t",
"=",
"None",
")",
":",
"r\"\"\"Returns the estimated survival probability at time \\( t \\),\n \\( \\widehat{\\mathbb{P}}(T > t|X) \\) for some input data \\( x \\).\n\n Parameters\n ----------\n x: np.ndarray\n A numpy array of the input features, \\( x \\).\n t: list or float\n a list or float of the times at which survival probability is\n to be computed\n Returns:\n np.array: numpy array of the survival probabilites at each time in t.\n\n \"\"\"",
"if",
"not",
"self",
".",
"fitted",
":",
"raise",
"Exception",
"(",
"\"The model has not been fitted yet. Please fit the \"",
"+",
"\"model using the `fit` method on some training data \"",
"+",
"\"before calling `predict_survival`.\"",
")",
"x",
"=",
"self",
".",
"_preprocess_test_data",
"(",
"x",
")",
"if",
"t",
"is",
"not",
"None",
":",
"if",
"not",
"isinstance",
"(",
"t",
",",
"list",
")",
":",
"t",
"=",
"[",
"t",
"]",
"scores",
"=",
"predict_survival",
"(",
"self",
".",
"torch_model",
",",
"x",
",",
"t",
")",
"return",
"scores"
] |
A Deep Cox Proportional Hazards model.
|
[
"A",
"Deep",
"Cox",
"Proportional",
"Hazards",
"model",
"."
] |
[
"\"\"\"A Deep Cox Proportional Hazards model.\n\n This is the main interface to a Deep Cox Proportional Hazards model.\n A model is instantiated with approporiate set of hyperparameters and\n fit on numpy arrays consisting of the features, event/censoring times\n and the event/censoring indicators.\n\n For full details on Deep Cox Proportional Hazards, refer [1], [2].\n\n References\n ----------\n [1] <a href=\"https://arxiv.org/abs/1606.00931\">DeepSurv: personalized\n treatment recommender system using a Cox proportional hazards\n deep neural network. BMC medical research methodology (2018)</a>\n\n [2] <a href=\"https://onlinelibrary.wiley.com/doi/pdf/10.1002/sim.4780140108\">\n A neural network model for survival data. Statistics in medicine (1995)</a>\n\n Parameters\n ----------\n k: int\n The number of underlying Cox distributions.\n layers: list\n A list of integers consisting of the number of neurons in each\n hidden layer.\n random_seed: int\n Controls the reproducibility of called functions.\n Example\n -------\n >>> from auton_survival import DeepCoxPH\n >>> model = DeepCoxPH()\n >>> model.fit(x, t, e)\n\n \"\"\"",
"\"\"\"Helper function to return a torch model.\"\"\"",
"# Add random seed to get the same results like in dcm __init__.py",
"r\"\"\"This method is used to train an instance of the DSM model.\n\n Parameters\n ----------\n x: np.ndarray\n A numpy array of the input features, \\( x \\).\n t: np.ndarray\n A numpy array of the event/censoring times, \\( t \\).\n e: np.ndarray\n A numpy array of the event/censoring indicators, \\( \\delta \\).\n \\( \\delta = 1 \\) means the event took place.\n vsize: float\n Amount of data to set aside as the validation set.\n val_data: tuple\n A tuple of the validation dataset. If passed vsize is ignored.\n iters: int\n The maximum number of training iterations on the training dataset.\n learning_rate: float\n The learning rate for the `Adam` optimizer.\n batch_size: int\n learning is performed on mini-batches of input data. this parameter\n specifies the size of each mini-batch.\n optimizer: str\n The choice of the gradient based optimization method. One of\n 'Adam', 'RMSProp' or 'SGD'.\n \n \"\"\"",
"#Todo: Change this somehow. The base design shouldn't depend on child",
"r\"\"\"Returns the estimated survival probability at time \\( t \\),\n \\( \\widehat{\\mathbb{P}}(T > t|X) \\) for some input data \\( x \\).\n\n Parameters\n ----------\n x: np.ndarray\n A numpy array of the input features, \\( x \\).\n t: list or float\n a list or float of the times at which survival probability is\n to be computed\n Returns:\n np.array: numpy array of the survival probabilites at each time in t.\n\n \"\"\""
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 14
| 1,535
| 311
|
8eb435a51555f2d543210af301f36dc25badee89
|
jbellis/j2cl
|
transpiler/java/com/google/j2cl/transpiler/ast/OperationExpansionUtils.java
|
[
"Apache-2.0"
] |
Java
|
OperationExpansionUtils
|
/**
* Utility functions for expanding assignment, increment and decrement expressions.
*
* <p>For example:
*
* <ul>
* <li>i++ becomes i = i + 1
* <li>a = i++ becomes a = (v = i, i = i + 1, v)
* <li>a = change().i++ becomes a = (q = change(), v = q.i, q.i = q.i + 1, v)
* </ul>
*
* <p>This kind of rewrite is useful when the numeric type in question is represented by an
* immutable emulation class or when a conversion operation (such as boxing or unboxing) needs to be
* inserted between the numeric and assignment stages of an operation.
*/
|
Utility functions for expanding assignment, increment and decrement expressions.
For example.
This kind of rewrite is useful when the numeric type in question is represented by an
immutable emulation class or when a conversion operation (such as boxing or unboxing) needs to be
inserted between the numeric and assignment stages of an operation.
|
[
"Utility",
"functions",
"for",
"expanding",
"assignment",
"increment",
"and",
"decrement",
"expressions",
".",
"For",
"example",
".",
"This",
"kind",
"of",
"rewrite",
"is",
"useful",
"when",
"the",
"numeric",
"type",
"in",
"question",
"is",
"represented",
"by",
"an",
"immutable",
"emulation",
"class",
"or",
"when",
"a",
"conversion",
"operation",
"(",
"such",
"as",
"boxing",
"or",
"unboxing",
")",
"needs",
"to",
"be",
"inserted",
"between",
"the",
"numeric",
"and",
"assignment",
"stages",
"of",
"an",
"operation",
"."
] |
public class OperationExpansionUtils {
public static Expression expandCompoundExpression(BinaryExpression binaryExpression) {
checkArgument(binaryExpression.getOperator().isCompoundAssignment());
BinaryOperator operator = binaryExpression.getOperator();
Expression leftOperand = binaryExpression.getLeftOperand();
Expression rightOperand = binaryExpression.getRightOperand();
List<VariableDeclarationFragment> temporaryVariableDeclarations = new ArrayList<>();
Expression lhs =
leftOperand.isIdempotent()
? leftOperand
: decomposeLhs(leftOperand, temporaryVariableDeclarations);
return constructReturnedExpression(
temporaryVariableDeclarations,
assignToLeftOperand(lhs, operator.getUnderlyingBinaryOperator(), rightOperand));
}
/**
* Decomposes the lhs of a compound assignment (or the operand of a prefix/postfix expressions
* introducing temporary variables if necessary.
*/
private static Expression decomposeLhs(
Expression lhs, List<VariableDeclarationFragment> temporaryVariableDeclarations) {
if (lhs instanceof VariableReference) {
// The lhs will be modified but it can be safely evaluated twice in a row without caring to
// avoid double side-effects if expanded. See the counter example showing an incorrect
// rewrite:
// a[++i] += i => a[++i] = a[++i] + x
return lhs;
}
if (lhs instanceof ArrayAccess) {
return decomposeArrayAccess((ArrayAccess) lhs, temporaryVariableDeclarations);
}
checkState(lhs instanceof FieldAccess);
return decomposeFieldAccess((FieldAccess) lhs, temporaryVariableDeclarations);
}
private static FieldAccess decomposeFieldAccess(
FieldAccess lhs, List<VariableDeclarationFragment> temporaryVariableDeclarations) {
if (lhs.getTarget().isStatic()) {
// The qualifier here should not be extracted since it is a constructor reference.
//
// Note that checking idempotence of the qualifier is not correct since it might still be
// affected by the side effects in the rhs, e.g.
//
// SomeClass a = foo;
// String rv = a.result = (a = bar).toString();
//
// if this was not decomposed (because 'a' is idempotent), the above snippet would modify
// the instance 'foo' but return the value of 'bar.result' instead of 'foo.result' (see
// expandAssignmentExpression).
// What ensures correctness here without a rewrite is the qualifier being constant - not
// being idempotent.
return lhs;
}
// The qualifier is not guaranteed to be free of side effects, so evaluate it first and assign
// to a temporary variable.
Expression qualifier = lhs.getQualifier();
Variable qualifierVariable =
createTemporaryVariableDeclaration(
qualifier.getTypeDescriptor(), "$qualifier", qualifier, temporaryVariableDeclarations);
return FieldAccess.Builder.from(lhs).setQualifier(qualifierVariable.createReference()).build();
}
/** Creates a variable that holds the value of {@code expression} to avoid evaluating it twice. */
private static Variable createTemporaryVariableDeclaration(
TypeDescriptor variableType,
String variableName,
Expression expression,
List<VariableDeclarationFragment> temporaryVariableDeclarations) {
Variable qualifierVariable =
Variable.newBuilder()
.setFinal(true)
.setName(variableName)
.setTypeDescriptor(variableType)
.build();
temporaryVariableDeclarations.add(
VariableDeclarationFragment.newBuilder()
.setVariable(qualifierVariable)
.setInitializer(expression)
.build());
return qualifierVariable;
}
private static ArrayAccess decomposeArrayAccess(
ArrayAccess lhs, List<VariableDeclarationFragment> temporaryVariableDeclarations) {
Variable arrayExpressionVariable =
createTemporaryVariableDeclaration(
lhs.getArrayExpression().getTypeDescriptor(),
"$array",
lhs.getArrayExpression(),
temporaryVariableDeclarations);
Variable indexExpressionVariable =
createTemporaryVariableDeclaration(
PrimitiveTypes.INT, "$index", lhs.getIndexExpression(), temporaryVariableDeclarations);
return ArrayAccess.newBuilder()
.setArrayExpression(arrayExpressionVariable.createReference())
.setIndexExpression(indexExpressionVariable.createReference())
.build();
}
/**
* Returns a multiexpression that declares {@code temporaryVariableDeclarations} and executes
* {@code expressions}.
*/
private static Expression constructReturnedExpression(
List<VariableDeclarationFragment> temporaryVariableDeclarations, Expression... expressions) {
MultiExpression.Builder builder = MultiExpression.newBuilder();
if (!temporaryVariableDeclarations.isEmpty()) {
builder.addExpressions(
VariableDeclarationExpression.newBuilder()
.addVariableDeclarationFragments(temporaryVariableDeclarations)
.build());
}
return builder.addExpressions(expressions).build();
}
public static Expression expandExpression(PostfixExpression postfixExpression) {
Expression operand = postfixExpression.getOperand();
PostfixOperator operator = postfixExpression.getOperator();
List<VariableDeclarationFragment> temporaryVariableDeclarations = new ArrayList<>();
Expression lhs =
operand.isIdempotent() ? operand : decomposeLhs(operand, temporaryVariableDeclarations);
Variable valueVariable =
createTemporaryVariableDeclaration(
operand.getTypeDescriptor(), "$value", lhs, temporaryVariableDeclarations);
return constructReturnedExpression(
temporaryVariableDeclarations,
// a++; => (let $value = a, a = a + 1, $value)
assignToLeftOperand(
lhs.clone(),
operator.getUnderlyingBinaryOperator(),
createLiteralOne(operand.getTypeDescriptor())),
valueVariable.createReference());
}
public static Expression expandExpression(PrefixExpression prefixExpression) {
checkArgument(prefixExpression.getOperator().hasSideEffect());
Expression operand = prefixExpression.getOperand();
PrefixOperator operator = prefixExpression.getOperator();
List<VariableDeclarationFragment> temporaryVariables = new ArrayList<>();
Expression lhs = operand.isIdempotent() ? operand : decomposeLhs(operand, temporaryVariables);
return constructReturnedExpression(
temporaryVariables,
assignToLeftOperand(
lhs,
operator.getUnderlyingBinaryOperator(),
createLiteralOne(operand.getTypeDescriptor())));
}
public static Expression expandAssignmentExpression(BinaryExpression binaryExpression) {
checkArgument(binaryExpression.getOperator() == BinaryOperator.ASSIGN);
List<VariableDeclarationFragment> temporaryVariables = new ArrayList<>();
Expression newLhs = decomposeLhs(binaryExpression.getLeftOperand(), temporaryVariables);
Variable returnedVariable;
Expression newRhs = binaryExpression.getRightOperand();
if (newLhs instanceof VariableReference) {
// No need to introduce a temporary variable for the result since even if the rhs modifies it,
// it will be overwritten by the assignment operation itself.
returnedVariable = ((VariableReference) newLhs).getTarget();
} else {
returnedVariable =
createTemporaryVariableDeclaration(
newLhs.getTypeDescriptor(),
"$value",
binaryExpression.getRightOperand(),
temporaryVariables);
newRhs = returnedVariable.createReference();
}
return constructReturnedExpression(
temporaryVariables,
BinaryExpression.Builder.asAssignmentTo(newLhs).setRightOperand(newRhs).build(),
returnedVariable.createReference());
}
/** Returns number literal with value 1. */
private static NumberLiteral createLiteralOne(TypeDescriptor typeDescriptor) {
return new NumberLiteral(typeDescriptor.toUnboxedType(), 1);
}
/** Returns assignment in the form of {leftOperand = leftOperand operator (rightOperand)}. */
private static BinaryExpression assignToLeftOperand(
Expression leftOperand, BinaryOperator operator, Expression rightOperand) {
checkArgument(leftOperand.isIdempotent());
return BinaryExpression.Builder.asAssignmentTo(leftOperand)
.setRightOperand(
maybeCast(
leftOperand.getTypeDescriptor(),
BinaryExpression.newBuilder()
.setLeftOperand(leftOperand.clone())
.setOperator(operator)
.setRightOperand(rightOperand)
.build()))
.build();
}
// When expanding compound assignments (and prefix/postfix operations) there is an implicit
// (narrowing) cast that might need to be inserted.
//
// Byte b;
// ++b;
//
// is equivalent to
//
// Byte b;
// b = (byte) (b + 1);
//
@SuppressWarnings("ReferenceEquality")
private static Expression maybeCast(TypeDescriptor typeDescriptor, Expression expression) {
typeDescriptor =
TypeDescriptors.isBoxedType(typeDescriptor)
? typeDescriptor.toUnboxedType()
: typeDescriptor;
if (!TypeDescriptors.isNumericPrimitive(typeDescriptor)
|| typeDescriptor == expression.getTypeDescriptor()) {
return expression;
}
return CastExpression.newBuilder()
.setCastTypeDescriptor(typeDescriptor)
.setExpression(expression)
.build();
}
private OperationExpansionUtils() {}
}
|
[
"public",
"class",
"OperationExpansionUtils",
"{",
"public",
"static",
"Expression",
"expandCompoundExpression",
"(",
"BinaryExpression",
"binaryExpression",
")",
"{",
"checkArgument",
"(",
"binaryExpression",
".",
"getOperator",
"(",
")",
".",
"isCompoundAssignment",
"(",
")",
")",
";",
"BinaryOperator",
"operator",
"=",
"binaryExpression",
".",
"getOperator",
"(",
")",
";",
"Expression",
"leftOperand",
"=",
"binaryExpression",
".",
"getLeftOperand",
"(",
")",
";",
"Expression",
"rightOperand",
"=",
"binaryExpression",
".",
"getRightOperand",
"(",
")",
";",
"List",
"<",
"VariableDeclarationFragment",
">",
"temporaryVariableDeclarations",
"=",
"new",
"ArrayList",
"<",
">",
"(",
")",
";",
"Expression",
"lhs",
"=",
"leftOperand",
".",
"isIdempotent",
"(",
")",
"?",
"leftOperand",
":",
"decomposeLhs",
"(",
"leftOperand",
",",
"temporaryVariableDeclarations",
")",
";",
"return",
"constructReturnedExpression",
"(",
"temporaryVariableDeclarations",
",",
"assignToLeftOperand",
"(",
"lhs",
",",
"operator",
".",
"getUnderlyingBinaryOperator",
"(",
")",
",",
"rightOperand",
")",
")",
";",
"}",
"/**\n * Decomposes the lhs of a compound assignment (or the operand of a prefix/postfix expressions\n * introducing temporary variables if necessary.\n */",
"private",
"static",
"Expression",
"decomposeLhs",
"(",
"Expression",
"lhs",
",",
"List",
"<",
"VariableDeclarationFragment",
">",
"temporaryVariableDeclarations",
")",
"{",
"if",
"(",
"lhs",
"instanceof",
"VariableReference",
")",
"{",
"return",
"lhs",
";",
"}",
"if",
"(",
"lhs",
"instanceof",
"ArrayAccess",
")",
"{",
"return",
"decomposeArrayAccess",
"(",
"(",
"ArrayAccess",
")",
"lhs",
",",
"temporaryVariableDeclarations",
")",
";",
"}",
"checkState",
"(",
"lhs",
"instanceof",
"FieldAccess",
")",
";",
"return",
"decomposeFieldAccess",
"(",
"(",
"FieldAccess",
")",
"lhs",
",",
"temporaryVariableDeclarations",
")",
";",
"}",
"private",
"static",
"FieldAccess",
"decomposeFieldAccess",
"(",
"FieldAccess",
"lhs",
",",
"List",
"<",
"VariableDeclarationFragment",
">",
"temporaryVariableDeclarations",
")",
"{",
"if",
"(",
"lhs",
".",
"getTarget",
"(",
")",
".",
"isStatic",
"(",
")",
")",
"{",
"return",
"lhs",
";",
"}",
"Expression",
"qualifier",
"=",
"lhs",
".",
"getQualifier",
"(",
")",
";",
"Variable",
"qualifierVariable",
"=",
"createTemporaryVariableDeclaration",
"(",
"qualifier",
".",
"getTypeDescriptor",
"(",
")",
",",
"\"",
"$qualifier",
"\"",
",",
"qualifier",
",",
"temporaryVariableDeclarations",
")",
";",
"return",
"FieldAccess",
".",
"Builder",
".",
"from",
"(",
"lhs",
")",
".",
"setQualifier",
"(",
"qualifierVariable",
".",
"createReference",
"(",
")",
")",
".",
"build",
"(",
")",
";",
"}",
"/** Creates a variable that holds the value of {@code expression} to avoid evaluating it twice. */",
"private",
"static",
"Variable",
"createTemporaryVariableDeclaration",
"(",
"TypeDescriptor",
"variableType",
",",
"String",
"variableName",
",",
"Expression",
"expression",
",",
"List",
"<",
"VariableDeclarationFragment",
">",
"temporaryVariableDeclarations",
")",
"{",
"Variable",
"qualifierVariable",
"=",
"Variable",
".",
"newBuilder",
"(",
")",
".",
"setFinal",
"(",
"true",
")",
".",
"setName",
"(",
"variableName",
")",
".",
"setTypeDescriptor",
"(",
"variableType",
")",
".",
"build",
"(",
")",
";",
"temporaryVariableDeclarations",
".",
"add",
"(",
"VariableDeclarationFragment",
".",
"newBuilder",
"(",
")",
".",
"setVariable",
"(",
"qualifierVariable",
")",
".",
"setInitializer",
"(",
"expression",
")",
".",
"build",
"(",
")",
")",
";",
"return",
"qualifierVariable",
";",
"}",
"private",
"static",
"ArrayAccess",
"decomposeArrayAccess",
"(",
"ArrayAccess",
"lhs",
",",
"List",
"<",
"VariableDeclarationFragment",
">",
"temporaryVariableDeclarations",
")",
"{",
"Variable",
"arrayExpressionVariable",
"=",
"createTemporaryVariableDeclaration",
"(",
"lhs",
".",
"getArrayExpression",
"(",
")",
".",
"getTypeDescriptor",
"(",
")",
",",
"\"",
"$array",
"\"",
",",
"lhs",
".",
"getArrayExpression",
"(",
")",
",",
"temporaryVariableDeclarations",
")",
";",
"Variable",
"indexExpressionVariable",
"=",
"createTemporaryVariableDeclaration",
"(",
"PrimitiveTypes",
".",
"INT",
",",
"\"",
"$index",
"\"",
",",
"lhs",
".",
"getIndexExpression",
"(",
")",
",",
"temporaryVariableDeclarations",
")",
";",
"return",
"ArrayAccess",
".",
"newBuilder",
"(",
")",
".",
"setArrayExpression",
"(",
"arrayExpressionVariable",
".",
"createReference",
"(",
")",
")",
".",
"setIndexExpression",
"(",
"indexExpressionVariable",
".",
"createReference",
"(",
")",
")",
".",
"build",
"(",
")",
";",
"}",
"/**\n * Returns a multiexpression that declares {@code temporaryVariableDeclarations} and executes\n * {@code expressions}.\n */",
"private",
"static",
"Expression",
"constructReturnedExpression",
"(",
"List",
"<",
"VariableDeclarationFragment",
">",
"temporaryVariableDeclarations",
",",
"Expression",
"...",
"expressions",
")",
"{",
"MultiExpression",
".",
"Builder",
"builder",
"=",
"MultiExpression",
".",
"newBuilder",
"(",
")",
";",
"if",
"(",
"!",
"temporaryVariableDeclarations",
".",
"isEmpty",
"(",
")",
")",
"{",
"builder",
".",
"addExpressions",
"(",
"VariableDeclarationExpression",
".",
"newBuilder",
"(",
")",
".",
"addVariableDeclarationFragments",
"(",
"temporaryVariableDeclarations",
")",
".",
"build",
"(",
")",
")",
";",
"}",
"return",
"builder",
".",
"addExpressions",
"(",
"expressions",
")",
".",
"build",
"(",
")",
";",
"}",
"public",
"static",
"Expression",
"expandExpression",
"(",
"PostfixExpression",
"postfixExpression",
")",
"{",
"Expression",
"operand",
"=",
"postfixExpression",
".",
"getOperand",
"(",
")",
";",
"PostfixOperator",
"operator",
"=",
"postfixExpression",
".",
"getOperator",
"(",
")",
";",
"List",
"<",
"VariableDeclarationFragment",
">",
"temporaryVariableDeclarations",
"=",
"new",
"ArrayList",
"<",
">",
"(",
")",
";",
"Expression",
"lhs",
"=",
"operand",
".",
"isIdempotent",
"(",
")",
"?",
"operand",
":",
"decomposeLhs",
"(",
"operand",
",",
"temporaryVariableDeclarations",
")",
";",
"Variable",
"valueVariable",
"=",
"createTemporaryVariableDeclaration",
"(",
"operand",
".",
"getTypeDescriptor",
"(",
")",
",",
"\"",
"$value",
"\"",
",",
"lhs",
",",
"temporaryVariableDeclarations",
")",
";",
"return",
"constructReturnedExpression",
"(",
"temporaryVariableDeclarations",
",",
"assignToLeftOperand",
"(",
"lhs",
".",
"clone",
"(",
")",
",",
"operator",
".",
"getUnderlyingBinaryOperator",
"(",
")",
",",
"createLiteralOne",
"(",
"operand",
".",
"getTypeDescriptor",
"(",
")",
")",
")",
",",
"valueVariable",
".",
"createReference",
"(",
")",
")",
";",
"}",
"public",
"static",
"Expression",
"expandExpression",
"(",
"PrefixExpression",
"prefixExpression",
")",
"{",
"checkArgument",
"(",
"prefixExpression",
".",
"getOperator",
"(",
")",
".",
"hasSideEffect",
"(",
")",
")",
";",
"Expression",
"operand",
"=",
"prefixExpression",
".",
"getOperand",
"(",
")",
";",
"PrefixOperator",
"operator",
"=",
"prefixExpression",
".",
"getOperator",
"(",
")",
";",
"List",
"<",
"VariableDeclarationFragment",
">",
"temporaryVariables",
"=",
"new",
"ArrayList",
"<",
">",
"(",
")",
";",
"Expression",
"lhs",
"=",
"operand",
".",
"isIdempotent",
"(",
")",
"?",
"operand",
":",
"decomposeLhs",
"(",
"operand",
",",
"temporaryVariables",
")",
";",
"return",
"constructReturnedExpression",
"(",
"temporaryVariables",
",",
"assignToLeftOperand",
"(",
"lhs",
",",
"operator",
".",
"getUnderlyingBinaryOperator",
"(",
")",
",",
"createLiteralOne",
"(",
"operand",
".",
"getTypeDescriptor",
"(",
")",
")",
")",
")",
";",
"}",
"public",
"static",
"Expression",
"expandAssignmentExpression",
"(",
"BinaryExpression",
"binaryExpression",
")",
"{",
"checkArgument",
"(",
"binaryExpression",
".",
"getOperator",
"(",
")",
"==",
"BinaryOperator",
".",
"ASSIGN",
")",
";",
"List",
"<",
"VariableDeclarationFragment",
">",
"temporaryVariables",
"=",
"new",
"ArrayList",
"<",
">",
"(",
")",
";",
"Expression",
"newLhs",
"=",
"decomposeLhs",
"(",
"binaryExpression",
".",
"getLeftOperand",
"(",
")",
",",
"temporaryVariables",
")",
";",
"Variable",
"returnedVariable",
";",
"Expression",
"newRhs",
"=",
"binaryExpression",
".",
"getRightOperand",
"(",
")",
";",
"if",
"(",
"newLhs",
"instanceof",
"VariableReference",
")",
"{",
"returnedVariable",
"=",
"(",
"(",
"VariableReference",
")",
"newLhs",
")",
".",
"getTarget",
"(",
")",
";",
"}",
"else",
"{",
"returnedVariable",
"=",
"createTemporaryVariableDeclaration",
"(",
"newLhs",
".",
"getTypeDescriptor",
"(",
")",
",",
"\"",
"$value",
"\"",
",",
"binaryExpression",
".",
"getRightOperand",
"(",
")",
",",
"temporaryVariables",
")",
";",
"newRhs",
"=",
"returnedVariable",
".",
"createReference",
"(",
")",
";",
"}",
"return",
"constructReturnedExpression",
"(",
"temporaryVariables",
",",
"BinaryExpression",
".",
"Builder",
".",
"asAssignmentTo",
"(",
"newLhs",
")",
".",
"setRightOperand",
"(",
"newRhs",
")",
".",
"build",
"(",
")",
",",
"returnedVariable",
".",
"createReference",
"(",
")",
")",
";",
"}",
"/** Returns number literal with value 1. */",
"private",
"static",
"NumberLiteral",
"createLiteralOne",
"(",
"TypeDescriptor",
"typeDescriptor",
")",
"{",
"return",
"new",
"NumberLiteral",
"(",
"typeDescriptor",
".",
"toUnboxedType",
"(",
")",
",",
"1",
")",
";",
"}",
"/** Returns assignment in the form of {leftOperand = leftOperand operator (rightOperand)}. */",
"private",
"static",
"BinaryExpression",
"assignToLeftOperand",
"(",
"Expression",
"leftOperand",
",",
"BinaryOperator",
"operator",
",",
"Expression",
"rightOperand",
")",
"{",
"checkArgument",
"(",
"leftOperand",
".",
"isIdempotent",
"(",
")",
")",
";",
"return",
"BinaryExpression",
".",
"Builder",
".",
"asAssignmentTo",
"(",
"leftOperand",
")",
".",
"setRightOperand",
"(",
"maybeCast",
"(",
"leftOperand",
".",
"getTypeDescriptor",
"(",
")",
",",
"BinaryExpression",
".",
"newBuilder",
"(",
")",
".",
"setLeftOperand",
"(",
"leftOperand",
".",
"clone",
"(",
")",
")",
".",
"setOperator",
"(",
"operator",
")",
".",
"setRightOperand",
"(",
"rightOperand",
")",
".",
"build",
"(",
")",
")",
")",
".",
"build",
"(",
")",
";",
"}",
"@",
"SuppressWarnings",
"(",
"\"",
"ReferenceEquality",
"\"",
")",
"private",
"static",
"Expression",
"maybeCast",
"(",
"TypeDescriptor",
"typeDescriptor",
",",
"Expression",
"expression",
")",
"{",
"typeDescriptor",
"=",
"TypeDescriptors",
".",
"isBoxedType",
"(",
"typeDescriptor",
")",
"?",
"typeDescriptor",
".",
"toUnboxedType",
"(",
")",
":",
"typeDescriptor",
";",
"if",
"(",
"!",
"TypeDescriptors",
".",
"isNumericPrimitive",
"(",
"typeDescriptor",
")",
"||",
"typeDescriptor",
"==",
"expression",
".",
"getTypeDescriptor",
"(",
")",
")",
"{",
"return",
"expression",
";",
"}",
"return",
"CastExpression",
".",
"newBuilder",
"(",
")",
".",
"setCastTypeDescriptor",
"(",
"typeDescriptor",
")",
".",
"setExpression",
"(",
"expression",
")",
".",
"build",
"(",
")",
";",
"}",
"private",
"OperationExpansionUtils",
"(",
")",
"{",
"}",
"}"
] |
Utility functions for expanding assignment, increment and decrement expressions.
|
[
"Utility",
"functions",
"for",
"expanding",
"assignment",
"increment",
"and",
"decrement",
"expressions",
"."
] |
[
"// The lhs will be modified but it can be safely evaluated twice in a row without caring to",
"// avoid double side-effects if expanded. See the counter example showing an incorrect",
"// rewrite:",
"// a[++i] += i => a[++i] = a[++i] + x",
"// The qualifier here should not be extracted since it is a constructor reference.",
"//",
"// Note that checking idempotence of the qualifier is not correct since it might still be",
"// affected by the side effects in the rhs, e.g.",
"//",
"// SomeClass a = foo;",
"// String rv = a.result = (a = bar).toString();",
"//",
"// if this was not decomposed (because 'a' is idempotent), the above snippet would modify",
"// the instance 'foo' but return the value of 'bar.result' instead of 'foo.result' (see",
"// expandAssignmentExpression).",
"// What ensures correctness here without a rewrite is the qualifier being constant - not",
"// being idempotent.",
"// The qualifier is not guaranteed to be free of side effects, so evaluate it first and assign",
"// to a temporary variable.",
"// a++; => (let $value = a, a = a + 1, $value)",
"// No need to introduce a temporary variable for the result since even if the rhs modifies it,",
"// it will be overwritten by the assignment operation itself.",
"// When expanding compound assignments (and prefix/postfix operations) there is an implicit",
"// (narrowing) cast that might need to be inserted.",
"//",
"// Byte b;",
"// ++b;",
"//",
"// is equivalent to",
"//",
"// Byte b;",
"// b = (byte) (b + 1);",
"//"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 18
| 1,837
| 158
|
525504cb8c03437d6529c3c578a9d112390e9fe3
|
jricher/spring-security-oauth
|
spring-security-oauth2/src/main/java/org/springframework/security/oauth2/common/OAuth2AccessTokenDeserializer.java
|
[
"Apache-2.0"
] |
Java
|
OAuth2AccessTokenDeserializer
|
/**
* <p>
* Provides the ability to deserialize JSON response into an {@link OAuth2AccessToken} with jackson by implementing
* {@link JsonDeserializer}.
* </p>
* <p>
* The expected format of the access token is defined by <a
* href="http://tools.ietf.org/html/draft-ietf-oauth-v2-22#section-5.1">Successful Response</a>.
* </p>
*
* @author Rob Winch
* @see OAuth2AccessTokenDeserializer
*/
|
Provides the ability to deserialize JSON response into an OAuth2AccessToken with jackson by implementing
JsonDeserializer.
The expected format of the access token is defined by Successful Response.
@author Rob Winch
@see OAuth2AccessTokenDeserializer
|
[
"Provides",
"the",
"ability",
"to",
"deserialize",
"JSON",
"response",
"into",
"an",
"OAuth2AccessToken",
"with",
"jackson",
"by",
"implementing",
"JsonDeserializer",
".",
"The",
"expected",
"format",
"of",
"the",
"access",
"token",
"is",
"defined",
"by",
"Successful",
"Response",
".",
"@author",
"Rob",
"Winch",
"@see",
"OAuth2AccessTokenDeserializer"
] |
@SuppressWarnings("deprecation")
public final class OAuth2AccessTokenDeserializer extends StdDeserializer<OAuth2AccessToken> {
public OAuth2AccessTokenDeserializer() {
super(OAuth2AccessToken.class);
}
@Override
public OAuth2AccessToken deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException,
JsonProcessingException {
String tokenValue = null;
String tokenType = null;
String refreshToken = null;
Long expiresIn = null;
Set<String> scope = null;
Map<String, Object> additionalInformation = new LinkedHashMap<String, Object>();
// TODO What should occur if a parameter exists twice
while (jp.nextToken() != JsonToken.END_OBJECT) {
String name = jp.getCurrentName();
jp.nextToken();
if (OAuth2AccessToken.ACCESS_TOKEN.equals(name)) {
tokenValue = jp.getText();
}
else if (OAuth2AccessToken.TOKEN_TYPE.equals(name)) {
tokenType = jp.getText();
}
else if (OAuth2AccessToken.REFRESH_TOKEN.equals(name)) {
refreshToken = jp.getText();
}
else if (OAuth2AccessToken.EXPIRES_IN.equals(name)) {
expiresIn = jp.getLongValue();
}
else if (OAuth2AccessToken.SCOPE.equals(name)) {
String text = jp.getText();
scope = OAuth2Utils.parseParameterList(text);
} else {
additionalInformation.put(name, jp.readValueAs(Object.class));
}
}
// TODO What should occur if a required parameter (tokenValue or tokenType) is missing?
DefaultOAuth2AccessToken accessToken = new DefaultOAuth2AccessToken(tokenValue);
accessToken.setTokenType(tokenType);
if (expiresIn != null) {
accessToken.setExpiration(new Date(System.currentTimeMillis() + (expiresIn * 1000)));
}
if (refreshToken != null) {
accessToken.setRefreshToken(new DefaultOAuth2RefreshToken(refreshToken));
}
accessToken.setScope(scope);
accessToken.setAdditionalInformation(additionalInformation);
return accessToken;
}
}
|
[
"@",
"SuppressWarnings",
"(",
"\"",
"deprecation",
"\"",
")",
"public",
"final",
"class",
"OAuth2AccessTokenDeserializer",
"extends",
"StdDeserializer",
"<",
"OAuth2AccessToken",
">",
"{",
"public",
"OAuth2AccessTokenDeserializer",
"(",
")",
"{",
"super",
"(",
"OAuth2AccessToken",
".",
"class",
")",
";",
"}",
"@",
"Override",
"public",
"OAuth2AccessToken",
"deserialize",
"(",
"JsonParser",
"jp",
",",
"DeserializationContext",
"ctxt",
")",
"throws",
"IOException",
",",
"JsonProcessingException",
"{",
"String",
"tokenValue",
"=",
"null",
";",
"String",
"tokenType",
"=",
"null",
";",
"String",
"refreshToken",
"=",
"null",
";",
"Long",
"expiresIn",
"=",
"null",
";",
"Set",
"<",
"String",
">",
"scope",
"=",
"null",
";",
"Map",
"<",
"String",
",",
"Object",
">",
"additionalInformation",
"=",
"new",
"LinkedHashMap",
"<",
"String",
",",
"Object",
">",
"(",
")",
";",
"while",
"(",
"jp",
".",
"nextToken",
"(",
")",
"!=",
"JsonToken",
".",
"END_OBJECT",
")",
"{",
"String",
"name",
"=",
"jp",
".",
"getCurrentName",
"(",
")",
";",
"jp",
".",
"nextToken",
"(",
")",
";",
"if",
"(",
"OAuth2AccessToken",
".",
"ACCESS_TOKEN",
".",
"equals",
"(",
"name",
")",
")",
"{",
"tokenValue",
"=",
"jp",
".",
"getText",
"(",
")",
";",
"}",
"else",
"if",
"(",
"OAuth2AccessToken",
".",
"TOKEN_TYPE",
".",
"equals",
"(",
"name",
")",
")",
"{",
"tokenType",
"=",
"jp",
".",
"getText",
"(",
")",
";",
"}",
"else",
"if",
"(",
"OAuth2AccessToken",
".",
"REFRESH_TOKEN",
".",
"equals",
"(",
"name",
")",
")",
"{",
"refreshToken",
"=",
"jp",
".",
"getText",
"(",
")",
";",
"}",
"else",
"if",
"(",
"OAuth2AccessToken",
".",
"EXPIRES_IN",
".",
"equals",
"(",
"name",
")",
")",
"{",
"expiresIn",
"=",
"jp",
".",
"getLongValue",
"(",
")",
";",
"}",
"else",
"if",
"(",
"OAuth2AccessToken",
".",
"SCOPE",
".",
"equals",
"(",
"name",
")",
")",
"{",
"String",
"text",
"=",
"jp",
".",
"getText",
"(",
")",
";",
"scope",
"=",
"OAuth2Utils",
".",
"parseParameterList",
"(",
"text",
")",
";",
"}",
"else",
"{",
"additionalInformation",
".",
"put",
"(",
"name",
",",
"jp",
".",
"readValueAs",
"(",
"Object",
".",
"class",
")",
")",
";",
"}",
"}",
"DefaultOAuth2AccessToken",
"accessToken",
"=",
"new",
"DefaultOAuth2AccessToken",
"(",
"tokenValue",
")",
";",
"accessToken",
".",
"setTokenType",
"(",
"tokenType",
")",
";",
"if",
"(",
"expiresIn",
"!=",
"null",
")",
"{",
"accessToken",
".",
"setExpiration",
"(",
"new",
"Date",
"(",
"System",
".",
"currentTimeMillis",
"(",
")",
"+",
"(",
"expiresIn",
"*",
"1000",
")",
")",
")",
";",
"}",
"if",
"(",
"refreshToken",
"!=",
"null",
")",
"{",
"accessToken",
".",
"setRefreshToken",
"(",
"new",
"DefaultOAuth2RefreshToken",
"(",
"refreshToken",
")",
")",
";",
"}",
"accessToken",
".",
"setScope",
"(",
"scope",
")",
";",
"accessToken",
".",
"setAdditionalInformation",
"(",
"additionalInformation",
")",
";",
"return",
"accessToken",
";",
"}",
"}"
] |
<p>
Provides the ability to deserialize JSON response into an {@link OAuth2AccessToken} with jackson by implementing
{@link JsonDeserializer}.
|
[
"<p",
">",
"Provides",
"the",
"ability",
"to",
"deserialize",
"JSON",
"response",
"into",
"an",
"{",
"@link",
"OAuth2AccessToken",
"}",
"with",
"jackson",
"by",
"implementing",
"{",
"@link",
"JsonDeserializer",
"}",
"."
] |
[
"// TODO What should occur if a parameter exists twice",
"// TODO What should occur if a required parameter (tokenValue or tokenType) is missing?"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 19
| 434
| 109
|
0161766fe397b7f5f712f67ae79034a057909bc1
|
googleinterns/cabby
|
cabby/data/wikidata/info_item.py
|
[
"Apache-2.0"
] |
Python
|
WikidataEntity
|
Simplifed representation of a Wikidata entity.
`url` is the URL of the entity.
`title` is the name of the entity.
`location` is a Point representing the geo-location of the entity.
`instance` is the Wikidata instance property.
`qid` is the Wikidata id assigned to this entity (which can be recovered from
the URL, but is pulled out for convenience).
`tags` is the tags of the entity.
`text` is created from a concatenation of the entity's tags.
|
Simplifed representation of a Wikidata entity.
`url` is the URL of the entity.
`title` is the name of the entity.
`location` is a Point representing the geo-location of the entity.
`instance` is the Wikidata instance property.
`qid` is the Wikidata id assigned to this entity (which can be recovered from
the URL, but is pulled out for convenience).
`tags` is the tags of the entity.
`text` is created from a concatenation of the entity's tags.
|
[
"Simplifed",
"representation",
"of",
"a",
"Wikidata",
"entity",
".",
"`",
"url",
"`",
"is",
"the",
"URL",
"of",
"the",
"entity",
".",
"`",
"title",
"`",
"is",
"the",
"name",
"of",
"the",
"entity",
".",
"`",
"location",
"`",
"is",
"a",
"Point",
"representing",
"the",
"geo",
"-",
"location",
"of",
"the",
"entity",
".",
"`",
"instance",
"`",
"is",
"the",
"Wikidata",
"instance",
"property",
".",
"`",
"qid",
"`",
"is",
"the",
"Wikidata",
"id",
"assigned",
"to",
"this",
"entity",
"(",
"which",
"can",
"be",
"recovered",
"from",
"the",
"URL",
"but",
"is",
"pulled",
"out",
"for",
"convenience",
")",
".",
"`",
"tags",
"`",
"is",
"the",
"tags",
"of",
"the",
"entity",
".",
"`",
"text",
"`",
"is",
"created",
"from",
"a",
"concatenation",
"of",
"the",
"entity",
"'",
"s",
"tags",
"."
] |
class WikidataEntity:
"""Simplifed representation of a Wikidata entity.
`url` is the URL of the entity.
`title` is the name of the entity.
`location` is a Point representing the geo-location of the entity.
`instance` is the Wikidata instance property.
`qid` is the Wikidata id assigned to this entity (which can be recovered from
the URL, but is pulled out for convenience).
`tags` is the tags of the entity.
`text` is created from a concatenation of the entity's tags.
"""
url: Text = attr.ib()
title: Text = attr.ib()
location: Point = attr.ib()
instance: Text = attr.ib()
qid: Text = attr.ib(init=False)
tags: Dict = attr.ib()
text: Text = attr.ib(init=False)
def __attrs_post_init__(self):
# The QID is the part of the URL that comes after the last / character.
self.qid = self.url[self.url.rindex('/')+1:]
self.text = create_sample_from_tags(self.tags)
@classmethod
def from_sparql_result_info(cls, result):
"""Construct an Entity from the results of a SPARQL query."""
point_match = _POINT_RE.match(result['point']['value'])
return WikidataEntity(
result['place']['value'],
result['placeLabel']['value'],
Point(float(point_match.group(1)), float(point_match.group(2))),
result['instance']['value'],
result
)
|
[
"class",
"WikidataEntity",
":",
"url",
":",
"Text",
"=",
"attr",
".",
"ib",
"(",
")",
"title",
":",
"Text",
"=",
"attr",
".",
"ib",
"(",
")",
"location",
":",
"Point",
"=",
"attr",
".",
"ib",
"(",
")",
"instance",
":",
"Text",
"=",
"attr",
".",
"ib",
"(",
")",
"qid",
":",
"Text",
"=",
"attr",
".",
"ib",
"(",
"init",
"=",
"False",
")",
"tags",
":",
"Dict",
"=",
"attr",
".",
"ib",
"(",
")",
"text",
":",
"Text",
"=",
"attr",
".",
"ib",
"(",
"init",
"=",
"False",
")",
"def",
"__attrs_post_init__",
"(",
"self",
")",
":",
"self",
".",
"qid",
"=",
"self",
".",
"url",
"[",
"self",
".",
"url",
".",
"rindex",
"(",
"'/'",
")",
"+",
"1",
":",
"]",
"self",
".",
"text",
"=",
"create_sample_from_tags",
"(",
"self",
".",
"tags",
")",
"@",
"classmethod",
"def",
"from_sparql_result_info",
"(",
"cls",
",",
"result",
")",
":",
"\"\"\"Construct an Entity from the results of a SPARQL query.\"\"\"",
"point_match",
"=",
"_POINT_RE",
".",
"match",
"(",
"result",
"[",
"'point'",
"]",
"[",
"'value'",
"]",
")",
"return",
"WikidataEntity",
"(",
"result",
"[",
"'place'",
"]",
"[",
"'value'",
"]",
",",
"result",
"[",
"'placeLabel'",
"]",
"[",
"'value'",
"]",
",",
"Point",
"(",
"float",
"(",
"point_match",
".",
"group",
"(",
"1",
")",
")",
",",
"float",
"(",
"point_match",
".",
"group",
"(",
"2",
")",
")",
")",
",",
"result",
"[",
"'instance'",
"]",
"[",
"'value'",
"]",
",",
"result",
")"
] |
Simplifed representation of a Wikidata entity.
|
[
"Simplifed",
"representation",
"of",
"a",
"Wikidata",
"entity",
"."
] |
[
"\"\"\"Simplifed representation of a Wikidata entity.\n\n `url` is the URL of the entity.\n `title` is the name of the entity.\n `location` is a Point representing the geo-location of the entity.\n `instance` is the Wikidata instance property. \n `qid` is the Wikidata id assigned to this entity (which can be recovered from\n the URL, but is pulled out for convenience).\n `tags` is the tags of the entity.\n `text` is created from a concatenation of the entity's tags.\n\n \"\"\"",
"# The QID is the part of the URL that comes after the last / character.",
"\"\"\"Construct an Entity from the results of a SPARQL query.\"\"\""
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 15
| 337
| 119
|
83881c10cac82e058e4598cc17ece8af90dffdb4
|
DiscPy/DiscPy
|
discpy/application/permissions.py
|
[
"MIT"
] |
Python
|
ApplicationCommandPermissions
|
A class that allows you to define permissions for an application command
in a :class:`Guild`.
Parameters
-----------
command: :class:`application.ApplicationCommand`
The application command whose permissions are being defined.
guild_id: :class:`int`
The ID of guild in which permissions are applied.
Attributes
----------
overwrite: List[:class:`CommandPermissionOverwrite`]
The overwrites this permissions set holds.
|
A class that allows you to define permissions for an application command
in a :class:`Guild`.
Parameters
:class:`application.ApplicationCommand`
The application command whose permissions are being defined.
guild_id: :class:`int`
The ID of guild in which permissions are applied.
Attributes
List[:class:`CommandPermissionOverwrite`]
The overwrites this permissions set holds.
|
[
"A",
"class",
"that",
"allows",
"you",
"to",
"define",
"permissions",
"for",
"an",
"application",
"command",
"in",
"a",
":",
"class",
":",
"`",
"Guild",
"`",
".",
"Parameters",
":",
"class",
":",
"`",
"application",
".",
"ApplicationCommand",
"`",
"The",
"application",
"command",
"whose",
"permissions",
"are",
"being",
"defined",
".",
"guild_id",
":",
":",
"class",
":",
"`",
"int",
"`",
"The",
"ID",
"of",
"guild",
"in",
"which",
"permissions",
"are",
"applied",
".",
"Attributes",
"List",
"[",
":",
"class",
":",
"`",
"CommandPermissionOverwrite",
"`",
"]",
"The",
"overwrites",
"this",
"permissions",
"set",
"holds",
"."
] |
class ApplicationCommandPermissions:
"""A class that allows you to define permissions for an application command
in a :class:`Guild`.
Parameters
-----------
command: :class:`application.ApplicationCommand`
The application command whose permissions are being defined.
guild_id: :class:`int`
The ID of guild in which permissions are applied.
Attributes
----------
overwrite: List[:class:`CommandPermissionOverwrite`]
The overwrites this permissions set holds.
"""
def __init__(self, guild_id: int, command: ApplicationCommand = None):
self.command = command # type: ignore
self.guild_id = guild_id
self.overwrites = []
def get_overwrite(self, entity_id: int) -> Optional[CommandPermissionOverwrite]:
"""Gets permission overwrite for provided entity ID.
Parameters
-----------
entity_id: :class:`int`
The ID of role or user whose overwrite should be get.
Returns
-------
Optional[:class:`.CommandPermissionOverwrite`]
The permission overwrite if found, otherwise ``None``
"""
for overwrite in self.overwrites:
if overwrite.role_id == entity_id or overwrite.user_id == entity_id:
return overwrite
def add_overwrite(self, **options: Any) -> CommandPermissionOverwrite:
"""Adds a permission overwrite to this permissions set.
Parameters
-----------
**options:
The options of :class:`.CommandPermissionOverwrite`
Returns
-------
:class:`CommandPermissionOverwrite`
The permission overwrite that was added.
"""
overwrite = CommandPermissionOverwrite(**options)
self.overwrites.append(overwrite)
return overwrite
def remove_overwrite(self, entity_id: int) -> None:
"""Removes a permission overwrite for provided entity ID.
This method will not raise error if overwrite is not found.
Parameters
-----------
entity_id: :class:`int`
The ID of role or user whose overwrite should be removed.
"""
for overwrite in self.overwrites:
if overwrite.role_id == entity_id or overwrite.user_id == entity_id:
return self.overwrites.remove(overwrite)
|
[
"class",
"ApplicationCommandPermissions",
":",
"def",
"__init__",
"(",
"self",
",",
"guild_id",
":",
"int",
",",
"command",
":",
"ApplicationCommand",
"=",
"None",
")",
":",
"self",
".",
"command",
"=",
"command",
"self",
".",
"guild_id",
"=",
"guild_id",
"self",
".",
"overwrites",
"=",
"[",
"]",
"def",
"get_overwrite",
"(",
"self",
",",
"entity_id",
":",
"int",
")",
"->",
"Optional",
"[",
"CommandPermissionOverwrite",
"]",
":",
"\"\"\"Gets permission overwrite for provided entity ID.\n\n Parameters\n -----------\n entity_id: :class:`int`\n The ID of role or user whose overwrite should be get.\n\n Returns\n -------\n Optional[:class:`.CommandPermissionOverwrite`]\n The permission overwrite if found, otherwise ``None``\n \"\"\"",
"for",
"overwrite",
"in",
"self",
".",
"overwrites",
":",
"if",
"overwrite",
".",
"role_id",
"==",
"entity_id",
"or",
"overwrite",
".",
"user_id",
"==",
"entity_id",
":",
"return",
"overwrite",
"def",
"add_overwrite",
"(",
"self",
",",
"**",
"options",
":",
"Any",
")",
"->",
"CommandPermissionOverwrite",
":",
"\"\"\"Adds a permission overwrite to this permissions set.\n\n Parameters\n -----------\n **options:\n The options of :class:`.CommandPermissionOverwrite`\n\n Returns\n -------\n :class:`CommandPermissionOverwrite`\n The permission overwrite that was added.\n \"\"\"",
"overwrite",
"=",
"CommandPermissionOverwrite",
"(",
"**",
"options",
")",
"self",
".",
"overwrites",
".",
"append",
"(",
"overwrite",
")",
"return",
"overwrite",
"def",
"remove_overwrite",
"(",
"self",
",",
"entity_id",
":",
"int",
")",
"->",
"None",
":",
"\"\"\"Removes a permission overwrite for provided entity ID.\n\n This method will not raise error if overwrite is not found.\n\n Parameters\n -----------\n entity_id: :class:`int`\n The ID of role or user whose overwrite should be removed.\n \"\"\"",
"for",
"overwrite",
"in",
"self",
".",
"overwrites",
":",
"if",
"overwrite",
".",
"role_id",
"==",
"entity_id",
"or",
"overwrite",
".",
"user_id",
"==",
"entity_id",
":",
"return",
"self",
".",
"overwrites",
".",
"remove",
"(",
"overwrite",
")"
] |
A class that allows you to define permissions for an application command
in a :class:`Guild`.
|
[
"A",
"class",
"that",
"allows",
"you",
"to",
"define",
"permissions",
"for",
"an",
"application",
"command",
"in",
"a",
":",
"class",
":",
"`",
"Guild",
"`",
"."
] |
[
"\"\"\"A class that allows you to define permissions for an application command\n in a :class:`Guild`.\n\n Parameters\n -----------\n command: :class:`application.ApplicationCommand`\n The application command whose permissions are being defined.\n guild_id: :class:`int`\n The ID of guild in which permissions are applied.\n\n Attributes\n ----------\n overwrite: List[:class:`CommandPermissionOverwrite`]\n The overwrites this permissions set holds.\n \"\"\"",
"# type: ignore",
"\"\"\"Gets permission overwrite for provided entity ID.\n\n Parameters\n -----------\n entity_id: :class:`int`\n The ID of role or user whose overwrite should be get.\n\n Returns\n -------\n Optional[:class:`.CommandPermissionOverwrite`]\n The permission overwrite if found, otherwise ``None``\n \"\"\"",
"\"\"\"Adds a permission overwrite to this permissions set.\n\n Parameters\n -----------\n **options:\n The options of :class:`.CommandPermissionOverwrite`\n\n Returns\n -------\n :class:`CommandPermissionOverwrite`\n The permission overwrite that was added.\n \"\"\"",
"\"\"\"Removes a permission overwrite for provided entity ID.\n\n This method will not raise error if overwrite is not found.\n\n Parameters\n -----------\n entity_id: :class:`int`\n The ID of role or user whose overwrite should be removed.\n \"\"\""
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 13
| 464
| 95
|
0d62ee8fe92abf895c478f089d9f30f901b49258
|
sailfly/nuxeo
|
nuxeo-jsf/nuxeo-platform-ui-web/src/main/java/org/nuxeo/ecm/platform/ui/web/util/NuxeoExceptionInterceptor.java
|
[
"Apache-2.0"
] |
Java
|
NuxeoExceptionInterceptor
|
/**
* Intercepts Seam Bean call during the INVOKE_APPLICATION phase to see if a {@link RecoverableClientException} is
* raised. If this is the case, the INVOKE call returns null and the associated FacesMessage is generated.
*
* @author <a href="mailto:[email protected]">Tiry</a>
* @since 5.6
*/
|
Intercepts Seam Bean call during the INVOKE_APPLICATION phase to see if a RecoverableClientException is
raised. If this is the case, the INVOKE call returns null and the associated FacesMessage is generated.
|
[
"Intercepts",
"Seam",
"Bean",
"call",
"during",
"the",
"INVOKE_APPLICATION",
"phase",
"to",
"see",
"if",
"a",
"RecoverableClientException",
"is",
"raised",
".",
"If",
"this",
"is",
"the",
"case",
"the",
"INVOKE",
"call",
"returns",
"null",
"and",
"the",
"associated",
"FacesMessage",
"is",
"generated",
"."
] |
@Interceptor
public class NuxeoExceptionInterceptor extends AbstractInterceptor {
private static final long serialVersionUID = 1L;
protected PhaseId getPhase() {
return FacesLifecycle.getPhaseId();
}
protected Severity getSeverity(RecoverableClientException ce) {
if (ce.getSeverity() == RecoverableClientException.Severity.WARN) {
return Severity.WARN;
} else if (ce.getSeverity() == RecoverableClientException.Severity.FATAL) {
return Severity.FATAL;
}
return Severity.ERROR;
}
protected String getI18nMessage(String messageKey) {
@SuppressWarnings("unchecked")
Map<String, String> messages = (Map<String, String>) Component.getInstance(
"org.jboss.seam.international.messages", true);
if (messages == null) {
return messageKey;
}
String i18nMessage = messages.get(messageKey);
if (i18nMessage != null) {
return i18nMessage;
} else {
return messageKey;
}
}
@Override
public Object aroundInvoke(InvocationContext invocationContext) throws Exception { // stupid Seam API
try {
return invocationContext.proceed();
} catch (Exception t) { // deals with interrupt below
ExceptionUtils.checkInterrupt(t);
RecoverableClientException ce = null;
if (t instanceof RecoverableClientException) {
ce = (RecoverableClientException) t;
} else {
Throwable unwrappedException = ExceptionHelper.unwrapException(t);
if (unwrappedException instanceof RecoverableClientException) {
ce = (RecoverableClientException) unwrappedException;
}
}
if (ce != null) {
Severity severity = getSeverity(ce);
FacesMessages.instance().add(severity, getI18nMessage(ce.getLocalizedMessage()),
(Object[]) ce.geLocalizedMessageParams());
return null;
}
throw t;
}
}
@Override
public boolean isInterceptorEnabled() {
PhaseId phase = getPhase();
if (phase == null) {
return true;
}
if (phase.equals(PhaseId.INVOKE_APPLICATION)) {
return true;
}
return false;
}
}
|
[
"@",
"Interceptor",
"public",
"class",
"NuxeoExceptionInterceptor",
"extends",
"AbstractInterceptor",
"{",
"private",
"static",
"final",
"long",
"serialVersionUID",
"=",
"1L",
";",
"protected",
"PhaseId",
"getPhase",
"(",
")",
"{",
"return",
"FacesLifecycle",
".",
"getPhaseId",
"(",
")",
";",
"}",
"protected",
"Severity",
"getSeverity",
"(",
"RecoverableClientException",
"ce",
")",
"{",
"if",
"(",
"ce",
".",
"getSeverity",
"(",
")",
"==",
"RecoverableClientException",
".",
"Severity",
".",
"WARN",
")",
"{",
"return",
"Severity",
".",
"WARN",
";",
"}",
"else",
"if",
"(",
"ce",
".",
"getSeverity",
"(",
")",
"==",
"RecoverableClientException",
".",
"Severity",
".",
"FATAL",
")",
"{",
"return",
"Severity",
".",
"FATAL",
";",
"}",
"return",
"Severity",
".",
"ERROR",
";",
"}",
"protected",
"String",
"getI18nMessage",
"(",
"String",
"messageKey",
")",
"{",
"@",
"SuppressWarnings",
"(",
"\"",
"unchecked",
"\"",
")",
"Map",
"<",
"String",
",",
"String",
">",
"messages",
"=",
"(",
"Map",
"<",
"String",
",",
"String",
">",
")",
"Component",
".",
"getInstance",
"(",
"\"",
"org.jboss.seam.international.messages",
"\"",
",",
"true",
")",
";",
"if",
"(",
"messages",
"==",
"null",
")",
"{",
"return",
"messageKey",
";",
"}",
"String",
"i18nMessage",
"=",
"messages",
".",
"get",
"(",
"messageKey",
")",
";",
"if",
"(",
"i18nMessage",
"!=",
"null",
")",
"{",
"return",
"i18nMessage",
";",
"}",
"else",
"{",
"return",
"messageKey",
";",
"}",
"}",
"@",
"Override",
"public",
"Object",
"aroundInvoke",
"(",
"InvocationContext",
"invocationContext",
")",
"throws",
"Exception",
"{",
"try",
"{",
"return",
"invocationContext",
".",
"proceed",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"t",
")",
"{",
"ExceptionUtils",
".",
"checkInterrupt",
"(",
"t",
")",
";",
"RecoverableClientException",
"ce",
"=",
"null",
";",
"if",
"(",
"t",
"instanceof",
"RecoverableClientException",
")",
"{",
"ce",
"=",
"(",
"RecoverableClientException",
")",
"t",
";",
"}",
"else",
"{",
"Throwable",
"unwrappedException",
"=",
"ExceptionHelper",
".",
"unwrapException",
"(",
"t",
")",
";",
"if",
"(",
"unwrappedException",
"instanceof",
"RecoverableClientException",
")",
"{",
"ce",
"=",
"(",
"RecoverableClientException",
")",
"unwrappedException",
";",
"}",
"}",
"if",
"(",
"ce",
"!=",
"null",
")",
"{",
"Severity",
"severity",
"=",
"getSeverity",
"(",
"ce",
")",
";",
"FacesMessages",
".",
"instance",
"(",
")",
".",
"add",
"(",
"severity",
",",
"getI18nMessage",
"(",
"ce",
".",
"getLocalizedMessage",
"(",
")",
")",
",",
"(",
"Object",
"[",
"]",
")",
"ce",
".",
"geLocalizedMessageParams",
"(",
")",
")",
";",
"return",
"null",
";",
"}",
"throw",
"t",
";",
"}",
"}",
"@",
"Override",
"public",
"boolean",
"isInterceptorEnabled",
"(",
")",
"{",
"PhaseId",
"phase",
"=",
"getPhase",
"(",
")",
";",
"if",
"(",
"phase",
"==",
"null",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"phase",
".",
"equals",
"(",
"PhaseId",
".",
"INVOKE_APPLICATION",
")",
")",
"{",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}",
"}"
] |
Intercepts Seam Bean call during the INVOKE_APPLICATION phase to see if a {@link RecoverableClientException} is
raised.
|
[
"Intercepts",
"Seam",
"Bean",
"call",
"during",
"the",
"INVOKE_APPLICATION",
"phase",
"to",
"see",
"if",
"a",
"{",
"@link",
"RecoverableClientException",
"}",
"is",
"raised",
"."
] |
[
"// stupid Seam API",
"// deals with interrupt below"
] |
[
{
"param": "AbstractInterceptor",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "AbstractInterceptor",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 17
| 481
| 83
|
2c8a98b211a287154d312e60fc35929c3ac326d9
|
jluiselli/artistoo
|
src/hamiltonian/VolumeConstraint.js
|
[
"MIT"
] |
JavaScript
|
VolumeConstraint
|
/**
* Implements the volume constraint of Potts models.
*
* This constraint is typically used together with {@link Adhesion}.
*
* See {@link VolumeConstraint#constructor} for the required parameters.
*
* @example
* // Build a CPM and add the constraint
* let CPM = require( "path/to/build" )
* let C = new CPM.CPM( [200,200], {
* T : 20,
* J : [[0,20],[20,10]]
* })
* C.add( new CPM.VolumeConstraint( {
* V : [0,500],
* LAMBDA_V : [0,5]
* } ) )
*
* // Or add automatically by entering the parameters in the CPM
* let C2 = new CPM.CPM( [200,200], {
* T : 20,
* J : [[0,20],[20,10]],
* V : [0,500],
* LAMBDA_V : [0,5]
* })
*/
|
Implements the volume constraint of Potts models.
This constraint is typically used together with Adhesion.
See VolumeConstraint#constructor for the required parameters.
|
[
"Implements",
"the",
"volume",
"constraint",
"of",
"Potts",
"models",
".",
"This",
"constraint",
"is",
"typically",
"used",
"together",
"with",
"Adhesion",
".",
"See",
"VolumeConstraint#constructor",
"for",
"the",
"required",
"parameters",
"."
] |
class VolumeConstraint extends SoftConstraint {
/** The constructor of the VolumeConstraint requires a conf object with parameters.
@param {object} conf - parameter object for this constraint
@param {PerKindNonNegative} conf.LAMBDA_V - strength of the constraint per cellkind.
@param {PerKindNonNegative} conf.V - Target volume per cellkind.
*/
constructor( conf ){
super( conf )
}
/** This method checks that all required parameters are present in the object supplied to
the constructor, and that they are of the right format. It throws an error when this
is not the case.*/
confChecker(){
let checker = new ParameterChecker( this.conf, this.C )
checker.confCheckParameter( "LAMBDA_V", "KindArray", "NonNegative" )
checker.confCheckParameter( "V", "KindArray", "NonNegative" )
}
/** Method to compute the Hamiltonian for this constraint.
@param {IndexCoordinate} sourcei - coordinate of the source pixel that tries to copy.
@param {IndexCoordinate} targeti - coordinate of the target pixel the source is trying
to copy into.
@param {CellId} src_type - cellid of the source pixel.
@param {CellId} tgt_type - cellid of the target pixel.
@return {number} the change in Hamiltonian for this copy attempt and this constraint.*/
deltaH( sourcei, targeti, src_type, tgt_type ){
// volume gain of src cell
let deltaH = this.volconstraint( 1, src_type ) -
this.volconstraint( 0, src_type )
// volume loss of tgt cell
deltaH += this.volconstraint( -1, tgt_type ) -
this.volconstraint( 0, tgt_type )
return deltaH
}
/* ======= VOLUME ======= */
/** The volume constraint term of the Hamiltonian for the cell with id t.
@param {number} vgain - Use vgain=0 for energy of current volume, vgain=1
for energy if cell gains a pixel, and vgain = -1 for energy if cell loses a pixel.
@param {CellId} t - the cellid of the cell whose volume energy we are computing.
@return {number} the volume energy of this cell.
*/
volconstraint ( vgain, t ){
const l = this.cellParameter("LAMBDA_V", t)
// the background "cell" has no volume constraint.
if( t == 0 || l == 0 ) return 0
const vdiff = this.cellParameter("V", t) - (this.C.getVolume(t) + vgain)
return l*vdiff*vdiff
}
}
|
[
"class",
"VolumeConstraint",
"extends",
"SoftConstraint",
"{",
"constructor",
"(",
"conf",
")",
"{",
"super",
"(",
"conf",
")",
"}",
"confChecker",
"(",
")",
"{",
"let",
"checker",
"=",
"new",
"ParameterChecker",
"(",
"this",
".",
"conf",
",",
"this",
".",
"C",
")",
"checker",
".",
"confCheckParameter",
"(",
"\"LAMBDA_V\"",
",",
"\"KindArray\"",
",",
"\"NonNegative\"",
")",
"checker",
".",
"confCheckParameter",
"(",
"\"V\"",
",",
"\"KindArray\"",
",",
"\"NonNegative\"",
")",
"}",
"deltaH",
"(",
"sourcei",
",",
"targeti",
",",
"src_type",
",",
"tgt_type",
")",
"{",
"let",
"deltaH",
"=",
"this",
".",
"volconstraint",
"(",
"1",
",",
"src_type",
")",
"-",
"this",
".",
"volconstraint",
"(",
"0",
",",
"src_type",
")",
"deltaH",
"+=",
"this",
".",
"volconstraint",
"(",
"-",
"1",
",",
"tgt_type",
")",
"-",
"this",
".",
"volconstraint",
"(",
"0",
",",
"tgt_type",
")",
"return",
"deltaH",
"}",
"volconstraint",
"(",
"vgain",
",",
"t",
")",
"{",
"const",
"l",
"=",
"this",
".",
"cellParameter",
"(",
"\"LAMBDA_V\"",
",",
"t",
")",
"if",
"(",
"t",
"==",
"0",
"||",
"l",
"==",
"0",
")",
"return",
"0",
"const",
"vdiff",
"=",
"this",
".",
"cellParameter",
"(",
"\"V\"",
",",
"t",
")",
"-",
"(",
"this",
".",
"C",
".",
"getVolume",
"(",
"t",
")",
"+",
"vgain",
")",
"return",
"l",
"*",
"vdiff",
"*",
"vdiff",
"}",
"}"
] |
Implements the volume constraint of Potts models.
|
[
"Implements",
"the",
"volume",
"constraint",
"of",
"Potts",
"models",
"."
] |
[
"/** The constructor of the VolumeConstraint requires a conf object with parameters.\n\t@param {object} conf - parameter object for this constraint\n\t@param {PerKindNonNegative} conf.LAMBDA_V - strength of the constraint per cellkind.\n\t@param {PerKindNonNegative} conf.V - Target volume per cellkind.\n\t*/",
"/** This method checks that all required parameters are present in the object supplied to\n\tthe constructor, and that they are of the right format. It throws an error when this\n\tis not the case.*/",
"/** Method to compute the Hamiltonian for this constraint. \n\t @param {IndexCoordinate} sourcei - coordinate of the source pixel that tries to copy.\n\t @param {IndexCoordinate} targeti - coordinate of the target pixel the source is trying\n\t to copy into.\n\t @param {CellId} src_type - cellid of the source pixel.\n\t @param {CellId} tgt_type - cellid of the target pixel. \n\t @return {number} the change in Hamiltonian for this copy attempt and this constraint.*/",
"// volume gain of src cell",
"// volume loss of tgt cell",
"/* ======= VOLUME ======= */",
"/** The volume constraint term of the Hamiltonian for the cell with id t.\n\t@param {number} vgain - Use vgain=0 for energy of current volume, vgain=1 \n\t\tfor energy if cell gains a pixel, and vgain = -1 for energy if cell loses a pixel.\n\t@param {CellId} t - the cellid of the cell whose volume energy we are computing.\n\t@return {number} the volume energy of this cell.\n\t*/",
"// the background \"cell\" has no volume constraint."
] |
[
{
"param": "SoftConstraint",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "SoftConstraint",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 13
| 594
| 245
|
ef0d74846daec9fa786f7a9033d64c023387d28c
|
selenamarie/openconferenceware
|
app/mixins/tracks_faux_routes_mixin.rb
|
[
"MIT"
] |
Ruby
|
TracksFauxRoutesMixin
|
# = FauxRoutesMixin
#
# The FauxRoutesMixin generates a bunch of route helpers for the
# TracksController and SessionTypesController nested resources.
#
# == Examples
#
# Long-hand way of expressing "/events/:event_id/tracks/:track_id":
# event_track_path(@event, @track)
#
# Faux route helper for expressing the same thing and getting Event from @event:
# track_path(@track)
#
|
FauxRoutesMixin
The FauxRoutesMixin generates a bunch of route helpers for the
TracksController and SessionTypesController nested resources.
Examples
Faux route helper for expressing the same thing and getting Event from @event:
track_path(@track)
|
[
"FauxRoutesMixin",
"The",
"FauxRoutesMixin",
"generates",
"a",
"bunch",
"of",
"route",
"helpers",
"for",
"the",
"TracksController",
"and",
"SessionTypesController",
"nested",
"resources",
".",
"Examples",
"Faux",
"route",
"helper",
"for",
"expressing",
"the",
"same",
"thing",
"and",
"getting",
"Event",
"from",
"@event",
":",
"track_path",
"(",
"@track",
")"
] |
module TracksFauxRoutesMixin
# FIXME this implementation is 10x more complex than it should be, but I don't know how to make it simpler
# FIXME this should be renamed / generalized since it now handles sesion types in addition to tracks.
def self.included(mixee)
mixee.extend(Methods)
if mixee.ancestors.include?(ActionController::Base)
mixee.class_eval do
Methods.instance_methods.each do |name|
#IK# puts "Helperized faux route: #{name}"
helper_method(name)
end
end
end
end
module Methods
generate = proc{|*args|
opts = args.extract_options!
verb = opts[:verb]
noun = opts[:noun]
item = opts[:item]
for kind in %w[path url]
real = "#{verb ? verb+'_' : nil}event_#{noun}_#{kind}"
faux = "#{verb ? verb+'_' : nil}#{noun}_#{kind}"
#IK# puts "Creating faux route: #{faux} <= #{real}"
if item
define_method(faux, proc{|track, *args| send(real, track.event, track, *args)})
else
define_method(faux, proc{|*args| send(real, @event, *args)})
end
end
}
generate[:noun => "tracks"]
generate[:noun => "track", :verb => "new"]
generate[:noun => "track", :item => true]
generate[:noun => "track", :verb => "edit", :item => true]
generate[:noun => "session_types"]
generate[:noun => "session_type", :verb => "new"]
generate[:noun => "session_type", :item => true]
generate[:noun => "session_type", :verb => "edit", :item => true]
end
include Methods
extend Methods
end
|
[
"module",
"TracksFauxRoutesMixin",
"def",
"self",
".",
"included",
"(",
"mixee",
")",
"mixee",
".",
"extend",
"(",
"Methods",
")",
"if",
"mixee",
".",
"ancestors",
".",
"include?",
"(",
"ActionController",
"::",
"Base",
")",
"mixee",
".",
"class_eval",
"do",
"Methods",
".",
"instance_methods",
".",
"each",
"do",
"|",
"name",
"|",
"helper_method",
"(",
"name",
")",
"end",
"end",
"end",
"end",
"module",
"Methods",
"generate",
"=",
"proc",
"{",
"|",
"*",
"args",
"|",
"opts",
"=",
"args",
".",
"extract_options!",
"verb",
"=",
"opts",
"[",
":verb",
"]",
"noun",
"=",
"opts",
"[",
":noun",
"]",
"item",
"=",
"opts",
"[",
":item",
"]",
"for",
"kind",
"in",
"%w[",
"path",
"url",
"]",
"real",
"=",
"\"#{verb ? verb+'_' : nil}event_#{noun}_#{kind}\"",
"faux",
"=",
"\"#{verb ? verb+'_' : nil}#{noun}_#{kind}\"",
"if",
"item",
"define_method",
"(",
"faux",
",",
"proc",
"{",
"|",
"track",
",",
"*",
"args",
"|",
"send",
"(",
"real",
",",
"track",
".",
"event",
",",
"track",
",",
"*",
"args",
")",
"}",
")",
"else",
"define_method",
"(",
"faux",
",",
"proc",
"{",
"|",
"*",
"args",
"|",
"send",
"(",
"real",
",",
"@event",
",",
"*",
"args",
")",
"}",
")",
"end",
"end",
"}",
"generate",
"[",
":noun",
"=>",
"\"tracks\"",
"]",
"generate",
"[",
":noun",
"=>",
"\"track\"",
",",
":verb",
"=>",
"\"new\"",
"]",
"generate",
"[",
":noun",
"=>",
"\"track\"",
",",
":item",
"=>",
"true",
"]",
"generate",
"[",
":noun",
"=>",
"\"track\"",
",",
":verb",
"=>",
"\"edit\"",
",",
":item",
"=>",
"true",
"]",
"generate",
"[",
":noun",
"=>",
"\"session_types\"",
"]",
"generate",
"[",
":noun",
"=>",
"\"session_type\"",
",",
":verb",
"=>",
"\"new\"",
"]",
"generate",
"[",
":noun",
"=>",
"\"session_type\"",
",",
":item",
"=>",
"true",
"]",
"generate",
"[",
":noun",
"=>",
"\"session_type\"",
",",
":verb",
"=>",
"\"edit\"",
",",
":item",
"=>",
"true",
"]",
"end",
"include",
"Methods",
"extend",
"Methods",
"end"
] |
FauxRoutesMixin
The FauxRoutesMixin generates a bunch of route helpers for the
TracksController and SessionTypesController nested resources.
|
[
"FauxRoutesMixin",
"The",
"FauxRoutesMixin",
"generates",
"a",
"bunch",
"of",
"route",
"helpers",
"for",
"the",
"TracksController",
"and",
"SessionTypesController",
"nested",
"resources",
"."
] |
[
"# FIXME this implementation is 10x more complex than it should be, but I don't know how to make it simpler",
"# FIXME this should be renamed / generalized since it now handles sesion types in addition to tracks.",
"#IK# puts \"Helperized faux route: #{name}\"",
"#IK# puts \"Creating faux route: #{faux} <= #{real}\""
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 21
| 422
| 93
|
0dfa93641472d0d05b6dbca6a9835cc068a27c8b
|
mccool/elastic-builder
|
src/core/script.js
|
[
"MIT"
] |
JavaScript
|
Script
|
/**
* Class supporting the Elasticsearch scripting API.
*
* [Elasticsearch reference](https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-scripting-using.html)
*
* Note: `inline` script type was deprecated in [elasticsearch v5.0](https://www.elastic.co/guide/en/elasticsearch/reference/5.6/breaking_50_scripting.html).
* `source` should be used instead. And similarly for `stored` scripts, type
* `id` must be used instead. `file` scripts were removed as part of the
* breaking changes in [elasticsearch v6.0](https://www.elastic.co/guide/en/elasticsearch/reference/6.0/breaking_60_scripting_changes.html#_file_scripts_removed)
*
* @param {string=} type One of `inline`, `stored`, `file`, `source`, `id`.
* @param {string=} source Source of the script.
* This needs to be specified if optional argument `type` is passed.
*
* @example
* const script = esb.script('inline', "doc['my_field'] * multiplier")
* .lang('expression')
* .params({ multiplier: 2 });
*
* // cat "log(_score * 2) + my_modifier" > config/scripts/calculate-score.groovy
* const script = esb.script()
* .lang('groovy')
* .file('calculate-score')
* .params({ my_modifier: 2 });
*/
|
Class supporting the Elasticsearch scripting API.
[Elasticsearch reference]
`inline` script type was deprecated in [elasticsearch v5.0].
`source` should be used instead. And similarly for `stored` scripts, type
`id` must be used instead. `file` scripts were removed as part of the
breaking changes in [elasticsearch v6.0]
cat "log(_score * 2) + my_modifier" > config/scripts/calculate-score.groovy
const script = esb.script()
.lang('groovy')
.file('calculate-score')
.params({ my_modifier: 2 }).
|
[
"Class",
"supporting",
"the",
"Elasticsearch",
"scripting",
"API",
".",
"[",
"Elasticsearch",
"reference",
"]",
"`",
"inline",
"`",
"script",
"type",
"was",
"deprecated",
"in",
"[",
"elasticsearch",
"v5",
".",
"0",
"]",
".",
"`",
"source",
"`",
"should",
"be",
"used",
"instead",
".",
"And",
"similarly",
"for",
"`",
"stored",
"`",
"scripts",
"type",
"`",
"id",
"`",
"must",
"be",
"used",
"instead",
".",
"`",
"file",
"`",
"scripts",
"were",
"removed",
"as",
"part",
"of",
"the",
"breaking",
"changes",
"in",
"[",
"elasticsearch",
"v6",
".",
"0",
"]",
"cat",
"\"",
"log",
"(",
"_score",
"*",
"2",
")",
"+",
"my_modifier",
"\"",
">",
"config",
"/",
"scripts",
"/",
"calculate",
"-",
"score",
".",
"groovy",
"const",
"script",
"=",
"esb",
".",
"script",
"()",
".",
"lang",
"(",
"'",
"groovy",
"'",
")",
".",
"file",
"(",
"'",
"calculate",
"-",
"score",
"'",
")",
".",
"params",
"(",
"{",
"my_modifier",
":",
"2",
"}",
")",
"."
] |
class Script {
// eslint-disable-next-line require-jsdoc
constructor(type, source) {
this._isTypeSet = false;
this._body = {};
// NOTE: Script syntax changed in elasticsearch 5.6 to use `id`/`source`
// instead of `inline`/`source`/`file`. This needs to be handled
// somehow.
if (!isNil(type) && !isNil(source)) {
const typeLower = type.toLowerCase();
switch (typeLower) {
case 'inline':
this.inline(source);
break;
case 'source':
this.source(source);
break;
case 'stored':
this.stored(source);
break;
case 'id':
this.id(source);
break;
case 'file':
this.file(source);
break;
default:
throw new Error(
'`type` must be one of `inline`, `stored`, `file`'
);
}
}
}
/**
* Print warning message to console namespaced by class name.
*
* @param {string} msg
* @private
*/
_warn(msg) {
console.warn(`[Script] ${msg}`);
}
/**
* Print warning messages to not mix `Script` source
*
* @private
*/
_checkMixedRepr() {
if (!this._isTypeSet) return;
this._warn(
'Script source(`inline`/`source`/`stored`/`id`/`file`) was already specified!'
);
this._warn('Overwriting.');
delete this._body.inline;
delete this._body.source;
delete this._body.stored;
delete this._body.id;
delete this._body.file;
}
/**
* Sets the type of script to be `inline` and specifies the source of the script.
*
* Note: This type was deprecated in elasticsearch v5.0. Use `source`
* instead if you are using elasticsearch `>= 5.0`.
*
* @param {string} scriptCode
* @returns {Script} returns `this` so that calls can be chained.
*/
inline(scriptCode) {
this._checkMixedRepr();
this._body.inline = scriptCode;
this._isTypeSet = true;
return this;
}
/**
* Sets the type of script to be `source` and specifies the source of the script.
*
* Note: `source` is an alias for the `inline` type which was deprecated
* in elasticsearch v5.0. So this type is supported only in versions
* `>= 5.0`.
*
* @param {string} scriptCode
* @returns {Script} returns `this` so that calls can be chained.
*/
source(scriptCode) {
this._checkMixedRepr();
this._body.source = scriptCode;
this._isTypeSet = true;
return this;
}
/**
* Specify the `stored` script by `id` which will be retrieved from cluster state.
*
* Note: This type was deprecated in elasticsearch v5.0. Use `id`
* instead if you are using elasticsearch `>= 5.0`.
*
* @param {string} scriptId The unique identifier for the stored script.
* @returns {Script} returns `this` so that calls can be chained.
*/
stored(scriptId) {
this._checkMixedRepr();
this._body.stored = scriptId;
this._isTypeSet = true;
return this;
}
/**
* Specify the stored script to be used by it's `id` which will be retrieved
* from cluster state.
*
* Note: `id` is an alias for the `stored` type which was deprecated in
* elasticsearch v5.0. So this type is supported only in versions `>= 5.0`.
*
* @param {string} scriptId The unique identifier for the stored script.
* @returns {Script} returns `this` so that calls can be chained.
*/
id(scriptId) {
this._checkMixedRepr();
this._body.id = scriptId;
this._isTypeSet = true;
return this;
}
/**
* Specify the `file` script by stored as a file in the scripts folder.
*
* Note: File scripts have been removed in elasticsearch 6.0. Instead, use
* stored scripts.
*
* @param {string} fileName The name of the script stored as a file in the scripts folder.
* For script file `config/scripts/calculate-score.groovy`,
* `fileName` should be `calculate-score`
* @returns {Script} returns `this` so that calls can be chained.
*/
file(fileName) {
this._checkMixedRepr();
this._body.file = fileName;
this._isTypeSet = true;
return this;
}
/**
* Specifies the language the script is written in. Defaults to `painless` but
* may be set to any of languages listed in [Scripting](https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-scripting.html).
* The default language may be changed in the `elasticsearch.yml` config file by setting
* `script.default_lang` to the appropriate language.
*
* For a `file` script, it should correspond with the script file suffix.
* `groovy` for `config/scripts/calculate-score.groovy`.
*
* Note: The Groovy, JavaScript, and Python scripting languages were
* deprecated in elasticsearch 5.0 and removed in 6.0. Use painless instead.
*
* @param {string} lang The language for the script.
* @returns {Script} returns `this` so that calls can be chained.
*/
lang(lang) {
this._body.lang = lang;
return this;
}
/**
* Specifies any named parameters that are passed into the script as variables.
*
* @param {Object} params Named parameters to be passed to script.
* @returns {Script} returns `this` so that calls can be chained.
*/
params(params) {
this._body.params = params;
return this;
}
/**
* Override default `toJSON` to return DSL representation for the `script`.
*
* @override
* @returns {Object} returns an Object which maps to the elasticsearch query DSL
*/
toJSON() {
// recursiveToJSON doesn't seem to be needed here
return this._body;
}
}
|
[
"class",
"Script",
"{",
"constructor",
"(",
"type",
",",
"source",
")",
"{",
"this",
".",
"_isTypeSet",
"=",
"false",
";",
"this",
".",
"_body",
"=",
"{",
"}",
";",
"if",
"(",
"!",
"isNil",
"(",
"type",
")",
"&&",
"!",
"isNil",
"(",
"source",
")",
")",
"{",
"const",
"typeLower",
"=",
"type",
".",
"toLowerCase",
"(",
")",
";",
"switch",
"(",
"typeLower",
")",
"{",
"case",
"'inline'",
":",
"this",
".",
"inline",
"(",
"source",
")",
";",
"break",
";",
"case",
"'source'",
":",
"this",
".",
"source",
"(",
"source",
")",
";",
"break",
";",
"case",
"'stored'",
":",
"this",
".",
"stored",
"(",
"source",
")",
";",
"break",
";",
"case",
"'id'",
":",
"this",
".",
"id",
"(",
"source",
")",
";",
"break",
";",
"case",
"'file'",
":",
"this",
".",
"file",
"(",
"source",
")",
";",
"break",
";",
"default",
":",
"throw",
"new",
"Error",
"(",
"'`type` must be one of `inline`, `stored`, `file`'",
")",
";",
"}",
"}",
"}",
"_warn",
"(",
"msg",
")",
"{",
"console",
".",
"warn",
"(",
"`",
"${",
"msg",
"}",
"`",
")",
";",
"}",
"_checkMixedRepr",
"(",
")",
"{",
"if",
"(",
"!",
"this",
".",
"_isTypeSet",
")",
"return",
";",
"this",
".",
"_warn",
"(",
"'Script source(`inline`/`source`/`stored`/`id`/`file`) was already specified!'",
")",
";",
"this",
".",
"_warn",
"(",
"'Overwriting.'",
")",
";",
"delete",
"this",
".",
"_body",
".",
"inline",
";",
"delete",
"this",
".",
"_body",
".",
"source",
";",
"delete",
"this",
".",
"_body",
".",
"stored",
";",
"delete",
"this",
".",
"_body",
".",
"id",
";",
"delete",
"this",
".",
"_body",
".",
"file",
";",
"}",
"inline",
"(",
"scriptCode",
")",
"{",
"this",
".",
"_checkMixedRepr",
"(",
")",
";",
"this",
".",
"_body",
".",
"inline",
"=",
"scriptCode",
";",
"this",
".",
"_isTypeSet",
"=",
"true",
";",
"return",
"this",
";",
"}",
"source",
"(",
"scriptCode",
")",
"{",
"this",
".",
"_checkMixedRepr",
"(",
")",
";",
"this",
".",
"_body",
".",
"source",
"=",
"scriptCode",
";",
"this",
".",
"_isTypeSet",
"=",
"true",
";",
"return",
"this",
";",
"}",
"stored",
"(",
"scriptId",
")",
"{",
"this",
".",
"_checkMixedRepr",
"(",
")",
";",
"this",
".",
"_body",
".",
"stored",
"=",
"scriptId",
";",
"this",
".",
"_isTypeSet",
"=",
"true",
";",
"return",
"this",
";",
"}",
"id",
"(",
"scriptId",
")",
"{",
"this",
".",
"_checkMixedRepr",
"(",
")",
";",
"this",
".",
"_body",
".",
"id",
"=",
"scriptId",
";",
"this",
".",
"_isTypeSet",
"=",
"true",
";",
"return",
"this",
";",
"}",
"file",
"(",
"fileName",
")",
"{",
"this",
".",
"_checkMixedRepr",
"(",
")",
";",
"this",
".",
"_body",
".",
"file",
"=",
"fileName",
";",
"this",
".",
"_isTypeSet",
"=",
"true",
";",
"return",
"this",
";",
"}",
"lang",
"(",
"lang",
")",
"{",
"this",
".",
"_body",
".",
"lang",
"=",
"lang",
";",
"return",
"this",
";",
"}",
"params",
"(",
"params",
")",
"{",
"this",
".",
"_body",
".",
"params",
"=",
"params",
";",
"return",
"this",
";",
"}",
"toJSON",
"(",
")",
"{",
"return",
"this",
".",
"_body",
";",
"}",
"}"
] |
Class supporting the Elasticsearch scripting API.
|
[
"Class",
"supporting",
"the",
"Elasticsearch",
"scripting",
"API",
"."
] |
[
"// eslint-disable-next-line require-jsdoc",
"// NOTE: Script syntax changed in elasticsearch 5.6 to use `id`/`source`",
"// instead of `inline`/`source`/`file`. This needs to be handled",
"// somehow.",
"/**\n * Print warning message to console namespaced by class name.\n *\n * @param {string} msg\n * @private\n */",
"/**\n * Print warning messages to not mix `Script` source\n *\n * @private\n */",
"/**\n * Sets the type of script to be `inline` and specifies the source of the script.\n *\n * Note: This type was deprecated in elasticsearch v5.0. Use `source`\n * instead if you are using elasticsearch `>= 5.0`.\n *\n * @param {string} scriptCode\n * @returns {Script} returns `this` so that calls can be chained.\n */",
"/**\n * Sets the type of script to be `source` and specifies the source of the script.\n *\n * Note: `source` is an alias for the `inline` type which was deprecated\n * in elasticsearch v5.0. So this type is supported only in versions\n * `>= 5.0`.\n *\n * @param {string} scriptCode\n * @returns {Script} returns `this` so that calls can be chained.\n */",
"/**\n * Specify the `stored` script by `id` which will be retrieved from cluster state.\n *\n * Note: This type was deprecated in elasticsearch v5.0. Use `id`\n * instead if you are using elasticsearch `>= 5.0`.\n *\n * @param {string} scriptId The unique identifier for the stored script.\n * @returns {Script} returns `this` so that calls can be chained.\n */",
"/**\n * Specify the stored script to be used by it's `id` which will be retrieved\n * from cluster state.\n *\n * Note: `id` is an alias for the `stored` type which was deprecated in\n * elasticsearch v5.0. So this type is supported only in versions `>= 5.0`.\n *\n * @param {string} scriptId The unique identifier for the stored script.\n * @returns {Script} returns `this` so that calls can be chained.\n */",
"/**\n * Specify the `file` script by stored as a file in the scripts folder.\n *\n * Note: File scripts have been removed in elasticsearch 6.0. Instead, use\n * stored scripts.\n *\n * @param {string} fileName The name of the script stored as a file in the scripts folder.\n * For script file `config/scripts/calculate-score.groovy`,\n * `fileName` should be `calculate-score`\n * @returns {Script} returns `this` so that calls can be chained.\n */",
"/**\n * Specifies the language the script is written in. Defaults to `painless` but\n * may be set to any of languages listed in [Scripting](https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-scripting.html).\n * The default language may be changed in the `elasticsearch.yml` config file by setting\n * `script.default_lang` to the appropriate language.\n *\n * For a `file` script, it should correspond with the script file suffix.\n * `groovy` for `config/scripts/calculate-score.groovy`.\n *\n * Note: The Groovy, JavaScript, and Python scripting languages were\n * deprecated in elasticsearch 5.0 and removed in 6.0. Use painless instead.\n *\n * @param {string} lang The language for the script.\n * @returns {Script} returns `this` so that calls can be chained.\n */",
"/**\n * Specifies any named parameters that are passed into the script as variables.\n *\n * @param {Object} params Named parameters to be passed to script.\n * @returns {Script} returns `this` so that calls can be chained.\n */",
"/**\n * Override default `toJSON` to return DSL representation for the `script`.\n *\n * @override\n * @returns {Object} returns an Object which maps to the elasticsearch query DSL\n */",
"// recursiveToJSON doesn't seem to be needed here"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 14
| 1,469
| 320
|
dd7a8430ccb0043a93d15afc2c77ce17bba87ca5
|
ShogoAkiyama54/leetcode
|
src/string/DecodeWays.java
|
[
"MIT"
] |
Java
|
DecodeWays
|
/**
* @author Shogo Akiyama
* Solved on 09/28/2019
*
* 91. Decode Ways
* https://leetcode.com/problems/decode-ways/
* Difficulty: Medium
*
* Approach: Divide and Conquer
* Runtime: 2 ms, faster than 55.00% of Java online submissions for Decode Ways.
* Memory Usage: 36.1 MB, less than 71.70% of Java online submissions for Decode Ways.
*
* @see StringTest#testDecodeWays()
*/
|
@author Shogo Akiyama
Solved on 09/28/2019
91.
Divide and Conquer
Runtime: 2 ms, faster than 55.00% of Java online submissions for Decode Ways.
Memory Usage: 36.1 MB, less than 71.70% of Java online submissions for Decode Ways.
|
[
"@author",
"Shogo",
"Akiyama",
"Solved",
"on",
"09",
"/",
"28",
"/",
"2019",
"91",
".",
"Divide",
"and",
"Conquer",
"Runtime",
":",
"2",
"ms",
"faster",
"than",
"55",
".",
"00%",
"of",
"Java",
"online",
"submissions",
"for",
"Decode",
"Ways",
".",
"Memory",
"Usage",
":",
"36",
".",
"1",
"MB",
"less",
"than",
"71",
".",
"70%",
"of",
"Java",
"online",
"submissions",
"for",
"Decode",
"Ways",
"."
] |
public class DecodeWays {
public int numDecodings(String s) {
int[] vals = new int[s.length()];
for (int i = 0; i < s.length(); i++) {
vals[i] = Integer.valueOf(s.charAt(i) + "");
}
return dc(vals, 0, vals.length - 1);
}
private int dc(int[] nums, int s, int e) {
if (e - s + 1 <= 1) {
if (e == s && nums[e] == 0) {
return 0;
}
return 1;
}
int mid = (e + s) / 2;
int count = dc(nums, s, mid);
count *= dc(nums, mid + 1, e);
if ((nums[mid] == 1) || (nums[mid] == 2 && nums[mid + 1] >= 0 && nums[mid + 1] <= 6)) {
int middleCount = dc(nums, s, mid - 1);
middleCount *= dc(nums, mid + 2, e);
count += middleCount;
}
return count;
}
}
|
[
"public",
"class",
"DecodeWays",
"{",
"public",
"int",
"numDecodings",
"(",
"String",
"s",
")",
"{",
"int",
"[",
"]",
"vals",
"=",
"new",
"int",
"[",
"s",
".",
"length",
"(",
")",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"s",
".",
"length",
"(",
")",
";",
"i",
"++",
")",
"{",
"vals",
"[",
"i",
"]",
"=",
"Integer",
".",
"valueOf",
"(",
"s",
".",
"charAt",
"(",
"i",
")",
"+",
"\"",
"\"",
")",
";",
"}",
"return",
"dc",
"(",
"vals",
",",
"0",
",",
"vals",
".",
"length",
"-",
"1",
")",
";",
"}",
"private",
"int",
"dc",
"(",
"int",
"[",
"]",
"nums",
",",
"int",
"s",
",",
"int",
"e",
")",
"{",
"if",
"(",
"e",
"-",
"s",
"+",
"1",
"<=",
"1",
")",
"{",
"if",
"(",
"e",
"==",
"s",
"&&",
"nums",
"[",
"e",
"]",
"==",
"0",
")",
"{",
"return",
"0",
";",
"}",
"return",
"1",
";",
"}",
"int",
"mid",
"=",
"(",
"e",
"+",
"s",
")",
"/",
"2",
";",
"int",
"count",
"=",
"dc",
"(",
"nums",
",",
"s",
",",
"mid",
")",
";",
"count",
"*=",
"dc",
"(",
"nums",
",",
"mid",
"+",
"1",
",",
"e",
")",
";",
"if",
"(",
"(",
"nums",
"[",
"mid",
"]",
"==",
"1",
")",
"||",
"(",
"nums",
"[",
"mid",
"]",
"==",
"2",
"&&",
"nums",
"[",
"mid",
"+",
"1",
"]",
">=",
"0",
"&&",
"nums",
"[",
"mid",
"+",
"1",
"]",
"<=",
"6",
")",
")",
"{",
"int",
"middleCount",
"=",
"dc",
"(",
"nums",
",",
"s",
",",
"mid",
"-",
"1",
")",
";",
"middleCount",
"*=",
"dc",
"(",
"nums",
",",
"mid",
"+",
"2",
",",
"e",
")",
";",
"count",
"+=",
"middleCount",
";",
"}",
"return",
"count",
";",
"}",
"}"
] |
@author Shogo Akiyama
Solved on 09/28/2019
|
[
"@author",
"Shogo",
"Akiyama",
"Solved",
"on",
"09",
"/",
"28",
"/",
"2019"
] |
[] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 14
| 258
| 129
|
3312e67f734f7419a5fba4c7f1966ef576249b67
|
computestdev/computest-openrunner
|
runner-modules/runResult/lib/Event.js
|
[
"Apache-2.0"
] |
JavaScript
|
Event
|
/**
* An event is a time period which describes an event that occurred within the browser itself or the document.
*
* Each event has a "type" name, multiple events may have the same type name. The type name should describe what the event was.
* And event may contain child events. For example a "http-request" event might contain "dns", "wait", "transfer" child events.
*
* Events without a begin should, in principal, not occur. However events without an end are valid (which means that the event ends
* _after_ the script run)
*/
|
An event is a time period which describes an event that occurred within the browser itself or the document.
Each event has a "type" name, multiple events may have the same type name. The type name should describe what the event was.
And event may contain child events.
Events without a begin should, in principal, not occur. However events without an end are valid (which means that the event ends
_after_ the script run)
|
[
"An",
"event",
"is",
"a",
"time",
"period",
"which",
"describes",
"an",
"event",
"that",
"occurred",
"within",
"the",
"browser",
"itself",
"or",
"the",
"document",
".",
"Each",
"event",
"has",
"a",
"\"",
"type",
"\"",
"name",
"multiple",
"events",
"may",
"have",
"the",
"same",
"type",
"name",
".",
"The",
"type",
"name",
"should",
"describe",
"what",
"the",
"event",
"was",
".",
"And",
"event",
"may",
"contain",
"child",
"events",
".",
"Events",
"without",
"a",
"begin",
"should",
"in",
"principal",
"not",
"occur",
".",
"However",
"events",
"without",
"an",
"end",
"are",
"valid",
"(",
"which",
"means",
"that",
"the",
"event",
"ends",
"_after_",
"the",
"script",
"run",
")"
] |
class Event {
/**
* Does the given value look like an Event?
*
* @param {*} object
* @return {boolean}
*/
static isEvent(object) {
return Boolean(
object &&
typeof object.type === 'string' &&
TimePeriod.isTimePeriod(object.timing) &&
typeof object.toJSONObject === 'function' &&
typeof object.addChild === 'function' &&
typeof object.setMetaData === 'function',
);
}
/**
* @param {!String} type
* @param {!TimePoint} beginTimePoint
* @param {?TimePoint} [endTimePoint=null]
* @return {Event}
*/
static fromTimePoint(type, beginTimePoint, endTimePoint = null) {
const event = new Event(type);
event.timing.begin = beginTimePoint;
event.timing.end = endTimePoint;
return event;
}
/**
* @param {!String} type
* @param {!number} beginTime Unix time in Milliseconds, see Date.now()
* @param {?number} [endTime=null] Unix time in Milliseconds, see Date.now()
* @return {Event}
*/
static fromTime(type, beginTime, endTime = null) {
const event = new Event(type);
if (typeof beginTime !== 'number') {
throw illegalArgumentError('Event.fromTime: Second argument (beginTime) is mandatory and must be a number');
}
event.timing.begin = new TimePoint(beginTime, {});
if (endTime !== null) {
if (typeof endTime !== 'number') {
throw illegalArgumentError('Event.fromTime: Third argument (endTime) must be a number or null');
}
event.timing.end = new TimePoint(endTime, {});
}
return event;
}
/**
* @param {string} type The type name of this Event. Multiple events can have the same type name.
*/
constructor(type) {
this[PRIVATE] = Object.seal({
children: new Set(),
comment: '',
longTitle: '',
metaData: new Map(),
shortTitle: '',
timing: new TimePeriod(),
type: String(type),
tabId: null,
frameId: null,
frameContentId: null,
});
Object.freeze(this);
}
/**
* The type name of this Event. Multiple events can have the same type name.
*
* @return {string}
*/
get type() {
return this[PRIVATE].type;
}
/**
* The time period that this event represents. This value is never null, however the TimePeriod itself might have null
* begin/end TimePoint's. For example, if an event is still on going, the "begin" is set, but the "end" will be null.
*
* @return {TimePeriod}
*/
get timing() {
return this[PRIVATE].timing;
}
/**
* @param {TimePeriod} value
*/
set timing(value) {
if (!TimePeriod.isTimePeriod(value)) {
throw illegalArgumentError('Event.timing: Value must be a TimePeriod');
}
this[PRIVATE].timing = value;
}
/**
* @param {Event} event
* @return {Event} The same value as `event`
*/
addChild(event) {
if (!Event.isEvent(event)) {
throw illegalArgumentError('Event.addChild: First argument must be an Event object');
}
this[PRIVATE].children.add(event);
return event;
}
/**
* Create an event and add it as a child
* @param {!String} type
* @param {!TimePoint} beginTimePoint
* @param {?TimePoint} [endTimePoint=null]
* @return {Event}
*/
childTimePointEvent(type, beginTimePoint, endTimePoint = null) {
const event = Event.fromTimePoint(type, beginTimePoint, endTimePoint);
return this.addChild(event);
}
/**
* Create an event and add it as a child
* @param {!String} type
* @param {!number} beginTime Unix time in Milliseconds, see Date.now()
* @param {?number} [endTime=null] Unix time in Milliseconds, see Date.now()
* @return {Event}
*/
childTimeEvent(type, beginTime, endTime = null) {
const event = Event.fromTime(type, beginTime, endTime);
return this.addChild(event);
}
/**
* @return {Iterator.<Event>}
*/
get children() {
return this[PRIVATE].children.values();
}
/**
* The "comment" field may be provided by a script creator to provide extra human readable information
*
* @return {string}
*/
get comment() {
return this[PRIVATE].comment;
}
/**
* The "comment" field may be provided by a script creator to provide extra human readable information
*
* @param {string} value
*/
set comment(value) {
this[PRIVATE].comment = String(value);
}
/**
* The "shortTitle" field is an automatically generated human readable title to be displayed in GUI's. Its content may be clipped in
* such GUI's so it should be short as possible.
*
* @return {string}
*/
get shortTitle() {
return this[PRIVATE].shortTitle;
}
/**
* The "shortTitle" field is an automatically generated human readable title to be displayed in GUI's. Its content may be clipped in
* such GUI's so it should be short as possible.
*
* @param {string} value
*/
set shortTitle(value) {
this[PRIVATE].shortTitle = String(value);
}
/**
* The "longTitle" field is an automatically generated human readable title to be displayed in GUI's. Its content should not be clipped
* in such GUI's and may be of any length.
*
* @return {string}
*/
get longTitle() {
return this[PRIVATE].longTitle;
}
/**
* The "longTitle" field is an automatically generated human readable title to be displayed in GUI's. Its content should not be clipped
* in such GUI's and may be of any length.
*
* @param {string} value
*/
set longTitle(value) {
this[PRIVATE].longTitle = String(value);
}
/**
* Return all metadata entries that have been set
* @return {Iterator.<[String, *]>}
*/
get metaData() {
return this[PRIVATE].metaData.entries();
}
/**
* Get the metadata value for the given key
* @param {String} key
* @return {*}
*/
getMetaData(key) {
if (typeof key !== 'string') {
throw illegalArgumentError('Event.getMetaData: First argument (key) must be a string');
}
return this[PRIVATE].metaData.has(key)
? this[PRIVATE].metaData.get(key)
: null;
}
/**
* Get the metadata value for the given key
* @param {String} key
* @param {*} value Any value that is convertible to json
*/
setMetaData(key, value) {
if (typeof key !== 'string') {
throw illegalArgumentError('Event.setMetaData: First argument (key) must be a string');
}
// jsonClone() ensures that everything is cloned, but also that the stored value can be properly converted to json when
// compiling the complete run result (fail early)
const valueCopy = jsonClone(value);
deepFreeze(valueCopy); // freeze so that the return value of getMetaData() can not be modified
this[PRIVATE].metaData.set(key, valueCopy);
}
/**
*
* @return {?string}
*/
get tabId() {
return this[PRIVATE].tabId;
}
/**
*
* @param {?string} value
*/
set tabId(value) {
this[PRIVATE].tabId = value ? String(value) : null;
}
/**
*
* @return {?number}
*/
get frameId() {
return this[PRIVATE].frameId;
}
/**
*
* @param {?number} value
*/
set frameId(value) {
this[PRIVATE].frameId = value ? Number(value) : null;
}
/**
*
* @return {?string}
*/
get frameContentId() {
return this[PRIVATE].frameContentId;
}
/**
*
* @param {?string} value
*/
set frameContentId(value) {
this[PRIVATE].frameContentId = value ? String(value) : null;
}
/**
* @return {{
* children: Array,
* timing: ({
* begin: (?{contentCounter: ?number, parentCounter: ?number, time: number}),
* end: (?{contentCounter: ?number, parentCounter: ?number, time: number}),
* duration: number
* }),
* type: string
* }}
*/
toJSONObject() {
const metaData = {};
for (const [key, value] of this.metaData) {
// the result of toJSONObject should not be "live", nor expose any "frozen" objects
metaData[key] = jsonClone(value);
}
// Firefox appears to maintain key order, so put the keys in an order that makes it more convenient to read the resulting json
/* eslint-disable sort-keys */
const result = {
type: this.type,
shortTitle: this.shortTitle,
longTitle: this.longTitle,
comment: this.comment,
id: null, // Set by parent-process/RunResult
timing: this.timing.toJSONObject(),
metaData: metaData,
children: [...this.children].map(event => event.toJSONObject()),
tabId: this.tabId,
frameId: this.frameId,
frameContentId: this.frameContentId,
};
/* eslint-enable sort-keys */
result.children.sort((a, b) => TimePoint.compare(a.timing.begin, b.timing.begin));
return result;
}
}
|
[
"class",
"Event",
"{",
"static",
"isEvent",
"(",
"object",
")",
"{",
"return",
"Boolean",
"(",
"object",
"&&",
"typeof",
"object",
".",
"type",
"===",
"'string'",
"&&",
"TimePeriod",
".",
"isTimePeriod",
"(",
"object",
".",
"timing",
")",
"&&",
"typeof",
"object",
".",
"toJSONObject",
"===",
"'function'",
"&&",
"typeof",
"object",
".",
"addChild",
"===",
"'function'",
"&&",
"typeof",
"object",
".",
"setMetaData",
"===",
"'function'",
",",
")",
";",
"}",
"static",
"fromTimePoint",
"(",
"type",
",",
"beginTimePoint",
",",
"endTimePoint",
"=",
"null",
")",
"{",
"const",
"event",
"=",
"new",
"Event",
"(",
"type",
")",
";",
"event",
".",
"timing",
".",
"begin",
"=",
"beginTimePoint",
";",
"event",
".",
"timing",
".",
"end",
"=",
"endTimePoint",
";",
"return",
"event",
";",
"}",
"static",
"fromTime",
"(",
"type",
",",
"beginTime",
",",
"endTime",
"=",
"null",
")",
"{",
"const",
"event",
"=",
"new",
"Event",
"(",
"type",
")",
";",
"if",
"(",
"typeof",
"beginTime",
"!==",
"'number'",
")",
"{",
"throw",
"illegalArgumentError",
"(",
"'Event.fromTime: Second argument (beginTime) is mandatory and must be a number'",
")",
";",
"}",
"event",
".",
"timing",
".",
"begin",
"=",
"new",
"TimePoint",
"(",
"beginTime",
",",
"{",
"}",
")",
";",
"if",
"(",
"endTime",
"!==",
"null",
")",
"{",
"if",
"(",
"typeof",
"endTime",
"!==",
"'number'",
")",
"{",
"throw",
"illegalArgumentError",
"(",
"'Event.fromTime: Third argument (endTime) must be a number or null'",
")",
";",
"}",
"event",
".",
"timing",
".",
"end",
"=",
"new",
"TimePoint",
"(",
"endTime",
",",
"{",
"}",
")",
";",
"}",
"return",
"event",
";",
"}",
"constructor",
"(",
"type",
")",
"{",
"this",
"[",
"PRIVATE",
"]",
"=",
"Object",
".",
"seal",
"(",
"{",
"children",
":",
"new",
"Set",
"(",
")",
",",
"comment",
":",
"''",
",",
"longTitle",
":",
"''",
",",
"metaData",
":",
"new",
"Map",
"(",
")",
",",
"shortTitle",
":",
"''",
",",
"timing",
":",
"new",
"TimePeriod",
"(",
")",
",",
"type",
":",
"String",
"(",
"type",
")",
",",
"tabId",
":",
"null",
",",
"frameId",
":",
"null",
",",
"frameContentId",
":",
"null",
",",
"}",
")",
";",
"Object",
".",
"freeze",
"(",
"this",
")",
";",
"}",
"get",
"type",
"(",
")",
"{",
"return",
"this",
"[",
"PRIVATE",
"]",
".",
"type",
";",
"}",
"get",
"timing",
"(",
")",
"{",
"return",
"this",
"[",
"PRIVATE",
"]",
".",
"timing",
";",
"}",
"set",
"timing",
"(",
"value",
")",
"{",
"if",
"(",
"!",
"TimePeriod",
".",
"isTimePeriod",
"(",
"value",
")",
")",
"{",
"throw",
"illegalArgumentError",
"(",
"'Event.timing: Value must be a TimePeriod'",
")",
";",
"}",
"this",
"[",
"PRIVATE",
"]",
".",
"timing",
"=",
"value",
";",
"}",
"addChild",
"(",
"event",
")",
"{",
"if",
"(",
"!",
"Event",
".",
"isEvent",
"(",
"event",
")",
")",
"{",
"throw",
"illegalArgumentError",
"(",
"'Event.addChild: First argument must be an Event object'",
")",
";",
"}",
"this",
"[",
"PRIVATE",
"]",
".",
"children",
".",
"add",
"(",
"event",
")",
";",
"return",
"event",
";",
"}",
"childTimePointEvent",
"(",
"type",
",",
"beginTimePoint",
",",
"endTimePoint",
"=",
"null",
")",
"{",
"const",
"event",
"=",
"Event",
".",
"fromTimePoint",
"(",
"type",
",",
"beginTimePoint",
",",
"endTimePoint",
")",
";",
"return",
"this",
".",
"addChild",
"(",
"event",
")",
";",
"}",
"childTimeEvent",
"(",
"type",
",",
"beginTime",
",",
"endTime",
"=",
"null",
")",
"{",
"const",
"event",
"=",
"Event",
".",
"fromTime",
"(",
"type",
",",
"beginTime",
",",
"endTime",
")",
";",
"return",
"this",
".",
"addChild",
"(",
"event",
")",
";",
"}",
"get",
"children",
"(",
")",
"{",
"return",
"this",
"[",
"PRIVATE",
"]",
".",
"children",
".",
"values",
"(",
")",
";",
"}",
"get",
"comment",
"(",
")",
"{",
"return",
"this",
"[",
"PRIVATE",
"]",
".",
"comment",
";",
"}",
"set",
"comment",
"(",
"value",
")",
"{",
"this",
"[",
"PRIVATE",
"]",
".",
"comment",
"=",
"String",
"(",
"value",
")",
";",
"}",
"get",
"shortTitle",
"(",
")",
"{",
"return",
"this",
"[",
"PRIVATE",
"]",
".",
"shortTitle",
";",
"}",
"set",
"shortTitle",
"(",
"value",
")",
"{",
"this",
"[",
"PRIVATE",
"]",
".",
"shortTitle",
"=",
"String",
"(",
"value",
")",
";",
"}",
"get",
"longTitle",
"(",
")",
"{",
"return",
"this",
"[",
"PRIVATE",
"]",
".",
"longTitle",
";",
"}",
"set",
"longTitle",
"(",
"value",
")",
"{",
"this",
"[",
"PRIVATE",
"]",
".",
"longTitle",
"=",
"String",
"(",
"value",
")",
";",
"}",
"get",
"metaData",
"(",
")",
"{",
"return",
"this",
"[",
"PRIVATE",
"]",
".",
"metaData",
".",
"entries",
"(",
")",
";",
"}",
"getMetaData",
"(",
"key",
")",
"{",
"if",
"(",
"typeof",
"key",
"!==",
"'string'",
")",
"{",
"throw",
"illegalArgumentError",
"(",
"'Event.getMetaData: First argument (key) must be a string'",
")",
";",
"}",
"return",
"this",
"[",
"PRIVATE",
"]",
".",
"metaData",
".",
"has",
"(",
"key",
")",
"?",
"this",
"[",
"PRIVATE",
"]",
".",
"metaData",
".",
"get",
"(",
"key",
")",
":",
"null",
";",
"}",
"setMetaData",
"(",
"key",
",",
"value",
")",
"{",
"if",
"(",
"typeof",
"key",
"!==",
"'string'",
")",
"{",
"throw",
"illegalArgumentError",
"(",
"'Event.setMetaData: First argument (key) must be a string'",
")",
";",
"}",
"const",
"valueCopy",
"=",
"jsonClone",
"(",
"value",
")",
";",
"deepFreeze",
"(",
"valueCopy",
")",
";",
"this",
"[",
"PRIVATE",
"]",
".",
"metaData",
".",
"set",
"(",
"key",
",",
"valueCopy",
")",
";",
"}",
"get",
"tabId",
"(",
")",
"{",
"return",
"this",
"[",
"PRIVATE",
"]",
".",
"tabId",
";",
"}",
"set",
"tabId",
"(",
"value",
")",
"{",
"this",
"[",
"PRIVATE",
"]",
".",
"tabId",
"=",
"value",
"?",
"String",
"(",
"value",
")",
":",
"null",
";",
"}",
"get",
"frameId",
"(",
")",
"{",
"return",
"this",
"[",
"PRIVATE",
"]",
".",
"frameId",
";",
"}",
"set",
"frameId",
"(",
"value",
")",
"{",
"this",
"[",
"PRIVATE",
"]",
".",
"frameId",
"=",
"value",
"?",
"Number",
"(",
"value",
")",
":",
"null",
";",
"}",
"get",
"frameContentId",
"(",
")",
"{",
"return",
"this",
"[",
"PRIVATE",
"]",
".",
"frameContentId",
";",
"}",
"set",
"frameContentId",
"(",
"value",
")",
"{",
"this",
"[",
"PRIVATE",
"]",
".",
"frameContentId",
"=",
"value",
"?",
"String",
"(",
"value",
")",
":",
"null",
";",
"}",
"toJSONObject",
"(",
")",
"{",
"const",
"metaData",
"=",
"{",
"}",
";",
"for",
"(",
"const",
"[",
"key",
",",
"value",
"]",
"of",
"this",
".",
"metaData",
")",
"{",
"metaData",
"[",
"key",
"]",
"=",
"jsonClone",
"(",
"value",
")",
";",
"}",
"const",
"result",
"=",
"{",
"type",
":",
"this",
".",
"type",
",",
"shortTitle",
":",
"this",
".",
"shortTitle",
",",
"longTitle",
":",
"this",
".",
"longTitle",
",",
"comment",
":",
"this",
".",
"comment",
",",
"id",
":",
"null",
",",
"timing",
":",
"this",
".",
"timing",
".",
"toJSONObject",
"(",
")",
",",
"metaData",
":",
"metaData",
",",
"children",
":",
"[",
"...",
"this",
".",
"children",
"]",
".",
"map",
"(",
"event",
"=>",
"event",
".",
"toJSONObject",
"(",
")",
")",
",",
"tabId",
":",
"this",
".",
"tabId",
",",
"frameId",
":",
"this",
".",
"frameId",
",",
"frameContentId",
":",
"this",
".",
"frameContentId",
",",
"}",
";",
"result",
".",
"children",
".",
"sort",
"(",
"(",
"a",
",",
"b",
")",
"=>",
"TimePoint",
".",
"compare",
"(",
"a",
".",
"timing",
".",
"begin",
",",
"b",
".",
"timing",
".",
"begin",
")",
")",
";",
"return",
"result",
";",
"}",
"}"
] |
An event is a time period which describes an event that occurred within the browser itself or the document.
|
[
"An",
"event",
"is",
"a",
"time",
"period",
"which",
"describes",
"an",
"event",
"that",
"occurred",
"within",
"the",
"browser",
"itself",
"or",
"the",
"document",
"."
] |
[
"/**\n * Does the given value look like an Event?\n *\n * @param {*} object\n * @return {boolean}\n */",
"/**\n * @param {!String} type\n * @param {!TimePoint} beginTimePoint\n * @param {?TimePoint} [endTimePoint=null]\n * @return {Event}\n */",
"/**\n * @param {!String} type\n * @param {!number} beginTime Unix time in Milliseconds, see Date.now()\n * @param {?number} [endTime=null] Unix time in Milliseconds, see Date.now()\n * @return {Event}\n */",
"/**\n * @param {string} type The type name of this Event. Multiple events can have the same type name.\n */",
"/**\n * The type name of this Event. Multiple events can have the same type name.\n *\n * @return {string}\n */",
"/**\n * The time period that this event represents. This value is never null, however the TimePeriod itself might have null\n * begin/end TimePoint's. For example, if an event is still on going, the \"begin\" is set, but the \"end\" will be null.\n *\n * @return {TimePeriod}\n */",
"/**\n * @param {TimePeriod} value\n */",
"/**\n * @param {Event} event\n * @return {Event} The same value as `event`\n */",
"/**\n * Create an event and add it as a child\n * @param {!String} type\n * @param {!TimePoint} beginTimePoint\n * @param {?TimePoint} [endTimePoint=null]\n * @return {Event}\n */",
"/**\n * Create an event and add it as a child\n * @param {!String} type\n * @param {!number} beginTime Unix time in Milliseconds, see Date.now()\n * @param {?number} [endTime=null] Unix time in Milliseconds, see Date.now()\n * @return {Event}\n */",
"/**\n * @return {Iterator.<Event>}\n */",
"/**\n * The \"comment\" field may be provided by a script creator to provide extra human readable information\n *\n * @return {string}\n */",
"/**\n * The \"comment\" field may be provided by a script creator to provide extra human readable information\n *\n * @param {string} value\n */",
"/**\n * The \"shortTitle\" field is an automatically generated human readable title to be displayed in GUI's. Its content may be clipped in\n * such GUI's so it should be short as possible.\n *\n * @return {string}\n */",
"/**\n * The \"shortTitle\" field is an automatically generated human readable title to be displayed in GUI's. Its content may be clipped in\n * such GUI's so it should be short as possible.\n *\n * @param {string} value\n */",
"/**\n * The \"longTitle\" field is an automatically generated human readable title to be displayed in GUI's. Its content should not be clipped\n * in such GUI's and may be of any length.\n *\n * @return {string}\n */",
"/**\n * The \"longTitle\" field is an automatically generated human readable title to be displayed in GUI's. Its content should not be clipped\n * in such GUI's and may be of any length.\n *\n * @param {string} value\n */",
"/**\n * Return all metadata entries that have been set\n * @return {Iterator.<[String, *]>}\n */",
"/**\n * Get the metadata value for the given key\n * @param {String} key\n * @return {*}\n */",
"/**\n * Get the metadata value for the given key\n * @param {String} key\n * @param {*} value Any value that is convertible to json\n */",
"// jsonClone() ensures that everything is cloned, but also that the stored value can be properly converted to json when",
"// compiling the complete run result (fail early)",
"// freeze so that the return value of getMetaData() can not be modified",
"/**\n *\n * @return {?string}\n */",
"/**\n *\n * @param {?string} value\n */",
"/**\n *\n * @return {?number}\n */",
"/**\n *\n * @param {?number} value\n */",
"/**\n *\n * @return {?string}\n */",
"/**\n *\n * @param {?string} value\n */",
"/**\n * @return {{\n * children: Array,\n * timing: ({\n * begin: (?{contentCounter: ?number, parentCounter: ?number, time: number}),\n * end: (?{contentCounter: ?number, parentCounter: ?number, time: number}),\n * duration: number\n * }),\n * type: string\n * }}\n */",
"// the result of toJSONObject should not be \"live\", nor expose any \"frozen\" objects",
"// Firefox appears to maintain key order, so put the keys in an order that makes it more convenient to read the resulting json",
"/* eslint-disable sort-keys */",
"// Set by parent-process/RunResult",
"/* eslint-enable sort-keys */"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 16
| 2,236
| 120
|
2d5b8ac8b0dd873c560845cead10310212bfb158
|
geocom-gis/lucenenet
|
src/Lucene.Net/Store/SimpleFSDirectory.cs
|
[
"Apache-2.0"
] |
C#
|
SimpleFSDirectory
|
/// <summary>
/// A straightforward implementation of <see cref="FSDirectory"/>
/// using <see cref="FileStream"/>. However, this class has
/// poor concurrent performance (multiple threads will
/// bottleneck) as it synchronizes when multiple threads
/// read from the same file. It's usually better to use
/// <see cref="NIOFSDirectory"/> or <see cref="MMapDirectory"/> instead.
/// </summary>
|
A straightforward implementation of
using . However, this class has
poor concurrent performance (multiple threads will
bottleneck) as it synchronizes when multiple threads
read from the same file. It's usually better to use
or instead.
|
[
"A",
"straightforward",
"implementation",
"of",
"using",
".",
"However",
"this",
"class",
"has",
"poor",
"concurrent",
"performance",
"(",
"multiple",
"threads",
"will",
"bottleneck",
")",
"as",
"it",
"synchronizes",
"when",
"multiple",
"threads",
"read",
"from",
"the",
"same",
"file",
".",
"It",
"'",
"s",
"usually",
"better",
"to",
"use",
"or",
"instead",
"."
] |
public class SimpleFSDirectory : FSDirectory
{
public SimpleFSDirectory(DirectoryInfo path, LockFactory lockFactory)
: base(path, lockFactory)
{
}
public SimpleFSDirectory(DirectoryInfo path)
: base(path, null)
{
}
public SimpleFSDirectory(string path, LockFactory lockFactory)
: this(new DirectoryInfo(path), lockFactory)
{
}
public SimpleFSDirectory(string path)
: this(path, null)
{
}
public override IndexInput OpenInput(string name, IOContext context)
{
EnsureOpen();
var path = new FileInfo(Path.Combine(Directory.FullName, name));
var raf = new FileStream(path.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
return new SimpleFSIndexInput("SimpleFSIndexInput(path=\"" + path.FullName + "\")", raf, context);
}
public override IndexInputSlicer CreateSlicer(string name, IOContext context)
{
EnsureOpen();
var file = new FileInfo(Path.Combine(Directory.FullName, name));
var descriptor = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
return new IndexInputSlicerAnonymousInnerClassHelper(context, file, descriptor);
}
private class IndexInputSlicerAnonymousInnerClassHelper : IndexInputSlicer
{
private readonly IOContext context;
private readonly FileInfo file;
private readonly FileStream descriptor;
public IndexInputSlicerAnonymousInnerClassHelper(IOContext context, FileInfo file, FileStream descriptor)
{
this.context = context;
this.file = file;
this.descriptor = descriptor;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
descriptor.Dispose();
}
}
public override IndexInput OpenSlice(string sliceDescription, long offset, long length)
{
return new SimpleFSIndexInput("SimpleFSIndexInput(" + sliceDescription + " in path=\"" + file.FullName + "\" slice=" + offset + ":" + (offset + length) + ")", descriptor, offset, length, BufferedIndexInput.GetBufferSize(context));
}
[Obsolete("Only for reading CFS files from 3.x indexes.")]
public override IndexInput OpenFullSlice()
{
try
{
return OpenSlice("full-slice", 0, descriptor.Length);
}
catch (IOException ex)
{
throw new Exception(ex.ToString(), ex);
}
}
}
protected internal class SimpleFSIndexInput : BufferedIndexInput
{
//
//
protected internal readonly FileStream m_file;
public bool IsClone { get; set; }
protected internal readonly long m_off;
protected internal readonly long m_end;
public SimpleFSIndexInput(string resourceDesc, FileStream file, IOContext context)
: base(resourceDesc, context)
{
this.m_file = file;
this.m_off = 0L;
this.m_end = file.Length;
this.IsClone = false;
}
public SimpleFSIndexInput(string resourceDesc, FileStream file, long off, long length, int bufferSize)
: base(resourceDesc, bufferSize)
{
this.m_file = file;
this.m_off = off;
this.m_end = off + length;
this.IsClone = true;
}
protected override void Dispose(bool disposing)
{
if (disposing && !IsClone)
{
m_file.Dispose();
}
}
public override object Clone()
{
SimpleFSIndexInput clone = (SimpleFSIndexInput)base.Clone();
clone.IsClone = true;
return clone;
}
public override sealed long Length
{
get { return m_end - m_off; }
}
protected override void ReadInternal(byte[] b, int offset, int len)
{
lock (m_file)
{
long position = m_off + GetFilePointer();
m_file.Seek(position, SeekOrigin.Begin);
int total = 0;
if (position + len > m_end)
{
throw new EndOfStreamException("read past EOF: " + this);
}
try
{
total = m_file.Read(b, offset, len);
}
catch (IOException ioe)
{
throw new IOException(ioe.Message + ": " + this, ioe);
}
}
}
protected override void SeekInternal(long position)
{
}
public virtual bool IsFDValid
{
get
{
return m_file != null;
}
}
}
}
|
[
"public",
"class",
"SimpleFSDirectory",
":",
"FSDirectory",
"{",
"public",
"SimpleFSDirectory",
"(",
"DirectoryInfo",
"path",
",",
"LockFactory",
"lockFactory",
")",
":",
"base",
"(",
"path",
",",
"lockFactory",
")",
"{",
"}",
"public",
"SimpleFSDirectory",
"(",
"DirectoryInfo",
"path",
")",
":",
"base",
"(",
"path",
",",
"null",
")",
"{",
"}",
"public",
"SimpleFSDirectory",
"(",
"string",
"path",
",",
"LockFactory",
"lockFactory",
")",
":",
"this",
"(",
"new",
"DirectoryInfo",
"(",
"path",
")",
",",
"lockFactory",
")",
"{",
"}",
"public",
"SimpleFSDirectory",
"(",
"string",
"path",
")",
":",
"this",
"(",
"path",
",",
"null",
")",
"{",
"}",
"public",
"override",
"IndexInput",
"OpenInput",
"(",
"string",
"name",
",",
"IOContext",
"context",
")",
"{",
"EnsureOpen",
"(",
")",
";",
"var",
"path",
"=",
"new",
"FileInfo",
"(",
"Path",
".",
"Combine",
"(",
"Directory",
".",
"FullName",
",",
"name",
")",
")",
";",
"var",
"raf",
"=",
"new",
"FileStream",
"(",
"path",
".",
"FullName",
",",
"FileMode",
".",
"Open",
",",
"FileAccess",
".",
"Read",
",",
"FileShare",
".",
"ReadWrite",
")",
";",
"return",
"new",
"SimpleFSIndexInput",
"(",
"\"",
"SimpleFSIndexInput(path=",
"\\\"",
"\"",
"+",
"path",
".",
"FullName",
"+",
"\"",
"\\\"",
")",
"\"",
",",
"raf",
",",
"context",
")",
";",
"}",
"public",
"override",
"IndexInputSlicer",
"CreateSlicer",
"(",
"string",
"name",
",",
"IOContext",
"context",
")",
"{",
"EnsureOpen",
"(",
")",
";",
"var",
"file",
"=",
"new",
"FileInfo",
"(",
"Path",
".",
"Combine",
"(",
"Directory",
".",
"FullName",
",",
"name",
")",
")",
";",
"var",
"descriptor",
"=",
"new",
"FileStream",
"(",
"file",
".",
"FullName",
",",
"FileMode",
".",
"Open",
",",
"FileAccess",
".",
"Read",
",",
"FileShare",
".",
"ReadWrite",
")",
";",
"return",
"new",
"IndexInputSlicerAnonymousInnerClassHelper",
"(",
"context",
",",
"file",
",",
"descriptor",
")",
";",
"}",
"private",
"class",
"IndexInputSlicerAnonymousInnerClassHelper",
":",
"IndexInputSlicer",
"{",
"private",
"readonly",
"IOContext",
"context",
";",
"private",
"readonly",
"FileInfo",
"file",
";",
"private",
"readonly",
"FileStream",
"descriptor",
";",
"public",
"IndexInputSlicerAnonymousInnerClassHelper",
"(",
"IOContext",
"context",
",",
"FileInfo",
"file",
",",
"FileStream",
"descriptor",
")",
"{",
"this",
".",
"context",
"=",
"context",
";",
"this",
".",
"file",
"=",
"file",
";",
"this",
".",
"descriptor",
"=",
"descriptor",
";",
"}",
"protected",
"override",
"void",
"Dispose",
"(",
"bool",
"disposing",
")",
"{",
"if",
"(",
"disposing",
")",
"{",
"descriptor",
".",
"Dispose",
"(",
")",
";",
"}",
"}",
"public",
"override",
"IndexInput",
"OpenSlice",
"(",
"string",
"sliceDescription",
",",
"long",
"offset",
",",
"long",
"length",
")",
"{",
"return",
"new",
"SimpleFSIndexInput",
"(",
"\"",
"SimpleFSIndexInput(",
"\"",
"+",
"sliceDescription",
"+",
"\"",
" in path=",
"\\\"",
"\"",
"+",
"file",
".",
"FullName",
"+",
"\"",
"\\\"",
" slice=",
"\"",
"+",
"offset",
"+",
"\"",
":",
"\"",
"+",
"(",
"offset",
"+",
"length",
")",
"+",
"\"",
")",
"\"",
",",
"descriptor",
",",
"offset",
",",
"length",
",",
"BufferedIndexInput",
".",
"GetBufferSize",
"(",
"context",
")",
")",
";",
"}",
"[",
"Obsolete",
"(",
"\"",
"Only for reading CFS files from 3.x indexes.",
"\"",
")",
"]",
"public",
"override",
"IndexInput",
"OpenFullSlice",
"(",
")",
"{",
"try",
"{",
"return",
"OpenSlice",
"(",
"\"",
"full-slice",
"\"",
",",
"0",
",",
"descriptor",
".",
"Length",
")",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"throw",
"new",
"Exception",
"(",
"ex",
".",
"ToString",
"(",
")",
",",
"ex",
")",
";",
"}",
"}",
"}",
"protected",
"internal",
"class",
"SimpleFSIndexInput",
":",
"BufferedIndexInput",
"{",
"protected",
"internal",
"readonly",
"FileStream",
"m_file",
";",
"public",
"bool",
"IsClone",
"{",
"get",
";",
"set",
";",
"}",
"protected",
"internal",
"readonly",
"long",
"m_off",
";",
"protected",
"internal",
"readonly",
"long",
"m_end",
";",
"public",
"SimpleFSIndexInput",
"(",
"string",
"resourceDesc",
",",
"FileStream",
"file",
",",
"IOContext",
"context",
")",
":",
"base",
"(",
"resourceDesc",
",",
"context",
")",
"{",
"this",
".",
"m_file",
"=",
"file",
";",
"this",
".",
"m_off",
"=",
"0L",
";",
"this",
".",
"m_end",
"=",
"file",
".",
"Length",
";",
"this",
".",
"IsClone",
"=",
"false",
";",
"}",
"public",
"SimpleFSIndexInput",
"(",
"string",
"resourceDesc",
",",
"FileStream",
"file",
",",
"long",
"off",
",",
"long",
"length",
",",
"int",
"bufferSize",
")",
":",
"base",
"(",
"resourceDesc",
",",
"bufferSize",
")",
"{",
"this",
".",
"m_file",
"=",
"file",
";",
"this",
".",
"m_off",
"=",
"off",
";",
"this",
".",
"m_end",
"=",
"off",
"+",
"length",
";",
"this",
".",
"IsClone",
"=",
"true",
";",
"}",
"protected",
"override",
"void",
"Dispose",
"(",
"bool",
"disposing",
")",
"{",
"if",
"(",
"disposing",
"&&",
"!",
"IsClone",
")",
"{",
"m_file",
".",
"Dispose",
"(",
")",
";",
"}",
"}",
"public",
"override",
"object",
"Clone",
"(",
")",
"{",
"SimpleFSIndexInput",
"clone",
"=",
"(",
"SimpleFSIndexInput",
")",
"base",
".",
"Clone",
"(",
")",
";",
"clone",
".",
"IsClone",
"=",
"true",
";",
"return",
"clone",
";",
"}",
"public",
"override",
"sealed",
"long",
"Length",
"{",
"get",
"{",
"return",
"m_end",
"-",
"m_off",
";",
"}",
"}",
"protected",
"override",
"void",
"ReadInternal",
"(",
"byte",
"[",
"]",
"b",
",",
"int",
"offset",
",",
"int",
"len",
")",
"{",
"lock",
"(",
"m_file",
")",
"{",
"long",
"position",
"=",
"m_off",
"+",
"GetFilePointer",
"(",
")",
";",
"m_file",
".",
"Seek",
"(",
"position",
",",
"SeekOrigin",
".",
"Begin",
")",
";",
"int",
"total",
"=",
"0",
";",
"if",
"(",
"position",
"+",
"len",
">",
"m_end",
")",
"{",
"throw",
"new",
"EndOfStreamException",
"(",
"\"",
"read past EOF: ",
"\"",
"+",
"this",
")",
";",
"}",
"try",
"{",
"total",
"=",
"m_file",
".",
"Read",
"(",
"b",
",",
"offset",
",",
"len",
")",
";",
"}",
"catch",
"(",
"IOException",
"ioe",
")",
"{",
"throw",
"new",
"IOException",
"(",
"ioe",
".",
"Message",
"+",
"\"",
": ",
"\"",
"+",
"this",
",",
"ioe",
")",
";",
"}",
"}",
"}",
"protected",
"override",
"void",
"SeekInternal",
"(",
"long",
"position",
")",
"{",
"}",
"public",
"virtual",
"bool",
"IsFDValid",
"{",
"get",
"{",
"return",
"m_file",
"!=",
"null",
";",
"}",
"}",
"}",
"}"
] |
A straightforward implementation of
using .
|
[
"A",
"straightforward",
"implementation",
"of",
"using",
"."
] |
[
"/// <summary>",
"/// Create a new <see cref=\"SimpleFSDirectory\"/> for the named location.",
"/// </summary>",
"/// <param name=\"path\"> the path of the directory </param>",
"/// <param name=\"lockFactory\"> the lock factory to use, or null for the default",
"/// (<see cref=\"NativeFSLockFactory\"/>); </param>",
"/// <exception cref=\"IOException\"> if there is a low-level I/O error </exception>",
"/// <summary>",
"/// Create a new <see cref=\"SimpleFSDirectory\"/> for the named location and <see cref=\"NativeFSLockFactory\"/>.",
"/// </summary>",
"/// <param name=\"path\"> the path of the directory </param>",
"/// <exception cref=\"IOException\"> if there is a low-level I/O error </exception>",
"/// <summary>",
"/// Create a new <see cref=\"SimpleFSDirectory\"/> for the named location.",
"/// <para/>",
"/// LUCENENET specific overload for convenience using string instead of <see cref=\"DirectoryInfo\"/>.",
"/// </summary>",
"/// <param name=\"path\"> the path of the directory </param>",
"/// <param name=\"lockFactory\"> the lock factory to use, or null for the default",
"/// (<see cref=\"NativeFSLockFactory\"/>); </param>",
"/// <exception cref=\"IOException\"> if there is a low-level I/O error </exception>",
"/// <summary>",
"/// Create a new <see cref=\"SimpleFSDirectory\"/> for the named location and <see cref=\"NativeFSLockFactory\"/>.",
"/// <para/>",
"/// LUCENENET specific overload for convenience using string instead of <see cref=\"DirectoryInfo\"/>.",
"/// </summary>",
"/// <param name=\"path\"> the path of the directory </param>",
"/// <exception cref=\"IOException\"> if there is a low-level I/O error </exception>",
"/// <summary>",
"/// Creates an <see cref=\"IndexInput\"/> for the file with the given name. </summary>",
"/// <summary>",
"/// Reads bytes with <see cref=\"FileStream.Seek(long, SeekOrigin)\"/> followed by",
"/// <see cref=\"FileStream.Read(byte[], int, int)\"/>.",
"/// </summary>",
"// LUCENENET specific: chunk size not needed",
"///// <summary>",
"///// The maximum chunk size is 8192 bytes, because <seealso cref=\"RandomAccessFile\"/> mallocs",
"///// a native buffer outside of stack if the read buffer size is larger.",
"///// </summary>",
"//private const int CHUNK_SIZE = 8192;",
"/// <summary>",
"/// the file channel we will read from </summary>",
"/// <summary>",
"/// is this instance a clone and hence does not own the file to close it </summary>",
"/// <summary>",
"/// start offset: non-zero in the slice case </summary>",
"/// <summary>",
"/// end offset (start+length) </summary>",
"/// <summary>",
"/// <see cref=\"IndexInput\"/> methods </summary>",
"//while (total < len)",
"//{",
"// int toRead = Math.Min(CHUNK_SIZE, len - total);",
"// int i = m_file.Read(b, offset + total, toRead);",
"// if (i < 0) // be defensive here, even though we checked before hand, something could have changed",
"// {",
"// throw new EndOfStreamException(\"read past EOF: \" + this + \" off: \" + offset + \" len: \" + len + \" total: \" + total + \" chunkLen: \" + toRead + \" end: \" + m_end);",
"// }",
"// Debug.Assert(i > 0, \"RandomAccessFile.read with non zero-length toRead must always read at least one byte\");",
"// total += i;",
"//}",
"// LUCENENET specific: FileStream is already optimized to read natively",
"// using the buffer size that is passed through its constructor. So,",
"// all we need to do is Read().",
"//Debug.Assert(total == len);"
] |
[
{
"param": "FSDirectory",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "FSDirectory",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 20
| 966
| 94
|
0d5358ef02215e4745e3011344189d770e846535
|
Christian-Me/node-red-contrib-tools
|
timeTable.js
|
[
"MIT"
] |
JavaScript
|
TimeTable
|
/**
* Copyright 2021 Christian Meinert
*
* 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.
**/
|
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.
|
[
"Unless",
"required",
"by",
"applicable",
"law",
"or",
"agreed",
"to",
"in",
"writing",
"software",
"distributed",
"under",
"the",
"License",
"is",
"distributed",
"on",
"an",
"\"",
"AS",
"IS",
"\"",
"BASIS",
"WITHOUT",
"WARRANTIES",
"OR",
"CONDITIONS",
"OF",
"ANY",
"KIND",
"either",
"express",
"or",
"implied",
".",
"See",
"the",
"License",
"for",
"the",
"specific",
"language",
"governing",
"permissions",
"and",
"limitations",
"under",
"the",
"License",
"."
] |
class TimeTable {
constructor() {
var table = this;
table.content = [[]];
table.rowMap = {};
table.columns = 0;
table.rows = 0;
}
/*************************************************
* deep merge object / array
* @param {object} target target object
* @param {object} source source object
*************************************************/
mergeObject(target,source) {
if (typeof source === 'object') {
Object.keys(source).forEach(element => {
if (typeof source[element] !== "object") {
target[element] = source[element];
} else {
if (!target.hasOwnProperty(element)) {
target[element] = (Array.isArray(source[element])) ? [] : {};
}
this.mergeObject(target[element],source[element])
}
});
} else {
target=source;
}
}
/*************************************************
* get table data
* @return {array} [rows][columns]
*************************************************/
getTable() { return this.content };
/*************************************************
* set table data
* @param {array} data [rows][columns]
*************************************************/
setTable(data) {
if (Array.isArray(data)) {
delete this.content;
this.content = [];
this.mergeObject(this.content,data);
this.columns = this.content[0].length;
this.rows = this.content.length;
} else {console.warn('timeTable.setTable() data must be an array!', data);}
};
/*************************************************
* get row map
* @return {object} rowMap {id:row}
*************************************************/
getRowMap() { return this.rowMap };
/*************************************************
* set row map
* @param {object} rowMap {id:row}
*************************************************/
setRowMap(rowMap) {
if (typeof rowMap === 'object') {
delete this.rowMap;
this.rowMap = {};
this.mergeObject(this.rowMap,rowMap);
} else {console.warn('timeTable.rowMap() rowMap must be an object!', rowMap);}
};
/*************************************************
* get width (columns)
* @return {number} amount of columns
*************************************************/
getWidth() { return this.content[0].length };
/*************************************************
* get height (rows) without time row
* @return {number} amount of rows
*************************************************/
getHeight() { return this.content.length-1 };
/*************************************************
* set height (rows) and adding not populated rows
* @param {number} rows of rows without time row
*************************************************/
setHeight(rows) {
var table = this;
// console.log('setHeight',table.content);
let row = table.content.length;
while (row <= rows) {
table.content[row]=Array(table.content[0].length);
row++;
}
table.rows = table.content.length;
};
/*************************************************
* checks if a row id exists
* @param {string} id
* @return {number} amount of rows
*************************************************/
hasRow(id) { return this.content.hasOwnProperty(id); };
/*************************************************
* get table data
* @return {array} [rows][columns]
*************************************************/
getTableAsString() {
var table = this;
let result = '[';
table.content.forEach(row => {
result += '[';
row.forEach(col => {
if (result!==undefined) {
result += (result!==null) ? col : 'null';
}
result += ','
});
result.slice(0,-1); // remove the last comma
result += "],";
});
result.slice(0,-1); // remove the last comma
result += "]";
return result;
};
/*************************************************
* add a row
* @param {string|number} id of that row or index number
* @param {array} defaultRow (optional) default content
* @return {object} {row:rowData, isNew:true if new row was created) new or existing row
*************************************************/
addRow(id, defaultRow = []) {
var table = this;
var isNew = false;
switch (typeof id) {
case 'string':
if (!table.rowMap.hasOwnProperty(id)) { // add a new row
isNew=true;
table.content[table.content.length] = defaultRow;
table.content[table.content.length-1].length = table.content[0].length;
table.rowMap[id] = table.rows = table.content.length;
}
return {row:table.content[table.rowMap[id]-1],isNew:isNew};
case 'number':
if (id < table.content.length) {
return {row:table.content[id],isNew:isNew};
} else {
console.log(`timeTable.addRow(id) id index exceeds number of initialized rows is: ${id} max ${table.content.length}`);
return;
}
default :
console.log(`timeTable.addRow(id) id has to be of type number or string! is: "${typeof id}"`);
return;
}
};
/*************************************************
* add a column
* @param {number} time timestamp to be added
* @return {number} column index
*************************************************/
addColumnTimestamp(time) {
var table = this;
let col = table.content[0].findIndex(element => element >= time);
table.rows = table.content.length;
table.columns = table.content[0].length;
if (col < 0 || col === undefined) { // add new column @ the end
table.columns++;
table.content.forEach(row => row.length = table.columns);
col=table.columns;
} else if (time !== table.content[0][col]) { // insert a column
table.content.forEach(row => {
table.columns++;
row.splice(col, 0, undefined)
delete row[col];
});
} else { // existing column
col++;
}
table.content[0][col-1] = time;
return col;
};
/**
* add values
* @param {number} time timestamp to be added
* @param {array} values [{id,index,timestamp,value}] where index is used if present, timestamp is optional
* @return {number} column index
**/
addValue(time,values) {
var table = this;
var returnValue = {};
values.forEach(value => {
let column = 0;
column = table.addColumnTimestamp((time!==undefined) ? time : value.timestamp);
let row = table.addRow(id); // get or add row
})
Object.keys(values).forEach(id => {
row.row[returnValue.col-1] = values[id];
returnValue.newRow = row.isNew;
})
return returnValue;
}
/**
* limit the amount of columns
* @param {number} maximum columns
* @return {number} number of removed columns
**/
limitColumns(maxColumns) {
var table = this;
let toRemove = 0;
if (table.content[0].length > maxColumns) {
toRemove = table.content[0].length - maxColumns;
table.content.forEach(row => row.splice(0,toRemove));
}
return toRemove;
}
/**
* limit the time span
* @param {number} timeSpan seconds from now
* @return {number} number of removed columns
**/
limitTime(timeSpan) {
var table = this;
if (table.content[0].length < 1) return 0;
let limit = Date.now()/1000 - timeSpan;
let toRemove = 0;
while (toRemove < table.content[0].length && table.content[0][toRemove] < limit) { toRemove ++};
if (toRemove > 0) {
table.content.forEach(row => row.splice(0,toRemove));
}
return toRemove;
}
}
|
[
"class",
"TimeTable",
"{",
"constructor",
"(",
")",
"{",
"var",
"table",
"=",
"this",
";",
"table",
".",
"content",
"=",
"[",
"[",
"]",
"]",
";",
"table",
".",
"rowMap",
"=",
"{",
"}",
";",
"table",
".",
"columns",
"=",
"0",
";",
"table",
".",
"rows",
"=",
"0",
";",
"}",
"mergeObject",
"(",
"target",
",",
"source",
")",
"{",
"if",
"(",
"typeof",
"source",
"===",
"'object'",
")",
"{",
"Object",
".",
"keys",
"(",
"source",
")",
".",
"forEach",
"(",
"element",
"=>",
"{",
"if",
"(",
"typeof",
"source",
"[",
"element",
"]",
"!==",
"\"object\"",
")",
"{",
"target",
"[",
"element",
"]",
"=",
"source",
"[",
"element",
"]",
";",
"}",
"else",
"{",
"if",
"(",
"!",
"target",
".",
"hasOwnProperty",
"(",
"element",
")",
")",
"{",
"target",
"[",
"element",
"]",
"=",
"(",
"Array",
".",
"isArray",
"(",
"source",
"[",
"element",
"]",
")",
")",
"?",
"[",
"]",
":",
"{",
"}",
";",
"}",
"this",
".",
"mergeObject",
"(",
"target",
"[",
"element",
"]",
",",
"source",
"[",
"element",
"]",
")",
"}",
"}",
")",
";",
"}",
"else",
"{",
"target",
"=",
"source",
";",
"}",
"}",
"getTable",
"(",
")",
"{",
"return",
"this",
".",
"content",
"}",
";",
"setTable",
"(",
"data",
")",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"data",
")",
")",
"{",
"delete",
"this",
".",
"content",
";",
"this",
".",
"content",
"=",
"[",
"]",
";",
"this",
".",
"mergeObject",
"(",
"this",
".",
"content",
",",
"data",
")",
";",
"this",
".",
"columns",
"=",
"this",
".",
"content",
"[",
"0",
"]",
".",
"length",
";",
"this",
".",
"rows",
"=",
"this",
".",
"content",
".",
"length",
";",
"}",
"else",
"{",
"console",
".",
"warn",
"(",
"'timeTable.setTable() data must be an array!'",
",",
"data",
")",
";",
"}",
"}",
";",
"getRowMap",
"(",
")",
"{",
"return",
"this",
".",
"rowMap",
"}",
";",
"setRowMap",
"(",
"rowMap",
")",
"{",
"if",
"(",
"typeof",
"rowMap",
"===",
"'object'",
")",
"{",
"delete",
"this",
".",
"rowMap",
";",
"this",
".",
"rowMap",
"=",
"{",
"}",
";",
"this",
".",
"mergeObject",
"(",
"this",
".",
"rowMap",
",",
"rowMap",
")",
";",
"}",
"else",
"{",
"console",
".",
"warn",
"(",
"'timeTable.rowMap() rowMap must be an object!'",
",",
"rowMap",
")",
";",
"}",
"}",
";",
"getWidth",
"(",
")",
"{",
"return",
"this",
".",
"content",
"[",
"0",
"]",
".",
"length",
"}",
";",
"getHeight",
"(",
")",
"{",
"return",
"this",
".",
"content",
".",
"length",
"-",
"1",
"}",
";",
"setHeight",
"(",
"rows",
")",
"{",
"var",
"table",
"=",
"this",
";",
"let",
"row",
"=",
"table",
".",
"content",
".",
"length",
";",
"while",
"(",
"row",
"<=",
"rows",
")",
"{",
"table",
".",
"content",
"[",
"row",
"]",
"=",
"Array",
"(",
"table",
".",
"content",
"[",
"0",
"]",
".",
"length",
")",
";",
"row",
"++",
";",
"}",
"table",
".",
"rows",
"=",
"table",
".",
"content",
".",
"length",
";",
"}",
";",
"hasRow",
"(",
"id",
")",
"{",
"return",
"this",
".",
"content",
".",
"hasOwnProperty",
"(",
"id",
")",
";",
"}",
";",
"getTableAsString",
"(",
")",
"{",
"var",
"table",
"=",
"this",
";",
"let",
"result",
"=",
"'['",
";",
"table",
".",
"content",
".",
"forEach",
"(",
"row",
"=>",
"{",
"result",
"+=",
"'['",
";",
"row",
".",
"forEach",
"(",
"col",
"=>",
"{",
"if",
"(",
"result",
"!==",
"undefined",
")",
"{",
"result",
"+=",
"(",
"result",
"!==",
"null",
")",
"?",
"col",
":",
"'null'",
";",
"}",
"result",
"+=",
"','",
"}",
")",
";",
"result",
".",
"slice",
"(",
"0",
",",
"-",
"1",
")",
";",
"result",
"+=",
"\"],\"",
";",
"}",
")",
";",
"result",
".",
"slice",
"(",
"0",
",",
"-",
"1",
")",
";",
"result",
"+=",
"\"]\"",
";",
"return",
"result",
";",
"}",
";",
"addRow",
"(",
"id",
",",
"defaultRow",
"=",
"[",
"]",
")",
"{",
"var",
"table",
"=",
"this",
";",
"var",
"isNew",
"=",
"false",
";",
"switch",
"(",
"typeof",
"id",
")",
"{",
"case",
"'string'",
":",
"if",
"(",
"!",
"table",
".",
"rowMap",
".",
"hasOwnProperty",
"(",
"id",
")",
")",
"{",
"isNew",
"=",
"true",
";",
"table",
".",
"content",
"[",
"table",
".",
"content",
".",
"length",
"]",
"=",
"defaultRow",
";",
"table",
".",
"content",
"[",
"table",
".",
"content",
".",
"length",
"-",
"1",
"]",
".",
"length",
"=",
"table",
".",
"content",
"[",
"0",
"]",
".",
"length",
";",
"table",
".",
"rowMap",
"[",
"id",
"]",
"=",
"table",
".",
"rows",
"=",
"table",
".",
"content",
".",
"length",
";",
"}",
"return",
"{",
"row",
":",
"table",
".",
"content",
"[",
"table",
".",
"rowMap",
"[",
"id",
"]",
"-",
"1",
"]",
",",
"isNew",
":",
"isNew",
"}",
";",
"case",
"'number'",
":",
"if",
"(",
"id",
"<",
"table",
".",
"content",
".",
"length",
")",
"{",
"return",
"{",
"row",
":",
"table",
".",
"content",
"[",
"id",
"]",
",",
"isNew",
":",
"isNew",
"}",
";",
"}",
"else",
"{",
"console",
".",
"log",
"(",
"`",
"${",
"id",
"}",
"${",
"table",
".",
"content",
".",
"length",
"}",
"`",
")",
";",
"return",
";",
"}",
"default",
":",
"console",
".",
"log",
"(",
"`",
"${",
"typeof",
"id",
"}",
"`",
")",
";",
"return",
";",
"}",
"}",
";",
"addColumnTimestamp",
"(",
"time",
")",
"{",
"var",
"table",
"=",
"this",
";",
"let",
"col",
"=",
"table",
".",
"content",
"[",
"0",
"]",
".",
"findIndex",
"(",
"element",
"=>",
"element",
">=",
"time",
")",
";",
"table",
".",
"rows",
"=",
"table",
".",
"content",
".",
"length",
";",
"table",
".",
"columns",
"=",
"table",
".",
"content",
"[",
"0",
"]",
".",
"length",
";",
"if",
"(",
"col",
"<",
"0",
"||",
"col",
"===",
"undefined",
")",
"{",
"table",
".",
"columns",
"++",
";",
"table",
".",
"content",
".",
"forEach",
"(",
"row",
"=>",
"row",
".",
"length",
"=",
"table",
".",
"columns",
")",
";",
"col",
"=",
"table",
".",
"columns",
";",
"}",
"else",
"if",
"(",
"time",
"!==",
"table",
".",
"content",
"[",
"0",
"]",
"[",
"col",
"]",
")",
"{",
"table",
".",
"content",
".",
"forEach",
"(",
"row",
"=>",
"{",
"table",
".",
"columns",
"++",
";",
"row",
".",
"splice",
"(",
"col",
",",
"0",
",",
"undefined",
")",
"delete",
"row",
"[",
"col",
"]",
";",
"}",
")",
";",
"}",
"else",
"{",
"col",
"++",
";",
"}",
"table",
".",
"content",
"[",
"0",
"]",
"[",
"col",
"-",
"1",
"]",
"=",
"time",
";",
"return",
"col",
";",
"}",
";",
"addValue",
"(",
"time",
",",
"values",
")",
"{",
"var",
"table",
"=",
"this",
";",
"var",
"returnValue",
"=",
"{",
"}",
";",
"values",
".",
"forEach",
"(",
"value",
"=>",
"{",
"let",
"column",
"=",
"0",
";",
"column",
"=",
"table",
".",
"addColumnTimestamp",
"(",
"(",
"time",
"!==",
"undefined",
")",
"?",
"time",
":",
"value",
".",
"timestamp",
")",
";",
"let",
"row",
"=",
"table",
".",
"addRow",
"(",
"id",
")",
";",
"}",
")",
"Object",
".",
"keys",
"(",
"values",
")",
".",
"forEach",
"(",
"id",
"=>",
"{",
"row",
".",
"row",
"[",
"returnValue",
".",
"col",
"-",
"1",
"]",
"=",
"values",
"[",
"id",
"]",
";",
"returnValue",
".",
"newRow",
"=",
"row",
".",
"isNew",
";",
"}",
")",
"return",
"returnValue",
";",
"}",
"limitColumns",
"(",
"maxColumns",
")",
"{",
"var",
"table",
"=",
"this",
";",
"let",
"toRemove",
"=",
"0",
";",
"if",
"(",
"table",
".",
"content",
"[",
"0",
"]",
".",
"length",
">",
"maxColumns",
")",
"{",
"toRemove",
"=",
"table",
".",
"content",
"[",
"0",
"]",
".",
"length",
"-",
"maxColumns",
";",
"table",
".",
"content",
".",
"forEach",
"(",
"row",
"=>",
"row",
".",
"splice",
"(",
"0",
",",
"toRemove",
")",
")",
";",
"}",
"return",
"toRemove",
";",
"}",
"limitTime",
"(",
"timeSpan",
")",
"{",
"var",
"table",
"=",
"this",
";",
"if",
"(",
"table",
".",
"content",
"[",
"0",
"]",
".",
"length",
"<",
"1",
")",
"return",
"0",
";",
"let",
"limit",
"=",
"Date",
".",
"now",
"(",
")",
"/",
"1000",
"-",
"timeSpan",
";",
"let",
"toRemove",
"=",
"0",
";",
"while",
"(",
"toRemove",
"<",
"table",
".",
"content",
"[",
"0",
"]",
".",
"length",
"&&",
"table",
".",
"content",
"[",
"0",
"]",
"[",
"toRemove",
"]",
"<",
"limit",
")",
"{",
"toRemove",
"++",
"}",
";",
"if",
"(",
"toRemove",
">",
"0",
")",
"{",
"table",
".",
"content",
".",
"forEach",
"(",
"row",
"=>",
"row",
".",
"splice",
"(",
"0",
",",
"toRemove",
")",
")",
";",
"}",
"return",
"toRemove",
";",
"}",
"}"
] |
Copyright 2021 Christian Meinert
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
|
[
"Copyright",
"2021",
"Christian",
"Meinert",
"Licensed",
"under",
"the",
"Apache",
"License",
"Version",
"2",
".",
"0",
"(",
"the",
"\"",
"License",
"\"",
")",
";",
"you",
"may",
"not",
"use",
"this",
"file",
"except",
"in",
"compliance",
"with",
"the",
"License",
"."
] |
[
"/*************************************************\n * deep merge object / array\n * @param {object} target target object\n * @param {object} source source object\n *************************************************/",
"/*************************************************\n * get table data\n * @return {array} [rows][columns]\n *************************************************/",
"/*************************************************\n * set table data\n * @param {array} data [rows][columns]\n *************************************************/",
"/*************************************************\n * get row map\n * @return {object} rowMap {id:row}\n *************************************************/",
"/*************************************************\n * set row map\n * @param {object} rowMap {id:row}\n *************************************************/",
"/*************************************************\n * get width (columns)\n * @return {number} amount of columns\n *************************************************/",
"/*************************************************\n * get height (rows) without time row\n * @return {number} amount of rows\n *************************************************/",
"/*************************************************\n * set height (rows) and adding not populated rows\n * @param {number} rows of rows without time row\n *************************************************/",
"// console.log('setHeight',table.content);",
"/*************************************************\n * checks if a row id exists\n * @param {string} id\n * @return {number} amount of rows\n *************************************************/",
"/*************************************************\n * get table data\n * @return {array} [rows][columns]\n *************************************************/",
"// remove the last comma",
"// remove the last comma",
"/*************************************************\n * add a row \n * @param {string|number} id of that row or index number\n * @param {array} defaultRow (optional) default content\n * @return {object} {row:rowData, isNew:true if new row was created) new or existing row\n *************************************************/",
"// add a new row",
"/*************************************************\n * add a column \n * @param {number} time timestamp to be added\n * @return {number} column index\n *************************************************/",
"// add new column @ the end",
"// insert a column",
"// existing column",
"/** \n * add values \n * @param {number} time timestamp to be added\n * @param {array} values [{id,index,timestamp,value}] where index is used if present, timestamp is optional\n * @return {number} column index\n **/",
"// get or add row",
"/** \n * limit the amount of columns\n * @param {number} maximum columns\n * @return {number} number of removed columns\n **/",
"/** \n * limit the time span\n * @param {number} timeSpan seconds from now\n * @return {number} number of removed columns\n **/"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 24
| 1,733
| 133
|
cdf2f702911f711111dee3a723c5b82c4621c08a
|
alexmalus/master-thesis-dtu
|
app/controllers/documents_controller.rb
|
[
"MIT"
] |
Ruby
|
DocumentsController
|
# == Schema Information
#
# Table name: documents
#
# id :integer not null, primary key
# project_id :integer
# sprint_id :integer
# release_id :integer
# user_story_id :integer
# file_id :string not null
# file_filename :string not null
# file_size :string not null
# file_content_type :string not null
# created_at :datetime not null
# updated_at :datetime not null
#
|
Schema Information
Table name: documents
|
[
"Schema",
"Information",
"Table",
"name",
":",
"documents"
] |
class DocumentsController < ApplicationController
# Once again note that, for models that are named differently, this method will have a different name (authenticate_admin! for Admin model).
before_action :authenticate_user!
before_action :set_document_and_project, only: [:edit, :update]
def new
@document = Document.new
@project = Project.find(params[:project_id])
if params[:attachment_type] == "all_project_documents"
@resource_id = ""
else
@resource_id = params[:resource_id]
end
@attachment_type = params[:attachment_type]
end
def create
if request.post?
document = Document.new(document_params)
document.save!
project = Project.find(params[:project_id])
case params[:attachment_type]
when "specific_user_story_documents"
user_story = UserStory.find(params[:resource_id])
user_story.documents << document
when "specific_release_documents"
release = Release.find(params[:resource_id])
release.documents << document
when "specific_sprint_documents"
sprint = Sprint.find(params[:resource_id])
sprint.documents << document
else
project.documents << document
end
flash[:notice] = "Document created"
redirect_to :controller => "projects", :action => :documents, :id => project.id
end
end
def edit
end
def update
if document.update(document_params)
flash[:notice] = "Document #{document.file_filename} updated"
redirect_to :controller => "projects", :action => :documents, :id => @project.id
else
render :edit
end
end
def destroy
@document = Document.find(params[:id])
flash[:notice] = "Document #{@document.file_filename} destroyed"
@document.destroy
# redirect_to :controller => "projects", :action => :documents, :id => @project.id
redirect_back(fallback_location: projects_path)
end
private
def set_document_and_project
document = Document.find(params[:id])
@project = Project.find(params[:project_id])
end
def document_params
params.permit(:project_id)
params.permit(:attachment_type)
params.permit(:resource_id)
# params.require(:document).permit(:file, :project_id, :attachment_type, :resource_id)
params.require(:document).permit(:file)
end
end
|
[
"class",
"DocumentsController",
"<",
"ApplicationController",
"before_action",
":authenticate_user!",
"before_action",
":set_document_and_project",
",",
"only",
":",
"[",
":edit",
",",
":update",
"]",
"def",
"new",
"@document",
"=",
"Document",
".",
"new",
"@project",
"=",
"Project",
".",
"find",
"(",
"params",
"[",
":project_id",
"]",
")",
"if",
"params",
"[",
":attachment_type",
"]",
"==",
"\"all_project_documents\"",
"@resource_id",
"=",
"\"\"",
"else",
"@resource_id",
"=",
"params",
"[",
":resource_id",
"]",
"end",
"@attachment_type",
"=",
"params",
"[",
":attachment_type",
"]",
"end",
"def",
"create",
"if",
"request",
".",
"post?",
"document",
"=",
"Document",
".",
"new",
"(",
"document_params",
")",
"document",
".",
"save!",
"project",
"=",
"Project",
".",
"find",
"(",
"params",
"[",
":project_id",
"]",
")",
"case",
"params",
"[",
":attachment_type",
"]",
"when",
"\"specific_user_story_documents\"",
"user_story",
"=",
"UserStory",
".",
"find",
"(",
"params",
"[",
":resource_id",
"]",
")",
"user_story",
".",
"documents",
"<<",
"document",
"when",
"\"specific_release_documents\"",
"release",
"=",
"Release",
".",
"find",
"(",
"params",
"[",
":resource_id",
"]",
")",
"release",
".",
"documents",
"<<",
"document",
"when",
"\"specific_sprint_documents\"",
"sprint",
"=",
"Sprint",
".",
"find",
"(",
"params",
"[",
":resource_id",
"]",
")",
"sprint",
".",
"documents",
"<<",
"document",
"else",
"project",
".",
"documents",
"<<",
"document",
"end",
"flash",
"[",
":notice",
"]",
"=",
"\"Document created\"",
"redirect_to",
":controller",
"=>",
"\"projects\"",
",",
":action",
"=>",
":documents",
",",
":id",
"=>",
"project",
".",
"id",
"end",
"end",
"def",
"edit",
"end",
"def",
"update",
"if",
"document",
".",
"update",
"(",
"document_params",
")",
"flash",
"[",
":notice",
"]",
"=",
"\"Document #{document.file_filename} updated\"",
"redirect_to",
":controller",
"=>",
"\"projects\"",
",",
":action",
"=>",
":documents",
",",
":id",
"=>",
"@project",
".",
"id",
"else",
"render",
":edit",
"end",
"end",
"def",
"destroy",
"@document",
"=",
"Document",
".",
"find",
"(",
"params",
"[",
":id",
"]",
")",
"flash",
"[",
":notice",
"]",
"=",
"\"Document #{@document.file_filename} destroyed\"",
"@document",
".",
"destroy",
"redirect_back",
"(",
"fallback_location",
":",
"projects_path",
")",
"end",
"private",
"def",
"set_document_and_project",
"document",
"=",
"Document",
".",
"find",
"(",
"params",
"[",
":id",
"]",
")",
"@project",
"=",
"Project",
".",
"find",
"(",
"params",
"[",
":project_id",
"]",
")",
"end",
"def",
"document_params",
"params",
".",
"permit",
"(",
":project_id",
")",
"params",
".",
"permit",
"(",
":attachment_type",
")",
"params",
".",
"permit",
"(",
":resource_id",
")",
"params",
".",
"require",
"(",
":document",
")",
".",
"permit",
"(",
":file",
")",
"end",
"end"
] |
Schema Information
Table name: documents
|
[
"Schema",
"Information",
"Table",
"name",
":",
"documents"
] |
[
"# Once again note that, for models that are named differently, this method will have a different name (authenticate_admin! for Admin model).",
"# redirect_to :controller => \"projects\", :action => :documents, :id => @project.id",
"# params.require(:document).permit(:file, :project_id, :attachment_type, :resource_id)"
] |
[
{
"param": "ApplicationController",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "ApplicationController",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 14
| 525
| 126
|
e85d76906953e49a3a946c9d27aaf8e20213d61b
|
LarryOsterman/azure-sdk-tools
|
packages/python-packages/api-stub-generator/apistub/nodes/_argtype.py
|
[
"MIT"
] |
Python
|
ArgType
|
Represents Argument type
:param str name: Name of the argument.
:param str argtype: Type of the argument (e.g. str, int, BlobBlock).
:param str default: Default value for the argument, If any.
:param str keyword: The keyword for the arg type.
:param FunctionNode func_node: The function node this belongs to.
|
Represents Argument type
|
[
"Represents",
"Argument",
"type"
] |
class ArgType:
"""Represents Argument type
:param str name: Name of the argument.
:param str argtype: Type of the argument (e.g. str, int, BlobBlock).
:param str default: Default value for the argument, If any.
:param str keyword: The keyword for the arg type.
:param FunctionNode func_node: The function node this belongs to.
"""
def __init__(self, name, *, argtype, default, keyword, func_node=None):
self.argname = name
if default == inspect.Parameter.empty:
self.is_required = True
self.default = None
elif default is None:
self.is_required = False
self.default = "..." if keyword == "keyword" else "None"
else:
self.is_required = False
self.default = str(default)
if argtype and not self.is_required and not keyword in ["ivar", "param"] and not argtype.startswith("Optional"):
self.argtype = f"Optional[{argtype}]"
else:
self.argtype = argtype
self.function_node = func_node
def generate_tokens(self, apiview, function_id, add_line_marker):
"""Generates token for the node and it's children recursively and add it to apiview
:param ~ApiVersion apiview: The ApiView
:param str function_id: Module level Unique ID created for function
:param bool include_default: Optional flag to indicate to include/exclude default value in tokens
"""
# Add arg name
self.id = function_id
if add_line_marker:
self.id = "{0}.param({1}".format(function_id, self.argname)
apiview.add_line_marker(self.id)
apiview.add_text(self.id, self.argname)
# add arg type
if self.argtype:
apiview.add_punctuation(":", False, True)
apiview.add_type(self.argtype, self.id)
elif self.argname not in (TYPE_NOT_REQUIRED):
# Type is not available. Add lint error in review
error_msg = TYPE_NOT_AVAILABLE.format(self.argname)
apiview.add_diagnostic(error_msg, self.id)
if self.function_node:
self.function_node.add_error(error_msg)
# add arg default value
if self.default:
apiview.add_punctuation("=", True, True)
# Add string literal or numeric literal based on the content within default
# Ideally this should be based on arg type. But type is not available for all args
# We should refer to arg type instead of content when all args have type
if self.default in SPECIAL_DEFAULT_VALUES or self.argtype != "str":
apiview.add_literal(self.default)
else:
apiview.add_stringliteral(self.default)
|
[
"class",
"ArgType",
":",
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"*",
",",
"argtype",
",",
"default",
",",
"keyword",
",",
"func_node",
"=",
"None",
")",
":",
"self",
".",
"argname",
"=",
"name",
"if",
"default",
"==",
"inspect",
".",
"Parameter",
".",
"empty",
":",
"self",
".",
"is_required",
"=",
"True",
"self",
".",
"default",
"=",
"None",
"elif",
"default",
"is",
"None",
":",
"self",
".",
"is_required",
"=",
"False",
"self",
".",
"default",
"=",
"\"...\"",
"if",
"keyword",
"==",
"\"keyword\"",
"else",
"\"None\"",
"else",
":",
"self",
".",
"is_required",
"=",
"False",
"self",
".",
"default",
"=",
"str",
"(",
"default",
")",
"if",
"argtype",
"and",
"not",
"self",
".",
"is_required",
"and",
"not",
"keyword",
"in",
"[",
"\"ivar\"",
",",
"\"param\"",
"]",
"and",
"not",
"argtype",
".",
"startswith",
"(",
"\"Optional\"",
")",
":",
"self",
".",
"argtype",
"=",
"f\"Optional[{argtype}]\"",
"else",
":",
"self",
".",
"argtype",
"=",
"argtype",
"self",
".",
"function_node",
"=",
"func_node",
"def",
"generate_tokens",
"(",
"self",
",",
"apiview",
",",
"function_id",
",",
"add_line_marker",
")",
":",
"\"\"\"Generates token for the node and it's children recursively and add it to apiview\n :param ~ApiVersion apiview: The ApiView\n :param str function_id: Module level Unique ID created for function \n :param bool include_default: Optional flag to indicate to include/exclude default value in tokens\n \"\"\"",
"self",
".",
"id",
"=",
"function_id",
"if",
"add_line_marker",
":",
"self",
".",
"id",
"=",
"\"{0}.param({1}\"",
".",
"format",
"(",
"function_id",
",",
"self",
".",
"argname",
")",
"apiview",
".",
"add_line_marker",
"(",
"self",
".",
"id",
")",
"apiview",
".",
"add_text",
"(",
"self",
".",
"id",
",",
"self",
".",
"argname",
")",
"if",
"self",
".",
"argtype",
":",
"apiview",
".",
"add_punctuation",
"(",
"\":\"",
",",
"False",
",",
"True",
")",
"apiview",
".",
"add_type",
"(",
"self",
".",
"argtype",
",",
"self",
".",
"id",
")",
"elif",
"self",
".",
"argname",
"not",
"in",
"(",
"TYPE_NOT_REQUIRED",
")",
":",
"error_msg",
"=",
"TYPE_NOT_AVAILABLE",
".",
"format",
"(",
"self",
".",
"argname",
")",
"apiview",
".",
"add_diagnostic",
"(",
"error_msg",
",",
"self",
".",
"id",
")",
"if",
"self",
".",
"function_node",
":",
"self",
".",
"function_node",
".",
"add_error",
"(",
"error_msg",
")",
"if",
"self",
".",
"default",
":",
"apiview",
".",
"add_punctuation",
"(",
"\"=\"",
",",
"True",
",",
"True",
")",
"if",
"self",
".",
"default",
"in",
"SPECIAL_DEFAULT_VALUES",
"or",
"self",
".",
"argtype",
"!=",
"\"str\"",
":",
"apiview",
".",
"add_literal",
"(",
"self",
".",
"default",
")",
"else",
":",
"apiview",
".",
"add_stringliteral",
"(",
"self",
".",
"default",
")"
] |
Represents Argument type
|
[
"Represents",
"Argument",
"type"
] |
[
"\"\"\"Represents Argument type\n :param str name: Name of the argument.\n :param str argtype: Type of the argument (e.g. str, int, BlobBlock).\n :param str default: Default value for the argument, If any.\n :param str keyword: The keyword for the arg type.\n :param FunctionNode func_node: The function node this belongs to.\n \"\"\"",
"\"\"\"Generates token for the node and it's children recursively and add it to apiview\n :param ~ApiVersion apiview: The ApiView\n :param str function_id: Module level Unique ID created for function \n :param bool include_default: Optional flag to indicate to include/exclude default value in tokens\n \"\"\"",
"# Add arg name",
"# add arg type",
"# Type is not available. Add lint error in review",
"# add arg default value",
"# Add string literal or numeric literal based on the content within default",
"# Ideally this should be based on arg type. But type is not available for all args",
"# We should refer to arg type instead of content when all args have type"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [
{
"identifier": "name",
"type": null,
"docstring": "Name of the argument.",
"docstring_tokens": [
"Name",
"of",
"the",
"argument",
"."
],
"default": null,
"is_optional": false
},
{
"identifier": "argtype",
"type": null,
"docstring": "Type of the argument .",
"docstring_tokens": [
"Type",
"of",
"the",
"argument",
"."
],
"default": null,
"is_optional": false
},
{
"identifier": "default",
"type": null,
"docstring": "Default value for the argument, If any.",
"docstring_tokens": [
"Default",
"value",
"for",
"the",
"argument",
"If",
"any",
"."
],
"default": null,
"is_optional": false
},
{
"identifier": "keyword",
"type": null,
"docstring": "The keyword for the arg type.",
"docstring_tokens": [
"The",
"keyword",
"for",
"the",
"arg",
"type",
"."
],
"default": null,
"is_optional": false
},
{
"identifier": "func_node",
"type": null,
"docstring": "The function node this belongs to.",
"docstring_tokens": [
"The",
"function",
"node",
"this",
"belongs",
"to",
"."
],
"default": null,
"is_optional": false
}
],
"others": []
}
| false
| 14
| 611
| 82
|
8f917de62fe901caa33008ed23a1e12010e77013
|
bcampbell-prosper/google-cloud-dotnet
|
apis/Google.Cloud.SecurityCenter.V1/Google.Cloud.SecurityCenter.V1/ResourceNames.cs
|
[
"Apache-2.0"
] |
C#
|
SecuritymarksNameOneof
|
/// <summary>
/// Resource name which will contain one of a choice of resource names.
/// </summary>
/// <remarks>
/// This resource name will contain one of the following:
/// <list type="bullet">
/// <item><description>AssetSecurityMarksName: A resource of type 'asset_security_marks'.</description></item>
/// <item><description>FindingSecurityMarksName: A resource of type 'finding_security_marks'.</description></item>
/// </list>
/// </remarks>
|
Resource name which will contain one of a choice of resource names.
|
[
"Resource",
"name",
"which",
"will",
"contain",
"one",
"of",
"a",
"choice",
"of",
"resource",
"names",
"."
] |
public sealed partial class SecuritymarksNameOneof : gax::IResourceName, sys::IEquatable<SecuritymarksNameOneof>
{
public enum OneofType
{
Unknown = 0,
AssetSecurityMarksName = 1,
FindingSecurityMarksName = 2,
}
public static SecuritymarksNameOneof Parse(string name, bool allowUnknown)
{
SecuritymarksNameOneof result;
if (TryParse(name, allowUnknown, out result))
{
return result;
}
throw new sys::ArgumentException("Invalid name", nameof(name));
}
public static bool TryParse(string name, bool allowUnknown, out SecuritymarksNameOneof result)
{
gax::GaxPreconditions.CheckNotNull(name, nameof(name));
AssetSecurityMarksName assetSecurityMarksName;
if (AssetSecurityMarksName.TryParse(name, out assetSecurityMarksName))
{
result = new SecuritymarksNameOneof(OneofType.AssetSecurityMarksName, assetSecurityMarksName);
return true;
}
FindingSecurityMarksName findingSecurityMarksName;
if (FindingSecurityMarksName.TryParse(name, out findingSecurityMarksName))
{
result = new SecuritymarksNameOneof(OneofType.FindingSecurityMarksName, findingSecurityMarksName);
return true;
}
if (allowUnknown)
{
gax::UnknownResourceName unknownResourceName;
if (gax::UnknownResourceName.TryParse(name, out unknownResourceName))
{
result = new SecuritymarksNameOneof(OneofType.Unknown, unknownResourceName);
return true;
}
}
result = null;
return false;
}
public static SecuritymarksNameOneof From(AssetSecurityMarksName assetSecurityMarksName) => new SecuritymarksNameOneof(OneofType.AssetSecurityMarksName, assetSecurityMarksName);
public static SecuritymarksNameOneof From(FindingSecurityMarksName findingSecurityMarksName) => new SecuritymarksNameOneof(OneofType.FindingSecurityMarksName, findingSecurityMarksName);
private static bool IsValid(OneofType type, gax::IResourceName name)
{
switch (type)
{
case OneofType.Unknown: return true;
case OneofType.AssetSecurityMarksName: return name is AssetSecurityMarksName;
case OneofType.FindingSecurityMarksName: return name is FindingSecurityMarksName;
default: return false;
}
}
public SecuritymarksNameOneof(OneofType type, gax::IResourceName name)
{
Type = gax::GaxPreconditions.CheckEnumValue<OneofType>(type, nameof(type));
Name = gax::GaxPreconditions.CheckNotNull(name, nameof(name));
if (!IsValid(type, name))
{
throw new sys::ArgumentException($"Mismatched OneofType '{type}' and resource name '{name}'");
}
}
public OneofType Type { get; }
public gax::IResourceName Name { get; }
private T CheckAndReturn<T>(OneofType type)
{
if (Type != type)
{
throw new sys::InvalidOperationException($"Requested type {type}, but this one-of contains type {Type}");
}
return (T)Name;
}
public AssetSecurityMarksName AssetSecurityMarksName => CheckAndReturn<AssetSecurityMarksName>(OneofType.AssetSecurityMarksName);
public FindingSecurityMarksName FindingSecurityMarksName => CheckAndReturn<FindingSecurityMarksName>(OneofType.FindingSecurityMarksName);
public gax::ResourceNameKind Kind => gax::ResourceNameKind.Oneof;
public override string ToString() => Name.ToString();
public override int GetHashCode() => ToString().GetHashCode();
public override bool Equals(object obj) => Equals(obj as SecuritymarksNameOneof);
public bool Equals(SecuritymarksNameOneof other) => ToString() == other?.ToString();
public static bool operator ==(SecuritymarksNameOneof a, SecuritymarksNameOneof b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
public static bool operator !=(SecuritymarksNameOneof a, SecuritymarksNameOneof b) => !(a == b);
}
|
[
"public",
"sealed",
"partial",
"class",
"SecuritymarksNameOneof",
":",
"gax",
"::",
"IResourceName",
",",
"sys",
"::",
"IEquatable",
"<",
"SecuritymarksNameOneof",
">",
"{",
"public",
"enum",
"OneofType",
"{",
"Unknown",
"=",
"0",
",",
"AssetSecurityMarksName",
"=",
"1",
",",
"FindingSecurityMarksName",
"=",
"2",
",",
"}",
"public",
"static",
"SecuritymarksNameOneof",
"Parse",
"(",
"string",
"name",
",",
"bool",
"allowUnknown",
")",
"{",
"SecuritymarksNameOneof",
"result",
";",
"if",
"(",
"TryParse",
"(",
"name",
",",
"allowUnknown",
",",
"out",
"result",
")",
")",
"{",
"return",
"result",
";",
"}",
"throw",
"new",
"sys",
"::",
"ArgumentException",
"(",
"\"",
"Invalid name",
"\"",
",",
"nameof",
"(",
"name",
")",
")",
";",
"}",
"public",
"static",
"bool",
"TryParse",
"(",
"string",
"name",
",",
"bool",
"allowUnknown",
",",
"out",
"SecuritymarksNameOneof",
"result",
")",
"{",
"gax",
"::",
"GaxPreconditions",
".",
"CheckNotNull",
"(",
"name",
",",
"nameof",
"(",
"name",
")",
")",
";",
"AssetSecurityMarksName",
"assetSecurityMarksName",
";",
"if",
"(",
"AssetSecurityMarksName",
".",
"TryParse",
"(",
"name",
",",
"out",
"assetSecurityMarksName",
")",
")",
"{",
"result",
"=",
"new",
"SecuritymarksNameOneof",
"(",
"OneofType",
".",
"AssetSecurityMarksName",
",",
"assetSecurityMarksName",
")",
";",
"return",
"true",
";",
"}",
"FindingSecurityMarksName",
"findingSecurityMarksName",
";",
"if",
"(",
"FindingSecurityMarksName",
".",
"TryParse",
"(",
"name",
",",
"out",
"findingSecurityMarksName",
")",
")",
"{",
"result",
"=",
"new",
"SecuritymarksNameOneof",
"(",
"OneofType",
".",
"FindingSecurityMarksName",
",",
"findingSecurityMarksName",
")",
";",
"return",
"true",
";",
"}",
"if",
"(",
"allowUnknown",
")",
"{",
"gax",
"::",
"UnknownResourceName",
"unknownResourceName",
";",
"if",
"(",
"gax",
"::",
"UnknownResourceName",
".",
"TryParse",
"(",
"name",
",",
"out",
"unknownResourceName",
")",
")",
"{",
"result",
"=",
"new",
"SecuritymarksNameOneof",
"(",
"OneofType",
".",
"Unknown",
",",
"unknownResourceName",
")",
";",
"return",
"true",
";",
"}",
"}",
"result",
"=",
"null",
";",
"return",
"false",
";",
"}",
"public",
"static",
"SecuritymarksNameOneof",
"From",
"(",
"AssetSecurityMarksName",
"assetSecurityMarksName",
")",
"=>",
"new",
"SecuritymarksNameOneof",
"(",
"OneofType",
".",
"AssetSecurityMarksName",
",",
"assetSecurityMarksName",
")",
";",
"public",
"static",
"SecuritymarksNameOneof",
"From",
"(",
"FindingSecurityMarksName",
"findingSecurityMarksName",
")",
"=>",
"new",
"SecuritymarksNameOneof",
"(",
"OneofType",
".",
"FindingSecurityMarksName",
",",
"findingSecurityMarksName",
")",
";",
"private",
"static",
"bool",
"IsValid",
"(",
"OneofType",
"type",
",",
"gax",
"::",
"IResourceName",
"name",
")",
"{",
"switch",
"(",
"type",
")",
"{",
"case",
"OneofType",
".",
"Unknown",
":",
"return",
"true",
";",
"case",
"OneofType",
".",
"AssetSecurityMarksName",
":",
"return",
"name",
"is",
"AssetSecurityMarksName",
";",
"case",
"OneofType",
".",
"FindingSecurityMarksName",
":",
"return",
"name",
"is",
"FindingSecurityMarksName",
";",
"default",
":",
"return",
"false",
";",
"}",
"}",
"public",
"SecuritymarksNameOneof",
"(",
"OneofType",
"type",
",",
"gax",
"::",
"IResourceName",
"name",
")",
"{",
"Type",
"=",
"gax",
"::",
"GaxPreconditions",
".",
"CheckEnumValue",
"<",
"OneofType",
">",
"(",
"type",
",",
"nameof",
"(",
"type",
")",
")",
";",
"Name",
"=",
"gax",
"::",
"GaxPreconditions",
".",
"CheckNotNull",
"(",
"name",
",",
"nameof",
"(",
"name",
")",
")",
";",
"if",
"(",
"!",
"IsValid",
"(",
"type",
",",
"name",
")",
")",
"{",
"throw",
"new",
"sys",
"::",
"ArgumentException",
"(",
"$\"",
"Mismatched OneofType '",
"{",
"type",
"}",
"' and resource name '",
"{",
"name",
"}",
"'",
"\"",
")",
";",
"}",
"}",
"public",
"OneofType",
"Type",
"{",
"get",
";",
"}",
"public",
"gax",
"::",
"IResourceName",
"Name",
"{",
"get",
";",
"}",
"private",
"T",
"CheckAndReturn",
"<",
"T",
">",
"(",
"OneofType",
"type",
")",
"{",
"if",
"(",
"Type",
"!=",
"type",
")",
"{",
"throw",
"new",
"sys",
"::",
"InvalidOperationException",
"(",
"$\"",
"Requested type ",
"{",
"type",
"}",
", but this one-of contains type ",
"{",
"Type",
"}",
"\"",
")",
";",
"}",
"return",
"(",
"T",
")",
"Name",
";",
"}",
"public",
"AssetSecurityMarksName",
"AssetSecurityMarksName",
"=>",
"CheckAndReturn",
"<",
"AssetSecurityMarksName",
">",
"(",
"OneofType",
".",
"AssetSecurityMarksName",
")",
";",
"public",
"FindingSecurityMarksName",
"FindingSecurityMarksName",
"=>",
"CheckAndReturn",
"<",
"FindingSecurityMarksName",
">",
"(",
"OneofType",
".",
"FindingSecurityMarksName",
")",
";",
"public",
"gax",
"::",
"ResourceNameKind",
"Kind",
"=>",
"gax",
"::",
"ResourceNameKind",
".",
"Oneof",
";",
"public",
"override",
"string",
"ToString",
"(",
")",
"=>",
"Name",
".",
"ToString",
"(",
")",
";",
"public",
"override",
"int",
"GetHashCode",
"(",
")",
"=>",
"ToString",
"(",
")",
".",
"GetHashCode",
"(",
")",
";",
"public",
"override",
"bool",
"Equals",
"(",
"object",
"obj",
")",
"=>",
"Equals",
"(",
"obj",
"as",
"SecuritymarksNameOneof",
")",
";",
"public",
"bool",
"Equals",
"(",
"SecuritymarksNameOneof",
"other",
")",
"=>",
"ToString",
"(",
")",
"==",
"other",
"?",
".",
"ToString",
"(",
")",
";",
"public",
"static",
"bool",
"operator",
"==",
"(",
"SecuritymarksNameOneof",
"a",
",",
"SecuritymarksNameOneof",
"b",
")",
"=>",
"ReferenceEquals",
"(",
"a",
",",
"b",
")",
"||",
"(",
"a",
"?",
".",
"Equals",
"(",
"b",
")",
"??",
"false",
")",
";",
"public",
"static",
"bool",
"operator",
"!=",
"(",
"SecuritymarksNameOneof",
"a",
",",
"SecuritymarksNameOneof",
"b",
")",
"=>",
"!",
"(",
"a",
"==",
"b",
")",
";",
"}"
] |
Resource name which will contain one of a choice of resource names.
|
[
"Resource",
"name",
"which",
"will",
"contain",
"one",
"of",
"a",
"choice",
"of",
"resource",
"names",
"."
] |
[
"/// <summary>",
"/// The possible contents of <see cref=\"SecuritymarksNameOneof\"/>.",
"/// </summary>",
"/// <summary>",
"/// A resource of an unknown type.",
"/// </summary>",
"/// <summary>",
"/// A resource of type 'asset_security_marks'.",
"/// </summary>",
"/// <summary>",
"/// A resource of type 'finding_security_marks'.",
"/// </summary>",
"/// <summary>",
"/// Parses a resource name in string form into a new <see cref=\"SecuritymarksNameOneof\"/> instance.",
"/// </summary>",
"/// <remarks>",
"/// To parse successfully the resource name must be one of the following:",
"/// <list type=\"bullet\">",
"/// <item><description>AssetSecurityMarksName: A resource of type 'asset_security_marks'.</description></item>",
"/// <item><description>FindingSecurityMarksName: A resource of type 'finding_security_marks'.</description></item>",
"/// </list>",
"/// Or an <see cref=\"gax::UnknownResourceName\"/> if <paramref name=\"allowUnknown\"/> is <c>true</c>.",
"/// </remarks>",
"/// <param name=\"name\">The resource name in string form. Must not be <c>null</c>.</param>",
"/// <param name=\"allowUnknown\">If true, will successfully parse an unknown resource name",
"/// into an <see cref=\"gax::UnknownResourceName\"/>; otherwise will throw an",
"/// <see cref=\"sys::ArgumentException\"/> if an unknown resource name is given.</param>",
"/// <returns>The parsed <see cref=\"SecuritymarksNameOneof\"/> if successful.</returns>",
"/// <summary>",
"/// Tries to parse a resource name in string form into a new <see cref=\"SecuritymarksNameOneof\"/> instance.",
"/// </summary>",
"/// <remarks>",
"/// To parse successfully the resource name must be one of the following:",
"/// <list type=\"bullet\">",
"/// <item><description>AssetSecurityMarksName: A resource of type 'asset_security_marks'.</description></item>",
"/// <item><description>FindingSecurityMarksName: A resource of type 'finding_security_marks'.</description></item>",
"/// </list>",
"/// Or an <see cref=\"gax::UnknownResourceName\"/> if <paramref name=\"allowUnknown\"/> is <c>true</c>.",
"/// </remarks>",
"/// <param name=\"name\">The resource name in string form. Must not be <c>null</c>.</param>",
"/// <param name=\"allowUnknown\">If true, will successfully parse an unknown resource name",
"/// into an <see cref=\"gax::UnknownResourceName\"/>.</param>",
"/// <param name=\"result\">When this method returns, the parsed <see cref=\"SecuritymarksNameOneof\"/>,",
"/// or <c>null</c> if parsing fails.</param>",
"/// <returns><c>true</c> if the name was parsed succssfully; <c>false</c> otherwise.</returns>",
"/// <summary>",
"/// Construct a new instance of <see cref=\"SecuritymarksNameOneof\"/> from the provided <see cref=\"AssetSecurityMarksName\"/>",
"/// </summary>",
"/// <param name=\"assetSecurityMarksName\">The <see cref=\"AssetSecurityMarksName\"/> to be contained within",
"/// the returned <see cref=\"SecuritymarksNameOneof\"/>. Must not be <c>null</c>.</param>",
"/// <returns>A new <see cref=\"SecuritymarksNameOneof\"/>, containing <paramref name=\"assetSecurityMarksName\"/>.</returns>",
"/// <summary>",
"/// Construct a new instance of <see cref=\"SecuritymarksNameOneof\"/> from the provided <see cref=\"FindingSecurityMarksName\"/>",
"/// </summary>",
"/// <param name=\"findingSecurityMarksName\">The <see cref=\"FindingSecurityMarksName\"/> to be contained within",
"/// the returned <see cref=\"SecuritymarksNameOneof\"/>. Must not be <c>null</c>.</param>",
"/// <returns>A new <see cref=\"SecuritymarksNameOneof\"/>, containing <paramref name=\"findingSecurityMarksName\"/>.</returns>",
"// Anything goes with Unknown.",
"/// <summary>",
"/// Constructs a new instance of the <see cref=\"SecuritymarksNameOneof\"/> resource name class",
"/// from a suitable <see cref=\"gax::IResourceName\"/> instance.",
"/// </summary>",
"/// <summary>",
"/// The <see cref=\"OneofType\"/> of the Name contained in this instance.",
"/// </summary>",
"/// <summary>",
"/// The <see cref=\"gax::IResourceName\"/> contained in this instance.",
"/// </summary>",
"/// <summary>",
"/// Get the contained <see cref=\"gax::IResourceName\"/> as <see cref=\"AssetSecurityMarksName\"/>.",
"/// </summary>",
"/// <remarks>",
"/// An <see cref=\"sys::InvalidOperationException\"/> will be thrown if this does not",
"/// contain an instance of <see cref=\"AssetSecurityMarksName\"/>.",
"/// </remarks>",
"/// <summary>",
"/// Get the contained <see cref=\"gax::IResourceName\"/> as <see cref=\"FindingSecurityMarksName\"/>.",
"/// </summary>",
"/// <remarks>",
"/// An <see cref=\"sys::InvalidOperationException\"/> will be thrown if this does not",
"/// contain an instance of <see cref=\"FindingSecurityMarksName\"/>.",
"/// </remarks>",
"/// <inheritdoc />",
"/// <inheritdoc />",
"/// <inheritdoc />",
"/// <inheritdoc />",
"/// <inheritdoc />",
"/// <inheritdoc />",
"/// <inheritdoc />"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": [
{
"identifier": "remarks",
"docstring": "This resource name will contain one of the following:\nAssetSecurityMarksName: A resource of type 'asset_security_marks'.FindingSecurityMarksName: A resource of type 'finding_security_marks'.",
"docstring_tokens": [
"This",
"resource",
"name",
"will",
"contain",
"one",
"of",
"the",
"following",
":",
"AssetSecurityMarksName",
":",
"A",
"resource",
"of",
"type",
"'",
"asset_security_marks",
"'",
".",
"FindingSecurityMarksName",
":",
"A",
"resource",
"of",
"type",
"'",
"finding_security_marks",
"'",
"."
]
}
]
}
| false
| 15
| 904
| 102
|
3e491f7b1a28f26b56d3973ff0ed6aaf0221d9c7
|
p-czaja/TizenFX
|
src/Tizen.NUI.Components/Controls/Control.cs
|
[
"Apache-2.0",
"MIT"
] |
C#
|
Control
|
/// <summary>
/// The control component is base class of tv nui components. It's abstract class, so cann't instantiate and can only be inherited.
/// </summary>
/// <since_tizen> 6 </since_tizen>
/// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API.
|
The control component is base class of tv nui components. It's abstract class, so cann't instantiate and can only be inherited.
|
[
"The",
"control",
"component",
"is",
"base",
"class",
"of",
"tv",
"nui",
"components",
".",
"It",
"'",
"s",
"abstract",
"class",
"so",
"cann",
"'",
"t",
"instantiate",
"and",
"can",
"only",
"be",
"inherited",
"."
] |
[EditorBrowsable(EditorBrowsableState.Never)]
public class Control : VisualView
{
[EditorBrowsable(EditorBrowsableState.Never)]
public new static readonly BindableProperty BackgroundImageProperty = BindableProperty.Create("ControlBackgroundImage", typeof(Selector<string>), typeof(Control), null, propertyChanged: (bindable, oldValue, newValue) =>
{
var control = (Control)bindable;
if (null != newValue)
{
control.BackgroundImageSelector.Clone((Selector<string>)newValue);
}
},
defaultValueCreator: (bindable) =>
{
var control = (Control)bindable;
return control.BackgroundImageSelector;
});
[EditorBrowsable(EditorBrowsableState.Never)]
public new static readonly BindableProperty BackgroundImageBorderProperty = BindableProperty.Create("ControlBackgroundImageBorder", typeof(Selector<Rectangle>), typeof(Control), default(Rectangle), propertyChanged: (bindable, oldValue, newValue) =>
{
var control = (Control)bindable;
if (null != newValue)
{
control.backgroundImageBorderSelector.Clone((Selector<Rectangle>)newValue);
}
},
defaultValueCreator: (bindable) =>
{
var control = (Control)bindable;
return control.backgroundImageBorderSelector;
});
[EditorBrowsable(EditorBrowsableState.Never)]
public new static readonly BindableProperty BackgroundColorProperty = BindableProperty.Create("ControlBackgroundColor", typeof(Selector<Color>), typeof(Control), null, propertyChanged: (bindable, oldValue, newValue) =>
{
var control = (Control)bindable;
if (null != newValue)
{
control.BackgroundColorSelector.Clone((Selector<Color>)newValue);
}
},
defaultValueCreator: (bindable) =>
{
var control = (Control)bindable;
return control.BackgroundColorSelector;
});
[EditorBrowsable(EditorBrowsableState.Never)]
protected string style;
private TapGestureDetector tapGestureDetector = new TapGestureDetector();
private bool isFocused = false;
internal ImageView backgroundImage = new ImageView();
internal ImageView shadowImage;
[EditorBrowsable(EditorBrowsableState.Never)]
public ControlStyle Style => ViewStyle as ControlStyle;
[EditorBrowsable(EditorBrowsableState.Never)]
public Control() : base()
{
Initialize(null);
}
[EditorBrowsable(EditorBrowsableState.Never)]
public Control(ControlStyle controlStyle) : base(controlStyle)
{
Initialize(null);
}
[EditorBrowsable(EditorBrowsableState.Never)]
public Control(string styleSheet) : base()
{
ViewStyle viewStyle = StyleManager.Instance.GetViewStyle(styleSheet);
if (viewStyle == null)
{
throw new InvalidOperationException($"There is no style {styleSheet}");
}
ApplyStyle(viewStyle);
this.style = styleSheet;
Initialize(style);
}
private TriggerableSelector<string> _backgroundImageSelector;
private TriggerableSelector<string> BackgroundImageSelector
{
get
{
if (null == _backgroundImageSelector)
{
_backgroundImageSelector = new TriggerableSelector<string>(backgroundImage, ImageView.ResourceUrlProperty);
}
return _backgroundImageSelector;
}
}
private TriggerableSelector<Rectangle> _backgroundImageBorderSelector;
private TriggerableSelector<Rectangle> backgroundImageBorderSelector
{
get
{
if (null == _backgroundImageBorderSelector)
{
_backgroundImageBorderSelector = new TriggerableSelector<Rectangle>(backgroundImage, ImageView.BorderProperty);
}
return _backgroundImageBorderSelector;
}
}
private TriggerableSelector<Color> _backgroundColorSelector;
private TriggerableSelector<Color> BackgroundColorSelector
{
get
{
if (null == _backgroundColorSelector)
{
_backgroundColorSelector = new TriggerableSelector<Color>(backgroundImage, View.BackgroundColorProperty);
}
return _backgroundColorSelector;
}
}
[EditorBrowsable(EditorBrowsableState.Never)]
public new Selector<string> BackgroundImage
{
get => (Selector<string>)GetValue(BackgroundImageProperty);
set => SetValue(BackgroundImageProperty, value);
}
[EditorBrowsable(EditorBrowsableState.Never)]
public new Selector<Rectangle> BackgroundImageBorder
{
get => (Selector<Rectangle>)GetValue(BackgroundImageBorderProperty);
set => SetValue(BackgroundImageBorderProperty, value);
}
[EditorBrowsable(EditorBrowsableState.Never)]
public new Selector<Color> BackgroundColor
{
get => (Selector<Color>)GetValue(BackgroundColorProperty);
set => SetValue(BackgroundColorProperty, value);
}
[EditorBrowsable(EditorBrowsableState.Never)]
public Selector<string> ShadowImage
{
get
{
return Style.Shadow.ResourceUrl;
}
set
{
Style.Shadow.ResourceUrl = value;
}
}
[EditorBrowsable(EditorBrowsableState.Never)]
public Selector<Rectangle> ShadowImageBorder
{
get
{
return Style.Shadow.Border;
}
set
{
Style.Shadow.Border = value;
}
}
internal void ApplyAttributes(View view, ViewStyle viewStyle)
{
view.CopyFrom(viewStyle);
}
internal bool StateFocusableOnTouchMode { get; set; }
internal bool IsFocused => (isFocused || HasFocus());
[EditorBrowsable(EditorBrowsableState.Never)]
protected override void Dispose(DisposeTypes type)
{
if (disposed)
{
return;
}
if (type == DisposeTypes.Explicit)
{
StyleManager.Instance.ThemeChangedEvent -= OnThemeChangedEvent;
tapGestureDetector.Detected -= OnTapGestureDetected;
tapGestureDetector.Detach(this);
}
if (backgroundImage != null)
{
Utility.Dispose(backgroundImage);
}
if (shadowImage != null)
{
Utility.Dispose(shadowImage);
}
base.Dispose(type);
}
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool OnKey(Key key)
{
return false;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public override void OnRelayout(Vector2 size, RelayoutContainer container)
{
OnUpdate();
}
[EditorBrowsable(EditorBrowsableState.Never)]
public override void OnFocusGained()
{
isFocused = true;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public override void OnFocusLost()
{
isFocused = false;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public override void ApplyStyle(ViewStyle viewStyle)
{
base.ApplyStyle(viewStyle);
ControlStyle controlStyle = viewStyle as ControlStyle;
if (null != controlStyle?.Shadow)
{
if (null == shadowImage)
{
shadowImage = new ImageView()
{
WidthResizePolicy = ResizePolicyType.FillToParent,
HeightResizePolicy = ResizePolicyType.FillToParent,
};
this.Add(shadowImage);
shadowImage.LowerToBottom();
}
shadowImage.ApplyStyle(controlStyle.Shadow);
}
if (null != controlStyle.BackgroundImage)
{
backgroundImage.WidthResizePolicy = ResizePolicyType.FillToParent;
backgroundImage.HeightResizePolicy = ResizePolicyType.FillToParent;
this.Add(backgroundImage);
}
}
[EditorBrowsable(EditorBrowsableState.Never)]
protected virtual void OnTapGestureDetected(object source, TapGestureDetector.DetectedEventArgs e) { }
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool OnTouch(Touch touch)
{
return false;
}
[EditorBrowsable(EditorBrowsableState.Never)]
protected virtual void OnUpdate()
{
}
[EditorBrowsable(EditorBrowsableState.Never)]
protected virtual void OnThemeChangedEvent(object sender, StyleManager.ThemeChangeEventArgs e) { }
[EditorBrowsable(EditorBrowsableState.Never)]
protected virtual void RegisterDetectionOfSubstyleChanges() { }
[EditorBrowsable(EditorBrowsableState.Never)]
protected override ViewStyle GetViewStyle()
{
return new ControlStyle();
}
private void Initialize(string style)
{
ControlState = ControlStates.Normal;
RegisterDetectionOfSubstyleChanges();
LeaveRequired = true;
StateFocusableOnTouchMode = false;
tapGestureDetector.Attach(this);
tapGestureDetector.Detected += OnTapGestureDetected;
StyleManager.Instance.ThemeChangedEvent += OnThemeChangedEvent;
}
}
|
[
"[",
"EditorBrowsable",
"(",
"EditorBrowsableState",
".",
"Never",
")",
"]",
"public",
"class",
"Control",
":",
"VisualView",
"{",
"[",
"EditorBrowsable",
"(",
"EditorBrowsableState",
".",
"Never",
")",
"]",
"public",
"new",
"static",
"readonly",
"BindableProperty",
"BackgroundImageProperty",
"=",
"BindableProperty",
".",
"Create",
"(",
"\"",
"ControlBackgroundImage",
"\"",
",",
"typeof",
"(",
"Selector",
"<",
"string",
">",
")",
",",
"typeof",
"(",
"Control",
")",
",",
"null",
",",
"propertyChanged",
":",
"(",
"bindable",
",",
"oldValue",
",",
"newValue",
")",
"=>",
"{",
"var",
"control",
"=",
"(",
"Control",
")",
"bindable",
";",
"if",
"(",
"null",
"!=",
"newValue",
")",
"{",
"control",
".",
"BackgroundImageSelector",
".",
"Clone",
"(",
"(",
"Selector",
"<",
"string",
">",
")",
"newValue",
")",
";",
"}",
"}",
",",
"defaultValueCreator",
":",
"(",
"bindable",
")",
"=>",
"{",
"var",
"control",
"=",
"(",
"Control",
")",
"bindable",
";",
"return",
"control",
".",
"BackgroundImageSelector",
";",
"}",
")",
";",
"[",
"EditorBrowsable",
"(",
"EditorBrowsableState",
".",
"Never",
")",
"]",
"public",
"new",
"static",
"readonly",
"BindableProperty",
"BackgroundImageBorderProperty",
"=",
"BindableProperty",
".",
"Create",
"(",
"\"",
"ControlBackgroundImageBorder",
"\"",
",",
"typeof",
"(",
"Selector",
"<",
"Rectangle",
">",
")",
",",
"typeof",
"(",
"Control",
")",
",",
"default",
"(",
"Rectangle",
")",
",",
"propertyChanged",
":",
"(",
"bindable",
",",
"oldValue",
",",
"newValue",
")",
"=>",
"{",
"var",
"control",
"=",
"(",
"Control",
")",
"bindable",
";",
"if",
"(",
"null",
"!=",
"newValue",
")",
"{",
"control",
".",
"backgroundImageBorderSelector",
".",
"Clone",
"(",
"(",
"Selector",
"<",
"Rectangle",
">",
")",
"newValue",
")",
";",
"}",
"}",
",",
"defaultValueCreator",
":",
"(",
"bindable",
")",
"=>",
"{",
"var",
"control",
"=",
"(",
"Control",
")",
"bindable",
";",
"return",
"control",
".",
"backgroundImageBorderSelector",
";",
"}",
")",
";",
"[",
"EditorBrowsable",
"(",
"EditorBrowsableState",
".",
"Never",
")",
"]",
"public",
"new",
"static",
"readonly",
"BindableProperty",
"BackgroundColorProperty",
"=",
"BindableProperty",
".",
"Create",
"(",
"\"",
"ControlBackgroundColor",
"\"",
",",
"typeof",
"(",
"Selector",
"<",
"Color",
">",
")",
",",
"typeof",
"(",
"Control",
")",
",",
"null",
",",
"propertyChanged",
":",
"(",
"bindable",
",",
"oldValue",
",",
"newValue",
")",
"=>",
"{",
"var",
"control",
"=",
"(",
"Control",
")",
"bindable",
";",
"if",
"(",
"null",
"!=",
"newValue",
")",
"{",
"control",
".",
"BackgroundColorSelector",
".",
"Clone",
"(",
"(",
"Selector",
"<",
"Color",
">",
")",
"newValue",
")",
";",
"}",
"}",
",",
"defaultValueCreator",
":",
"(",
"bindable",
")",
"=>",
"{",
"var",
"control",
"=",
"(",
"Control",
")",
"bindable",
";",
"return",
"control",
".",
"BackgroundColorSelector",
";",
"}",
")",
";",
"[",
"EditorBrowsable",
"(",
"EditorBrowsableState",
".",
"Never",
")",
"]",
"protected",
"string",
"style",
";",
"private",
"TapGestureDetector",
"tapGestureDetector",
"=",
"new",
"TapGestureDetector",
"(",
")",
";",
"private",
"bool",
"isFocused",
"=",
"false",
";",
"internal",
"ImageView",
"backgroundImage",
"=",
"new",
"ImageView",
"(",
")",
";",
"internal",
"ImageView",
"shadowImage",
";",
"[",
"EditorBrowsable",
"(",
"EditorBrowsableState",
".",
"Never",
")",
"]",
"public",
"ControlStyle",
"Style",
"=>",
"ViewStyle",
"as",
"ControlStyle",
";",
"[",
"EditorBrowsable",
"(",
"EditorBrowsableState",
".",
"Never",
")",
"]",
"public",
"Control",
"(",
")",
":",
"base",
"(",
")",
"{",
"Initialize",
"(",
"null",
")",
";",
"}",
"[",
"EditorBrowsable",
"(",
"EditorBrowsableState",
".",
"Never",
")",
"]",
"public",
"Control",
"(",
"ControlStyle",
"controlStyle",
")",
":",
"base",
"(",
"controlStyle",
")",
"{",
"Initialize",
"(",
"null",
")",
";",
"}",
"[",
"EditorBrowsable",
"(",
"EditorBrowsableState",
".",
"Never",
")",
"]",
"public",
"Control",
"(",
"string",
"styleSheet",
")",
":",
"base",
"(",
")",
"{",
"ViewStyle",
"viewStyle",
"=",
"StyleManager",
".",
"Instance",
".",
"GetViewStyle",
"(",
"styleSheet",
")",
";",
"if",
"(",
"viewStyle",
"==",
"null",
")",
"{",
"throw",
"new",
"InvalidOperationException",
"(",
"$\"",
"There is no style ",
"{",
"styleSheet",
"}",
"\"",
")",
";",
"}",
"ApplyStyle",
"(",
"viewStyle",
")",
";",
"this",
".",
"style",
"=",
"styleSheet",
";",
"Initialize",
"(",
"style",
")",
";",
"}",
"private",
"TriggerableSelector",
"<",
"string",
">",
"_backgroundImageSelector",
";",
"private",
"TriggerableSelector",
"<",
"string",
">",
"BackgroundImageSelector",
"{",
"get",
"{",
"if",
"(",
"null",
"==",
"_backgroundImageSelector",
")",
"{",
"_backgroundImageSelector",
"=",
"new",
"TriggerableSelector",
"<",
"string",
">",
"(",
"backgroundImage",
",",
"ImageView",
".",
"ResourceUrlProperty",
")",
";",
"}",
"return",
"_backgroundImageSelector",
";",
"}",
"}",
"private",
"TriggerableSelector",
"<",
"Rectangle",
">",
"_backgroundImageBorderSelector",
";",
"private",
"TriggerableSelector",
"<",
"Rectangle",
">",
"backgroundImageBorderSelector",
"{",
"get",
"{",
"if",
"(",
"null",
"==",
"_backgroundImageBorderSelector",
")",
"{",
"_backgroundImageBorderSelector",
"=",
"new",
"TriggerableSelector",
"<",
"Rectangle",
">",
"(",
"backgroundImage",
",",
"ImageView",
".",
"BorderProperty",
")",
";",
"}",
"return",
"_backgroundImageBorderSelector",
";",
"}",
"}",
"private",
"TriggerableSelector",
"<",
"Color",
">",
"_backgroundColorSelector",
";",
"private",
"TriggerableSelector",
"<",
"Color",
">",
"BackgroundColorSelector",
"{",
"get",
"{",
"if",
"(",
"null",
"==",
"_backgroundColorSelector",
")",
"{",
"_backgroundColorSelector",
"=",
"new",
"TriggerableSelector",
"<",
"Color",
">",
"(",
"backgroundImage",
",",
"View",
".",
"BackgroundColorProperty",
")",
";",
"}",
"return",
"_backgroundColorSelector",
";",
"}",
"}",
"[",
"EditorBrowsable",
"(",
"EditorBrowsableState",
".",
"Never",
")",
"]",
"public",
"new",
"Selector",
"<",
"string",
">",
"BackgroundImage",
"{",
"get",
"=>",
"(",
"Selector",
"<",
"string",
">",
")",
"GetValue",
"(",
"BackgroundImageProperty",
")",
";",
"set",
"=>",
"SetValue",
"(",
"BackgroundImageProperty",
",",
"value",
")",
";",
"}",
"[",
"EditorBrowsable",
"(",
"EditorBrowsableState",
".",
"Never",
")",
"]",
"public",
"new",
"Selector",
"<",
"Rectangle",
">",
"BackgroundImageBorder",
"{",
"get",
"=>",
"(",
"Selector",
"<",
"Rectangle",
">",
")",
"GetValue",
"(",
"BackgroundImageBorderProperty",
")",
";",
"set",
"=>",
"SetValue",
"(",
"BackgroundImageBorderProperty",
",",
"value",
")",
";",
"}",
"[",
"EditorBrowsable",
"(",
"EditorBrowsableState",
".",
"Never",
")",
"]",
"public",
"new",
"Selector",
"<",
"Color",
">",
"BackgroundColor",
"{",
"get",
"=>",
"(",
"Selector",
"<",
"Color",
">",
")",
"GetValue",
"(",
"BackgroundColorProperty",
")",
";",
"set",
"=>",
"SetValue",
"(",
"BackgroundColorProperty",
",",
"value",
")",
";",
"}",
"[",
"EditorBrowsable",
"(",
"EditorBrowsableState",
".",
"Never",
")",
"]",
"public",
"Selector",
"<",
"string",
">",
"ShadowImage",
"{",
"get",
"{",
"return",
"Style",
".",
"Shadow",
".",
"ResourceUrl",
";",
"}",
"set",
"{",
"Style",
".",
"Shadow",
".",
"ResourceUrl",
"=",
"value",
";",
"}",
"}",
"[",
"EditorBrowsable",
"(",
"EditorBrowsableState",
".",
"Never",
")",
"]",
"public",
"Selector",
"<",
"Rectangle",
">",
"ShadowImageBorder",
"{",
"get",
"{",
"return",
"Style",
".",
"Shadow",
".",
"Border",
";",
"}",
"set",
"{",
"Style",
".",
"Shadow",
".",
"Border",
"=",
"value",
";",
"}",
"}",
"internal",
"void",
"ApplyAttributes",
"(",
"View",
"view",
",",
"ViewStyle",
"viewStyle",
")",
"{",
"view",
".",
"CopyFrom",
"(",
"viewStyle",
")",
";",
"}",
"internal",
"bool",
"StateFocusableOnTouchMode",
"{",
"get",
";",
"set",
";",
"}",
"internal",
"bool",
"IsFocused",
"=>",
"(",
"isFocused",
"||",
"HasFocus",
"(",
")",
")",
";",
"[",
"EditorBrowsable",
"(",
"EditorBrowsableState",
".",
"Never",
")",
"]",
"protected",
"override",
"void",
"Dispose",
"(",
"DisposeTypes",
"type",
")",
"{",
"if",
"(",
"disposed",
")",
"{",
"return",
";",
"}",
"if",
"(",
"type",
"==",
"DisposeTypes",
".",
"Explicit",
")",
"{",
"StyleManager",
".",
"Instance",
".",
"ThemeChangedEvent",
"-=",
"OnThemeChangedEvent",
";",
"tapGestureDetector",
".",
"Detected",
"-=",
"OnTapGestureDetected",
";",
"tapGestureDetector",
".",
"Detach",
"(",
"this",
")",
";",
"}",
"if",
"(",
"backgroundImage",
"!=",
"null",
")",
"{",
"Utility",
".",
"Dispose",
"(",
"backgroundImage",
")",
";",
"}",
"if",
"(",
"shadowImage",
"!=",
"null",
")",
"{",
"Utility",
".",
"Dispose",
"(",
"shadowImage",
")",
";",
"}",
"base",
".",
"Dispose",
"(",
"type",
")",
";",
"}",
"[",
"EditorBrowsable",
"(",
"EditorBrowsableState",
".",
"Never",
")",
"]",
"public",
"override",
"bool",
"OnKey",
"(",
"Key",
"key",
")",
"{",
"return",
"false",
";",
"}",
"[",
"EditorBrowsable",
"(",
"EditorBrowsableState",
".",
"Never",
")",
"]",
"public",
"override",
"void",
"OnRelayout",
"(",
"Vector2",
"size",
",",
"RelayoutContainer",
"container",
")",
"{",
"OnUpdate",
"(",
")",
";",
"}",
"[",
"EditorBrowsable",
"(",
"EditorBrowsableState",
".",
"Never",
")",
"]",
"public",
"override",
"void",
"OnFocusGained",
"(",
")",
"{",
"isFocused",
"=",
"true",
";",
"}",
"[",
"EditorBrowsable",
"(",
"EditorBrowsableState",
".",
"Never",
")",
"]",
"public",
"override",
"void",
"OnFocusLost",
"(",
")",
"{",
"isFocused",
"=",
"false",
";",
"}",
"[",
"EditorBrowsable",
"(",
"EditorBrowsableState",
".",
"Never",
")",
"]",
"public",
"override",
"void",
"ApplyStyle",
"(",
"ViewStyle",
"viewStyle",
")",
"{",
"base",
".",
"ApplyStyle",
"(",
"viewStyle",
")",
";",
"ControlStyle",
"controlStyle",
"=",
"viewStyle",
"as",
"ControlStyle",
";",
"if",
"(",
"null",
"!=",
"controlStyle",
"?",
".",
"Shadow",
")",
"{",
"if",
"(",
"null",
"==",
"shadowImage",
")",
"{",
"shadowImage",
"=",
"new",
"ImageView",
"(",
")",
"{",
"WidthResizePolicy",
"=",
"ResizePolicyType",
".",
"FillToParent",
",",
"HeightResizePolicy",
"=",
"ResizePolicyType",
".",
"FillToParent",
",",
"}",
";",
"this",
".",
"Add",
"(",
"shadowImage",
")",
";",
"shadowImage",
".",
"LowerToBottom",
"(",
")",
";",
"}",
"shadowImage",
".",
"ApplyStyle",
"(",
"controlStyle",
".",
"Shadow",
")",
";",
"}",
"if",
"(",
"null",
"!=",
"controlStyle",
".",
"BackgroundImage",
")",
"{",
"backgroundImage",
".",
"WidthResizePolicy",
"=",
"ResizePolicyType",
".",
"FillToParent",
";",
"backgroundImage",
".",
"HeightResizePolicy",
"=",
"ResizePolicyType",
".",
"FillToParent",
";",
"this",
".",
"Add",
"(",
"backgroundImage",
")",
";",
"}",
"}",
"[",
"EditorBrowsable",
"(",
"EditorBrowsableState",
".",
"Never",
")",
"]",
"protected",
"virtual",
"void",
"OnTapGestureDetected",
"(",
"object",
"source",
",",
"TapGestureDetector",
".",
"DetectedEventArgs",
"e",
")",
"{",
"}",
"[",
"EditorBrowsable",
"(",
"EditorBrowsableState",
".",
"Never",
")",
"]",
"public",
"override",
"bool",
"OnTouch",
"(",
"Touch",
"touch",
")",
"{",
"return",
"false",
";",
"}",
"[",
"EditorBrowsable",
"(",
"EditorBrowsableState",
".",
"Never",
")",
"]",
"protected",
"virtual",
"void",
"OnUpdate",
"(",
")",
"{",
"}",
"[",
"EditorBrowsable",
"(",
"EditorBrowsableState",
".",
"Never",
")",
"]",
"protected",
"virtual",
"void",
"OnThemeChangedEvent",
"(",
"object",
"sender",
",",
"StyleManager",
".",
"ThemeChangeEventArgs",
"e",
")",
"{",
"}",
"[",
"EditorBrowsable",
"(",
"EditorBrowsableState",
".",
"Never",
")",
"]",
"protected",
"virtual",
"void",
"RegisterDetectionOfSubstyleChanges",
"(",
")",
"{",
"}",
"[",
"EditorBrowsable",
"(",
"EditorBrowsableState",
".",
"Never",
")",
"]",
"protected",
"override",
"ViewStyle",
"GetViewStyle",
"(",
")",
"{",
"return",
"new",
"ControlStyle",
"(",
")",
";",
"}",
"private",
"void",
"Initialize",
"(",
"string",
"style",
")",
"{",
"ControlState",
"=",
"ControlStates",
".",
"Normal",
";",
"RegisterDetectionOfSubstyleChanges",
"(",
")",
";",
"LeaveRequired",
"=",
"true",
";",
"StateFocusableOnTouchMode",
"=",
"false",
";",
"tapGestureDetector",
".",
"Attach",
"(",
"this",
")",
";",
"tapGestureDetector",
".",
"Detected",
"+=",
"OnTapGestureDetected",
";",
"StyleManager",
".",
"Instance",
".",
"ThemeChangedEvent",
"+=",
"OnThemeChangedEvent",
";",
"}",
"}"
] |
The control component is base class of tv nui components.
|
[
"The",
"control",
"component",
"is",
"base",
"class",
"of",
"tv",
"nui",
"components",
"."
] |
[
"/// <summary> BackgroundImageProperty</summary>",
"/// <summary>BackgroundBorderProperty</summary>",
"/// <summary> BackgroundColorProperty </summary>",
"/// <summary> Control style. </summary>",
"/// <since_tizen> 6 </since_tizen>",
"/// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API.",
"/// This will be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API.",
"/// <summary>",
"/// Construct an empty Control.",
"/// </summary>",
"/// <since_tizen> 6 </since_tizen>",
"/// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API.",
"/// <summary>",
"/// Construct with attributes",
"/// </summary>",
"/// <param name=\"attributes\">Create attributes customized by user</param>",
"/// <since_tizen> 6 </since_tizen>",
"/// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API.",
"/// <summary>",
"/// Construct with styleSheet",
"/// </summary>",
"/// <param name=\"styleSheet\">StyleSheet to be applied</param>",
"/// <since_tizen> 6 </since_tizen>",
"/// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API.",
"/// <summary>",
"/// Override view's BackgroundImage.",
"/// </summary>",
"/// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API.",
"/// <summary>",
"/// Override view's BackgroundImageBorder.",
"/// </summary>",
"/// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API.",
"/// <summary>",
"/// Override view's BackgroundBorder.",
"/// </summary>",
"/// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API.",
"/// <summary>",
"/// Shadow image.",
"/// </summary>",
"/// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API.",
"/// <summary>",
"/// Shadow image border.",
"/// </summary>",
"/// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API.",
"/// <summary>",
"/// Whether focusable when touch",
"/// </summary>",
"/// <since_tizen> 6 </since_tizen>",
"/// <summary>",
"/// Dispose Control and all children on it.",
"/// </summary>",
"/// <param name=\"type\">Dispose type.</param>",
"/// <since_tizen> 6 </since_tizen>",
"/// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API.",
"/// <summary>",
"/// Called after a key event is received by the view that has had its focus set.",
"/// </summary>",
"/// <param name=\"key\">The key event.</param>",
"/// <returns>True if the key event should be consumed.</returns>",
"/// <since_tizen> 6 </since_tizen>",
"/// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API.",
"/// <summary>",
"/// Called after the size negotiation has been finished for this control.<br />",
"/// The control is expected to assign this given size to itself or its children.<br />",
"/// Should be overridden by derived classes if they need to layout views differently after certain operations like add or remove views, resize, or after changing specific properties.<br />",
"/// As this function is called from inside the size negotiation algorithm, you cannot call RequestRelayout (the call would just be ignored).<br />",
"/// </summary>",
"/// <param name=\"size\">The allocated size.</param>",
"/// <param name=\"container\">The control should add views to this container that it is not able to allocate a size for.</param>",
"/// <since_tizen> 6 </since_tizen>",
"/// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API.",
"/// <summary>",
"/// Called when the control gain key input focus. Should be overridden by derived classes if they need to customize what happens when the focus is gained.",
"/// </summary>",
"/// <since_tizen> 6 </since_tizen>",
"/// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API.",
"/// <summary>",
"/// Called when the control loses key input focus. Should be overridden by derived classes if they need to customize what happens when the focus is lost.",
"/// </summary>",
"/// <since_tizen> 6 </since_tizen>",
"/// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API.",
"/// This will be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API.",
"/// <summary>",
"/// Tap gesture callback.",
"/// </summary>",
"/// <param name=\"source\">The sender</param>",
"/// <param name=\"e\">The tap gesture event data</param>",
"/// <since_tizen> 6 </since_tizen>",
"/// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API.",
"/// <summary>",
"/// Called after a touch event is received by the owning view.<br />",
"/// CustomViewBehaviour.REQUIRES_TOUCH_EVENTS must be enabled during construction. See CustomView(ViewWrapperImpl.CustomViewBehaviour behaviour).<br />",
"/// </summary>",
"/// <param name=\"touch\">The touch event.</param>",
"/// <returns>True if the event should be consumed.</returns>",
"/// <since_tizen> 6 </since_tizen>",
"/// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API.",
"/// <summary>",
"/// Update by attributes.",
"/// </summary>",
"/// <since_tizen> 6 </since_tizen>",
"/// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API.",
"/// <summary>",
"/// Theme change callback when theme is changed, this callback will be trigger.",
"/// </summary>",
"/// <param name=\"sender\">The sender</param>",
"/// <param name=\"e\">The event data</param>",
"/// <since_tizen> 6 </since_tizen>",
"/// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API.",
"/// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API.",
"/// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API."
] |
[
{
"param": "VisualView",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "VisualView",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": [
{
"identifier": "since_tizen",
"docstring": null,
"docstring_tokens": [
"None"
]
}
]
}
| false
| 20
| 1,761
| 80
|
2dea5dc03258498ebe294af10b71bd03056a1f03
|
zealoussnow/chromium
|
third_party/android_support_test_runner/rules/src/main/java/android/support/test/rule/UiThreadTestRule.java
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] |
Java
|
UiThreadTestRule
|
/**
* This rule allows the test method annotated with {@link UiThreadTest} to execute on the
* application's main thread (or UI thread).
* <p/>
* Note, methods annotated with
* <a href="http://junit.sourceforge.net/javadoc/org/junit/Before.html"><code>Before</code></a> and
* <a href="http://junit.sourceforge.net/javadoc/org/junit/After.html"><code>After</code></a> will
* also be executed on the UI thread.
*
* @see android.support.test.annotation.UiThreadTest
*/
|
This rule allows the test method annotated with UiThreadTest to execute on the
application's main thread (or UI thread).
Note, methods annotated with
Before and
After will
also be executed on the UI thread.
|
[
"This",
"rule",
"allows",
"the",
"test",
"method",
"annotated",
"with",
"UiThreadTest",
"to",
"execute",
"on",
"the",
"application",
"'",
"s",
"main",
"thread",
"(",
"or",
"UI",
"thread",
")",
".",
"Note",
"methods",
"annotated",
"with",
"Before",
"and",
"After",
"will",
"also",
"be",
"executed",
"on",
"the",
"UI",
"thread",
"."
] |
@Beta
public class UiThreadTestRule implements TestRule {
private static final String LOG_TAG = "UiThreadTestRule";
@Override
public Statement apply(final Statement base, Description description) {
return new UiThreadStatement(base, shouldRunOnUiThread(description));
}
protected boolean shouldRunOnUiThread(Description description) {
return description.getAnnotation(UiThreadTest.class) != null;
}
/**
* Helper for running portions of a test on the UI thread.
* <p/>
* Note, in most cases it is simpler to annotate the test method with
* {@link UiThreadTest}, which will run the entire test method including methods annotated with
* <a href="http://junit.sourceforge.net/javadoc/org/junit/Before.html"><code>Before</code></a>
* and <a href="http://junit.sourceforge.net/javadoc/org/junit/After.html">
* <code>After</code></a> on the UI thread.
* <p/>
* Use this method if you need to switch in and out of the UI thread to perform your test.
*
* @param runnable runnable containing test code in the {@link Runnable#run()} method
*
* @see android.support.test.annotation.UiThreadTest
*/
public void runOnUiThread(final Runnable runnable) throws Throwable {
if (Looper.myLooper() == Looper.getMainLooper()) {
Log.w(LOG_TAG, "Already on the UI thread, this method should not be called from the " +
"main application thread");
runnable.run();
} else {
FutureTask<Void> task = new FutureTask<>(runnable, null);
getInstrumentation().runOnMainSync(task);
try {
task.get();
} catch (ExecutionException e) {
// Expose the original exception
throw e.getCause();
}
}
}
}
|
[
"@",
"Beta",
"public",
"class",
"UiThreadTestRule",
"implements",
"TestRule",
"{",
"private",
"static",
"final",
"String",
"LOG_TAG",
"=",
"\"",
"UiThreadTestRule",
"\"",
";",
"@",
"Override",
"public",
"Statement",
"apply",
"(",
"final",
"Statement",
"base",
",",
"Description",
"description",
")",
"{",
"return",
"new",
"UiThreadStatement",
"(",
"base",
",",
"shouldRunOnUiThread",
"(",
"description",
")",
")",
";",
"}",
"protected",
"boolean",
"shouldRunOnUiThread",
"(",
"Description",
"description",
")",
"{",
"return",
"description",
".",
"getAnnotation",
"(",
"UiThreadTest",
".",
"class",
")",
"!=",
"null",
";",
"}",
"/**\n * Helper for running portions of a test on the UI thread.\n * <p/>\n * Note, in most cases it is simpler to annotate the test method with\n * {@link UiThreadTest}, which will run the entire test method including methods annotated with\n * <a href=\"http://junit.sourceforge.net/javadoc/org/junit/Before.html\"><code>Before</code></a>\n * and <a href=\"http://junit.sourceforge.net/javadoc/org/junit/After.html\">\n * <code>After</code></a> on the UI thread.\n * <p/>\n * Use this method if you need to switch in and out of the UI thread to perform your test.\n *\n * @param runnable runnable containing test code in the {@link Runnable#run()} method\n *\n * @see android.support.test.annotation.UiThreadTest\n */",
"public",
"void",
"runOnUiThread",
"(",
"final",
"Runnable",
"runnable",
")",
"throws",
"Throwable",
"{",
"if",
"(",
"Looper",
".",
"myLooper",
"(",
")",
"==",
"Looper",
".",
"getMainLooper",
"(",
")",
")",
"{",
"Log",
".",
"w",
"(",
"LOG_TAG",
",",
"\"",
"Already on the UI thread, this method should not be called from the ",
"\"",
"+",
"\"",
"main application thread",
"\"",
")",
";",
"runnable",
".",
"run",
"(",
")",
";",
"}",
"else",
"{",
"FutureTask",
"<",
"Void",
">",
"task",
"=",
"new",
"FutureTask",
"<",
">",
"(",
"runnable",
",",
"null",
")",
";",
"getInstrumentation",
"(",
")",
".",
"runOnMainSync",
"(",
"task",
")",
";",
"try",
"{",
"task",
".",
"get",
"(",
")",
";",
"}",
"catch",
"(",
"ExecutionException",
"e",
")",
"{",
"throw",
"e",
".",
"getCause",
"(",
")",
";",
"}",
"}",
"}",
"}"
] |
This rule allows the test method annotated with {@link UiThreadTest} to execute on the
application's main thread (or UI thread).
|
[
"This",
"rule",
"allows",
"the",
"test",
"method",
"annotated",
"with",
"{",
"@link",
"UiThreadTest",
"}",
"to",
"execute",
"on",
"the",
"application",
"'",
"s",
"main",
"thread",
"(",
"or",
"UI",
"thread",
")",
"."
] |
[
"// Expose the original exception"
] |
[
{
"param": "TestRule",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "TestRule",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 13
| 401
| 124
|
e19efc6e6d56abae564265dfc7890448d3d3e535
|
guopeisheng/OOP
|
HW08/libs/WWJ/code/src/gov/nasa/worldwind/render/GlobeBrowserBalloon.java
|
[
"Apache-2.0"
] |
Java
|
GlobeBrowserBalloon
|
/**
* A <code>{@link gov.nasa.worldwind.render.GlobeBalloon}</code> that displays HTML, JavaScript, and Flash content using
* the system's native browser, and who's origin is located at a position on the <code>Globe</code>.
*
* @author pabercrombie
* @version $Id: GlobeBrowserBalloon.java 1171 2013-02-11 21:45:02Z dcollins $
* @see gov.nasa.worldwind.render.AbstractBrowserBalloon
*/
|
A gov.nasa.worldwind.render.GlobeBalloon that displays HTML, JavaScript, and Flash content using
the system's native browser, and who's origin is located at a position on the Globe.
@author pabercrombie
@version $Id: GlobeBrowserBalloon.java 1171 2013-02-11 21:45:02Z dcollins $
@see gov.nasa.worldwind.render.AbstractBrowserBalloon
|
[
"A",
"gov",
".",
"nasa",
".",
"worldwind",
".",
"render",
".",
"GlobeBalloon",
"that",
"displays",
"HTML",
"JavaScript",
"and",
"Flash",
"content",
"using",
"the",
"system",
"'",
"s",
"native",
"browser",
"and",
"who",
"'",
"s",
"origin",
"is",
"located",
"at",
"a",
"position",
"on",
"the",
"Globe",
".",
"@author",
"pabercrombie",
"@version",
"$Id",
":",
"GlobeBrowserBalloon",
".",
"java",
"1171",
"2013",
"-",
"02",
"-",
"11",
"21",
":",
"45",
":",
"02Z",
"dcollins",
"$",
"@see",
"gov",
".",
"nasa",
".",
"worldwind",
".",
"render",
".",
"AbstractBrowserBalloon"
] |
public class GlobeBrowserBalloon extends AbstractBrowserBalloon implements GlobeBalloon
{
/**
* Indicates this balloon's geographic position. The position's altitude is interpreted relative to this balloon's
* <code>altitudeMode</code>. Initialized to a non-<code>null</code> value at construction.
*/
protected Position position;
/**
* Indicates how this balloon's altitude is interpreted. One of <code>WorldWind.ABSOLUTE</code>,
* <code>WorldWind.RELATIVE_TO_GROUND</code>, or <code>WorldWind.CLAMP_TO_GROUND</code>. If the altitude mode is 0
* or an unrecognized code, this balloon assumes an altitude mode of <code>WorldWind.ABSOLUTE</code>. Initially 0.
*/
protected int altitudeMode;
/** The model-coordinate point corresponding to this balloon's position. May be <code>null</code>. */
protected Vec4 placePoint;
/**
* The projection of this balloon's <code>placePoint</code> in the viewport (on the screen). May be
* <code>null</code>.
*/
protected Vec4 screenPlacePoint;
/**
* Constructs a new <code>GlobeBrowserBalloon</code> with the specified text content and position.
*
* @param text the balloon's initial text content.
* @param position the balloon's initial position.
*
* @throws IllegalArgumentException if either <code>text</code> or <code>position</code> are <code>null</code>.
*/
public GlobeBrowserBalloon(String text, Position position)
{
super(text);
if (position == null)
{
String message = Logging.getMessage("nullValue.PositionIsNull");
Logging.logger().severe(message);
throw new IllegalArgumentException(message);
}
this.position = position;
}
/** {@inheritDoc} */
public Position getPosition()
{
return this.position;
}
/** {@inheritDoc} */
public void setPosition(Position position)
{
if (position == null)
{
String message = Logging.getMessage("nullValue.PositionIsNull");
Logging.logger().severe(message);
throw new IllegalArgumentException(message);
}
this.position = position;
}
/** {@inheritDoc} */
public int getAltitudeMode()
{
return altitudeMode;
}
/** {@inheritDoc} */
public void setAltitudeMode(int altitudeMode)
{
this.altitudeMode = altitudeMode;
}
/**
* Computes and stores this balloon's model and screen coordinates. This assigns balloon coordinate properties as
* follows:
* <p/>
* <ul> <li><code>placePoint</code> - this balloon's model-coordinate point, according to its altitude mode.</li>
* <li><code>screenPlacePoint</code> - screen-space projection of the <code>placePoint</code>.</li>
* <li><code>screenOffset</code> - the balloon frame's screen-coordinate offset from this balloon's
* <code>screenPlacePoint</code>.</li> <li><code>screenRect</code> - the balloon frame's screen-coordinate
* rectangle.</li> <li><code>screenExtent</code> - this balloon's screen-coordinate bounding rectangle.</li>
* <li><code>screenPickExtent</code> - this balloon's screen-coordinate bounding rectangle, including area covered
* by the balloon's pickable outline.</li> <li><code>webViewRect</code> - the WebView's screen-coordinate content
* frame.</li> <li><code>eyeDistance</code> - always 0.</li>
*
* @param dc the current draw context.
*/
protected void computeBalloonPoints(DrawContext dc)
{
this.placePoint = null;
this.screenPlacePoint = null;
this.screenOffset = null;
this.screenRect = null;
this.screenExtent = null;
this.screenPickExtent = null;
this.webViewRect = null;
this.eyeDistance = 0;
if (this.altitudeMode == WorldWind.CLAMP_TO_GROUND)
{
this.placePoint = dc.computeTerrainPoint(
this.position.getLatitude(), this.position.getLongitude(), 0);
}
else if (this.altitudeMode == WorldWind.RELATIVE_TO_GROUND)
{
this.placePoint = dc.computeTerrainPoint(
this.position.getLatitude(), this.position.getLongitude(), this.position.getAltitude());
}
else // Default to ABSOLUTE
{
double height = this.position.getElevation() * dc.getVerticalExaggeration();
this.placePoint = dc.getGlobe().computePointFromPosition(
this.position.getLatitude(), this.position.getLongitude(), height);
}
// Exit immediately if the place point is null. In this case we cannot compute the data that depends on the
// place point: screen place point, screen rectangle, WebView rectangle, and eye distance.
if (this.placePoint == null)
return;
BalloonAttributes activeAttrs = this.getActiveAttributes();
Dimension size = this.computeSize(dc, activeAttrs);
// Compute the screen place point as the projection of the place point into screen coordinates.
this.screenPlacePoint = dc.getView().project(this.placePoint);
// Cache the screen offset computed from the active attributes.
this.screenOffset = this.computeOffset(dc, activeAttrs, size.width, size.height);
// Compute the screen rectangle given the screen projection of the place point, the current screen offset, and
// the current screen size. Note: The screen offset denotes how to place the screen reference point relative to
// the frame. For example, an offset of (-10, -10) in pixels places the reference point below and to the left
// of the frame. Since the screen reference point is fixed, the frame appears to move relative to the reference
// point.
this.screenRect = new Rectangle((int) (this.screenPlacePoint.x - this.screenOffset.x),
(int) (this.screenPlacePoint.y - this.screenOffset.y),
size.width, size.height);
// Compute the screen extent as the rectangle containing the balloon's screen rectangle and its place point.
this.screenExtent = new Rectangle(this.screenRect);
this.screenExtent.add(this.screenPlacePoint.x, this.screenPlacePoint.y);
// Compute the pickable screen extent as the screen extent, plus the width of the balloon's pickable outline.
// This extent is used during picking to ensure that the balloon's outline is pickable when it exceeds the
// balloon's screen extent.
this.screenPickExtent = this.computeFramePickRect(this.screenExtent);
// Compute the WebView rectangle as an inset of the screen rectangle, given the current inset values.
this.webViewRect = this.computeWebViewRectForFrameRect(activeAttrs, this.screenRect);
// Compute the eye distance as the distance from the place point to the View's eye point.
this.eyeDistance = this.isAlwaysOnTop() ? 0 : dc.getView().getEyePoint().distanceTo3(this.placePoint);
}
/** {@inheritDoc} */
protected void setupDepthTest(DrawContext dc)
{
GL gl = dc.getGL();
if (!this.isAlwaysOnTop() && this.screenPlacePoint != null
&& dc.getView().getEyePosition().getElevation() < (dc.getGlobe().getMaxElevation()
* dc.getVerticalExaggeration()))
{
gl.glEnable(GL.GL_DEPTH_TEST);
gl.glDepthMask(false);
// Adjust depth of image to bring it slightly forward
double depth = this.screenPlacePoint.z - (8d * 0.00048875809d);
depth = depth < 0d ? 0d : (depth > 1d ? 1d : depth);
gl.glDepthFunc(GL.GL_LESS);
gl.glDepthRange(depth, depth);
}
else
{
gl.glDisable(GL.GL_DEPTH_TEST);
}
}
/**
* {@inheritDoc}
* <p/>
* Overridden to return <code>false</code> if the balloon's position is either behind the <code>View's</code> near
* clipping plane or in front of the <code>View's</code> far clipping plane. Otherwise this delegates to the super
* class' behavior.
*/
@Override
protected boolean intersectsFrustum(DrawContext dc)
{
View view = dc.getView();
// Test the balloon against the near and far clipping planes.
Frustum frustum = view.getFrustumInModelCoordinates();
//noinspection SimplifiableIfStatement
if (this.placePoint != null
&& (frustum.getNear().distanceTo(this.placePoint) < 0
|| frustum.getFar().distanceTo(this.placePoint) < 0))
{
return false;
}
return super.intersectsFrustum(dc);
}
/**
* {@inheritDoc}
* <p/>
* Overridden to use this balloon's position as the picked object's position.
*/
@Override
protected PickedObject createPickedObject(DrawContext dc, Color pickColor)
{
PickedObject po = super.createPickedObject(dc, pickColor);
// Set the picked object's position to the balloon's position.
po.setPosition(this.position);
return po;
}
}
|
[
"public",
"class",
"GlobeBrowserBalloon",
"extends",
"AbstractBrowserBalloon",
"implements",
"GlobeBalloon",
"{",
"/**\n * Indicates this balloon's geographic position. The position's altitude is interpreted relative to this balloon's\n * <code>altitudeMode</code>. Initialized to a non-<code>null</code> value at construction.\n */",
"protected",
"Position",
"position",
";",
"/**\n * Indicates how this balloon's altitude is interpreted. One of <code>WorldWind.ABSOLUTE</code>,\n * <code>WorldWind.RELATIVE_TO_GROUND</code>, or <code>WorldWind.CLAMP_TO_GROUND</code>. If the altitude mode is 0\n * or an unrecognized code, this balloon assumes an altitude mode of <code>WorldWind.ABSOLUTE</code>. Initially 0.\n */",
"protected",
"int",
"altitudeMode",
";",
"/** The model-coordinate point corresponding to this balloon's position. May be <code>null</code>. */",
"protected",
"Vec4",
"placePoint",
";",
"/**\n * The projection of this balloon's <code>placePoint</code> in the viewport (on the screen). May be\n * <code>null</code>.\n */",
"protected",
"Vec4",
"screenPlacePoint",
";",
"/**\n * Constructs a new <code>GlobeBrowserBalloon</code> with the specified text content and position.\n *\n * @param text the balloon's initial text content.\n * @param position the balloon's initial position.\n *\n * @throws IllegalArgumentException if either <code>text</code> or <code>position</code> are <code>null</code>.\n */",
"public",
"GlobeBrowserBalloon",
"(",
"String",
"text",
",",
"Position",
"position",
")",
"{",
"super",
"(",
"text",
")",
";",
"if",
"(",
"position",
"==",
"null",
")",
"{",
"String",
"message",
"=",
"Logging",
".",
"getMessage",
"(",
"\"",
"nullValue.PositionIsNull",
"\"",
")",
";",
"Logging",
".",
"logger",
"(",
")",
".",
"severe",
"(",
"message",
")",
";",
"throw",
"new",
"IllegalArgumentException",
"(",
"message",
")",
";",
"}",
"this",
".",
"position",
"=",
"position",
";",
"}",
"/** {@inheritDoc} */",
"public",
"Position",
"getPosition",
"(",
")",
"{",
"return",
"this",
".",
"position",
";",
"}",
"/** {@inheritDoc} */",
"public",
"void",
"setPosition",
"(",
"Position",
"position",
")",
"{",
"if",
"(",
"position",
"==",
"null",
")",
"{",
"String",
"message",
"=",
"Logging",
".",
"getMessage",
"(",
"\"",
"nullValue.PositionIsNull",
"\"",
")",
";",
"Logging",
".",
"logger",
"(",
")",
".",
"severe",
"(",
"message",
")",
";",
"throw",
"new",
"IllegalArgumentException",
"(",
"message",
")",
";",
"}",
"this",
".",
"position",
"=",
"position",
";",
"}",
"/** {@inheritDoc} */",
"public",
"int",
"getAltitudeMode",
"(",
")",
"{",
"return",
"altitudeMode",
";",
"}",
"/** {@inheritDoc} */",
"public",
"void",
"setAltitudeMode",
"(",
"int",
"altitudeMode",
")",
"{",
"this",
".",
"altitudeMode",
"=",
"altitudeMode",
";",
"}",
"/**\n * Computes and stores this balloon's model and screen coordinates. This assigns balloon coordinate properties as\n * follows:\n * <p/>\n * <ul> <li><code>placePoint</code> - this balloon's model-coordinate point, according to its altitude mode.</li>\n * <li><code>screenPlacePoint</code> - screen-space projection of the <code>placePoint</code>.</li>\n * <li><code>screenOffset</code> - the balloon frame's screen-coordinate offset from this balloon's\n * <code>screenPlacePoint</code>.</li> <li><code>screenRect</code> - the balloon frame's screen-coordinate\n * rectangle.</li> <li><code>screenExtent</code> - this balloon's screen-coordinate bounding rectangle.</li>\n * <li><code>screenPickExtent</code> - this balloon's screen-coordinate bounding rectangle, including area covered\n * by the balloon's pickable outline.</li> <li><code>webViewRect</code> - the WebView's screen-coordinate content\n * frame.</li> <li><code>eyeDistance</code> - always 0.</li>\n *\n * @param dc the current draw context.\n */",
"protected",
"void",
"computeBalloonPoints",
"(",
"DrawContext",
"dc",
")",
"{",
"this",
".",
"placePoint",
"=",
"null",
";",
"this",
".",
"screenPlacePoint",
"=",
"null",
";",
"this",
".",
"screenOffset",
"=",
"null",
";",
"this",
".",
"screenRect",
"=",
"null",
";",
"this",
".",
"screenExtent",
"=",
"null",
";",
"this",
".",
"screenPickExtent",
"=",
"null",
";",
"this",
".",
"webViewRect",
"=",
"null",
";",
"this",
".",
"eyeDistance",
"=",
"0",
";",
"if",
"(",
"this",
".",
"altitudeMode",
"==",
"WorldWind",
".",
"CLAMP_TO_GROUND",
")",
"{",
"this",
".",
"placePoint",
"=",
"dc",
".",
"computeTerrainPoint",
"(",
"this",
".",
"position",
".",
"getLatitude",
"(",
")",
",",
"this",
".",
"position",
".",
"getLongitude",
"(",
")",
",",
"0",
")",
";",
"}",
"else",
"if",
"(",
"this",
".",
"altitudeMode",
"==",
"WorldWind",
".",
"RELATIVE_TO_GROUND",
")",
"{",
"this",
".",
"placePoint",
"=",
"dc",
".",
"computeTerrainPoint",
"(",
"this",
".",
"position",
".",
"getLatitude",
"(",
")",
",",
"this",
".",
"position",
".",
"getLongitude",
"(",
")",
",",
"this",
".",
"position",
".",
"getAltitude",
"(",
")",
")",
";",
"}",
"else",
"{",
"double",
"height",
"=",
"this",
".",
"position",
".",
"getElevation",
"(",
")",
"*",
"dc",
".",
"getVerticalExaggeration",
"(",
")",
";",
"this",
".",
"placePoint",
"=",
"dc",
".",
"getGlobe",
"(",
")",
".",
"computePointFromPosition",
"(",
"this",
".",
"position",
".",
"getLatitude",
"(",
")",
",",
"this",
".",
"position",
".",
"getLongitude",
"(",
")",
",",
"height",
")",
";",
"}",
"if",
"(",
"this",
".",
"placePoint",
"==",
"null",
")",
"return",
";",
"BalloonAttributes",
"activeAttrs",
"=",
"this",
".",
"getActiveAttributes",
"(",
")",
";",
"Dimension",
"size",
"=",
"this",
".",
"computeSize",
"(",
"dc",
",",
"activeAttrs",
")",
";",
"this",
".",
"screenPlacePoint",
"=",
"dc",
".",
"getView",
"(",
")",
".",
"project",
"(",
"this",
".",
"placePoint",
")",
";",
"this",
".",
"screenOffset",
"=",
"this",
".",
"computeOffset",
"(",
"dc",
",",
"activeAttrs",
",",
"size",
".",
"width",
",",
"size",
".",
"height",
")",
";",
"this",
".",
"screenRect",
"=",
"new",
"Rectangle",
"(",
"(",
"int",
")",
"(",
"this",
".",
"screenPlacePoint",
".",
"x",
"-",
"this",
".",
"screenOffset",
".",
"x",
")",
",",
"(",
"int",
")",
"(",
"this",
".",
"screenPlacePoint",
".",
"y",
"-",
"this",
".",
"screenOffset",
".",
"y",
")",
",",
"size",
".",
"width",
",",
"size",
".",
"height",
")",
";",
"this",
".",
"screenExtent",
"=",
"new",
"Rectangle",
"(",
"this",
".",
"screenRect",
")",
";",
"this",
".",
"screenExtent",
".",
"add",
"(",
"this",
".",
"screenPlacePoint",
".",
"x",
",",
"this",
".",
"screenPlacePoint",
".",
"y",
")",
";",
"this",
".",
"screenPickExtent",
"=",
"this",
".",
"computeFramePickRect",
"(",
"this",
".",
"screenExtent",
")",
";",
"this",
".",
"webViewRect",
"=",
"this",
".",
"computeWebViewRectForFrameRect",
"(",
"activeAttrs",
",",
"this",
".",
"screenRect",
")",
";",
"this",
".",
"eyeDistance",
"=",
"this",
".",
"isAlwaysOnTop",
"(",
")",
"?",
"0",
":",
"dc",
".",
"getView",
"(",
")",
".",
"getEyePoint",
"(",
")",
".",
"distanceTo3",
"(",
"this",
".",
"placePoint",
")",
";",
"}",
"/** {@inheritDoc} */",
"protected",
"void",
"setupDepthTest",
"(",
"DrawContext",
"dc",
")",
"{",
"GL",
"gl",
"=",
"dc",
".",
"getGL",
"(",
")",
";",
"if",
"(",
"!",
"this",
".",
"isAlwaysOnTop",
"(",
")",
"&&",
"this",
".",
"screenPlacePoint",
"!=",
"null",
"&&",
"dc",
".",
"getView",
"(",
")",
".",
"getEyePosition",
"(",
")",
".",
"getElevation",
"(",
")",
"<",
"(",
"dc",
".",
"getGlobe",
"(",
")",
".",
"getMaxElevation",
"(",
")",
"*",
"dc",
".",
"getVerticalExaggeration",
"(",
")",
")",
")",
"{",
"gl",
".",
"glEnable",
"(",
"GL",
".",
"GL_DEPTH_TEST",
")",
";",
"gl",
".",
"glDepthMask",
"(",
"false",
")",
";",
"double",
"depth",
"=",
"this",
".",
"screenPlacePoint",
".",
"z",
"-",
"(",
"8d",
"*",
"0.00048875809d",
")",
";",
"depth",
"=",
"depth",
"<",
"0d",
"?",
"0d",
":",
"(",
"depth",
">",
"1d",
"?",
"1d",
":",
"depth",
")",
";",
"gl",
".",
"glDepthFunc",
"(",
"GL",
".",
"GL_LESS",
")",
";",
"gl",
".",
"glDepthRange",
"(",
"depth",
",",
"depth",
")",
";",
"}",
"else",
"{",
"gl",
".",
"glDisable",
"(",
"GL",
".",
"GL_DEPTH_TEST",
")",
";",
"}",
"}",
"/**\n * {@inheritDoc}\n * <p/>\n * Overridden to return <code>false</code> if the balloon's position is either behind the <code>View's</code> near\n * clipping plane or in front of the <code>View's</code> far clipping plane. Otherwise this delegates to the super\n * class' behavior.\n */",
"@",
"Override",
"protected",
"boolean",
"intersectsFrustum",
"(",
"DrawContext",
"dc",
")",
"{",
"View",
"view",
"=",
"dc",
".",
"getView",
"(",
")",
";",
"Frustum",
"frustum",
"=",
"view",
".",
"getFrustumInModelCoordinates",
"(",
")",
";",
"if",
"(",
"this",
".",
"placePoint",
"!=",
"null",
"&&",
"(",
"frustum",
".",
"getNear",
"(",
")",
".",
"distanceTo",
"(",
"this",
".",
"placePoint",
")",
"<",
"0",
"||",
"frustum",
".",
"getFar",
"(",
")",
".",
"distanceTo",
"(",
"this",
".",
"placePoint",
")",
"<",
"0",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"super",
".",
"intersectsFrustum",
"(",
"dc",
")",
";",
"}",
"/**\n * {@inheritDoc}\n * <p/>\n * Overridden to use this balloon's position as the picked object's position.\n */",
"@",
"Override",
"protected",
"PickedObject",
"createPickedObject",
"(",
"DrawContext",
"dc",
",",
"Color",
"pickColor",
")",
"{",
"PickedObject",
"po",
"=",
"super",
".",
"createPickedObject",
"(",
"dc",
",",
"pickColor",
")",
";",
"po",
".",
"setPosition",
"(",
"this",
".",
"position",
")",
";",
"return",
"po",
";",
"}",
"}"
] |
A <code>{@link gov.nasa.worldwind.render.GlobeBalloon}</code> that displays HTML, JavaScript, and Flash content using
the system's native browser, and who's origin is located at a position on the <code>Globe</code>.
|
[
"A",
"<code",
">",
"{",
"@link",
"gov",
".",
"nasa",
".",
"worldwind",
".",
"render",
".",
"GlobeBalloon",
"}",
"<",
"/",
"code",
">",
"that",
"displays",
"HTML",
"JavaScript",
"and",
"Flash",
"content",
"using",
"the",
"system",
"'",
"s",
"native",
"browser",
"and",
"who",
"'",
"s",
"origin",
"is",
"located",
"at",
"a",
"position",
"on",
"the",
"<code",
">",
"Globe<",
"/",
"code",
">",
"."
] |
[
"// Default to ABSOLUTE",
"// Exit immediately if the place point is null. In this case we cannot compute the data that depends on the",
"// place point: screen place point, screen rectangle, WebView rectangle, and eye distance.",
"// Compute the screen place point as the projection of the place point into screen coordinates.",
"// Cache the screen offset computed from the active attributes.",
"// Compute the screen rectangle given the screen projection of the place point, the current screen offset, and",
"// the current screen size. Note: The screen offset denotes how to place the screen reference point relative to",
"// the frame. For example, an offset of (-10, -10) in pixels places the reference point below and to the left",
"// of the frame. Since the screen reference point is fixed, the frame appears to move relative to the reference",
"// point.",
"// Compute the screen extent as the rectangle containing the balloon's screen rectangle and its place point.",
"// Compute the pickable screen extent as the screen extent, plus the width of the balloon's pickable outline.",
"// This extent is used during picking to ensure that the balloon's outline is pickable when it exceeds the",
"// balloon's screen extent.",
"// Compute the WebView rectangle as an inset of the screen rectangle, given the current inset values.",
"// Compute the eye distance as the distance from the place point to the View's eye point.",
"// Adjust depth of image to bring it slightly forward",
"// Test the balloon against the near and far clipping planes.",
"//noinspection SimplifiableIfStatement",
"// Set the picked object's position to the balloon's position."
] |
[
{
"param": "AbstractBrowserBalloon",
"type": null
},
{
"param": "GlobeBalloon",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "AbstractBrowserBalloon",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "GlobeBalloon",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 14
| 2,014
| 120
|
b161697b2e269e22033cd79d6f67fa754a39ae38
|
ishisaka/StyleCopAnalyzers
|
StyleCop.Analyzers/StyleCop.Analyzers/SpacingRules/SA1016OpeningAttributeBracketsMustBeSpacedCorrectly.cs
|
[
"Apache-2.0"
] |
C#
|
SA1016OpeningAttributeBracketsMustBeSpacedCorrectly
|
/// <summary>
/// An opening attribute bracket within a C# element is not spaced correctly.
/// </summary>
/// <remarks>
/// <para>A violation of this rule occurs when the spacing around an opening attribute bracket is not
/// correct.</para>
///
/// <para>An opening attribute bracket should never be followed by whitespace, unless the bracket is the last
/// character on the line.</para>
/// </remarks>
|
An opening attribute bracket within a C# element is not spaced correctly.
|
[
"An",
"opening",
"attribute",
"bracket",
"within",
"a",
"C#",
"element",
"is",
"not",
"spaced",
"correctly",
"."
] |
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class SA1016OpeningAttributeBracketsMustBeSpacedCorrectly : DiagnosticAnalyzer
{
public const string DiagnosticId = "SA1016";
internal const string Title = "Opening attribute brackets must be spaced correctly";
internal const string MessageFormat = "Opening attribute brackets must not be followed by a space.";
internal const string Category = "StyleCop.CSharp.SpacingRules";
internal const string Description = "An opening attribute bracket within a C# element is not spaced correctly.";
internal const string HelpLink = "http://www.stylecop.com/docs/SA1016.html";
public static readonly DiagnosticDescriptor Descriptor =
new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, AnalyzerConstants.DisabledNoTests, Description, HelpLink);
private static readonly ImmutableArray<DiagnosticDescriptor> _supportedDiagnostics =
ImmutableArray.Create(Descriptor);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return _supportedDiagnostics;
}
}
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxTreeAction(HandleSyntaxTree);
}
private void HandleSyntaxTree(SyntaxTreeAnalysisContext context)
{
SyntaxNode root = context.Tree.GetCompilationUnitRoot(context.CancellationToken);
foreach (var token in root.DescendantTokens())
{
switch (token.CSharpKind())
{
case SyntaxKind.OpenBracketToken:
HandleOpenBracketToken(context, token);
break;
default:
break;
}
}
}
private void HandleOpenBracketToken(SyntaxTreeAnalysisContext context, SyntaxToken token)
{
if (token.IsMissing)
return;
if (!token.Parent.IsKind(SyntaxKind.AttributeList))
return;
if (!token.HasTrailingTrivia || token.TrailingTrivia.Any(SyntaxKind.EndOfLineTrivia))
return;
context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation()));
}
}
|
[
"[",
"DiagnosticAnalyzer",
"(",
"LanguageNames",
".",
"CSharp",
")",
"]",
"public",
"class",
"SA1016OpeningAttributeBracketsMustBeSpacedCorrectly",
":",
"DiagnosticAnalyzer",
"{",
"public",
"const",
"string",
"DiagnosticId",
"=",
"\"",
"SA1016",
"\"",
";",
"internal",
"const",
"string",
"Title",
"=",
"\"",
"Opening attribute brackets must be spaced correctly",
"\"",
";",
"internal",
"const",
"string",
"MessageFormat",
"=",
"\"",
"Opening attribute brackets must not be followed by a space.",
"\"",
";",
"internal",
"const",
"string",
"Category",
"=",
"\"",
"StyleCop.CSharp.SpacingRules",
"\"",
";",
"internal",
"const",
"string",
"Description",
"=",
"\"",
"An opening attribute bracket within a C# element is not spaced correctly.",
"\"",
";",
"internal",
"const",
"string",
"HelpLink",
"=",
"\"",
"http://www.stylecop.com/docs/SA1016.html",
"\"",
";",
"public",
"static",
"readonly",
"DiagnosticDescriptor",
"Descriptor",
"=",
"new",
"DiagnosticDescriptor",
"(",
"DiagnosticId",
",",
"Title",
",",
"MessageFormat",
",",
"Category",
",",
"DiagnosticSeverity",
".",
"Warning",
",",
"AnalyzerConstants",
".",
"DisabledNoTests",
",",
"Description",
",",
"HelpLink",
")",
";",
"private",
"static",
"readonly",
"ImmutableArray",
"<",
"DiagnosticDescriptor",
">",
"_supportedDiagnostics",
"=",
"ImmutableArray",
".",
"Create",
"(",
"Descriptor",
")",
";",
"public",
"override",
"ImmutableArray",
"<",
"DiagnosticDescriptor",
">",
"SupportedDiagnostics",
"{",
"get",
"{",
"return",
"_supportedDiagnostics",
";",
"}",
"}",
"public",
"override",
"void",
"Initialize",
"(",
"AnalysisContext",
"context",
")",
"{",
"context",
".",
"RegisterSyntaxTreeAction",
"(",
"HandleSyntaxTree",
")",
";",
"}",
"private",
"void",
"HandleSyntaxTree",
"(",
"SyntaxTreeAnalysisContext",
"context",
")",
"{",
"SyntaxNode",
"root",
"=",
"context",
".",
"Tree",
".",
"GetCompilationUnitRoot",
"(",
"context",
".",
"CancellationToken",
")",
";",
"foreach",
"(",
"var",
"token",
"in",
"root",
".",
"DescendantTokens",
"(",
")",
")",
"{",
"switch",
"(",
"token",
".",
"CSharpKind",
"(",
")",
")",
"{",
"case",
"SyntaxKind",
".",
"OpenBracketToken",
":",
"HandleOpenBracketToken",
"(",
"context",
",",
"token",
")",
";",
"break",
";",
"default",
":",
"break",
";",
"}",
"}",
"}",
"private",
"void",
"HandleOpenBracketToken",
"(",
"SyntaxTreeAnalysisContext",
"context",
",",
"SyntaxToken",
"token",
")",
"{",
"if",
"(",
"token",
".",
"IsMissing",
")",
"return",
";",
"if",
"(",
"!",
"token",
".",
"Parent",
".",
"IsKind",
"(",
"SyntaxKind",
".",
"AttributeList",
")",
")",
"return",
";",
"if",
"(",
"!",
"token",
".",
"HasTrailingTrivia",
"||",
"token",
".",
"TrailingTrivia",
".",
"Any",
"(",
"SyntaxKind",
".",
"EndOfLineTrivia",
")",
")",
"return",
";",
"context",
".",
"ReportDiagnostic",
"(",
"Diagnostic",
".",
"Create",
"(",
"Descriptor",
",",
"token",
".",
"GetLocation",
"(",
")",
")",
")",
";",
"}",
"}"
] |
An opening attribute bracket within a C# element is not spaced correctly.
|
[
"An",
"opening",
"attribute",
"bracket",
"within",
"a",
"C#",
"element",
"is",
"not",
"spaced",
"correctly",
"."
] |
[
"/// <inheritdoc/>",
"/// <inheritdoc/>",
"// Opening attribute brackets must not be followed by a space."
] |
[
{
"param": "DiagnosticAnalyzer",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "DiagnosticAnalyzer",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": [
{
"identifier": "remarks",
"docstring": "A violation of this rule occurs when the spacing around an opening attribute bracket is not\ncorrect.An opening attribute bracket should never be followed by whitespace, unless the bracket is the last\ncharacter on the line.",
"docstring_tokens": [
"A",
"violation",
"of",
"this",
"rule",
"occurs",
"when",
"the",
"spacing",
"around",
"an",
"opening",
"attribute",
"bracket",
"is",
"not",
"correct",
".",
"An",
"opening",
"attribute",
"bracket",
"should",
"never",
"be",
"followed",
"by",
"whitespace",
"unless",
"the",
"bracket",
"is",
"the",
"last",
"character",
"on",
"the",
"line",
"."
]
}
]
}
| false
| 14
| 426
| 86
|
c31f757840235e974e0f07c434ec47ebf39f2647
|
Siyy/SharpDX-Samples
|
Desktop/MediaFoundation/MediaEngineAppVideo/Program.cs
|
[
"MIT"
] |
C#
|
Program
|
/// <summary>
/// Demonstrates simple usage of MediaEngine on Windows by playing a video and audio selected by a file dialog.
/// Note that this sample is not "Dispose" safe and is not releasing any COM resources.
/// Also please note that this sample might not work on NVidia Cards (due to video engine broken on many drivers),
/// This has been tested and working on Intel and ATI.
/// </summary>
|
Demonstrates simple usage of MediaEngine on Windows by playing a video and audio selected by a file dialog.
Note that this sample is not "Dispose" safe and is not releasing any COM resources.
Also please note that this sample might not work on NVidia Cards (due to video engine broken on many drivers),
This has been tested and working on Intel and ATI.
|
[
"Demonstrates",
"simple",
"usage",
"of",
"MediaEngine",
"on",
"Windows",
"by",
"playing",
"a",
"video",
"and",
"audio",
"selected",
"by",
"a",
"file",
"dialog",
".",
"Note",
"that",
"this",
"sample",
"is",
"not",
"\"",
"Dispose",
"\"",
"safe",
"and",
"is",
"not",
"releasing",
"any",
"COM",
"resources",
".",
"Also",
"please",
"note",
"that",
"this",
"sample",
"might",
"not",
"work",
"on",
"NVidia",
"Cards",
"(",
"due",
"to",
"video",
"engine",
"broken",
"on",
"many",
"drivers",
")",
"This",
"has",
"been",
"tested",
"and",
"working",
"on",
"Intel",
"and",
"ATI",
"."
] |
class Program
{
private static readonly ManualResetEvent eventReadyToPlay = new ManualResetEvent(false);
private static bool isMusicStopped;
private static MediaEngineEx mediaEngineEx;
private static DXDevice device;
private static SwapChain swapChain;
private static DXGIDeviceManager dxgiManager;
[STAThread]
static void Main(string[] args)
{
var openFileDialog = new OpenFileDialog { Title = "Select a file", Filter = "Media Files(*.WMV;*.MP4;*.AVI)|*.WMV;*.MP4;*.AVI" };
var result = openFileDialog.ShowDialog();
if (result == DialogResult.Cancel)
{
return;
}
MediaManager.Startup();
var renderForm = new SharpDX.Windows.RenderForm();
device = CreateDeviceForVideo(out dxgiManager);
var mediaEngineFactory = new MediaEngineClassFactory();
MediaEngineAttributes attr = new MediaEngineAttributes();
attr.VideoOutputFormat = (int)SharpDX.DXGI.Format.B8G8R8A8_UNorm;
attr.DxgiManager = dxgiManager;
var mediaEngine = new MediaEngine(mediaEngineFactory, attr, MediaEngineCreateFlags.None);
mediaEngine.PlaybackEvent += OnPlaybackCallback;
mediaEngineEx = mediaEngine.QueryInterface<MediaEngineEx>();
var fileStream = openFileDialog.OpenFile();
var stream = new ByteStream(fileStream);
var url = new Uri(openFileDialog.FileName, UriKind.RelativeOrAbsolute);
mediaEngineEx.SetSourceFromByteStream(stream, url.AbsoluteUri);
if (!eventReadyToPlay.WaitOne(1000))
{
Console.WriteLine("Unexpected error: Unable to play this file");
}
swapChain = CreateSwapChain(device, renderForm.Handle);
var texture = Texture2D.FromSwapChain<Texture2D>(swapChain, 0);
var surface = texture.QueryInterface<SharpDX.DXGI.Surface>();
int w, h;
mediaEngine.GetNativeVideoSize(out w, out h);
mediaEngineEx.Play();
long ts;
RenderLoop.Run(renderForm, () =>
{
if (mediaEngine.OnVideoStreamTick(out ts))
{
mediaEngine.TransferVideoFrame(surface, null, new SharpDX.Rectangle(0, 0, w, h), null);
}
swapChain.Present(1, SharpDX.DXGI.PresentFlags.None);
});
mediaEngine.Shutdown();
swapChain.Dispose();
device.Dispose();
}
private static void OnPlaybackCallback(MediaEngineEvent playEvent, long param1, int param2)
{
switch (playEvent)
{
case MediaEngineEvent.CanPlay:
eventReadyToPlay.Set();
break;
case MediaEngineEvent.TimeUpdate:
break;
case MediaEngineEvent.Error:
case MediaEngineEvent.Abort:
case MediaEngineEvent.Ended:
isMusicStopped = true;
break;
}
}
private static DXDevice CreateDeviceForVideo(out DXGIDeviceManager manager)
{
var device = new DXDevice(SharpDX.Direct3D.DriverType.Hardware, DeviceCreationFlags.BgraSupport | DeviceCreationFlags.VideoSupport);
DeviceMultithread mt = device.QueryInterface<DeviceMultithread>();
mt.SetMultithreadProtected(true);
manager = new DXGIDeviceManager();
manager.ResetDevice(device);
return device;
}
private static SwapChain CreateSwapChain(DXDevice dxdevice, IntPtr handle)
{
var dxgidevice = dxdevice.QueryInterface<SharpDX.DXGI.Device>();
var adapter = dxgidevice.Adapter.QueryInterface<Adapter>();
var factory = adapter.GetParent<Factory1>();
SwapChainDescription sd = new SwapChainDescription()
{
BufferCount = 1,
ModeDescription = new ModeDescription(0, 0, new Rational(60, 1), Format.B8G8R8A8_UNorm),
IsWindowed = true,
OutputHandle = handle,
SampleDescription = new SampleDescription(1,0),
SwapEffect = SwapEffect.Discard,
Usage = Usage.RenderTargetOutput,
Flags = SwapChainFlags.None
};
return new SwapChain(factory, dxdevice, sd);
}
}
|
[
"class",
"Program",
"{",
"private",
"static",
"readonly",
"ManualResetEvent",
"eventReadyToPlay",
"=",
"new",
"ManualResetEvent",
"(",
"false",
")",
";",
"private",
"static",
"bool",
"isMusicStopped",
";",
"private",
"static",
"MediaEngineEx",
"mediaEngineEx",
";",
"private",
"static",
"DXDevice",
"device",
";",
"private",
"static",
"SwapChain",
"swapChain",
";",
"private",
"static",
"DXGIDeviceManager",
"dxgiManager",
";",
"[",
"STAThread",
"]",
"static",
"void",
"Main",
"(",
"string",
"[",
"]",
"args",
")",
"{",
"var",
"openFileDialog",
"=",
"new",
"OpenFileDialog",
"{",
"Title",
"=",
"\"",
"Select a file",
"\"",
",",
"Filter",
"=",
"\"",
"Media Files(*.WMV;*.MP4;*.AVI)|*.WMV;*.MP4;*.AVI",
"\"",
"}",
";",
"var",
"result",
"=",
"openFileDialog",
".",
"ShowDialog",
"(",
")",
";",
"if",
"(",
"result",
"==",
"DialogResult",
".",
"Cancel",
")",
"{",
"return",
";",
"}",
"MediaManager",
".",
"Startup",
"(",
")",
";",
"var",
"renderForm",
"=",
"new",
"SharpDX",
".",
"Windows",
".",
"RenderForm",
"(",
")",
";",
"device",
"=",
"CreateDeviceForVideo",
"(",
"out",
"dxgiManager",
")",
";",
"var",
"mediaEngineFactory",
"=",
"new",
"MediaEngineClassFactory",
"(",
")",
";",
"MediaEngineAttributes",
"attr",
"=",
"new",
"MediaEngineAttributes",
"(",
")",
";",
"attr",
".",
"VideoOutputFormat",
"=",
"(",
"int",
")",
"SharpDX",
".",
"DXGI",
".",
"Format",
".",
"B8G8R8A8_UNorm",
";",
"attr",
".",
"DxgiManager",
"=",
"dxgiManager",
";",
"var",
"mediaEngine",
"=",
"new",
"MediaEngine",
"(",
"mediaEngineFactory",
",",
"attr",
",",
"MediaEngineCreateFlags",
".",
"None",
")",
";",
"mediaEngine",
".",
"PlaybackEvent",
"+=",
"OnPlaybackCallback",
";",
"mediaEngineEx",
"=",
"mediaEngine",
".",
"QueryInterface",
"<",
"MediaEngineEx",
">",
"(",
")",
";",
"var",
"fileStream",
"=",
"openFileDialog",
".",
"OpenFile",
"(",
")",
";",
"var",
"stream",
"=",
"new",
"ByteStream",
"(",
"fileStream",
")",
";",
"var",
"url",
"=",
"new",
"Uri",
"(",
"openFileDialog",
".",
"FileName",
",",
"UriKind",
".",
"RelativeOrAbsolute",
")",
";",
"mediaEngineEx",
".",
"SetSourceFromByteStream",
"(",
"stream",
",",
"url",
".",
"AbsoluteUri",
")",
";",
"if",
"(",
"!",
"eventReadyToPlay",
".",
"WaitOne",
"(",
"1000",
")",
")",
"{",
"Console",
".",
"WriteLine",
"(",
"\"",
"Unexpected error: Unable to play this file",
"\"",
")",
";",
"}",
"swapChain",
"=",
"CreateSwapChain",
"(",
"device",
",",
"renderForm",
".",
"Handle",
")",
";",
"var",
"texture",
"=",
"Texture2D",
".",
"FromSwapChain",
"<",
"Texture2D",
">",
"(",
"swapChain",
",",
"0",
")",
";",
"var",
"surface",
"=",
"texture",
".",
"QueryInterface",
"<",
"SharpDX",
".",
"DXGI",
".",
"Surface",
">",
"(",
")",
";",
"int",
"w",
",",
"h",
";",
"mediaEngine",
".",
"GetNativeVideoSize",
"(",
"out",
"w",
",",
"out",
"h",
")",
";",
"mediaEngineEx",
".",
"Play",
"(",
")",
";",
"long",
"ts",
";",
"RenderLoop",
".",
"Run",
"(",
"renderForm",
",",
"(",
")",
"=>",
"{",
"if",
"(",
"mediaEngine",
".",
"OnVideoStreamTick",
"(",
"out",
"ts",
")",
")",
"{",
"mediaEngine",
".",
"TransferVideoFrame",
"(",
"surface",
",",
"null",
",",
"new",
"SharpDX",
".",
"Rectangle",
"(",
"0",
",",
"0",
",",
"w",
",",
"h",
")",
",",
"null",
")",
";",
"}",
"swapChain",
".",
"Present",
"(",
"1",
",",
"SharpDX",
".",
"DXGI",
".",
"PresentFlags",
".",
"None",
")",
";",
"}",
")",
";",
"mediaEngine",
".",
"Shutdown",
"(",
")",
";",
"swapChain",
".",
"Dispose",
"(",
")",
";",
"device",
".",
"Dispose",
"(",
")",
";",
"}",
"private",
"static",
"void",
"OnPlaybackCallback",
"(",
"MediaEngineEvent",
"playEvent",
",",
"long",
"param1",
",",
"int",
"param2",
")",
"{",
"switch",
"(",
"playEvent",
")",
"{",
"case",
"MediaEngineEvent",
".",
"CanPlay",
":",
"eventReadyToPlay",
".",
"Set",
"(",
")",
";",
"break",
";",
"case",
"MediaEngineEvent",
".",
"TimeUpdate",
":",
"break",
";",
"case",
"MediaEngineEvent",
".",
"Error",
":",
"case",
"MediaEngineEvent",
".",
"Abort",
":",
"case",
"MediaEngineEvent",
".",
"Ended",
":",
"isMusicStopped",
"=",
"true",
";",
"break",
";",
"}",
"}",
"private",
"static",
"DXDevice",
"CreateDeviceForVideo",
"(",
"out",
"DXGIDeviceManager",
"manager",
")",
"{",
"var",
"device",
"=",
"new",
"DXDevice",
"(",
"SharpDX",
".",
"Direct3D",
".",
"DriverType",
".",
"Hardware",
",",
"DeviceCreationFlags",
".",
"BgraSupport",
"|",
"DeviceCreationFlags",
".",
"VideoSupport",
")",
";",
"DeviceMultithread",
"mt",
"=",
"device",
".",
"QueryInterface",
"<",
"DeviceMultithread",
">",
"(",
")",
";",
"mt",
".",
"SetMultithreadProtected",
"(",
"true",
")",
";",
"manager",
"=",
"new",
"DXGIDeviceManager",
"(",
")",
";",
"manager",
".",
"ResetDevice",
"(",
"device",
")",
";",
"return",
"device",
";",
"}",
"private",
"static",
"SwapChain",
"CreateSwapChain",
"(",
"DXDevice",
"dxdevice",
",",
"IntPtr",
"handle",
")",
"{",
"var",
"dxgidevice",
"=",
"dxdevice",
".",
"QueryInterface",
"<",
"SharpDX",
".",
"DXGI",
".",
"Device",
">",
"(",
")",
";",
"var",
"adapter",
"=",
"dxgidevice",
".",
"Adapter",
".",
"QueryInterface",
"<",
"Adapter",
">",
"(",
")",
";",
"var",
"factory",
"=",
"adapter",
".",
"GetParent",
"<",
"Factory1",
">",
"(",
")",
";",
"SwapChainDescription",
"sd",
"=",
"new",
"SwapChainDescription",
"(",
")",
"{",
"BufferCount",
"=",
"1",
",",
"ModeDescription",
"=",
"new",
"ModeDescription",
"(",
"0",
",",
"0",
",",
"new",
"Rational",
"(",
"60",
",",
"1",
")",
",",
"Format",
".",
"B8G8R8A8_UNorm",
")",
",",
"IsWindowed",
"=",
"true",
",",
"OutputHandle",
"=",
"handle",
",",
"SampleDescription",
"=",
"new",
"SampleDescription",
"(",
"1",
",",
"0",
")",
",",
"SwapEffect",
"=",
"SwapEffect",
".",
"Discard",
",",
"Usage",
"=",
"Usage",
".",
"RenderTargetOutput",
",",
"Flags",
"=",
"SwapChainFlags",
".",
"None",
"}",
";",
"return",
"new",
"SwapChain",
"(",
"factory",
",",
"dxdevice",
",",
"sd",
")",
";",
"}",
"}"
] |
Demonstrates simple usage of MediaEngine on Windows by playing a video and audio selected by a file dialog.
|
[
"Demonstrates",
"simple",
"usage",
"of",
"MediaEngine",
"on",
"Windows",
"by",
"playing",
"a",
"video",
"and",
"audio",
"selected",
"by",
"a",
"file",
"dialog",
"."
] |
[
"/// <summary>",
"/// The event raised when MediaEngine is ready to play the music.",
"/// </summary>",
"/// <summary>",
"/// Set when the music is stopped.",
"/// </summary>",
"/// <summary>",
"/// The instance of MediaEngineEx",
"/// </summary>",
"/// <summary>",
"/// Our dx11 device",
"/// </summary>",
"/// <summary>",
"/// Our SwapChain",
"/// </summary>",
"/// <summary>",
"/// DXGI Manager",
"/// </summary>",
"/// <summary>",
"/// Defines the entry point of the application.",
"/// </summary>",
"/// <param name=\"args\">The args.</param>",
"// Select a File to play",
"// Initialize MediaFoundation",
"// Creates the MediaEngineClassFactory",
"//Assign our dxgi manager, and set format to bgra",
"// Creates MediaEngine for AudioOnly ",
"// Register our PlayBackEvent",
"// Query for MediaEngineEx interface",
"// Opens the file",
"// Create a ByteStream object from it",
"// Creates an URL to the file",
"// Set the source stream",
"// Wait for MediaEngine to be ready",
"//Create our swapchain",
"//Get DXGI surface to be used by our media engine",
"//Get our video size",
"// Play the music",
"//Transfer frame if a new one is available",
"/// <summary>",
"/// Called when [playback callback].",
"/// </summary>",
"/// <param name=\"playEvent\">The play event.</param>",
"/// <param name=\"param1\">The param1.</param>",
"/// <param name=\"param2\">The param2.</param>",
"/// <summary>",
"/// Creates device with necessary flags for video processing",
"/// </summary>",
"/// <param name=\"manager\">DXGI Manager, used to create media engine</param>",
"/// <returns>Device with video support</returns>",
"//Device need bgra and video support",
"//Add multi thread protection on device",
"//Reset device",
"/// <summary>",
"/// Creates swap chain ready to use for video output",
"/// </summary>",
"/// <param name=\"dxdevice\">DirectX11 device</param>",
"/// <param name=\"handle\">RenderForm Handle</param>",
"/// <returns>SwapChain</returns>",
"//Walk up device to retrieve Factory, necessary to create SwapChain",
"/*To be allowed to be used as video, texture must be of the same format (eg: bgra), and needs to be bindable are render target.\n * you do not need to create render target view, only the flag*/"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 20
| 914
| 85
|
15008a4ef83709f4ef7bd55a3c690ca0432054e8
|
davidor/protocol-redis
|
lib/protocol/redis/methods/server.rb
|
[
"Unlicense",
"MIT"
] |
Ruby
|
Protocol
|
# Copyright, 2018, by Samuel G. D. Williams. <http://www.codeotaku.com>
# Copyright, 2018, by Huba Nagy.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
|
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions.
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
|
[
"Permission",
"is",
"hereby",
"granted",
"free",
"of",
"charge",
"to",
"any",
"person",
"obtaining",
"a",
"copy",
"of",
"this",
"software",
"and",
"associated",
"documentation",
"files",
"(",
"the",
"\"",
"Software",
"\"",
")",
"to",
"deal",
"in",
"the",
"Software",
"without",
"restriction",
"including",
"without",
"limitation",
"the",
"rights",
"to",
"use",
"copy",
"modify",
"merge",
"publish",
"distribute",
"sublicense",
"and",
"/",
"or",
"sell",
"copies",
"of",
"the",
"Software",
"and",
"to",
"permit",
"persons",
"to",
"whom",
"the",
"Software",
"is",
"furnished",
"to",
"do",
"so",
"subject",
"to",
"the",
"following",
"conditions",
".",
"The",
"above",
"copyright",
"notice",
"and",
"this",
"permission",
"notice",
"shall",
"be",
"included",
"in",
"all",
"copies",
"or",
"substantial",
"portions",
"of",
"the",
"Software",
"."
] |
module Protocol
module Redis
module Methods
module Server
# Get information and statistics about the server.
# @see https://redis.io/commands/info
# @param section [String]
def info
metadata = {}
call('INFO').each_line(Redis::Connection::CRLF) do |line|
key, value = line.split(':')
if value
metadata[key.to_sym] = value.chomp!
end
end
return metadata
end
# Remove all keys from the current database.
# @see https://redis.io/commands/flushdb
# @param async [Enum]
def flushdb!
call('FLUSHDB')
end
end
end
end
end
|
[
"module",
"Protocol",
"module",
"Redis",
"module",
"Methods",
"module",
"Server",
"def",
"info",
"metadata",
"=",
"{",
"}",
"call",
"(",
"'INFO'",
")",
".",
"each_line",
"(",
"Redis",
"::",
"Connection",
"::",
"CRLF",
")",
"do",
"|",
"line",
"|",
"key",
",",
"value",
"=",
"line",
".",
"split",
"(",
"':'",
")",
"if",
"value",
"metadata",
"[",
"key",
".",
"to_sym",
"]",
"=",
"value",
".",
"chomp!",
"end",
"end",
"return",
"metadata",
"end",
"def",
"flushdb!",
"call",
"(",
"'FLUSHDB'",
")",
"end",
"end",
"end",
"end",
"end"
] |
Copyright, 2018, by Samuel G. D. Williams.
|
[
"Copyright",
"2018",
"by",
"Samuel",
"G",
".",
"D",
".",
"Williams",
"."
] |
[
"# Get information and statistics about the server.",
"# @see https://redis.io/commands/info",
"# @param section [String]",
"# Remove all keys from the current database.",
"# @see https://redis.io/commands/flushdb",
"# @param async [Enum]"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 19
| 174
| 264
|
8b4d66ae49342b005ff06d4355e62da8c24c48ca
|
nagalakshmichitta520/gitlabhq
|
app/workers/process_commit_worker.rb
|
[
"MIT"
] |
Ruby
|
ProcessCommitWorker
|
# Worker for processing individual commit messages pushed to a repository.
#
# Jobs for this worker are scheduled for every commit that contains mentionable
# references in its message and does not exist in the upstream project. As a
# result of this the workload of this worker should be kept to a bare minimum.
# Consider using an extra worker if you need to add any extra (and potentially
# slow) processing of commits.
|
Worker for processing individual commit messages pushed to a repository.
Jobs for this worker are scheduled for every commit that contains mentionable
references in its message and does not exist in the upstream project. As a
result of this the workload of this worker should be kept to a bare minimum.
Consider using an extra worker if you need to add any extra (and potentially
slow) processing of commits.
|
[
"Worker",
"for",
"processing",
"individual",
"commit",
"messages",
"pushed",
"to",
"a",
"repository",
".",
"Jobs",
"for",
"this",
"worker",
"are",
"scheduled",
"for",
"every",
"commit",
"that",
"contains",
"mentionable",
"references",
"in",
"its",
"message",
"and",
"does",
"not",
"exist",
"in",
"the",
"upstream",
"project",
".",
"As",
"a",
"result",
"of",
"this",
"the",
"workload",
"of",
"this",
"worker",
"should",
"be",
"kept",
"to",
"a",
"bare",
"minimum",
".",
"Consider",
"using",
"an",
"extra",
"worker",
"if",
"you",
"need",
"to",
"add",
"any",
"extra",
"(",
"and",
"potentially",
"slow",
")",
"processing",
"of",
"commits",
"."
] |
class ProcessCommitWorker
include ApplicationWorker
feature_category :source_code_management
latency_sensitive_worker!
# project_id - The ID of the project this commit belongs to.
# user_id - The ID of the user that pushed the commit.
# commit_hash - Hash containing commit details to use for constructing a
# Commit object without having to use the Git repository.
# default - The data was pushed to the default branch.
# rubocop: disable CodeReuse/ActiveRecord
def perform(project_id, user_id, commit_hash, default = false)
project = Project.find_by(id: project_id)
return unless project
user = User.find_by(id: user_id)
return unless user
commit = build_commit(project, commit_hash)
author = commit.author || user
process_commit_message(project, commit, user, author, default)
update_issue_metrics(commit, author)
end
# rubocop: enable CodeReuse/ActiveRecord
def process_commit_message(project, commit, user, author, default = false)
# Ignore closing references from GitLab-generated commit messages.
find_closing_issues = default && !commit.merged_merge_request?(user)
closed_issues = find_closing_issues ? commit.closes_issues(user) : []
close_issues(project, user, author, commit, closed_issues) if closed_issues.any?
commit.create_cross_references!(author, closed_issues)
end
def close_issues(project, user, author, commit, issues)
# We don't want to run permission related queries for every single issue,
# therefore we use IssueCollection here and skip the authorization check in
# Issues::CloseService#execute.
IssueCollection.new(issues).updatable_by_user(user).each do |issue|
Issues::CloseService.new(project, author)
.close_issue(issue, closed_via: commit)
end
end
# rubocop: disable CodeReuse/ActiveRecord
def update_issue_metrics(commit, author)
mentioned_issues = commit.all_references(author).issues
return if mentioned_issues.empty?
Issue::Metrics.where(issue_id: mentioned_issues.map(&:id), first_mentioned_in_commit_at: nil)
.update_all(first_mentioned_in_commit_at: commit.committed_date)
end
# rubocop: enable CodeReuse/ActiveRecord
def build_commit(project, hash)
date_suffix = '_date'
# When processing Sidekiq payloads various timestamps are stored as Strings.
# Commit in turn expects Time-like instances upon input, so we have to
# manually parse these values.
hash.each do |key, value|
if key.to_s.end_with?(date_suffix) && value.is_a?(String)
hash[key] = Time.parse(value)
end
end
Commit.from_hash(hash, project)
end
end
|
[
"class",
"ProcessCommitWorker",
"include",
"ApplicationWorker",
"feature_category",
":source_code_management",
"latency_sensitive_worker!",
"def",
"perform",
"(",
"project_id",
",",
"user_id",
",",
"commit_hash",
",",
"default",
"=",
"false",
")",
"project",
"=",
"Project",
".",
"find_by",
"(",
"id",
":",
"project_id",
")",
"return",
"unless",
"project",
"user",
"=",
"User",
".",
"find_by",
"(",
"id",
":",
"user_id",
")",
"return",
"unless",
"user",
"commit",
"=",
"build_commit",
"(",
"project",
",",
"commit_hash",
")",
"author",
"=",
"commit",
".",
"author",
"||",
"user",
"process_commit_message",
"(",
"project",
",",
"commit",
",",
"user",
",",
"author",
",",
"default",
")",
"update_issue_metrics",
"(",
"commit",
",",
"author",
")",
"end",
"def",
"process_commit_message",
"(",
"project",
",",
"commit",
",",
"user",
",",
"author",
",",
"default",
"=",
"false",
")",
"find_closing_issues",
"=",
"default",
"&&",
"!",
"commit",
".",
"merged_merge_request?",
"(",
"user",
")",
"closed_issues",
"=",
"find_closing_issues",
"?",
"commit",
".",
"closes_issues",
"(",
"user",
")",
":",
"[",
"]",
"close_issues",
"(",
"project",
",",
"user",
",",
"author",
",",
"commit",
",",
"closed_issues",
")",
"if",
"closed_issues",
".",
"any?",
"commit",
".",
"create_cross_references!",
"(",
"author",
",",
"closed_issues",
")",
"end",
"def",
"close_issues",
"(",
"project",
",",
"user",
",",
"author",
",",
"commit",
",",
"issues",
")",
"IssueCollection",
".",
"new",
"(",
"issues",
")",
".",
"updatable_by_user",
"(",
"user",
")",
".",
"each",
"do",
"|",
"issue",
"|",
"Issues",
"::",
"CloseService",
".",
"new",
"(",
"project",
",",
"author",
")",
".",
"close_issue",
"(",
"issue",
",",
"closed_via",
":",
"commit",
")",
"end",
"end",
"def",
"update_issue_metrics",
"(",
"commit",
",",
"author",
")",
"mentioned_issues",
"=",
"commit",
".",
"all_references",
"(",
"author",
")",
".",
"issues",
"return",
"if",
"mentioned_issues",
".",
"empty?",
"Issue",
"::",
"Metrics",
".",
"where",
"(",
"issue_id",
":",
"mentioned_issues",
".",
"map",
"(",
"&",
":id",
")",
",",
"first_mentioned_in_commit_at",
":",
"nil",
")",
".",
"update_all",
"(",
"first_mentioned_in_commit_at",
":",
"commit",
".",
"committed_date",
")",
"end",
"def",
"build_commit",
"(",
"project",
",",
"hash",
")",
"date_suffix",
"=",
"'_date'",
"hash",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"if",
"key",
".",
"to_s",
".",
"end_with?",
"(",
"date_suffix",
")",
"&&",
"value",
".",
"is_a?",
"(",
"String",
")",
"hash",
"[",
"key",
"]",
"=",
"Time",
".",
"parse",
"(",
"value",
")",
"end",
"end",
"Commit",
".",
"from_hash",
"(",
"hash",
",",
"project",
")",
"end",
"end"
] |
Worker for processing individual commit messages pushed to a repository.
|
[
"Worker",
"for",
"processing",
"individual",
"commit",
"messages",
"pushed",
"to",
"a",
"repository",
"."
] |
[
"# project_id - The ID of the project this commit belongs to.",
"# user_id - The ID of the user that pushed the commit.",
"# commit_hash - Hash containing commit details to use for constructing a",
"# Commit object without having to use the Git repository.",
"# default - The data was pushed to the default branch.",
"# rubocop: disable CodeReuse/ActiveRecord",
"# rubocop: enable CodeReuse/ActiveRecord",
"# Ignore closing references from GitLab-generated commit messages.",
"# We don't want to run permission related queries for every single issue,",
"# therefore we use IssueCollection here and skip the authorization check in",
"# Issues::CloseService#execute.",
"# rubocop: disable CodeReuse/ActiveRecord",
"# rubocop: enable CodeReuse/ActiveRecord",
"# When processing Sidekiq payloads various timestamps are stored as Strings.",
"# Commit in turn expects Time-like instances upon input, so we have to",
"# manually parse these values."
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 13
| 605
| 86
|
139542b732bd26073f7938920f79b9d63ef6b243
|
AaronC81/ruby_jard_compat
|
lib/ruby_jard/box_drawer.rb
|
[
"MIT"
] |
Ruby
|
BoxDrawer
|
##
# Drawer to draw a nice single-line box that maximize screen area
#
# Each screen has 4 corners and clock-wise corresponding ID:
# - Top-left => 1
# - Top-right => 2
# - Bottom-right => 3
# - Bottom-left => 4
#
# For each screen, add each point to a coordinator hash.
# - If a point is occupied by 1 screen, draw normal box corner symbol.
# - If a point is occupied by 2 screens, look up in a map, and draw corresponding intersection corner symbol.
# - If a point is occupied by 3 or more screens, it's definitely a + symbol.
#
# The corner list at each point (x, y) is unique. If 2 screens overlap a point with same corner ID, it means
# 2 screens overlap, and have same corner symbol.
|
For each screen, add each point to a coordinator hash.
If a point is occupied by 1 screen, draw normal box corner symbol.
If a point is occupied by 2 screens, look up in a map, and draw corresponding intersection corner symbol.
If a point is occupied by 3 or more screens, it's definitely a + symbol.
The corner list at each point (x, y) is unique. If 2 screens overlap a point with same corner ID, it means
2 screens overlap, and have same corner symbol.
|
[
"For",
"each",
"screen",
"add",
"each",
"point",
"to",
"a",
"coordinator",
"hash",
".",
"If",
"a",
"point",
"is",
"occupied",
"by",
"1",
"screen",
"draw",
"normal",
"box",
"corner",
"symbol",
".",
"If",
"a",
"point",
"is",
"occupied",
"by",
"2",
"screens",
"look",
"up",
"in",
"a",
"map",
"and",
"draw",
"corresponding",
"intersection",
"corner",
"symbol",
".",
"If",
"a",
"point",
"is",
"occupied",
"by",
"3",
"or",
"more",
"screens",
"it",
"'",
"s",
"definitely",
"a",
"+",
"symbol",
".",
"The",
"corner",
"list",
"at",
"each",
"point",
"(",
"x",
"y",
")",
"is",
"unique",
".",
"If",
"2",
"screens",
"overlap",
"a",
"point",
"with",
"same",
"corner",
"ID",
"it",
"means",
"2",
"screens",
"overlap",
"and",
"have",
"same",
"corner",
"symbol",
"."
] |
class BoxDrawer
CORNERS = [
TOP_LEFT = 1,
TOP_RIGHT = 2,
BOTTOM_RIGHT = 3,
BOTTOM_LEFT = 4
].freeze
HORIZONTAL_LINE = '─'
VERTICAL_LINE = '│'
CROSS_CORNER = '┼'
NORMALS_CORNERS = {
TOP_LEFT => '┌',
TOP_RIGHT => '┐',
BOTTOM_RIGHT => '┘',
BOTTOM_LEFT => '└'
}.freeze
OVERLAPPED_CORNERS = {
[TOP_LEFT, TOP_RIGHT] => '┬',
[TOP_LEFT, BOTTOM_RIGHT] => '┼',
[TOP_LEFT, BOTTOM_LEFT] => '├',
[TOP_RIGHT, BOTTOM_RIGHT] => '┤',
[TOP_RIGHT, BOTTOM_LEFT] => '┼',
[BOTTOM_RIGHT, BOTTOM_LEFT] => '┴'
}.freeze
def initialize(console:, screens:, color_scheme:)
@console = console
@screens = screens
@color_decorator = RubyJard::Decorators::ColorDecorator.new(color_scheme)
end
def draw
draw_basic_lines
corners = calculate_corners
draw_corners(corners)
draw_titles
end
private
def draw_basic_lines
# Exclude the corners
@screens.each do |screen|
@console.move_to(screen.layout.box_x + 1, screen.layout.box_y)
@console.print colorize_border(HORIZONTAL_LINE * (screen.layout.box_width - 2))
@console.move_to(screen.layout.box_x + 1, screen.layout.box_y + screen.layout.box_height - 1)
@console.print colorize_border(HORIZONTAL_LINE * (screen.layout.box_width - 2))
(screen.layout.box_y + 1..screen.layout.box_y + screen.layout.box_height - 2).each do |moving_y|
@console.move_to(screen.layout.box_x, moving_y)
@console.print colorize_border(VERTICAL_LINE)
@console.move_to(screen.layout.box_x + screen.layout.box_width - 1, moving_y)
@console.print colorize_border(VERTICAL_LINE)
end
end
end
def draw_corners(corners)
corners.each do |x, corners_x|
corners_x.each do |y, ids|
@console.move_to(x, y)
case ids.length
when 1
@console.print colorize_border(NORMALS_CORNERS[ids.first])
when 2
ids = ids.sort
@console.print colorize_border(OVERLAPPED_CORNERS[ids])
else
@console.print colorize_border(CROSS_CORNER)
end
end
end
end
def draw_titles
@screens.each do |screen|
next unless screen.respond_to?(:title)
@console.move_to(screen.layout.box_x + 1, screen.layout.box_y)
total_length = 0
title_parts = Array(screen.title)
title_parts.each_with_index do |title_part, index|
break if total_length >= screen.layout.box_width
title_part = title_part[0..screen.layout.box_width - total_length - 2 - 1 - 2]
if index == 0
@console.print @color_decorator.decorate(:title, " #{title_part} ")
else
@console.print @color_decorator.decorate(:title_secondary, " #{title_part} ")
end
total_length += title_part.length + 2
end
title_background = screen.layout.box_width - total_length - 2
@console.print @color_decorator.decorate(
:title_background,
HORIZONTAL_LINE * (title_background < 0 ? 0 : title_background)
)
end
end
def calculate_corners
corners = {}
@screens.each do |screen|
mark_corner(
corners,
screen.layout.box_x,
screen.layout.box_y,
TOP_LEFT
)
mark_corner(
corners,
screen.layout.box_x + screen.layout.box_width - 1,
screen.layout.box_y,
TOP_RIGHT
)
mark_corner(
corners,
screen.layout.box_x + screen.layout.box_width - 1,
screen.layout.box_y + screen.layout.box_height - 1,
BOTTOM_RIGHT
)
mark_corner(
corners,
screen.layout.box_x,
screen.layout.box_y + screen.layout.box_height - 1,
BOTTOM_LEFT
)
end
corners
end
def mark_corner(corners, x, y, id)
corners[x] ||= {}
corners[x][y] ||= []
corners[x][y] << id unless corners[x][y].include?(id)
end
def colorize_border(content)
@color_decorator.decorate(:border, content)
end
end
|
[
"class",
"BoxDrawer",
"CORNERS",
"=",
"[",
"TOP_LEFT",
"=",
"1",
",",
"TOP_RIGHT",
"=",
"2",
",",
"BOTTOM_RIGHT",
"=",
"3",
",",
"BOTTOM_LEFT",
"=",
"4",
"]",
".",
"freeze",
"HORIZONTAL_LINE",
"=",
"'─'",
"VERTICAL_LINE",
"=",
"'│'",
"CROSS_CORNER",
"=",
"'┼'",
"NORMALS_CORNERS",
"=",
"{",
"TOP_LEFT",
"=>",
"'┌',",
"",
"TOP_RIGHT",
"=>",
"'┐',",
"",
"BOTTOM_RIGHT",
"=>",
"'┘',",
"",
"BOTTOM_LEFT",
"=>",
"'└'",
"}",
".",
"freeze",
"OVERLAPPED_CORNERS",
"=",
"{",
"[",
"TOP_LEFT",
",",
"TOP_RIGHT",
"]",
"=>",
"'┬',",
"",
"[",
"TOP_LEFT",
",",
"BOTTOM_RIGHT",
"]",
"=>",
"'┼',",
"",
"[",
"TOP_LEFT",
",",
"BOTTOM_LEFT",
"]",
"=>",
"'├',",
"",
"[",
"TOP_RIGHT",
",",
"BOTTOM_RIGHT",
"]",
"=>",
"'┤',",
"",
"[",
"TOP_RIGHT",
",",
"BOTTOM_LEFT",
"]",
"=>",
"'┼',",
"",
"[",
"BOTTOM_RIGHT",
",",
"BOTTOM_LEFT",
"]",
"=>",
"'┴'",
"}",
".",
"freeze",
"def",
"initialize",
"(",
"console",
":",
",",
"screens",
":",
",",
"color_scheme",
":",
")",
"@console",
"=",
"console",
"@screens",
"=",
"screens",
"@color_decorator",
"=",
"RubyJard",
"::",
"Decorators",
"::",
"ColorDecorator",
".",
"new",
"(",
"color_scheme",
")",
"end",
"def",
"draw",
"draw_basic_lines",
"corners",
"=",
"calculate_corners",
"draw_corners",
"(",
"corners",
")",
"draw_titles",
"end",
"private",
"def",
"draw_basic_lines",
"@screens",
".",
"each",
"do",
"|",
"screen",
"|",
"@console",
".",
"move_to",
"(",
"screen",
".",
"layout",
".",
"box_x",
"+",
"1",
",",
"screen",
".",
"layout",
".",
"box_y",
")",
"@console",
".",
"print",
"colorize_border",
"(",
"HORIZONTAL_LINE",
"*",
"(",
"screen",
".",
"layout",
".",
"box_width",
"-",
"2",
")",
")",
"@console",
".",
"move_to",
"(",
"screen",
".",
"layout",
".",
"box_x",
"+",
"1",
",",
"screen",
".",
"layout",
".",
"box_y",
"+",
"screen",
".",
"layout",
".",
"box_height",
"-",
"1",
")",
"@console",
".",
"print",
"colorize_border",
"(",
"HORIZONTAL_LINE",
"*",
"(",
"screen",
".",
"layout",
".",
"box_width",
"-",
"2",
")",
")",
"(",
"screen",
".",
"layout",
".",
"box_y",
"+",
"1",
"..",
"screen",
".",
"layout",
".",
"box_y",
"+",
"screen",
".",
"layout",
".",
"box_height",
"-",
"2",
")",
".",
"each",
"do",
"|",
"moving_y",
"|",
"@console",
".",
"move_to",
"(",
"screen",
".",
"layout",
".",
"box_x",
",",
"moving_y",
")",
"@console",
".",
"print",
"colorize_border",
"(",
"VERTICAL_LINE",
")",
"@console",
".",
"move_to",
"(",
"screen",
".",
"layout",
".",
"box_x",
"+",
"screen",
".",
"layout",
".",
"box_width",
"-",
"1",
",",
"moving_y",
")",
"@console",
".",
"print",
"colorize_border",
"(",
"VERTICAL_LINE",
")",
"end",
"end",
"end",
"def",
"draw_corners",
"(",
"corners",
")",
"corners",
".",
"each",
"do",
"|",
"x",
",",
"corners_x",
"|",
"corners_x",
".",
"each",
"do",
"|",
"y",
",",
"ids",
"|",
"@console",
".",
"move_to",
"(",
"x",
",",
"y",
")",
"case",
"ids",
".",
"length",
"when",
"1",
"@console",
".",
"print",
"colorize_border",
"(",
"NORMALS_CORNERS",
"[",
"ids",
".",
"first",
"]",
")",
"when",
"2",
"ids",
"=",
"ids",
".",
"sort",
"@console",
".",
"print",
"colorize_border",
"(",
"OVERLAPPED_CORNERS",
"[",
"ids",
"]",
")",
"else",
"@console",
".",
"print",
"colorize_border",
"(",
"CROSS_CORNER",
")",
"end",
"end",
"end",
"end",
"def",
"draw_titles",
"@screens",
".",
"each",
"do",
"|",
"screen",
"|",
"next",
"unless",
"screen",
".",
"respond_to?",
"(",
":title",
")",
"@console",
".",
"move_to",
"(",
"screen",
".",
"layout",
".",
"box_x",
"+",
"1",
",",
"screen",
".",
"layout",
".",
"box_y",
")",
"total_length",
"=",
"0",
"title_parts",
"=",
"Array",
"(",
"screen",
".",
"title",
")",
"title_parts",
".",
"each_with_index",
"do",
"|",
"title_part",
",",
"index",
"|",
"break",
"if",
"total_length",
">=",
"screen",
".",
"layout",
".",
"box_width",
"title_part",
"=",
"title_part",
"[",
"0",
"..",
"screen",
".",
"layout",
".",
"box_width",
"-",
"total_length",
"-",
"2",
"-",
"1",
"-",
"2",
"]",
"if",
"index",
"==",
"0",
"@console",
".",
"print",
"@color_decorator",
".",
"decorate",
"(",
":title",
",",
"\" #{title_part} \"",
")",
"else",
"@console",
".",
"print",
"@color_decorator",
".",
"decorate",
"(",
":title_secondary",
",",
"\" #{title_part} \"",
")",
"end",
"total_length",
"+=",
"title_part",
".",
"length",
"+",
"2",
"end",
"title_background",
"=",
"screen",
".",
"layout",
".",
"box_width",
"-",
"total_length",
"-",
"2",
"@console",
".",
"print",
"@color_decorator",
".",
"decorate",
"(",
":title_background",
",",
"HORIZONTAL_LINE",
"*",
"(",
"title_background",
"<",
"0",
"?",
"0",
":",
"title_background",
")",
")",
"end",
"end",
"def",
"calculate_corners",
"corners",
"=",
"{",
"}",
"@screens",
".",
"each",
"do",
"|",
"screen",
"|",
"mark_corner",
"(",
"corners",
",",
"screen",
".",
"layout",
".",
"box_x",
",",
"screen",
".",
"layout",
".",
"box_y",
",",
"TOP_LEFT",
")",
"mark_corner",
"(",
"corners",
",",
"screen",
".",
"layout",
".",
"box_x",
"+",
"screen",
".",
"layout",
".",
"box_width",
"-",
"1",
",",
"screen",
".",
"layout",
".",
"box_y",
",",
"TOP_RIGHT",
")",
"mark_corner",
"(",
"corners",
",",
"screen",
".",
"layout",
".",
"box_x",
"+",
"screen",
".",
"layout",
".",
"box_width",
"-",
"1",
",",
"screen",
".",
"layout",
".",
"box_y",
"+",
"screen",
".",
"layout",
".",
"box_height",
"-",
"1",
",",
"BOTTOM_RIGHT",
")",
"mark_corner",
"(",
"corners",
",",
"screen",
".",
"layout",
".",
"box_x",
",",
"screen",
".",
"layout",
".",
"box_y",
"+",
"screen",
".",
"layout",
".",
"box_height",
"-",
"1",
",",
"BOTTOM_LEFT",
")",
"end",
"corners",
"end",
"def",
"mark_corner",
"(",
"corners",
",",
"x",
",",
"y",
",",
"id",
")",
"corners",
"[",
"x",
"]",
"||=",
"{",
"}",
"corners",
"[",
"x",
"]",
"[",
"y",
"]",
"||=",
"[",
"]",
"corners",
"[",
"x",
"]",
"[",
"y",
"]",
"<<",
"id",
"unless",
"corners",
"[",
"x",
"]",
"[",
"y",
"]",
".",
"include?",
"(",
"id",
")",
"end",
"def",
"colorize_border",
"(",
"content",
")",
"@color_decorator",
".",
"decorate",
"(",
":border",
",",
"content",
")",
"end",
"end"
] |
Drawer to draw a nice single-line box that maximize screen area
Each screen has 4 corners and clock-wise corresponding ID:
Top-left => 1
Top-right => 2
Bottom-right => 3
Bottom-left => 4
|
[
"Drawer",
"to",
"draw",
"a",
"nice",
"single",
"-",
"line",
"box",
"that",
"maximize",
"screen",
"area",
"Each",
"screen",
"has",
"4",
"corners",
"and",
"clock",
"-",
"wise",
"corresponding",
"ID",
":",
"Top",
"-",
"left",
"=",
">",
"1",
"Top",
"-",
"right",
"=",
">",
"2",
"Bottom",
"-",
"right",
"=",
">",
"3",
"Bottom",
"-",
"left",
"=",
">",
"4"
] |
[
"# Exclude the corners"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 20
| 1,031
| 182
|
89c7c9ec93fe5379eaef98e6322770a743e205fb
|
jart/phoenix-1
|
phoenix-core/src/main/java/org/apache/phoenix/expression/function/RegexpSplitFunction.java
|
[
"Apache-2.0"
] |
Java
|
RegexpSplitFunction
|
/**
* Function to split a string value into a {@code VARCHAR_ARRAY}.
* <p>
* Usage:
* {@code REGEXP_SPLIT(<source_str>, <split_pattern>)}
* <p>
* {@code source_str} is the string in which we want to split. {@code split_pattern} is a
* Java compatible regular expression string to split the source string.
*
* The function returns a {@link org.apache.phoenix.schema.types.PVarcharArray}
*/
|
Function to split a string value into a VARCHAR_ARRAY.
The function returns a org.apache.phoenix.schema.types.PVarcharArray
|
[
"Function",
"to",
"split",
"a",
"string",
"value",
"into",
"a",
"VARCHAR_ARRAY",
".",
"The",
"function",
"returns",
"a",
"org",
".",
"apache",
".",
"phoenix",
".",
"schema",
".",
"types",
".",
"PVarcharArray"
] |
@FunctionParseNode.BuiltInFunction(name=RegexpSplitFunction.NAME, args= {
@FunctionParseNode.Argument(allowedTypes={PVarchar.class}),
@FunctionParseNode.Argument(allowedTypes={PVarchar.class})})
public class RegexpSplitFunction extends ScalarFunction {
public static final String NAME = "REGEXP_SPLIT";
private Splitter initializedSplitter = null;
public RegexpSplitFunction() {}
public RegexpSplitFunction(List<Expression> children) {
super(children);
init();
}
private void init() {
Expression patternExpression = children.get(1);
if (patternExpression instanceof LiteralExpression) {
Object patternValue = ((LiteralExpression) patternExpression).getValue();
if (patternValue != null) {
initializedSplitter = Splitter.onPattern(patternValue.toString());
}
}
}
@Override
public void readFields(DataInput input) throws IOException {
super.readFields(input);
init();
}
@Override
public String getName() {
return NAME;
}
@Override
public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) {
if (!children.get(0).evaluate(tuple, ptr)) {
return false;
}
Expression sourceStrExpression = children.get(0);
String sourceStr = (String) PVarchar.INSTANCE.toObject(ptr, sourceStrExpression.getSortOrder());
if (sourceStr == null) { // sourceStr evaluated to null
ptr.set(ByteUtil.EMPTY_BYTE_ARRAY);
return true;
}
return split(tuple, ptr, sourceStr);
}
private boolean split(Tuple tuple, ImmutableBytesWritable ptr, String sourceStr) {
Splitter splitter = initializedSplitter;
if (splitter == null) {
Expression patternExpression = children.get(1);
if (!patternExpression.evaluate(tuple, ptr)) {
return false;
}
if (ptr.getLength() == 0) {
return true; // ptr is already set to null
}
String patternStr = (String) PVarchar.INSTANCE.toObject(
ptr, patternExpression.getSortOrder());
splitter = Splitter.onPattern(patternStr);
}
List<String> splitStrings = Lists.newArrayList(splitter.split(sourceStr));
PhoenixArray splitArray = new PhoenixArray(PVarchar.INSTANCE, splitStrings.toArray());
ptr.set(PVarcharArray.INSTANCE.toBytes(splitArray));
return true;
}
@Override
public PDataType getDataType() {
return PVarcharArray.INSTANCE;
}
}
|
[
"@",
"FunctionParseNode",
".",
"BuiltInFunction",
"(",
"name",
"=",
"RegexpSplitFunction",
".",
"NAME",
",",
"args",
"=",
"{",
"@",
"FunctionParseNode",
".",
"Argument",
"(",
"allowedTypes",
"=",
"{",
"PVarchar",
".",
"class",
"}",
")",
",",
"@",
"FunctionParseNode",
".",
"Argument",
"(",
"allowedTypes",
"=",
"{",
"PVarchar",
".",
"class",
"}",
")",
"}",
")",
"public",
"class",
"RegexpSplitFunction",
"extends",
"ScalarFunction",
"{",
"public",
"static",
"final",
"String",
"NAME",
"=",
"\"",
"REGEXP_SPLIT",
"\"",
";",
"private",
"Splitter",
"initializedSplitter",
"=",
"null",
";",
"public",
"RegexpSplitFunction",
"(",
")",
"{",
"}",
"public",
"RegexpSplitFunction",
"(",
"List",
"<",
"Expression",
">",
"children",
")",
"{",
"super",
"(",
"children",
")",
";",
"init",
"(",
")",
";",
"}",
"private",
"void",
"init",
"(",
")",
"{",
"Expression",
"patternExpression",
"=",
"children",
".",
"get",
"(",
"1",
")",
";",
"if",
"(",
"patternExpression",
"instanceof",
"LiteralExpression",
")",
"{",
"Object",
"patternValue",
"=",
"(",
"(",
"LiteralExpression",
")",
"patternExpression",
")",
".",
"getValue",
"(",
")",
";",
"if",
"(",
"patternValue",
"!=",
"null",
")",
"{",
"initializedSplitter",
"=",
"Splitter",
".",
"onPattern",
"(",
"patternValue",
".",
"toString",
"(",
")",
")",
";",
"}",
"}",
"}",
"@",
"Override",
"public",
"void",
"readFields",
"(",
"DataInput",
"input",
")",
"throws",
"IOException",
"{",
"super",
".",
"readFields",
"(",
"input",
")",
";",
"init",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"String",
"getName",
"(",
")",
"{",
"return",
"NAME",
";",
"}",
"@",
"Override",
"public",
"boolean",
"evaluate",
"(",
"Tuple",
"tuple",
",",
"ImmutableBytesWritable",
"ptr",
")",
"{",
"if",
"(",
"!",
"children",
".",
"get",
"(",
"0",
")",
".",
"evaluate",
"(",
"tuple",
",",
"ptr",
")",
")",
"{",
"return",
"false",
";",
"}",
"Expression",
"sourceStrExpression",
"=",
"children",
".",
"get",
"(",
"0",
")",
";",
"String",
"sourceStr",
"=",
"(",
"String",
")",
"PVarchar",
".",
"INSTANCE",
".",
"toObject",
"(",
"ptr",
",",
"sourceStrExpression",
".",
"getSortOrder",
"(",
")",
")",
";",
"if",
"(",
"sourceStr",
"==",
"null",
")",
"{",
"ptr",
".",
"set",
"(",
"ByteUtil",
".",
"EMPTY_BYTE_ARRAY",
")",
";",
"return",
"true",
";",
"}",
"return",
"split",
"(",
"tuple",
",",
"ptr",
",",
"sourceStr",
")",
";",
"}",
"private",
"boolean",
"split",
"(",
"Tuple",
"tuple",
",",
"ImmutableBytesWritable",
"ptr",
",",
"String",
"sourceStr",
")",
"{",
"Splitter",
"splitter",
"=",
"initializedSplitter",
";",
"if",
"(",
"splitter",
"==",
"null",
")",
"{",
"Expression",
"patternExpression",
"=",
"children",
".",
"get",
"(",
"1",
")",
";",
"if",
"(",
"!",
"patternExpression",
".",
"evaluate",
"(",
"tuple",
",",
"ptr",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"ptr",
".",
"getLength",
"(",
")",
"==",
"0",
")",
"{",
"return",
"true",
";",
"}",
"String",
"patternStr",
"=",
"(",
"String",
")",
"PVarchar",
".",
"INSTANCE",
".",
"toObject",
"(",
"ptr",
",",
"patternExpression",
".",
"getSortOrder",
"(",
")",
")",
";",
"splitter",
"=",
"Splitter",
".",
"onPattern",
"(",
"patternStr",
")",
";",
"}",
"List",
"<",
"String",
">",
"splitStrings",
"=",
"Lists",
".",
"newArrayList",
"(",
"splitter",
".",
"split",
"(",
"sourceStr",
")",
")",
";",
"PhoenixArray",
"splitArray",
"=",
"new",
"PhoenixArray",
"(",
"PVarchar",
".",
"INSTANCE",
",",
"splitStrings",
".",
"toArray",
"(",
")",
")",
";",
"ptr",
".",
"set",
"(",
"PVarcharArray",
".",
"INSTANCE",
".",
"toBytes",
"(",
"splitArray",
")",
")",
";",
"return",
"true",
";",
"}",
"@",
"Override",
"public",
"PDataType",
"getDataType",
"(",
")",
"{",
"return",
"PVarcharArray",
".",
"INSTANCE",
";",
"}",
"}"
] |
Function to split a string value into a {@code VARCHAR_ARRAY}.
|
[
"Function",
"to",
"split",
"a",
"string",
"value",
"into",
"a",
"{",
"@code",
"VARCHAR_ARRAY",
"}",
"."
] |
[
"// sourceStr evaluated to null",
"// ptr is already set to null"
] |
[
{
"param": "ScalarFunction",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "ScalarFunction",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 15
| 536
| 104
|
541c410ea760a3690955bd14ee5ab1204de790cd
|
Rogue-Harbour/unity-sdk
|
Assets/DeltaDNA/Runtime/Notifications/IosNotifications.cs
|
[
"Apache-2.0"
] |
C#
|
IosNotifications
|
/// <summary>
/// iOS Notifications Plugin enables a game to register with Apple's push notification service. It provides
/// some additional functionality not easily accessible from Unity. By using the events, a game can be
/// notified when a game has registered with the service and when push notification has occured. We use
/// these events to log notifications with the DeltaDNA platform.
/// </summary>
|
iOS Notifications Plugin enables a game to register with Apple's push notification service. It provides
some additional functionality not easily accessible from Unity. By using the events, a game can be
notified when a game has registered with the service and when push notification has occured. We use
these events to log notifications with the DeltaDNA platform.
|
[
"iOS",
"Notifications",
"Plugin",
"enables",
"a",
"game",
"to",
"register",
"with",
"Apple",
"'",
"s",
"push",
"notification",
"service",
".",
"It",
"provides",
"some",
"additional",
"functionality",
"not",
"easily",
"accessible",
"from",
"Unity",
".",
"By",
"using",
"the",
"events",
"a",
"game",
"can",
"be",
"notified",
"when",
"a",
"game",
"has",
"registered",
"with",
"the",
"service",
"and",
"when",
"push",
"notification",
"has",
"occured",
".",
"We",
"use",
"these",
"events",
"to",
"log",
"notifications",
"with",
"the",
"DeltaDNA",
"platform",
"."
] |
public class IosNotifications : MonoBehaviour
{
#if UNITY_IOS && !UNITY_EDITOR
[DllImport ("__Internal")]
private static extern void _markUnityLoaded();
#endif
public event Action<string> OnDidLaunchWithPushNotification;
public event Action<string> OnDidReceivePushNotification;
public event Action<string> OnDidRegisterForPushNotifications;
public event Action<string> OnDidFailToRegisterForPushNotifications;
void Awake()
{
gameObject.name = this.GetType().ToString();
DontDestroyOnLoad(this);
#if UNITY_IOS && !UNITY_EDITOR
_markUnityLoaded();
#endif
}
public void RegisterForPushNotifications()
{
if (Application.platform == RuntimePlatform.IPhonePlayer) {
#if UNITY_IPHONE
#if UNITY_4_5 || UNITY_4_6 || UNITY_4_7
NotificationServices.RegisterForRemoteNotificationTypes(
RemoteNotificationType.Alert |
RemoteNotificationType.Badge |
RemoteNotificationType.Sound);
#else
UnityEngine.iOS.NotificationServices.RegisterForNotifications(
UnityEngine.iOS.NotificationType.Alert |
UnityEngine.iOS.NotificationType.Badge |
UnityEngine.iOS.NotificationType.Sound);
#endif
#endif
}
}
public void UnregisterForPushNotifications()
{
if (Application.platform == RuntimePlatform.IPhonePlayer) {
#if UNITY_IPHONE
#if UNITY_4_5 || UNITY_4_6 || UNITY_4_7
NotificationServices.UnregisterForRemoteNotifications();
#else
UnityEngine.iOS.NotificationServices.UnregisterForRemoteNotifications();
#endif
#endif
}
}
#region Native Bridge
public void DidLaunchWithPushNotification(string notification)
{
Debug.Log("[DeltaDna] Did launch with iOS push notification");
Logger.LogDebug("Did launch with iOS push notification");
var payload = DeltaDNA.MiniJSON.Json.Deserialize(notification) as Dictionary<string, object>;
payload["_ddCommunicationSender"] = "APPLE_NOTIFICATION";
DDNA.Instance.RecordPushNotification(payload);
if (OnDidLaunchWithPushNotification != null)
{
OnDidLaunchWithPushNotification(notification);
}
}
public void DidReceivePushNotification(string notification)
{
Debug.Log("[DeltaDna] Did receive iOS push notification");
Logger.LogDebug("Did receive iOS push notification");
var payload = DeltaDNA.MiniJSON.Json.Deserialize(notification) as Dictionary<string, object>;
payload["_ddCommunicationSender"] = "APPLE_NOTIFICATION";
DDNA.Instance.RecordPushNotification(payload);
if (OnDidReceivePushNotification != null)
{
OnDidReceivePushNotification(notification);
}
}
public void DidRegisterForPushNotifications(string deviceToken)
{
Logger.LogInfo("Did register for iOS push notifications: "+deviceToken);
#if !DELTA_DNA_PUBLIC_REPO
if (Armoury.DeltaDnaApi.instance.willRegisterIOSPushNotifications && !string.IsNullOrEmpty(deviceToken) && !string.Equals(deviceToken, DDNA.Instance.PushNotificationToken))
{
DDNA.Instance.PushNotificationToken = deviceToken;
}
#else
DDNA.Instance.PushNotificationToken = deviceToken;
#endif
if (OnDidRegisterForPushNotifications != null) {
OnDidRegisterForPushNotifications(deviceToken);
}
}
public void DidFailToRegisterForPushNotifications(string error)
{
Logger.LogWarning("Did fail to register for iOS push notifications: "+error);
if (OnDidFailToRegisterForPushNotifications != null) {
OnDidFailToRegisterForPushNotifications(error);
}
}
#endregion
}
|
[
"public",
"class",
"IosNotifications",
":",
"MonoBehaviour",
"{",
"if",
"UNITY_IOS",
"&&",
"!",
"UNITY_EDITOR",
"[",
"DllImport",
"(",
"\"",
"__Internal",
"\"",
")",
"]",
"private",
"static",
"extern",
"void",
"_markUnityLoaded",
"(",
")",
";",
"endif",
"public",
"event",
"Action",
"<",
"string",
">",
"OnDidLaunchWithPushNotification",
";",
"public",
"event",
"Action",
"<",
"string",
">",
"OnDidReceivePushNotification",
";",
"public",
"event",
"Action",
"<",
"string",
">",
"OnDidRegisterForPushNotifications",
";",
"public",
"event",
"Action",
"<",
"string",
">",
"OnDidFailToRegisterForPushNotifications",
";",
"void",
"Awake",
"(",
")",
"{",
"gameObject",
".",
"name",
"=",
"this",
".",
"GetType",
"(",
")",
".",
"ToString",
"(",
")",
";",
"DontDestroyOnLoad",
"(",
"this",
")",
";",
"if",
"UNITY_IOS",
"&&",
"!",
"UNITY_EDITOR",
"_markUnityLoaded",
"(",
")",
";",
"endif",
"}",
"public",
"void",
"RegisterForPushNotifications",
"(",
")",
"{",
"if",
"(",
"Application",
".",
"platform",
"==",
"RuntimePlatform",
".",
"IPhonePlayer",
")",
"{",
"if",
"UNITY_IPHONE",
"if",
"UNITY_4_5",
"||",
"UNITY_4_6",
"||",
"UNITY_4_7",
"NotificationServices",
".",
"RegisterForRemoteNotificationTypes",
"(",
"RemoteNotificationType",
".",
"Alert",
"|",
"RemoteNotificationType",
".",
"Badge",
"|",
"RemoteNotificationType",
".",
"Sound",
")",
";",
"else",
"UnityEngine",
".",
"iOS",
".",
"NotificationServices",
".",
"RegisterForNotifications",
"(",
"UnityEngine",
".",
"iOS",
".",
"NotificationType",
".",
"Alert",
"|",
"UnityEngine",
".",
"iOS",
".",
"NotificationType",
".",
"Badge",
"|",
"UnityEngine",
".",
"iOS",
".",
"NotificationType",
".",
"Sound",
")",
";",
"endif",
"endif",
"}",
"}",
"public",
"void",
"UnregisterForPushNotifications",
"(",
")",
"{",
"if",
"(",
"Application",
".",
"platform",
"==",
"RuntimePlatform",
".",
"IPhonePlayer",
")",
"{",
"if",
"UNITY_IPHONE",
"if",
"UNITY_4_5",
"||",
"UNITY_4_6",
"||",
"UNITY_4_7",
"NotificationServices",
".",
"UnregisterForRemoteNotifications",
"(",
")",
";",
"else",
"UnityEngine",
".",
"iOS",
".",
"NotificationServices",
".",
"UnregisterForRemoteNotifications",
"(",
")",
";",
"endif",
"endif",
"}",
"}",
"region",
" Native Bridge",
"public",
"void",
"DidLaunchWithPushNotification",
"(",
"string",
"notification",
")",
"{",
"Debug",
".",
"Log",
"(",
"\"",
"[DeltaDna] Did launch with iOS push notification",
"\"",
")",
";",
"Logger",
".",
"LogDebug",
"(",
"\"",
"Did launch with iOS push notification",
"\"",
")",
";",
"var",
"payload",
"=",
"DeltaDNA",
".",
"MiniJSON",
".",
"Json",
".",
"Deserialize",
"(",
"notification",
")",
"as",
"Dictionary",
"<",
"string",
",",
"object",
">",
";",
"payload",
"[",
"\"",
"_ddCommunicationSender",
"\"",
"]",
"=",
"\"",
"APPLE_NOTIFICATION",
"\"",
";",
"DDNA",
".",
"Instance",
".",
"RecordPushNotification",
"(",
"payload",
")",
";",
"if",
"(",
"OnDidLaunchWithPushNotification",
"!=",
"null",
")",
"{",
"OnDidLaunchWithPushNotification",
"(",
"notification",
")",
";",
"}",
"}",
"public",
"void",
"DidReceivePushNotification",
"(",
"string",
"notification",
")",
"{",
"Debug",
".",
"Log",
"(",
"\"",
"[DeltaDna] Did receive iOS push notification",
"\"",
")",
";",
"Logger",
".",
"LogDebug",
"(",
"\"",
"Did receive iOS push notification",
"\"",
")",
";",
"var",
"payload",
"=",
"DeltaDNA",
".",
"MiniJSON",
".",
"Json",
".",
"Deserialize",
"(",
"notification",
")",
"as",
"Dictionary",
"<",
"string",
",",
"object",
">",
";",
"payload",
"[",
"\"",
"_ddCommunicationSender",
"\"",
"]",
"=",
"\"",
"APPLE_NOTIFICATION",
"\"",
";",
"DDNA",
".",
"Instance",
".",
"RecordPushNotification",
"(",
"payload",
")",
";",
"if",
"(",
"OnDidReceivePushNotification",
"!=",
"null",
")",
"{",
"OnDidReceivePushNotification",
"(",
"notification",
")",
";",
"}",
"}",
"public",
"void",
"DidRegisterForPushNotifications",
"(",
"string",
"deviceToken",
")",
"{",
"Logger",
".",
"LogInfo",
"(",
"\"",
"Did register for iOS push notifications: ",
"\"",
"+",
"deviceToken",
")",
";",
"if",
"!",
"DELTA_DNA_PUBLIC_REPO",
"if",
"(",
"Armoury",
".",
"DeltaDnaApi",
".",
"instance",
".",
"willRegisterIOSPushNotifications",
"&&",
"!",
"string",
".",
"IsNullOrEmpty",
"(",
"deviceToken",
")",
"&&",
"!",
"string",
".",
"Equals",
"(",
"deviceToken",
",",
"DDNA",
".",
"Instance",
".",
"PushNotificationToken",
")",
")",
"{",
"DDNA",
".",
"Instance",
".",
"PushNotificationToken",
"=",
"deviceToken",
";",
"}",
"else",
"DDNA",
".",
"Instance",
".",
"PushNotificationToken",
"=",
"deviceToken",
";",
"endif",
"if",
"(",
"OnDidRegisterForPushNotifications",
"!=",
"null",
")",
"{",
"OnDidRegisterForPushNotifications",
"(",
"deviceToken",
")",
";",
"}",
"}",
"public",
"void",
"DidFailToRegisterForPushNotifications",
"(",
"string",
"error",
")",
"{",
"Logger",
".",
"LogWarning",
"(",
"\"",
"Did fail to register for iOS push notifications: ",
"\"",
"+",
"error",
")",
";",
"if",
"(",
"OnDidFailToRegisterForPushNotifications",
"!=",
"null",
")",
"{",
"OnDidFailToRegisterForPushNotifications",
"(",
"error",
")",
";",
"}",
"}",
"endregion",
"}"
] |
iOS Notifications Plugin enables a game to register with Apple's push notification service.
|
[
"iOS",
"Notifications",
"Plugin",
"enables",
"a",
"game",
"to",
"register",
"with",
"Apple",
"'",
"s",
"push",
"notification",
"service",
"."
] |
[
"// Called with JSON string of the notification payload.",
"// Called with JSON string of the notification payload.",
"// Called with the deviceToken.",
"// Called with the error string.",
"/// <summary>",
"/// Registers for push notifications.",
"/// </summary>",
"/// <summary>",
"/// Unregisters for push notifications.",
"/// </summary>",
"/// if DeltaDna is set to register iOS push notifications then update the token reference.",
"/// else leave it alone! It will send a new \"notificationServices\" event each time the reference is updated,",
"/// regardless of if it is the exact same token."
] |
[
{
"param": "MonoBehaviour",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "MonoBehaviour",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 19
| 773
| 82
|
733ffd2e029aecfe49e3f3438849e8d732d3d60c
|
Vladimir-Novick/FuzzyRanks
|
Matching/PhoneticKey/SoundEx.cs
|
[
"MIT"
] |
C#
|
SoundEx
|
/// <summary>
/// Builds the soundex phonetic key of a string.
///
/// Examples:
/// length=4: "Miller" -> "M460"
/// length=4: "Peterson" -> "P362"
/// length=4: "Peters" -> "P362"
///
/// Rules:
/// 1. Replace all but the first letter of the string by its phonetic code.
/// 2. Eliminate any adjacent repetitions of codes.
/// 3. Eliminate all occurrences of code 0 (that is, eliminate vowels).
/// 4. Return the first four characters of the resulting string.
///
/// Soundex Table:
/// 1 b,f,p,v
/// 2 c,g,j,k,q,s,x,z
/// 3 d, t
/// 4 l
/// 5 m, n
/// 6 r
/// </summary>
|
Builds the soundex phonetic key of a string.
1. Replace all but the first letter of the string by its phonetic code.
2. Eliminate any adjacent repetitions of codes.
3. Eliminate all occurrences of code 0 (that is, eliminate vowels).
4. Return the first four characters of the resulting string.
|
[
"Builds",
"the",
"soundex",
"phonetic",
"key",
"of",
"a",
"string",
".",
"1",
".",
"Replace",
"all",
"but",
"the",
"first",
"letter",
"of",
"the",
"string",
"by",
"its",
"phonetic",
"code",
".",
"2",
".",
"Eliminate",
"any",
"adjacent",
"repetitions",
"of",
"codes",
".",
"3",
".",
"Eliminate",
"all",
"occurrences",
"of",
"code",
"0",
"(",
"that",
"is",
"eliminate",
"vowels",
")",
".",
"4",
".",
"Return",
"the",
"first",
"four",
"characters",
"of",
"the",
"resulting",
"string",
"."
] |
public class SoundEx : PhoneticKeyBuilder
{
public override string BuildKey(string str1)
{
return this.BuildSoundEx(str1);
}
private string BuildSoundEx(string str1)
{
if (string.IsNullOrEmpty(str1))
{
return string.Concat(Enumerable.Repeat("0", this.MaxLength));
}
str1 = str1.ToLower();
bool firstCharRemains = true;
int startIndex = 0;
var result = new StringBuilder();
if (!string.IsNullOrEmpty(str1))
{
string previousCode = "";
string currentCode = "";
string currentLetter = "";
str1 = str1.Replace('ä', 'a')
.Replace('ö', 'o')
.Replace('ü', 'u')
.Replace('ß', 's');
if (firstCharRemains)
{
result.Append(str1.Substring(0, 1));
startIndex++;
}
for (int i = startIndex; i < str1.Length; i++)
{
currentLetter = str1.Substring(i, 1).ToLower();
currentCode = "";
if ("bfpv".Contains(currentLetter))
{
currentCode = "1";
}
else if ("cgjkqsxz".Contains(currentLetter))
{
currentCode = "2";
}
else if ("dt".Contains(currentLetter))
{
currentCode = "3";
}
else if ("l".Contains(currentLetter))
{
currentCode = "4";
}
else if ("mn".Contains(currentLetter))
{
currentCode = "5";
}
else if ("r".Contains(currentLetter))
{
currentCode = "6";
}
if (currentCode != previousCode)
{
result.Append(currentCode);
}
if (result.Length == this.MaxLength)
{
break;
}
if (currentCode != "")
{
previousCode = currentCode;
}
}
}
if (result.Length < this.MaxLength)
{
result.Append(new string('0', (int)this.MaxLength - result.Length));
}
return result.ToString();
}
}
|
[
"public",
"class",
"SoundEx",
":",
"PhoneticKeyBuilder",
"{",
"public",
"override",
"string",
"BuildKey",
"(",
"string",
"str1",
")",
"{",
"return",
"this",
".",
"BuildSoundEx",
"(",
"str1",
")",
";",
"}",
"private",
"string",
"BuildSoundEx",
"(",
"string",
"str1",
")",
"{",
"if",
"(",
"string",
".",
"IsNullOrEmpty",
"(",
"str1",
")",
")",
"{",
"return",
"string",
".",
"Concat",
"(",
"Enumerable",
".",
"Repeat",
"(",
"\"",
"0",
"\"",
",",
"this",
".",
"MaxLength",
")",
")",
";",
"}",
"str1",
"=",
"str1",
".",
"ToLower",
"(",
")",
";",
"bool",
"firstCharRemains",
"=",
"true",
";",
"int",
"startIndex",
"=",
"0",
";",
"var",
"result",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"if",
"(",
"!",
"string",
".",
"IsNullOrEmpty",
"(",
"str1",
")",
")",
"{",
"string",
"previousCode",
"=",
"\"",
"\"",
";",
"string",
"currentCode",
"=",
"\"",
"\"",
";",
"string",
"currentLetter",
"=",
"\"",
"\"",
";",
"str1",
"=",
"str1",
".",
"Replace",
"(",
"'",
"ä'",
",",
" ",
"a",
"'",
")",
"\r",
".",
"Replace",
"(",
"'",
"ö'",
",",
" ",
"o",
"'",
")",
"\r",
".",
"Replace",
"(",
"'",
"ü'",
",",
" ",
"u",
"'",
")",
"\r",
".",
"Replace",
"(",
"'",
"ß'",
",",
" ",
"s",
"'",
")",
";",
"\r",
"if",
"(",
"firstCharRemains",
")",
"{",
"result",
".",
"Append",
"(",
"str1",
".",
"Substring",
"(",
"0",
",",
"1",
")",
")",
";",
"startIndex",
"++",
";",
"}",
"for",
"(",
"int",
"i",
"=",
"startIndex",
";",
"i",
"<",
"str1",
".",
"Length",
";",
"i",
"++",
")",
"{",
"currentLetter",
"=",
"str1",
".",
"Substring",
"(",
"i",
",",
"1",
")",
".",
"ToLower",
"(",
")",
";",
"currentCode",
"=",
"\"",
"\"",
";",
"if",
"(",
"\"",
"bfpv",
"\"",
".",
"Contains",
"(",
"currentLetter",
")",
")",
"{",
"currentCode",
"=",
"\"",
"1",
"\"",
";",
"}",
"else",
"if",
"(",
"\"",
"cgjkqsxz",
"\"",
".",
"Contains",
"(",
"currentLetter",
")",
")",
"{",
"currentCode",
"=",
"\"",
"2",
"\"",
";",
"}",
"else",
"if",
"(",
"\"",
"dt",
"\"",
".",
"Contains",
"(",
"currentLetter",
")",
")",
"{",
"currentCode",
"=",
"\"",
"3",
"\"",
";",
"}",
"else",
"if",
"(",
"\"",
"l",
"\"",
".",
"Contains",
"(",
"currentLetter",
")",
")",
"{",
"currentCode",
"=",
"\"",
"4",
"\"",
";",
"}",
"else",
"if",
"(",
"\"",
"mn",
"\"",
".",
"Contains",
"(",
"currentLetter",
")",
")",
"{",
"currentCode",
"=",
"\"",
"5",
"\"",
";",
"}",
"else",
"if",
"(",
"\"",
"r",
"\"",
".",
"Contains",
"(",
"currentLetter",
")",
")",
"{",
"currentCode",
"=",
"\"",
"6",
"\"",
";",
"}",
"if",
"(",
"currentCode",
"!=",
"previousCode",
")",
"{",
"result",
".",
"Append",
"(",
"currentCode",
")",
";",
"}",
"if",
"(",
"result",
".",
"Length",
"==",
"this",
".",
"MaxLength",
")",
"{",
"break",
";",
"}",
"if",
"(",
"currentCode",
"!=",
"\"",
"\"",
")",
"{",
"previousCode",
"=",
"currentCode",
";",
"}",
"}",
"}",
"if",
"(",
"result",
".",
"Length",
"<",
"this",
".",
"MaxLength",
")",
"{",
"result",
".",
"Append",
"(",
"new",
"string",
"(",
"'",
"0",
"'",
",",
"(",
"int",
")",
"this",
".",
"MaxLength",
"-",
"result",
".",
"Length",
")",
")",
";",
"}",
"return",
"result",
".",
"ToString",
"(",
")",
";",
"}",
"}"
] |
Builds the soundex phonetic key of a string.
|
[
"Builds",
"the",
"soundex",
"phonetic",
"key",
"of",
"a",
"string",
"."
] |
[
"// \"Miller\" -> \"miller\"",
"// replace umlauts \"jörg\" -> \"jorg\"\r",
"// First letter remains \"miller\" -> \"m\"",
"// take every letter",
"// encode letter by soundex table to a code",
"// only add, when changes (elimates double characters)",
"// cancel, when length is reached",
"// fill with zeros e.g. 000 to reach the maxlength"
] |
[
{
"param": "PhoneticKeyBuilder",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "PhoneticKeyBuilder",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 19
| 460
| 191
|
3f164719b427976a126ebfc3c3b6be8243c9c01e
|
dkinsey/hub
|
_plugins/canonicalizer.rb
|
[
"CC0-1.0"
] |
Ruby
|
Hub
|
# 18F Hub - Docs & connections between team members, projects, and skill sets
#
# Written in 2014 by Mike Bland ([email protected])
# on behalf of the 18F team, part of the US General Services Administration:
# https://18f.gsa.gov/
#
# To the extent possible under law, the author(s) have dedicated all copyright
# and related and neighboring rights to this software to the public domain
# worldwide. This software is distributed without any warranty.
#
# You should have received a copy of the CC0 Public Domain Dedication along
# with this software. If not, see
# <https://creativecommons.org/publicdomain/zero/1.0/>.
#
# @author Mike Bland ([email protected])
|
To the extent possible under law, the author(s) have dedicated all copyright
and related and neighboring rights to this software to the public domain
worldwide. This software is distributed without any warranty.
You should have received a copy of the CC0 Public Domain Dedication along
with this software. If not, see
.
|
[
"To",
"the",
"extent",
"possible",
"under",
"law",
"the",
"author",
"(",
"s",
")",
"have",
"dedicated",
"all",
"copyright",
"and",
"related",
"and",
"neighboring",
"rights",
"to",
"this",
"software",
"to",
"the",
"public",
"domain",
"worldwide",
".",
"This",
"software",
"is",
"distributed",
"without",
"any",
"warranty",
".",
"You",
"should",
"have",
"received",
"a",
"copy",
"of",
"the",
"CC0",
"Public",
"Domain",
"Dedication",
"along",
"with",
"this",
"software",
".",
"If",
"not",
"see",
"."
] |
module Hub
# Contains utility functions for canonicalizing names and the order of data.
class Canonicalizer
# Canonicalizes the order and names of certain fields within site_data.
def self.canonicalize_data(site_data)
sort_by_last_name! site_data['team']
canonicalize_locations(site_data)
canonicalize_projects(site_data)
canonicalize_working_groups(site_data)
canonicalize_snippets(site_data)
canonicalize_skills(site_data)
end
def self.canonicalize_locations(site_data)
if site_data.member? 'locations'
site_data['locations'].each do |l|
sort_by_last_name! (l['team'] || [])
['projects', 'working_groups'].each do |category|
l[category].sort_by!{|i| i['name']} if l[category]
end
end
end
end
def self.canonicalize_projects(site_data)
if site_data.member? 'projects'
site_data['projects'].each do |p|
sort_by_last_name! p['team'] if p['team']
end
end
end
def self.canonicalize_working_groups(site_data)
if site_data.member? 'working_groups'
site_data['working_groups'].each do |wg|
['leads', 'members'].each do |member_type|
sort_by_last_name! wg[member_type] if wg.member? member_type
end
end
site_data['team'].each do |member|
(member['working_groups'] || []).sort_by! {|wg| wg['name']}
end
end
end
def self.canonicalize_snippets(site_data)
if site_data.member? 'snippets_team_members'
sort_by_last_name! site_data['snippets_team_members']
end
end
def self.canonicalize_skills(site_data)
if site_data.member? 'skills'
site_data['skills'].each {|unused,xref| combine_skills! xref}
end
end
# Returns a canonicalized, URL-friendly substitute for an arbitrary string.
# +s+:: string to canonicalize
def self.canonicalize(s)
s.downcase.gsub(/\s+/, '-')
end
# Sorts in-place an array of team member data hashes based on the team
# members' last names. Returns the sorted, original array object.
# +team+:: An array of team member data hashes
def self.sort_by_last_name!(team)
team.sort_by! do |i|
if i['last_name']
[i['last_name'].downcase, i['first_name'].downcase]
else
n = i['full_name'].downcase.split(',')[0]
l = n.split.last
[l, n]
end
end
end
# Breaks a YYYYMMDD timestamp into a hyphenated version: YYYY-MM-DD
# +timestamp+:: timestamp in the form YYYYMMDD
def self.hyphenate_yyyymmdd(timestamp)
"#{timestamp[0..3]}-#{timestamp[4..5]}-#{timestamp[6..7]}"
end
# Consolidate skills entries that are not exactly the same. Selects the
# lexicographically smaller version of the skill name as a standard.
#
# In the future, we may just consider raising an error if there are two
# different strings for the same thing.
#
# +skills_ref+:: hash from skills => team members; updated in-place
def self.combine_skills!(skills_xref)
canonicals = {}
skills_xref.each do |skill, members|
canonicalized = Canonicalizer.canonicalize(skill)
if not canonicals.member? canonicalized
canonicals[canonicalized] = skill
else
current = canonicals[canonicalized]
if current < skill
skills_xref[current].concat(members)
members.clear
else
members.concat(skills_xref[current])
skills_xref[current].clear
canonicals[canonicalized] = skill
end
end
end
skills_xref.delete_if {|unused_skill,members| members.empty?}
end
end
end
|
[
"module",
"Hub",
"class",
"Canonicalizer",
"def",
"self",
".",
"canonicalize_data",
"(",
"site_data",
")",
"sort_by_last_name!",
"site_data",
"[",
"'team'",
"]",
"canonicalize_locations",
"(",
"site_data",
")",
"canonicalize_projects",
"(",
"site_data",
")",
"canonicalize_working_groups",
"(",
"site_data",
")",
"canonicalize_snippets",
"(",
"site_data",
")",
"canonicalize_skills",
"(",
"site_data",
")",
"end",
"def",
"self",
".",
"canonicalize_locations",
"(",
"site_data",
")",
"if",
"site_data",
".",
"member?",
"'locations'",
"site_data",
"[",
"'locations'",
"]",
".",
"each",
"do",
"|",
"l",
"|",
"sort_by_last_name!",
"(",
"l",
"[",
"'team'",
"]",
"||",
"[",
"]",
")",
"[",
"'projects'",
",",
"'working_groups'",
"]",
".",
"each",
"do",
"|",
"category",
"|",
"l",
"[",
"category",
"]",
".",
"sort_by!",
"{",
"|",
"i",
"|",
"i",
"[",
"'name'",
"]",
"}",
"if",
"l",
"[",
"category",
"]",
"end",
"end",
"end",
"end",
"def",
"self",
".",
"canonicalize_projects",
"(",
"site_data",
")",
"if",
"site_data",
".",
"member?",
"'projects'",
"site_data",
"[",
"'projects'",
"]",
".",
"each",
"do",
"|",
"p",
"|",
"sort_by_last_name!",
"p",
"[",
"'team'",
"]",
"if",
"p",
"[",
"'team'",
"]",
"end",
"end",
"end",
"def",
"self",
".",
"canonicalize_working_groups",
"(",
"site_data",
")",
"if",
"site_data",
".",
"member?",
"'working_groups'",
"site_data",
"[",
"'working_groups'",
"]",
".",
"each",
"do",
"|",
"wg",
"|",
"[",
"'leads'",
",",
"'members'",
"]",
".",
"each",
"do",
"|",
"member_type",
"|",
"sort_by_last_name!",
"wg",
"[",
"member_type",
"]",
"if",
"wg",
".",
"member?",
"member_type",
"end",
"end",
"site_data",
"[",
"'team'",
"]",
".",
"each",
"do",
"|",
"member",
"|",
"(",
"member",
"[",
"'working_groups'",
"]",
"||",
"[",
"]",
")",
".",
"sort_by!",
"{",
"|",
"wg",
"|",
"wg",
"[",
"'name'",
"]",
"}",
"end",
"end",
"end",
"def",
"self",
".",
"canonicalize_snippets",
"(",
"site_data",
")",
"if",
"site_data",
".",
"member?",
"'snippets_team_members'",
"sort_by_last_name!",
"site_data",
"[",
"'snippets_team_members'",
"]",
"end",
"end",
"def",
"self",
".",
"canonicalize_skills",
"(",
"site_data",
")",
"if",
"site_data",
".",
"member?",
"'skills'",
"site_data",
"[",
"'skills'",
"]",
".",
"each",
"{",
"|",
"unused",
",",
"xref",
"|",
"combine_skills!",
"xref",
"}",
"end",
"end",
"def",
"self",
".",
"canonicalize",
"(",
"s",
")",
"s",
".",
"downcase",
".",
"gsub",
"(",
"/",
"\\s",
"+",
"/",
",",
"'-'",
")",
"end",
"def",
"self",
".",
"sort_by_last_name!",
"(",
"team",
")",
"team",
".",
"sort_by!",
"do",
"|",
"i",
"|",
"if",
"i",
"[",
"'last_name'",
"]",
"[",
"i",
"[",
"'last_name'",
"]",
".",
"downcase",
",",
"i",
"[",
"'first_name'",
"]",
".",
"downcase",
"]",
"else",
"n",
"=",
"i",
"[",
"'full_name'",
"]",
".",
"downcase",
".",
"split",
"(",
"','",
")",
"[",
"0",
"]",
"l",
"=",
"n",
".",
"split",
".",
"last",
"[",
"l",
",",
"n",
"]",
"end",
"end",
"end",
"def",
"self",
".",
"hyphenate_yyyymmdd",
"(",
"timestamp",
")",
"\"#{timestamp[0..3]}-#{timestamp[4..5]}-#{timestamp[6..7]}\"",
"end",
"def",
"self",
".",
"combine_skills!",
"(",
"skills_xref",
")",
"canonicals",
"=",
"{",
"}",
"skills_xref",
".",
"each",
"do",
"|",
"skill",
",",
"members",
"|",
"canonicalized",
"=",
"Canonicalizer",
".",
"canonicalize",
"(",
"skill",
")",
"if",
"not",
"canonicals",
".",
"member?",
"canonicalized",
"canonicals",
"[",
"canonicalized",
"]",
"=",
"skill",
"else",
"current",
"=",
"canonicals",
"[",
"canonicalized",
"]",
"if",
"current",
"<",
"skill",
"skills_xref",
"[",
"current",
"]",
".",
"concat",
"(",
"members",
")",
"members",
".",
"clear",
"else",
"members",
".",
"concat",
"(",
"skills_xref",
"[",
"current",
"]",
")",
"skills_xref",
"[",
"current",
"]",
".",
"clear",
"canonicals",
"[",
"canonicalized",
"]",
"=",
"skill",
"end",
"end",
"end",
"skills_xref",
".",
"delete_if",
"{",
"|",
"unused_skill",
",",
"members",
"|",
"members",
".",
"empty?",
"}",
"end",
"end",
"end"
] |
18F Hub - Docs & connections between team members, projects, and skill sets
Written in 2014 by Mike Bland ([email protected])
on behalf of the 18F team, part of the US General Services Administration:
https://18f.gsa.gov
|
[
"18F",
"Hub",
"-",
"Docs",
"&",
"connections",
"between",
"team",
"members",
"projects",
"and",
"skill",
"sets",
"Written",
"in",
"2014",
"by",
"Mike",
"Bland",
"(",
"michael",
".",
"bland@gsa",
".",
"gov",
")",
"on",
"behalf",
"of",
"the",
"18F",
"team",
"part",
"of",
"the",
"US",
"General",
"Services",
"Administration",
":",
"https",
":",
"//",
"18f",
".",
"gsa",
".",
"gov"
] |
[
"# Contains utility functions for canonicalizing names and the order of data.",
"# Canonicalizes the order and names of certain fields within site_data.",
"# Returns a canonicalized, URL-friendly substitute for an arbitrary string.",
"# +s+:: string to canonicalize",
"# Sorts in-place an array of team member data hashes based on the team",
"# members' last names. Returns the sorted, original array object.",
"# +team+:: An array of team member data hashes",
"# Breaks a YYYYMMDD timestamp into a hyphenated version: YYYY-MM-DD",
"# +timestamp+:: timestamp in the form YYYYMMDD",
"# Consolidate skills entries that are not exactly the same. Selects the",
"# lexicographically smaller version of the skill name as a standard.",
"#",
"# In the future, we may just consider raising an error if there are two",
"# different strings for the same thing.",
"#",
"# +skills_ref+:: hash from skills => team members; updated in-place"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": [
{
"identifier": "author",
"docstring": "Mike Bland ([email protected])",
"docstring_tokens": [
"Mike",
"Bland",
"(",
"michael",
".",
"bland@gsa",
".",
"gov",
")"
]
}
]
}
| false
| 21
| 917
| 175
|
4a0719bb2ea2907585b32082a989be0909a2353d
|
prodigyfinance/ml2p
|
ml2p/core.py
|
[
"0BSD"
] |
Python
|
SageMakerEnv
|
An interface to the SageMaker docker environment.
Attributes that are expected to be available in both training and serving
environments:
* `env_type` - Whether this is a training, serving or local environment
(type: ml2p.core.SageMakerEnvType).
* `project` - The ML2P project name (type: str).
* `model_cls` - The fulled dotted Python name of the ml2p.core.Model class to
be used for training and prediction (type: str). This may be None if the
docker image itself specifies the name with `ml2p-docker --model ...`.
* `s3` - The URL of the project S3 bucket (type: ml2p.core.S3URL).
Attributes that are only expected to be available while training (and that will
be None when serving the model):
* `training_job_name` - The full job name of the training job (type: str).
Attributes that are only expected to be available while serving the model (and
that will be None when serving the model):
* `model_version` - The full job name of the deployed model, or None
during training (type: str).
* `record_invokes` - Whether to store a record of each invocation of the
endpoint in S3 (type: bool).
In the training environment settings are loaded from hyperparameters stored by
ML2P when the training job is created.
In the serving environment settings are loaded from environment variables stored
by ML2P when the model is created.
|
An interface to the SageMaker docker environment.
Attributes that are expected to be available in both training and serving
environments.
`env_type` - Whether this is a training, serving or local environment
(type: ml2p.core.SageMakerEnvType).
`project` - The ML2P project name (type: str).
`model_cls` - The fulled dotted Python name of the ml2p.core.Model class to
be used for training and prediction (type: str). This may be None if the
docker image itself specifies the name with `ml2p-docker --model ...`.
`s3` - The URL of the project S3 bucket (type: ml2p.core.S3URL).
Attributes that are only expected to be available while training (and that will
be None when serving the model).
`training_job_name` - The full job name of the training job (type: str).
Attributes that are only expected to be available while serving the model (and
that will be None when serving the model).
`model_version` - The full job name of the deployed model, or None
during training (type: str).
`record_invokes` - Whether to store a record of each invocation of the
endpoint in S3 (type: bool).
In the training environment settings are loaded from hyperparameters stored by
ML2P when the training job is created.
In the serving environment settings are loaded from environment variables stored
by ML2P when the model is created.
|
[
"An",
"interface",
"to",
"the",
"SageMaker",
"docker",
"environment",
".",
"Attributes",
"that",
"are",
"expected",
"to",
"be",
"available",
"in",
"both",
"training",
"and",
"serving",
"environments",
".",
"`",
"env_type",
"`",
"-",
"Whether",
"this",
"is",
"a",
"training",
"serving",
"or",
"local",
"environment",
"(",
"type",
":",
"ml2p",
".",
"core",
".",
"SageMakerEnvType",
")",
".",
"`",
"project",
"`",
"-",
"The",
"ML2P",
"project",
"name",
"(",
"type",
":",
"str",
")",
".",
"`",
"model_cls",
"`",
"-",
"The",
"fulled",
"dotted",
"Python",
"name",
"of",
"the",
"ml2p",
".",
"core",
".",
"Model",
"class",
"to",
"be",
"used",
"for",
"training",
"and",
"prediction",
"(",
"type",
":",
"str",
")",
".",
"This",
"may",
"be",
"None",
"if",
"the",
"docker",
"image",
"itself",
"specifies",
"the",
"name",
"with",
"`",
"ml2p",
"-",
"docker",
"--",
"model",
"...",
"`",
".",
"`",
"s3",
"`",
"-",
"The",
"URL",
"of",
"the",
"project",
"S3",
"bucket",
"(",
"type",
":",
"ml2p",
".",
"core",
".",
"S3URL",
")",
".",
"Attributes",
"that",
"are",
"only",
"expected",
"to",
"be",
"available",
"while",
"training",
"(",
"and",
"that",
"will",
"be",
"None",
"when",
"serving",
"the",
"model",
")",
".",
"`",
"training_job_name",
"`",
"-",
"The",
"full",
"job",
"name",
"of",
"the",
"training",
"job",
"(",
"type",
":",
"str",
")",
".",
"Attributes",
"that",
"are",
"only",
"expected",
"to",
"be",
"available",
"while",
"serving",
"the",
"model",
"(",
"and",
"that",
"will",
"be",
"None",
"when",
"serving",
"the",
"model",
")",
".",
"`",
"model_version",
"`",
"-",
"The",
"full",
"job",
"name",
"of",
"the",
"deployed",
"model",
"or",
"None",
"during",
"training",
"(",
"type",
":",
"str",
")",
".",
"`",
"record_invokes",
"`",
"-",
"Whether",
"to",
"store",
"a",
"record",
"of",
"each",
"invocation",
"of",
"the",
"endpoint",
"in",
"S3",
"(",
"type",
":",
"bool",
")",
".",
"In",
"the",
"training",
"environment",
"settings",
"are",
"loaded",
"from",
"hyperparameters",
"stored",
"by",
"ML2P",
"when",
"the",
"training",
"job",
"is",
"created",
".",
"In",
"the",
"serving",
"environment",
"settings",
"are",
"loaded",
"from",
"environment",
"variables",
"stored",
"by",
"ML2P",
"when",
"the",
"model",
"is",
"created",
"."
] |
class SageMakerEnv:
""" An interface to the SageMaker docker environment.
Attributes that are expected to be available in both training and serving
environments:
* `env_type` - Whether this is a training, serving or local environment
(type: ml2p.core.SageMakerEnvType).
* `project` - The ML2P project name (type: str).
* `model_cls` - The fulled dotted Python name of the ml2p.core.Model class to
be used for training and prediction (type: str). This may be None if the
docker image itself specifies the name with `ml2p-docker --model ...`.
* `s3` - The URL of the project S3 bucket (type: ml2p.core.S3URL).
Attributes that are only expected to be available while training (and that will
be None when serving the model):
* `training_job_name` - The full job name of the training job (type: str).
Attributes that are only expected to be available while serving the model (and
that will be None when serving the model):
* `model_version` - The full job name of the deployed model, or None
during training (type: str).
* `record_invokes` - Whether to store a record of each invocation of the
endpoint in S3 (type: bool).
In the training environment settings are loaded from hyperparameters stored by
ML2P when the training job is created.
In the serving environment settings are loaded from environment variables stored
by ML2P when the model is created.
"""
TRAIN = SageMakerEnvType.TRAIN
SERVE = SageMakerEnvType.SERVE
LOCAL = SageMakerEnvType.LOCAL
def __init__(self, ml_folder, environ=None):
self._ml_folder = pathlib.Path(ml_folder)
if environ is None:
if "TRAINING_JOB_NAME" in os.environ:
# this is a training job instance
environ = self._train_environ()
else:
# this is a serving instance
environ = self._serve_environ()
self.env_type = environ["env_type"]
self.training_job_name = environ["training_job_name"]
self.model_version = environ["model_version"]
self.record_invokes = environ["record_invokes"]
self.project = environ["project"]
self.model_cls = environ["model_cls"]
self.s3 = None
if environ["s3_url"]:
self.s3 = S3URL(environ["s3_url"])
def _train_environ(self):
environ = self.hyperparameters().get("ML2P_ENV", {})
return {
"env_type": self.TRAIN,
"training_job_name": os.environ.get("TRAINING_JOB_NAME", None),
"model_version": None,
"record_invokes": None,
"project": environ.get("ML2P_PROJECT", None),
"model_cls": environ.get("ML2P_MODEL_CLS", None),
"s3_url": environ.get("ML2P_S3_URL", None),
}
def _serve_environ(self):
environ = os.environ
return {
"env_type": self.SERVE,
"training_job_name": None,
"model_version": environ.get("ML2P_MODEL_VERSION", None),
"record_invokes": environ.get("ML2P_RECORD_INVOKES", "false") == "true",
"project": environ.get("ML2P_PROJECT", None),
"model_cls": environ.get("ML2P_MODEL_CLS", None),
"s3_url": environ.get("ML2P_S3_URL", None),
}
def hyperparameters(self):
hp_path = self._ml_folder / "input" / "config" / "hyperparameters.json"
if not hp_path.exists():
return {}
with hp_path.open() as f:
return hyperparameters.decode(json.load(f))
def resourceconfig(self):
rc_path = self._ml_folder / "input" / "config" / "resourceconfig.json"
if not rc_path.exists():
return {}
with rc_path.open() as f:
return json.load(f)
def dataset_folder(self, dataset=None):
if dataset is None:
dataset = "training"
else:
warnings.warn(
"Passing a dataset name to dataset_folder method(...) is deprecated."
" If you wish to access the ML2P training dataset, do not pass any"
" parameters. If you wish to access data for a specific channel, please"
" use data_channel_folder(...) instead, which matches the terminology"
" used by AWS SageMaker more accurately.",
DeprecationWarning,
)
return self._ml_folder / "input" / "data" / dataset
def data_channel_folder(self, channel):
return self._ml_folder / "input" / "data" / channel
def model_folder(self):
return self._ml_folder / "model"
def write_failure(self, text):
with open(self._ml_folder / "output" / "failure", "w") as f:
f.write(text)
|
[
"class",
"SageMakerEnv",
":",
"TRAIN",
"=",
"SageMakerEnvType",
".",
"TRAIN",
"SERVE",
"=",
"SageMakerEnvType",
".",
"SERVE",
"LOCAL",
"=",
"SageMakerEnvType",
".",
"LOCAL",
"def",
"__init__",
"(",
"self",
",",
"ml_folder",
",",
"environ",
"=",
"None",
")",
":",
"self",
".",
"_ml_folder",
"=",
"pathlib",
".",
"Path",
"(",
"ml_folder",
")",
"if",
"environ",
"is",
"None",
":",
"if",
"\"TRAINING_JOB_NAME\"",
"in",
"os",
".",
"environ",
":",
"environ",
"=",
"self",
".",
"_train_environ",
"(",
")",
"else",
":",
"environ",
"=",
"self",
".",
"_serve_environ",
"(",
")",
"self",
".",
"env_type",
"=",
"environ",
"[",
"\"env_type\"",
"]",
"self",
".",
"training_job_name",
"=",
"environ",
"[",
"\"training_job_name\"",
"]",
"self",
".",
"model_version",
"=",
"environ",
"[",
"\"model_version\"",
"]",
"self",
".",
"record_invokes",
"=",
"environ",
"[",
"\"record_invokes\"",
"]",
"self",
".",
"project",
"=",
"environ",
"[",
"\"project\"",
"]",
"self",
".",
"model_cls",
"=",
"environ",
"[",
"\"model_cls\"",
"]",
"self",
".",
"s3",
"=",
"None",
"if",
"environ",
"[",
"\"s3_url\"",
"]",
":",
"self",
".",
"s3",
"=",
"S3URL",
"(",
"environ",
"[",
"\"s3_url\"",
"]",
")",
"def",
"_train_environ",
"(",
"self",
")",
":",
"environ",
"=",
"self",
".",
"hyperparameters",
"(",
")",
".",
"get",
"(",
"\"ML2P_ENV\"",
",",
"{",
"}",
")",
"return",
"{",
"\"env_type\"",
":",
"self",
".",
"TRAIN",
",",
"\"training_job_name\"",
":",
"os",
".",
"environ",
".",
"get",
"(",
"\"TRAINING_JOB_NAME\"",
",",
"None",
")",
",",
"\"model_version\"",
":",
"None",
",",
"\"record_invokes\"",
":",
"None",
",",
"\"project\"",
":",
"environ",
".",
"get",
"(",
"\"ML2P_PROJECT\"",
",",
"None",
")",
",",
"\"model_cls\"",
":",
"environ",
".",
"get",
"(",
"\"ML2P_MODEL_CLS\"",
",",
"None",
")",
",",
"\"s3_url\"",
":",
"environ",
".",
"get",
"(",
"\"ML2P_S3_URL\"",
",",
"None",
")",
",",
"}",
"def",
"_serve_environ",
"(",
"self",
")",
":",
"environ",
"=",
"os",
".",
"environ",
"return",
"{",
"\"env_type\"",
":",
"self",
".",
"SERVE",
",",
"\"training_job_name\"",
":",
"None",
",",
"\"model_version\"",
":",
"environ",
".",
"get",
"(",
"\"ML2P_MODEL_VERSION\"",
",",
"None",
")",
",",
"\"record_invokes\"",
":",
"environ",
".",
"get",
"(",
"\"ML2P_RECORD_INVOKES\"",
",",
"\"false\"",
")",
"==",
"\"true\"",
",",
"\"project\"",
":",
"environ",
".",
"get",
"(",
"\"ML2P_PROJECT\"",
",",
"None",
")",
",",
"\"model_cls\"",
":",
"environ",
".",
"get",
"(",
"\"ML2P_MODEL_CLS\"",
",",
"None",
")",
",",
"\"s3_url\"",
":",
"environ",
".",
"get",
"(",
"\"ML2P_S3_URL\"",
",",
"None",
")",
",",
"}",
"def",
"hyperparameters",
"(",
"self",
")",
":",
"hp_path",
"=",
"self",
".",
"_ml_folder",
"/",
"\"input\"",
"/",
"\"config\"",
"/",
"\"hyperparameters.json\"",
"if",
"not",
"hp_path",
".",
"exists",
"(",
")",
":",
"return",
"{",
"}",
"with",
"hp_path",
".",
"open",
"(",
")",
"as",
"f",
":",
"return",
"hyperparameters",
".",
"decode",
"(",
"json",
".",
"load",
"(",
"f",
")",
")",
"def",
"resourceconfig",
"(",
"self",
")",
":",
"rc_path",
"=",
"self",
".",
"_ml_folder",
"/",
"\"input\"",
"/",
"\"config\"",
"/",
"\"resourceconfig.json\"",
"if",
"not",
"rc_path",
".",
"exists",
"(",
")",
":",
"return",
"{",
"}",
"with",
"rc_path",
".",
"open",
"(",
")",
"as",
"f",
":",
"return",
"json",
".",
"load",
"(",
"f",
")",
"def",
"dataset_folder",
"(",
"self",
",",
"dataset",
"=",
"None",
")",
":",
"if",
"dataset",
"is",
"None",
":",
"dataset",
"=",
"\"training\"",
"else",
":",
"warnings",
".",
"warn",
"(",
"\"Passing a dataset name to dataset_folder method(...) is deprecated.\"",
"\" If you wish to access the ML2P training dataset, do not pass any\"",
"\" parameters. If you wish to access data for a specific channel, please\"",
"\" use data_channel_folder(...) instead, which matches the terminology\"",
"\" used by AWS SageMaker more accurately.\"",
",",
"DeprecationWarning",
",",
")",
"return",
"self",
".",
"_ml_folder",
"/",
"\"input\"",
"/",
"\"data\"",
"/",
"dataset",
"def",
"data_channel_folder",
"(",
"self",
",",
"channel",
")",
":",
"return",
"self",
".",
"_ml_folder",
"/",
"\"input\"",
"/",
"\"data\"",
"/",
"channel",
"def",
"model_folder",
"(",
"self",
")",
":",
"return",
"self",
".",
"_ml_folder",
"/",
"\"model\"",
"def",
"write_failure",
"(",
"self",
",",
"text",
")",
":",
"with",
"open",
"(",
"self",
".",
"_ml_folder",
"/",
"\"output\"",
"/",
"\"failure\"",
",",
"\"w\"",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"text",
")"
] |
An interface to the SageMaker docker environment.
|
[
"An",
"interface",
"to",
"the",
"SageMaker",
"docker",
"environment",
"."
] |
[
"\"\"\" An interface to the SageMaker docker environment.\n\n Attributes that are expected to be available in both training and serving\n environments:\n\n * `env_type` - Whether this is a training, serving or local environment\n (type: ml2p.core.SageMakerEnvType).\n\n * `project` - The ML2P project name (type: str).\n\n * `model_cls` - The fulled dotted Python name of the ml2p.core.Model class to\n be used for training and prediction (type: str). This may be None if the\n docker image itself specifies the name with `ml2p-docker --model ...`.\n\n * `s3` - The URL of the project S3 bucket (type: ml2p.core.S3URL).\n\n Attributes that are only expected to be available while training (and that will\n be None when serving the model):\n\n * `training_job_name` - The full job name of the training job (type: str).\n\n Attributes that are only expected to be available while serving the model (and\n that will be None when serving the model):\n\n * `model_version` - The full job name of the deployed model, or None\n during training (type: str).\n\n * `record_invokes` - Whether to store a record of each invocation of the\n endpoint in S3 (type: bool).\n\n In the training environment settings are loaded from hyperparameters stored by\n ML2P when the training job is created.\n\n In the serving environment settings are loaded from environment variables stored\n by ML2P when the model is created.\n \"\"\"",
"# this is a training job instance",
"# this is a serving instance"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 14
| 1,106
| 338
|
6e8742ae9915d3b6b070d6d02c419d857409c0a8
|
perkexchange/kin-python
|
agora/model/payment.py
|
[
"MIT"
] |
Python
|
ReadOnlyPayment
|
The :class:`ReadOnlyPayment <ReadOnlyPayment>` object, which represents a payment that was retrieved from
history.
:param sender: The :class:`PublicKey <agora.keys.PublicKey>` of the sending account.
:param destination: The :class:`PublicKey <agora.keys.PublicKey>` of the destination account.
:param tx_type: The type of this payment.
:param quarks: The amount of the payment.
:param invoice: (optional) The :class:`Invoice <agora.model.invoice.Invoice>` associated with this payment. Only one
of invoice or memo will be set.
:param memo: (optional) The text memo associated with this transaction. Only one of invoice or memo will be set.
|
The :class:`ReadOnlyPayment ` object, which represents a payment that was retrieved from
history.
|
[
"The",
":",
"class",
":",
"`",
"ReadOnlyPayment",
"`",
"object",
"which",
"represents",
"a",
"payment",
"that",
"was",
"retrieved",
"from",
"history",
"."
] |
class ReadOnlyPayment:
"""The :class:`ReadOnlyPayment <ReadOnlyPayment>` object, which represents a payment that was retrieved from
history.
:param sender: The :class:`PublicKey <agora.keys.PublicKey>` of the sending account.
:param destination: The :class:`PublicKey <agora.keys.PublicKey>` of the destination account.
:param tx_type: The type of this payment.
:param quarks: The amount of the payment.
:param invoice: (optional) The :class:`Invoice <agora.model.invoice.Invoice>` associated with this payment. Only one
of invoice or memo will be set.
:param memo: (optional) The text memo associated with this transaction. Only one of invoice or memo will be set.
"""
def __init__(
self, sender: PublicKey, destination: PublicKey, tx_type: TransactionType, quarks: int,
invoice: Optional[Invoice] = None, memo: Optional[str] = None
):
self.sender = sender
self.destination = destination
self.tx_type = tx_type
self.quarks = quarks
self.invoice = invoice
self.memo = memo
def __eq__(self, other):
if not isinstance(other, ReadOnlyPayment):
return False
return (self.sender == other.sender and
self.destination == other.destination and
self.tx_type == other.tx_type and
self.quarks == other.quarks and
self.invoice == other.invoice and
self.memo == other.memo)
def __repr__(self):
return f'{self.__class__.__name__}(' \
f'sender={self.sender!r}, destination={self.destination!r}, tx_type={self.tx_type!r}, ' \
f'quarks={self.quarks}, invoice={self.invoice!r}, memo={self.memo!r})'
|
[
"class",
"ReadOnlyPayment",
":",
"def",
"__init__",
"(",
"self",
",",
"sender",
":",
"PublicKey",
",",
"destination",
":",
"PublicKey",
",",
"tx_type",
":",
"TransactionType",
",",
"quarks",
":",
"int",
",",
"invoice",
":",
"Optional",
"[",
"Invoice",
"]",
"=",
"None",
",",
"memo",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
":",
"self",
".",
"sender",
"=",
"sender",
"self",
".",
"destination",
"=",
"destination",
"self",
".",
"tx_type",
"=",
"tx_type",
"self",
".",
"quarks",
"=",
"quarks",
"self",
".",
"invoice",
"=",
"invoice",
"self",
".",
"memo",
"=",
"memo",
"def",
"__eq__",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"isinstance",
"(",
"other",
",",
"ReadOnlyPayment",
")",
":",
"return",
"False",
"return",
"(",
"self",
".",
"sender",
"==",
"other",
".",
"sender",
"and",
"self",
".",
"destination",
"==",
"other",
".",
"destination",
"and",
"self",
".",
"tx_type",
"==",
"other",
".",
"tx_type",
"and",
"self",
".",
"quarks",
"==",
"other",
".",
"quarks",
"and",
"self",
".",
"invoice",
"==",
"other",
".",
"invoice",
"and",
"self",
".",
"memo",
"==",
"other",
".",
"memo",
")",
"def",
"__repr__",
"(",
"self",
")",
":",
"return",
"f'{self.__class__.__name__}('",
"f'sender={self.sender!r}, destination={self.destination!r}, tx_type={self.tx_type!r}, '",
"f'quarks={self.quarks}, invoice={self.invoice!r}, memo={self.memo!r})'"
] |
The :class:`ReadOnlyPayment <ReadOnlyPayment>` object, which represents a payment that was retrieved from
history.
|
[
"The",
":",
"class",
":",
"`",
"ReadOnlyPayment",
"<ReadOnlyPayment",
">",
"`",
"object",
"which",
"represents",
"a",
"payment",
"that",
"was",
"retrieved",
"from",
"history",
"."
] |
[
"\"\"\"The :class:`ReadOnlyPayment <ReadOnlyPayment>` object, which represents a payment that was retrieved from\n history.\n\n :param sender: The :class:`PublicKey <agora.keys.PublicKey>` of the sending account.\n :param destination: The :class:`PublicKey <agora.keys.PublicKey>` of the destination account.\n :param tx_type: The type of this payment.\n :param quarks: The amount of the payment.\n :param invoice: (optional) The :class:`Invoice <agora.model.invoice.Invoice>` associated with this payment. Only one\n of invoice or memo will be set.\n :param memo: (optional) The text memo associated with this transaction. Only one of invoice or memo will be set.\n \"\"\""
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [
{
"identifier": "sender",
"type": null,
"docstring": "The :class:`PublicKey ` of the sending account.",
"docstring_tokens": [
"The",
":",
"class",
":",
"`",
"PublicKey",
"`",
"of",
"the",
"sending",
"account",
"."
],
"default": null,
"is_optional": null
},
{
"identifier": "destination",
"type": null,
"docstring": "The :class:`PublicKey ` of the destination account.",
"docstring_tokens": [
"The",
":",
"class",
":",
"`",
"PublicKey",
"`",
"of",
"the",
"destination",
"account",
"."
],
"default": null,
"is_optional": null
},
{
"identifier": "tx_type",
"type": null,
"docstring": "The type of this payment.",
"docstring_tokens": [
"The",
"type",
"of",
"this",
"payment",
"."
],
"default": null,
"is_optional": null
},
{
"identifier": "quarks",
"type": null,
"docstring": "The amount of the payment.",
"docstring_tokens": [
"The",
"amount",
"of",
"the",
"payment",
"."
],
"default": null,
"is_optional": null
},
{
"identifier": "invoice",
"type": null,
"docstring": "(optional) The :class:`Invoice ` associated with this payment. Only one\nof invoice or memo will be set.",
"docstring_tokens": [
"(",
"optional",
")",
"The",
":",
"class",
":",
"`",
"Invoice",
"`",
"associated",
"with",
"this",
"payment",
".",
"Only",
"one",
"of",
"invoice",
"or",
"memo",
"will",
"be",
"set",
"."
],
"default": null,
"is_optional": null
},
{
"identifier": "memo",
"type": null,
"docstring": "(optional) The text memo associated with this transaction. Only one of invoice or memo will be set.",
"docstring_tokens": [
"(",
"optional",
")",
"The",
"text",
"memo",
"associated",
"with",
"this",
"transaction",
".",
"Only",
"one",
"of",
"invoice",
"or",
"memo",
"will",
"be",
"set",
"."
],
"default": null,
"is_optional": null
}
],
"others": []
}
| false
| 14
| 399
| 157
|
aa9cabc3019de1508174245592fb9af120a67e3d
|
sebastianbernasek/redundant-regulation
|
gram/execution/batch.py
|
[
"MIT"
] |
Python
|
Batch
|
Class defines a collection of batch job submissions for Quest.
Attributes:
path (str) - path to batch directory
script_name (str) - name of script for running batch
parameters (iterable) - parameter sets
simulation_paths (dict) - relative paths to simulation directories
sim_kw (dict) - keyword arguments for simulation
Properties:
N (int) - number of samples in parameter space
|
Class defines a collection of batch job submissions for Quest.
Attributes.
path (str) - path to batch directory
script_name (str) - name of script for running batch
parameters (iterable) - parameter sets
simulation_paths (dict) - relative paths to simulation directories
sim_kw (dict) - keyword arguments for simulation
N (int) - number of samples in parameter space
|
[
"Class",
"defines",
"a",
"collection",
"of",
"batch",
"job",
"submissions",
"for",
"Quest",
".",
"Attributes",
".",
"path",
"(",
"str",
")",
"-",
"path",
"to",
"batch",
"directory",
"script_name",
"(",
"str",
")",
"-",
"name",
"of",
"script",
"for",
"running",
"batch",
"parameters",
"(",
"iterable",
")",
"-",
"parameter",
"sets",
"simulation_paths",
"(",
"dict",
")",
"-",
"relative",
"paths",
"to",
"simulation",
"directories",
"sim_kw",
"(",
"dict",
")",
"-",
"keyword",
"arguments",
"for",
"simulation",
"N",
"(",
"int",
")",
"-",
"number",
"of",
"samples",
"in",
"parameter",
"space"
] |
class Batch:
"""
Class defines a collection of batch job submissions for Quest.
Attributes:
path (str) - path to batch directory
script_name (str) - name of script for running batch
parameters (iterable) - parameter sets
simulation_paths (dict) - relative paths to simulation directories
sim_kw (dict) - keyword arguments for simulation
Properties:
N (int) - number of samples in parameter space
"""
def __init__(self, parameters):
"""
Instantiate batch of jobs.
Args:
parameters (iterable) - each entry is a parameter set that defines a simulation. Parameter sets are passed to the build_model method.
"""
self.simulation_paths = {}
self.parameters = parameters
self.script_name = 'run_batch.py'
def __getitem__(self, index):
""" Returns simulation instance. """
return self.load_simulation(index)
def __iter__(self):
""" Iterate over serialized simulations. """
self.count = 0
return self
def __next__(self):
""" Returns next simulation instance. """
if self.count < len(self.simulation_paths):
simulation = self.load_simulation(self.count)
self.count += 1
return simulation
else:
raise StopIteration
@property
def N(self):
""" Number of samples in parameter space. """
return len(self.parameters)
@staticmethod
def load(path):
""" Load batch from target <path>. """
with open(join(path, 'batch.pkl'), 'rb') as file:
batch = pickle.load(file)
batch.path = path
return batch
@staticmethod
def build_run_script(path,
script_name,
num_trajectories,
saveall,
deviations,
comparison):
"""
Writes bash run script for local use.
Args:
path (str) - path to simulation top directory
script_name (str) - name of run script
num_trajectories (int) - number of simulation trajectories
saveall (bool) - if True, save simulation trajectories
deviations (bool) - if True, use deviation variables
comparison (str) - type of comparison
"""
# define paths
path = abspath(path)
job_script_path = join(path, 'scripts', 'run.sh')
# copy run script to scripts directory
run_script = abspath(__file__).rsplit('/', maxsplit=2)[0]
run_script = join(run_script, 'scripts', script_name)
shutil.copy(run_script, join(path, 'scripts'))
# declare outer script that reads PATH from file
job_script = open(job_script_path, 'w')
job_script.write('#!/bin/bash\n')
# move to batch directory
job_script.write('cd {:s} \n\n'.format(path))
# run each batch
job_script.write('echo "Starting all batches at `date`"\n')
job_script.write('while read P; do\n')
job_script.write('echo "Processing batch ${P}"\n')
job_script.write('python ./scripts/{:s}'.format(script_name)+' ${P} ')
args = (num_trajectories, saveall, deviations, comparison)
job_script.write('-N {:d} -s {:d} -d {:d} -cm {:s} \n'.format(*args))
job_script.write('done < ./batches/index.txt \n')
job_script.write('echo "Completed all batches at `date`"\n')
job_script.write('exit\n')
# close the file
job_script.close()
# change the permissions
chmod(job_script_path, 0o755)
@staticmethod
def build_submission_script(path,
script_name,
num_trajectories=5000,
saveall=False,
deviations=False,
comparison='empirical',
walltime=10,
allocation='p30653'):
"""
Writes job submission script for QUEST.
Args:
path (str) - path to simulation top directory
script_name (str) - name of run script
num_trajectories (int) - number of simulation trajectories
saveall (bool) - if True, save simulation trajectories
deviations (bool) - if True, use deviation variables
comparison (str) - type of comparison
walltime (int) - estimated job run time
allocation (str) - project allocation, e.g. p30653 (comp. bio)
"""
# define paths
path = abspath(path)
job_script_path = join(path, 'scripts', 'submit.sh')
# copy run script to scripts directory
run_script = abspath(__file__).rsplit('/', maxsplit=2)[0]
run_script = join(run_script, 'scripts', script_name)
shutil.copy(run_script, join(path, 'scripts'))
# determine queue
if walltime <= 4:
queue = 'short'
elif walltime <= 48:
queue = 'normal'
else:
queue = 'long'
# declare outer script that reads PATH from file
job_script = open(job_script_path, 'w')
job_script.write('#!/bin/bash\n')
# move to batch directory
job_script.write('cd {:s} \n\n'.format(path))
# begin outer script for processing batch
job_script.write('while IFS=$\'\\t\' read P\n')
job_script.write('do\n')
job_script.write('b_id=$(echo $(basename ${P}) | cut -f 1 -d \'.\')\n')
job_script.write(' JOB=`msub - << EOJ\n\n')
# =========== begin submission script for individual batch ============
job_script.write('#! /bin/bash\n')
job_script.write('#MSUB -A {:s} \n'.format(allocation))
job_script.write('#MSUB -q {:s} \n'.format(queue))
job_script.write('#MSUB -l walltime={0:02d}:00:00 \n'.format(walltime))
job_script.write('#MSUB -m abe \n')
#job_script.write('#MSUB -M [email protected] \n')
job_script.write('#MSUB -o ./log/${b_id}/outlog \n')
job_script.write('#MSUB -e ./log/${b_id}/errlog \n')
job_script.write('#MSUB -N ${b_id} \n')
job_script.write('#MSUB -l nodes=1:ppn=1 \n')
job_script.write('#MSUB -l mem=1gb \n\n')
# load python module and metabolism virtual environment
job_script.write('module load python/anaconda3.6\n')
job_script.write('source activate ~/pythonenvs/metabolism_env\n\n')
# move to batch directory
job_script.write('cd {:s} \n\n'.format(path))
# run script
job_script.write('python ./scripts/{:s}'.format(script_name)+' ${P} ')
args = (num_trajectories, saveall, deviations, comparison)
job_script.write('-N {:d} -s {:d} -d {:d} -cm {:s} \n'.format(*args))
job_script.write('EOJ\n')
job_script.write('`\n\n')
# ============= end submission script for individual batch ============
# print job id
#job_script.write('echo "JobID = ${JOB} submitted on `date`"\n')
job_script.write('done < ./batches/index.txt \n')
job_script.write('echo "All batches submitted as of `date`"\n')
job_script.write('exit\n')
# close the file
job_script.close()
# change the permissions
chmod(job_script_path, 0o755)
def build_batches(self, batch_size=25):
"""
Creates directory and writes simulation paths for each batch.
Args:
batch_size (int) - number of simulations per batch
"""
# get directories for all batches and logs
batches_dir = join(self.path, 'batches')
logs_dir = join(self.path, 'log')
# create index file for batches
index_path = join(batches_dir, 'index.txt')
index = open(index_path, 'w')
# write file containing simulation paths for each batch
for i, simulation_path in self.simulation_paths.items():
# determine batch ID
batch_id = i // batch_size
# process new batch
if i % batch_size == 0:
# open batch file and append to index
batch_path = join(batches_dir, '{:d}.txt'.format(batch_id))
index.write('{:s}\n'.format(relpath(batch_path, self.path)))
batch_file = open(batch_path, 'w')
# create log directory for batch
mkdir(join(logs_dir, '{:d}'.format(batch_id)))
# write paths to batch file
batch_file.write('{:s}\n'.format(simulation_path))
# close batch file
if i % batch_size == (batch_size - 1):
batch_file.close()
chmod(batch_path, 0o755)
index.close()
chmod(index_path, 0o755)
def make_directory(self, directory='./'):
"""
Create directory for batch of jobs.
Args:
directory (str) - destination path
"""
# assign name to batch
timestamp = datetime.fromtimestamp(time()).strftime('%y%m%d_%H%M%S')
name = '{:s}_{:s}'.format(self.__class__.__name__, timestamp)
# create directory (overwrite existing one)
path = join(directory, name)
if not isdir(path):
mkdir(path)
self.path = path
# make subdirectories for simulations and scripts
mkdir(join(path, 'scripts'))
mkdir(join(path, 'simulations'))
mkdir(join(path, 'batches'))
mkdir(join(path, 'log'))
def build(self,
directory='./',
batch_size=25,
num_trajectories=5000,
saveall=False,
deviations=False,
comparison='empirical',
walltime=10,
allocation='p30653',
**sim_kw):
"""
Build directory tree for a batch of jobs. Instantiates and saves a simulation instance for each parameter set, then generates a single shell script to submit each simulation as a separate job.
Args:
directory (str) - destination path
batch_size (int) - number of simulations per batch
num_trajectories (int) - number of simulation trajectories
saveall (bool) - if True, save simulation trajectories
deviations (bool) - if True, use deviation variables
comparison (str) - type of comparison
walltime (int) - estimated job run time
allocation (str) - project allocation
sim_kw (dict) - keyword arguments for ConditionSimulation
"""
# create batch directory
self.make_directory(directory)
# store parameters (e.g. pulse conditions)
self.sim_kw = sim_kw
self.batch_size = batch_size
# build simulations
for i, parameters in enumerate(self.parameters):
simulation_path = join(self.path, 'simulations', '{:d}'.format(i))
self.simulation_paths[i] = relpath(simulation_path, self.path)
self.build_simulation(parameters, simulation_path, **sim_kw)
# save serialized batch
with open(join(self.path, 'batch.pkl'), 'wb') as file:
pickle.dump(self, file, protocol=-1)
# build parameter file for each batch
self.build_batches(batch_size=batch_size)
# build job run script
self.build_run_script(self.path,
self.script_name,
num_trajectories,
saveall,
deviations,
comparison)
# build job submission script
self.build_submission_script(self.path,
self.script_name,
num_trajectories,
saveall,
deviations,
comparison,
walltime=walltime,
allocation=allocation)
@classmethod
def build_simulation(cls, parameters, simulation_path, **kwargs):
"""
Builds and saves a simulation instance for a set of parameters.
Args:
parameters (iterable) - parameter sets
simulation_path (str) - simulation path
kwargs: keyword arguments for ConditionSimulation
"""
# build model
model = cls.build_model(parameters)
# instantiate simulation
simulation = ConditionSimulation(model, **kwargs)
# create simulation directory
if not isdir(simulation_path):
mkdir(simulation_path)
# save simulation
simulation.save(simulation_path)
def load_simulation(self, index):
"""
Load simulation instance from file.
Args:
index (int) - simulation index
Returns:
simulation (ConditionSimulation)
"""
simulation_path = join(self.path, self.simulation_paths[index])
return ConditionSimulation.load(simulation_path)
def apply(self, func):
"""
Applies function to entire batch of simulations.
Args:
func (function) - function operating on a simulation instance
Returns:
output (dict) - {simulation_id: function output} pairs
"""
f = lambda path: func(ConditionSimulation.load(path))
return {i: f(p) for i, p in self.simulation_paths.items()}
|
[
"class",
"Batch",
":",
"def",
"__init__",
"(",
"self",
",",
"parameters",
")",
":",
"\"\"\"\n Instantiate batch of jobs.\n\n Args:\n\n parameters (iterable) - each entry is a parameter set that defines a simulation. Parameter sets are passed to the build_model method.\n\n \"\"\"",
"self",
".",
"simulation_paths",
"=",
"{",
"}",
"self",
".",
"parameters",
"=",
"parameters",
"self",
".",
"script_name",
"=",
"'run_batch.py'",
"def",
"__getitem__",
"(",
"self",
",",
"index",
")",
":",
"\"\"\" Returns simulation instance. \"\"\"",
"return",
"self",
".",
"load_simulation",
"(",
"index",
")",
"def",
"__iter__",
"(",
"self",
")",
":",
"\"\"\" Iterate over serialized simulations. \"\"\"",
"self",
".",
"count",
"=",
"0",
"return",
"self",
"def",
"__next__",
"(",
"self",
")",
":",
"\"\"\" Returns next simulation instance. \"\"\"",
"if",
"self",
".",
"count",
"<",
"len",
"(",
"self",
".",
"simulation_paths",
")",
":",
"simulation",
"=",
"self",
".",
"load_simulation",
"(",
"self",
".",
"count",
")",
"self",
".",
"count",
"+=",
"1",
"return",
"simulation",
"else",
":",
"raise",
"StopIteration",
"@",
"property",
"def",
"N",
"(",
"self",
")",
":",
"\"\"\" Number of samples in parameter space. \"\"\"",
"return",
"len",
"(",
"self",
".",
"parameters",
")",
"@",
"staticmethod",
"def",
"load",
"(",
"path",
")",
":",
"\"\"\" Load batch from target <path>. \"\"\"",
"with",
"open",
"(",
"join",
"(",
"path",
",",
"'batch.pkl'",
")",
",",
"'rb'",
")",
"as",
"file",
":",
"batch",
"=",
"pickle",
".",
"load",
"(",
"file",
")",
"batch",
".",
"path",
"=",
"path",
"return",
"batch",
"@",
"staticmethod",
"def",
"build_run_script",
"(",
"path",
",",
"script_name",
",",
"num_trajectories",
",",
"saveall",
",",
"deviations",
",",
"comparison",
")",
":",
"\"\"\"\n Writes bash run script for local use.\n\n Args:\n\n path (str) - path to simulation top directory\n\n script_name (str) - name of run script\n\n num_trajectories (int) - number of simulation trajectories\n\n saveall (bool) - if True, save simulation trajectories\n\n deviations (bool) - if True, use deviation variables\n\n comparison (str) - type of comparison\n\n \"\"\"",
"path",
"=",
"abspath",
"(",
"path",
")",
"job_script_path",
"=",
"join",
"(",
"path",
",",
"'scripts'",
",",
"'run.sh'",
")",
"run_script",
"=",
"abspath",
"(",
"__file__",
")",
".",
"rsplit",
"(",
"'/'",
",",
"maxsplit",
"=",
"2",
")",
"[",
"0",
"]",
"run_script",
"=",
"join",
"(",
"run_script",
",",
"'scripts'",
",",
"script_name",
")",
"shutil",
".",
"copy",
"(",
"run_script",
",",
"join",
"(",
"path",
",",
"'scripts'",
")",
")",
"job_script",
"=",
"open",
"(",
"job_script_path",
",",
"'w'",
")",
"job_script",
".",
"write",
"(",
"'#!/bin/bash\\n'",
")",
"job_script",
".",
"write",
"(",
"'cd {:s} \\n\\n'",
".",
"format",
"(",
"path",
")",
")",
"job_script",
".",
"write",
"(",
"'echo \"Starting all batches at `date`\"\\n'",
")",
"job_script",
".",
"write",
"(",
"'while read P; do\\n'",
")",
"job_script",
".",
"write",
"(",
"'echo \"Processing batch ${P}\"\\n'",
")",
"job_script",
".",
"write",
"(",
"'python ./scripts/{:s}'",
".",
"format",
"(",
"script_name",
")",
"+",
"' ${P} '",
")",
"args",
"=",
"(",
"num_trajectories",
",",
"saveall",
",",
"deviations",
",",
"comparison",
")",
"job_script",
".",
"write",
"(",
"'-N {:d} -s {:d} -d {:d} -cm {:s} \\n'",
".",
"format",
"(",
"*",
"args",
")",
")",
"job_script",
".",
"write",
"(",
"'done < ./batches/index.txt \\n'",
")",
"job_script",
".",
"write",
"(",
"'echo \"Completed all batches at `date`\"\\n'",
")",
"job_script",
".",
"write",
"(",
"'exit\\n'",
")",
"job_script",
".",
"close",
"(",
")",
"chmod",
"(",
"job_script_path",
",",
"0o755",
")",
"@",
"staticmethod",
"def",
"build_submission_script",
"(",
"path",
",",
"script_name",
",",
"num_trajectories",
"=",
"5000",
",",
"saveall",
"=",
"False",
",",
"deviations",
"=",
"False",
",",
"comparison",
"=",
"'empirical'",
",",
"walltime",
"=",
"10",
",",
"allocation",
"=",
"'p30653'",
")",
":",
"\"\"\"\n Writes job submission script for QUEST.\n\n Args:\n\n path (str) - path to simulation top directory\n\n script_name (str) - name of run script\n\n num_trajectories (int) - number of simulation trajectories\n\n saveall (bool) - if True, save simulation trajectories\n\n deviations (bool) - if True, use deviation variables\n\n comparison (str) - type of comparison\n\n walltime (int) - estimated job run time\n\n allocation (str) - project allocation, e.g. p30653 (comp. bio)\n\n \"\"\"",
"path",
"=",
"abspath",
"(",
"path",
")",
"job_script_path",
"=",
"join",
"(",
"path",
",",
"'scripts'",
",",
"'submit.sh'",
")",
"run_script",
"=",
"abspath",
"(",
"__file__",
")",
".",
"rsplit",
"(",
"'/'",
",",
"maxsplit",
"=",
"2",
")",
"[",
"0",
"]",
"run_script",
"=",
"join",
"(",
"run_script",
",",
"'scripts'",
",",
"script_name",
")",
"shutil",
".",
"copy",
"(",
"run_script",
",",
"join",
"(",
"path",
",",
"'scripts'",
")",
")",
"if",
"walltime",
"<=",
"4",
":",
"queue",
"=",
"'short'",
"elif",
"walltime",
"<=",
"48",
":",
"queue",
"=",
"'normal'",
"else",
":",
"queue",
"=",
"'long'",
"job_script",
"=",
"open",
"(",
"job_script_path",
",",
"'w'",
")",
"job_script",
".",
"write",
"(",
"'#!/bin/bash\\n'",
")",
"job_script",
".",
"write",
"(",
"'cd {:s} \\n\\n'",
".",
"format",
"(",
"path",
")",
")",
"job_script",
".",
"write",
"(",
"'while IFS=$\\'\\\\t\\' read P\\n'",
")",
"job_script",
".",
"write",
"(",
"'do\\n'",
")",
"job_script",
".",
"write",
"(",
"'b_id=$(echo $(basename ${P}) | cut -f 1 -d \\'.\\')\\n'",
")",
"job_script",
".",
"write",
"(",
"' JOB=`msub - << EOJ\\n\\n'",
")",
"job_script",
".",
"write",
"(",
"'#! /bin/bash\\n'",
")",
"job_script",
".",
"write",
"(",
"'#MSUB -A {:s} \\n'",
".",
"format",
"(",
"allocation",
")",
")",
"job_script",
".",
"write",
"(",
"'#MSUB -q {:s} \\n'",
".",
"format",
"(",
"queue",
")",
")",
"job_script",
".",
"write",
"(",
"'#MSUB -l walltime={0:02d}:00:00 \\n'",
".",
"format",
"(",
"walltime",
")",
")",
"job_script",
".",
"write",
"(",
"'#MSUB -m abe \\n'",
")",
"job_script",
".",
"write",
"(",
"'#MSUB -o ./log/${b_id}/outlog \\n'",
")",
"job_script",
".",
"write",
"(",
"'#MSUB -e ./log/${b_id}/errlog \\n'",
")",
"job_script",
".",
"write",
"(",
"'#MSUB -N ${b_id} \\n'",
")",
"job_script",
".",
"write",
"(",
"'#MSUB -l nodes=1:ppn=1 \\n'",
")",
"job_script",
".",
"write",
"(",
"'#MSUB -l mem=1gb \\n\\n'",
")",
"job_script",
".",
"write",
"(",
"'module load python/anaconda3.6\\n'",
")",
"job_script",
".",
"write",
"(",
"'source activate ~/pythonenvs/metabolism_env\\n\\n'",
")",
"job_script",
".",
"write",
"(",
"'cd {:s} \\n\\n'",
".",
"format",
"(",
"path",
")",
")",
"job_script",
".",
"write",
"(",
"'python ./scripts/{:s}'",
".",
"format",
"(",
"script_name",
")",
"+",
"' ${P} '",
")",
"args",
"=",
"(",
"num_trajectories",
",",
"saveall",
",",
"deviations",
",",
"comparison",
")",
"job_script",
".",
"write",
"(",
"'-N {:d} -s {:d} -d {:d} -cm {:s} \\n'",
".",
"format",
"(",
"*",
"args",
")",
")",
"job_script",
".",
"write",
"(",
"'EOJ\\n'",
")",
"job_script",
".",
"write",
"(",
"'`\\n\\n'",
")",
"job_script",
".",
"write",
"(",
"'done < ./batches/index.txt \\n'",
")",
"job_script",
".",
"write",
"(",
"'echo \"All batches submitted as of `date`\"\\n'",
")",
"job_script",
".",
"write",
"(",
"'exit\\n'",
")",
"job_script",
".",
"close",
"(",
")",
"chmod",
"(",
"job_script_path",
",",
"0o755",
")",
"def",
"build_batches",
"(",
"self",
",",
"batch_size",
"=",
"25",
")",
":",
"\"\"\"\n Creates directory and writes simulation paths for each batch.\n\n Args:\n\n batch_size (int) - number of simulations per batch\n\n \"\"\"",
"batches_dir",
"=",
"join",
"(",
"self",
".",
"path",
",",
"'batches'",
")",
"logs_dir",
"=",
"join",
"(",
"self",
".",
"path",
",",
"'log'",
")",
"index_path",
"=",
"join",
"(",
"batches_dir",
",",
"'index.txt'",
")",
"index",
"=",
"open",
"(",
"index_path",
",",
"'w'",
")",
"for",
"i",
",",
"simulation_path",
"in",
"self",
".",
"simulation_paths",
".",
"items",
"(",
")",
":",
"batch_id",
"=",
"i",
"//",
"batch_size",
"if",
"i",
"%",
"batch_size",
"==",
"0",
":",
"batch_path",
"=",
"join",
"(",
"batches_dir",
",",
"'{:d}.txt'",
".",
"format",
"(",
"batch_id",
")",
")",
"index",
".",
"write",
"(",
"'{:s}\\n'",
".",
"format",
"(",
"relpath",
"(",
"batch_path",
",",
"self",
".",
"path",
")",
")",
")",
"batch_file",
"=",
"open",
"(",
"batch_path",
",",
"'w'",
")",
"mkdir",
"(",
"join",
"(",
"logs_dir",
",",
"'{:d}'",
".",
"format",
"(",
"batch_id",
")",
")",
")",
"batch_file",
".",
"write",
"(",
"'{:s}\\n'",
".",
"format",
"(",
"simulation_path",
")",
")",
"if",
"i",
"%",
"batch_size",
"==",
"(",
"batch_size",
"-",
"1",
")",
":",
"batch_file",
".",
"close",
"(",
")",
"chmod",
"(",
"batch_path",
",",
"0o755",
")",
"index",
".",
"close",
"(",
")",
"chmod",
"(",
"index_path",
",",
"0o755",
")",
"def",
"make_directory",
"(",
"self",
",",
"directory",
"=",
"'./'",
")",
":",
"\"\"\"\n Create directory for batch of jobs.\n\n Args:\n\n directory (str) - destination path\n\n \"\"\"",
"timestamp",
"=",
"datetime",
".",
"fromtimestamp",
"(",
"time",
"(",
")",
")",
".",
"strftime",
"(",
"'%y%m%d_%H%M%S'",
")",
"name",
"=",
"'{:s}_{:s}'",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"timestamp",
")",
"path",
"=",
"join",
"(",
"directory",
",",
"name",
")",
"if",
"not",
"isdir",
"(",
"path",
")",
":",
"mkdir",
"(",
"path",
")",
"self",
".",
"path",
"=",
"path",
"mkdir",
"(",
"join",
"(",
"path",
",",
"'scripts'",
")",
")",
"mkdir",
"(",
"join",
"(",
"path",
",",
"'simulations'",
")",
")",
"mkdir",
"(",
"join",
"(",
"path",
",",
"'batches'",
")",
")",
"mkdir",
"(",
"join",
"(",
"path",
",",
"'log'",
")",
")",
"def",
"build",
"(",
"self",
",",
"directory",
"=",
"'./'",
",",
"batch_size",
"=",
"25",
",",
"num_trajectories",
"=",
"5000",
",",
"saveall",
"=",
"False",
",",
"deviations",
"=",
"False",
",",
"comparison",
"=",
"'empirical'",
",",
"walltime",
"=",
"10",
",",
"allocation",
"=",
"'p30653'",
",",
"**",
"sim_kw",
")",
":",
"\"\"\"\n Build directory tree for a batch of jobs. Instantiates and saves a simulation instance for each parameter set, then generates a single shell script to submit each simulation as a separate job.\n\n Args:\n\n directory (str) - destination path\n\n batch_size (int) - number of simulations per batch\n\n num_trajectories (int) - number of simulation trajectories\n\n saveall (bool) - if True, save simulation trajectories\n\n deviations (bool) - if True, use deviation variables\n\n comparison (str) - type of comparison\n\n walltime (int) - estimated job run time\n\n allocation (str) - project allocation\n\n sim_kw (dict) - keyword arguments for ConditionSimulation\n\n \"\"\"",
"self",
".",
"make_directory",
"(",
"directory",
")",
"self",
".",
"sim_kw",
"=",
"sim_kw",
"self",
".",
"batch_size",
"=",
"batch_size",
"for",
"i",
",",
"parameters",
"in",
"enumerate",
"(",
"self",
".",
"parameters",
")",
":",
"simulation_path",
"=",
"join",
"(",
"self",
".",
"path",
",",
"'simulations'",
",",
"'{:d}'",
".",
"format",
"(",
"i",
")",
")",
"self",
".",
"simulation_paths",
"[",
"i",
"]",
"=",
"relpath",
"(",
"simulation_path",
",",
"self",
".",
"path",
")",
"self",
".",
"build_simulation",
"(",
"parameters",
",",
"simulation_path",
",",
"**",
"sim_kw",
")",
"with",
"open",
"(",
"join",
"(",
"self",
".",
"path",
",",
"'batch.pkl'",
")",
",",
"'wb'",
")",
"as",
"file",
":",
"pickle",
".",
"dump",
"(",
"self",
",",
"file",
",",
"protocol",
"=",
"-",
"1",
")",
"self",
".",
"build_batches",
"(",
"batch_size",
"=",
"batch_size",
")",
"self",
".",
"build_run_script",
"(",
"self",
".",
"path",
",",
"self",
".",
"script_name",
",",
"num_trajectories",
",",
"saveall",
",",
"deviations",
",",
"comparison",
")",
"self",
".",
"build_submission_script",
"(",
"self",
".",
"path",
",",
"self",
".",
"script_name",
",",
"num_trajectories",
",",
"saveall",
",",
"deviations",
",",
"comparison",
",",
"walltime",
"=",
"walltime",
",",
"allocation",
"=",
"allocation",
")",
"@",
"classmethod",
"def",
"build_simulation",
"(",
"cls",
",",
"parameters",
",",
"simulation_path",
",",
"**",
"kwargs",
")",
":",
"\"\"\"\n Builds and saves a simulation instance for a set of parameters.\n\n Args:\n\n parameters (iterable) - parameter sets\n\n simulation_path (str) - simulation path\n\n kwargs: keyword arguments for ConditionSimulation\n\n \"\"\"",
"model",
"=",
"cls",
".",
"build_model",
"(",
"parameters",
")",
"simulation",
"=",
"ConditionSimulation",
"(",
"model",
",",
"**",
"kwargs",
")",
"if",
"not",
"isdir",
"(",
"simulation_path",
")",
":",
"mkdir",
"(",
"simulation_path",
")",
"simulation",
".",
"save",
"(",
"simulation_path",
")",
"def",
"load_simulation",
"(",
"self",
",",
"index",
")",
":",
"\"\"\"\n Load simulation instance from file.\n\n Args:\n\n index (int) - simulation index\n\n Returns:\n\n simulation (ConditionSimulation)\n\n \"\"\"",
"simulation_path",
"=",
"join",
"(",
"self",
".",
"path",
",",
"self",
".",
"simulation_paths",
"[",
"index",
"]",
")",
"return",
"ConditionSimulation",
".",
"load",
"(",
"simulation_path",
")",
"def",
"apply",
"(",
"self",
",",
"func",
")",
":",
"\"\"\"\n Applies function to entire batch of simulations.\n\n Args:\n\n func (function) - function operating on a simulation instance\n\n Returns:\n\n output (dict) - {simulation_id: function output} pairs\n\n \"\"\"",
"f",
"=",
"lambda",
"path",
":",
"func",
"(",
"ConditionSimulation",
".",
"load",
"(",
"path",
")",
")",
"return",
"{",
"i",
":",
"f",
"(",
"p",
")",
"for",
"i",
",",
"p",
"in",
"self",
".",
"simulation_paths",
".",
"items",
"(",
")",
"}"
] |
Class defines a collection of batch job submissions for Quest.
|
[
"Class",
"defines",
"a",
"collection",
"of",
"batch",
"job",
"submissions",
"for",
"Quest",
"."
] |
[
"\"\"\"\n Class defines a collection of batch job submissions for Quest.\n\n Attributes:\n\n path (str) - path to batch directory\n\n script_name (str) - name of script for running batch\n\n parameters (iterable) - parameter sets\n\n simulation_paths (dict) - relative paths to simulation directories\n\n sim_kw (dict) - keyword arguments for simulation\n\n Properties:\n\n N (int) - number of samples in parameter space\n\n \"\"\"",
"\"\"\"\n Instantiate batch of jobs.\n\n Args:\n\n parameters (iterable) - each entry is a parameter set that defines a simulation. Parameter sets are passed to the build_model method.\n\n \"\"\"",
"\"\"\" Returns simulation instance. \"\"\"",
"\"\"\" Iterate over serialized simulations. \"\"\"",
"\"\"\" Returns next simulation instance. \"\"\"",
"\"\"\" Number of samples in parameter space. \"\"\"",
"\"\"\" Load batch from target <path>. \"\"\"",
"\"\"\"\n Writes bash run script for local use.\n\n Args:\n\n path (str) - path to simulation top directory\n\n script_name (str) - name of run script\n\n num_trajectories (int) - number of simulation trajectories\n\n saveall (bool) - if True, save simulation trajectories\n\n deviations (bool) - if True, use deviation variables\n\n comparison (str) - type of comparison\n\n \"\"\"",
"# define paths",
"# copy run script to scripts directory",
"# declare outer script that reads PATH from file",
"# move to batch directory",
"# run each batch",
"# close the file",
"# change the permissions",
"\"\"\"\n Writes job submission script for QUEST.\n\n Args:\n\n path (str) - path to simulation top directory\n\n script_name (str) - name of run script\n\n num_trajectories (int) - number of simulation trajectories\n\n saveall (bool) - if True, save simulation trajectories\n\n deviations (bool) - if True, use deviation variables\n\n comparison (str) - type of comparison\n\n walltime (int) - estimated job run time\n\n allocation (str) - project allocation, e.g. p30653 (comp. bio)\n\n \"\"\"",
"# define paths",
"# copy run script to scripts directory",
"# determine queue",
"# declare outer script that reads PATH from file",
"# move to batch directory",
"# begin outer script for processing batch",
"# =========== begin submission script for individual batch ============",
"#job_script.write('#MSUB -M [email protected] \\n')",
"# load python module and metabolism virtual environment",
"# move to batch directory",
"# run script",
"# ============= end submission script for individual batch ============",
"# print job id",
"#job_script.write('echo \"JobID = ${JOB} submitted on `date`\"\\n')",
"# close the file",
"# change the permissions",
"\"\"\"\n Creates directory and writes simulation paths for each batch.\n\n Args:\n\n batch_size (int) - number of simulations per batch\n\n \"\"\"",
"# get directories for all batches and logs",
"# create index file for batches",
"# write file containing simulation paths for each batch",
"# determine batch ID",
"# process new batch",
"# open batch file and append to index",
"# create log directory for batch",
"# write paths to batch file",
"# close batch file",
"\"\"\"\n Create directory for batch of jobs.\n\n Args:\n\n directory (str) - destination path\n\n \"\"\"",
"# assign name to batch",
"# create directory (overwrite existing one)",
"# make subdirectories for simulations and scripts",
"\"\"\"\n Build directory tree for a batch of jobs. Instantiates and saves a simulation instance for each parameter set, then generates a single shell script to submit each simulation as a separate job.\n\n Args:\n\n directory (str) - destination path\n\n batch_size (int) - number of simulations per batch\n\n num_trajectories (int) - number of simulation trajectories\n\n saveall (bool) - if True, save simulation trajectories\n\n deviations (bool) - if True, use deviation variables\n\n comparison (str) - type of comparison\n\n walltime (int) - estimated job run time\n\n allocation (str) - project allocation\n\n sim_kw (dict) - keyword arguments for ConditionSimulation\n\n \"\"\"",
"# create batch directory",
"# store parameters (e.g. pulse conditions)",
"# build simulations",
"# save serialized batch",
"# build parameter file for each batch",
"# build job run script",
"# build job submission script",
"\"\"\"\n Builds and saves a simulation instance for a set of parameters.\n\n Args:\n\n parameters (iterable) - parameter sets\n\n simulation_path (str) - simulation path\n\n kwargs: keyword arguments for ConditionSimulation\n\n \"\"\"",
"# build model",
"# instantiate simulation",
"# create simulation directory",
"# save simulation",
"\"\"\"\n Load simulation instance from file.\n\n Args:\n\n index (int) - simulation index\n\n Returns:\n\n simulation (ConditionSimulation)\n\n \"\"\"",
"\"\"\"\n Applies function to entire batch of simulations.\n\n Args:\n\n func (function) - function operating on a simulation instance\n\n Returns:\n\n output (dict) - {simulation_id: function output} pairs\n\n \"\"\""
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 17
| 2,923
| 93
|
8b0fc4785fb12fdc0a53cafee189d4b55a0b62ca
|
friedenberg/google-ads-dotnet
|
examples/ShoppingAds/AddPerformanceMaxProductListingGroupTree.cs
|
[
"Apache-2.0"
] |
C#
|
AssetGroupListingGroupFilterRemoveOperationFactory
|
/// <summary>
/// A factory that creates MutateOperation's for removing an existing tree of
/// AssetGroupListingGroupFilter's.
///
/// AssetGroupListingGroupFilter's must be removed in a specific order: all of the children
/// of a filter must be removed before the filter itself, otherwise the API will return an
/// error.
///
/// This object is intended to be used with an array of MutateOperations to perform a series
/// of related updates to an AssetGroup.
/// </summary>
|
A factory that creates MutateOperation's for removing an existing tree of
AssetGroupListingGroupFilter's.
AssetGroupListingGroupFilter's must be removed in a specific order: all of the children
of a filter must be removed before the filter itself, otherwise the API will return an
error.
This object is intended to be used with an array of MutateOperations to perform a series
of related updates to an AssetGroup.
|
[
"A",
"factory",
"that",
"creates",
"MutateOperation",
"'",
"s",
"for",
"removing",
"an",
"existing",
"tree",
"of",
"AssetGroupListingGroupFilter",
"'",
"s",
".",
"AssetGroupListingGroupFilter",
"'",
"s",
"must",
"be",
"removed",
"in",
"a",
"specific",
"order",
":",
"all",
"of",
"the",
"children",
"of",
"a",
"filter",
"must",
"be",
"removed",
"before",
"the",
"filter",
"itself",
"otherwise",
"the",
"API",
"will",
"return",
"an",
"error",
".",
"This",
"object",
"is",
"intended",
"to",
"be",
"used",
"with",
"an",
"array",
"of",
"MutateOperations",
"to",
"perform",
"a",
"series",
"of",
"related",
"updates",
"to",
"an",
"AssetGroup",
"."
] |
private class AssetGroupListingGroupFilterRemoveOperationFactory {
private string rootResourceName;
private Dictionary<string, AssetGroupListingGroupFilter> resources;
private Dictionary<string, HashSet<string>> parentsToChildren;
public AssetGroupListingGroupFilterRemoveOperationFactory(
List<AssetGroupListingGroupFilter> resources)
{
if (resources.Count == 0) {
throw new InvalidOperationException("No listing group filters to remove");
}
this.resources = new Dictionary<string, AssetGroupListingGroupFilter>();
this.parentsToChildren = new Dictionary<string, HashSet<string>>();
foreach (AssetGroupListingGroupFilter filter in resources)
{
this.resources[filter.ResourceName] = filter;
if (string.IsNullOrEmpty(filter.ParentListingGroupFilter))
{
if (!string.IsNullOrEmpty(this.rootResourceName))
{
throw new InvalidOperationException("More than one root node");
}
this.rootResourceName = filter.ResourceName;
continue;
}
string parentResourceName = filter.ParentListingGroupFilter;
HashSet<string> siblings;
if (this.parentsToChildren.ContainsKey(parentResourceName))
{
siblings = this.parentsToChildren[parentResourceName];
} else {
siblings = new HashSet<string>();
}
siblings.Add(filter.ResourceName);
this.parentsToChildren[parentResourceName] = siblings;
}
}
public List<MutateOperation> RemoveAll()
{
return this.RemoveDescendentsAndFilter(this.rootResourceName);
}
public List<MutateOperation> RemoveDescendentsAndFilter(string resourceName)
{
List<MutateOperation> operations = new List<MutateOperation>();
if (this.parentsToChildren.ContainsKey(resourceName))
{
HashSet<string> children = this.parentsToChildren[resourceName];
foreach (string child in children)
{
operations.AddRange(this.RemoveDescendentsAndFilter(child));
}
}
AssetGroupListingGroupFilterOperation operation =
new AssetGroupListingGroupFilterOperation()
{
Remove = resourceName
};
operations.Add(
new MutateOperation()
{
AssetGroupListingGroupFilterOperation = operation
}
);
return operations;
}
}
|
[
"private",
"class",
"AssetGroupListingGroupFilterRemoveOperationFactory",
"{",
"private",
"string",
"rootResourceName",
";",
"private",
"Dictionary",
"<",
"string",
",",
"AssetGroupListingGroupFilter",
">",
"resources",
";",
"private",
"Dictionary",
"<",
"string",
",",
"HashSet",
"<",
"string",
">",
">",
"parentsToChildren",
";",
"public",
"AssetGroupListingGroupFilterRemoveOperationFactory",
"(",
"List",
"<",
"AssetGroupListingGroupFilter",
">",
"resources",
")",
"{",
"if",
"(",
"resources",
".",
"Count",
"==",
"0",
")",
"{",
"throw",
"new",
"InvalidOperationException",
"(",
"\"",
"No listing group filters to remove",
"\"",
")",
";",
"}",
"this",
".",
"resources",
"=",
"new",
"Dictionary",
"<",
"string",
",",
"AssetGroupListingGroupFilter",
">",
"(",
")",
";",
"this",
".",
"parentsToChildren",
"=",
"new",
"Dictionary",
"<",
"string",
",",
"HashSet",
"<",
"string",
">",
">",
"(",
")",
";",
"foreach",
"(",
"AssetGroupListingGroupFilter",
"filter",
"in",
"resources",
")",
"{",
"this",
".",
"resources",
"[",
"filter",
".",
"ResourceName",
"]",
"=",
"filter",
";",
"if",
"(",
"string",
".",
"IsNullOrEmpty",
"(",
"filter",
".",
"ParentListingGroupFilter",
")",
")",
"{",
"if",
"(",
"!",
"string",
".",
"IsNullOrEmpty",
"(",
"this",
".",
"rootResourceName",
")",
")",
"{",
"throw",
"new",
"InvalidOperationException",
"(",
"\"",
"More than one root node",
"\"",
")",
";",
"}",
"this",
".",
"rootResourceName",
"=",
"filter",
".",
"ResourceName",
";",
"continue",
";",
"}",
"string",
"parentResourceName",
"=",
"filter",
".",
"ParentListingGroupFilter",
";",
"HashSet",
"<",
"string",
">",
"siblings",
";",
"if",
"(",
"this",
".",
"parentsToChildren",
".",
"ContainsKey",
"(",
"parentResourceName",
")",
")",
"{",
"siblings",
"=",
"this",
".",
"parentsToChildren",
"[",
"parentResourceName",
"]",
";",
"}",
"else",
"{",
"siblings",
"=",
"new",
"HashSet",
"<",
"string",
">",
"(",
")",
";",
"}",
"siblings",
".",
"Add",
"(",
"filter",
".",
"ResourceName",
")",
";",
"this",
".",
"parentsToChildren",
"[",
"parentResourceName",
"]",
"=",
"siblings",
";",
"}",
"}",
"public",
"List",
"<",
"MutateOperation",
">",
"RemoveAll",
"(",
")",
"{",
"return",
"this",
".",
"RemoveDescendentsAndFilter",
"(",
"this",
".",
"rootResourceName",
")",
";",
"}",
"public",
"List",
"<",
"MutateOperation",
">",
"RemoveDescendentsAndFilter",
"(",
"string",
"resourceName",
")",
"{",
"List",
"<",
"MutateOperation",
">",
"operations",
"=",
"new",
"List",
"<",
"MutateOperation",
">",
"(",
")",
";",
"if",
"(",
"this",
".",
"parentsToChildren",
".",
"ContainsKey",
"(",
"resourceName",
")",
")",
"{",
"HashSet",
"<",
"string",
">",
"children",
"=",
"this",
".",
"parentsToChildren",
"[",
"resourceName",
"]",
";",
"foreach",
"(",
"string",
"child",
"in",
"children",
")",
"{",
"operations",
".",
"AddRange",
"(",
"this",
".",
"RemoveDescendentsAndFilter",
"(",
"child",
")",
")",
";",
"}",
"}",
"AssetGroupListingGroupFilterOperation",
"operation",
"=",
"new",
"AssetGroupListingGroupFilterOperation",
"(",
")",
"{",
"Remove",
"=",
"resourceName",
"}",
";",
"operations",
".",
"Add",
"(",
"new",
"MutateOperation",
"(",
")",
"{",
"AssetGroupListingGroupFilterOperation",
"=",
"operation",
"}",
")",
";",
"return",
"operations",
";",
"}",
"}"
] |
A factory that creates MutateOperation's for removing an existing tree of
AssetGroupListingGroupFilter's.
|
[
"A",
"factory",
"that",
"creates",
"MutateOperation",
"'",
"s",
"for",
"removing",
"an",
"existing",
"tree",
"of",
"AssetGroupListingGroupFilter",
"'",
"s",
"."
] |
[
"// When the node has no parent, it means it's the root node, which is treated",
"// differently.",
"// Check to see if we've already visited a sibling in this group, and fetch or",
"// create a new set as required.",
"// [START add_performance_max_product_listing_group_tree_2]",
"/// <summary>",
"/// Creates a list of MutateOperation's that remove all of the resources in the tree",
"/// originally used to create this factory object.",
"/// </summary>",
"/// <returns>A list of MutateOperation's</returns>",
"// [END add_performance_max_product_listing_group_tree_2]",
"// [START add_performance_max_product_listing_group_tree_3]",
"/// <summary>",
"/// Creates a list of MutateOperation's that remove all the descendents of the specified",
"/// AssetGroupListingGroupFilter resource name. The order of removal is post-order,",
"/// where all the children (and their children, recursively) are removed first. Then,",
"/// the node itself is removed.",
"/// </summary>",
"/// <returns>A list of MutateOperation's</returns>",
"// [END add_performance_max_product_listing_group_tree_3]"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 16
| 453
| 105
|
4946de4c5a56e73bae09c65728fb64dc7e7e5ea9
|
RegisJesuitRobotics/AllRobots
|
src/main/java/frc/robot/RobotContainer.java
|
[
"BSD-3-Clause"
] |
Java
|
RobotContainer
|
/**
* This class is where the bulk of the robot should be declared. Since Command-based is a
* "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot}
* periodic methods (other than the scheduler calls). Instead, the structure of the robot (including
* subsystems, commands, and button mappings) should be declared here.
*/
|
This class is where the bulk of the robot should be declared. Since Command-based is a
"declarative" paradigm, very little robot logic should actually be handled in the Robot
periodic methods (other than the scheduler calls). Instead, the structure of the robot (including
subsystems, commands, and button mappings) should be declared here.
|
[
"This",
"class",
"is",
"where",
"the",
"bulk",
"of",
"the",
"robot",
"should",
"be",
"declared",
".",
"Since",
"Command",
"-",
"based",
"is",
"a",
"\"",
"declarative",
"\"",
"paradigm",
"very",
"little",
"robot",
"logic",
"should",
"actually",
"be",
"handled",
"in",
"the",
"Robot",
"periodic",
"methods",
"(",
"other",
"than",
"the",
"scheduler",
"calls",
")",
".",
"Instead",
"the",
"structure",
"of",
"the",
"robot",
"(",
"including",
"subsystems",
"commands",
"and",
"button",
"mappings",
")",
"should",
"be",
"declared",
"here",
"."
] |
public class RobotContainer {
// The robot's subsystems and commands are defined here...
enum Robots {
VEX,
ROMI
}
private final SendableChooser<Robots> robotChooser = new SendableChooser<>();
// Subsystems
ISubsystems subsystems = new frc.robot.subsystems.romi.RomiSubsystems();
// ISubsystems subsystems = new frc.robot.subsystems.vex.VexSubsystems();
// Commands
/** The container for the robot. Contains subsystems, OI devices, and commands. */
public RobotContainer() {
// Configure the button bindings
configureButtonBindings();
robotChooser.addOption("Vex", Robots.VEX);
robotChooser.addOption("Romi", Robots.ROMI);
SmartDashboard.putData(robotChooser);
// if (robotChooser.getSelected() == Robots.VEX) {
// subsystems = new frc.robot.subsystems.vex.VexSubsystems();
// } else {
// subsystems = new frc.robot.subsystems.romi.RomiSubsystems();
// }
subsystems.initialize();
}
/**
* Use this method to define your button->command mappings. Buttons can be created by
* instantiating a {@link GenericHID} or one of its subclasses ({@link
* edu.wpi.first.wpilibj.Joystick} or {@link XboxController}), and then passing it to a {@link
* edu.wpi.first.wpilibj2.command.button.JoystickButton}.
*/
private void configureButtonBindings() {}
/**
* Use this to pass the autonomous command to the main {@link Robot} class.
*
* @return the command to run in autonomous
*/
public Command getAutonomousCommand() {
// An ExampleCommand will run in autonomous
// return m_autoCommand;
// return null;
// return new DriveTime(0.8, 5, subsystems.getChassis());
// return new DriveDistance(0.8, 1, subsystems.getChassis(), subsystems.getWheelEncoders());
return new DriveDistancePidCommand(1, subsystems);
}
public Command getDriveCommand() {
return new RunCommand(
() ->
subsystems
.getChassis()
.drive(
subsystems.getDriver().getY(),
subsystems.getDriver().getX()),
subsystems.getChassis());
}
// Default operator drive command
// subsystems.getChassis().setDefaultCommand(
// new RunCommand(() -> subsystems.getChassis().drive(
// subsystems.getDriver().getY(),
// subsystems.getDriver().getX()),
// subsystems.getChassis()));
}
|
[
"public",
"class",
"RobotContainer",
"{",
"enum",
"Robots",
"{",
"VEX",
",",
"ROMI",
"}",
"private",
"final",
"SendableChooser",
"<",
"Robots",
">",
"robotChooser",
"=",
"new",
"SendableChooser",
"<",
">",
"(",
")",
";",
"ISubsystems",
"subsystems",
"=",
"new",
"frc",
".",
"robot",
".",
"subsystems",
".",
"romi",
".",
"RomiSubsystems",
"(",
")",
";",
"/** The container for the robot. Contains subsystems, OI devices, and commands. */",
"public",
"RobotContainer",
"(",
")",
"{",
"configureButtonBindings",
"(",
")",
";",
"robotChooser",
".",
"addOption",
"(",
"\"",
"Vex",
"\"",
",",
"Robots",
".",
"VEX",
")",
";",
"robotChooser",
".",
"addOption",
"(",
"\"",
"Romi",
"\"",
",",
"Robots",
".",
"ROMI",
")",
";",
"SmartDashboard",
".",
"putData",
"(",
"robotChooser",
")",
";",
"subsystems",
".",
"initialize",
"(",
")",
";",
"}",
"/**\n * Use this method to define your button->command mappings. Buttons can be created by\n * instantiating a {@link GenericHID} or one of its subclasses ({@link\n * edu.wpi.first.wpilibj.Joystick} or {@link XboxController}), and then passing it to a {@link\n * edu.wpi.first.wpilibj2.command.button.JoystickButton}.\n */",
"private",
"void",
"configureButtonBindings",
"(",
")",
"{",
"}",
"/**\n * Use this to pass the autonomous command to the main {@link Robot} class.\n *\n * @return the command to run in autonomous\n */",
"public",
"Command",
"getAutonomousCommand",
"(",
")",
"{",
"return",
"new",
"DriveDistancePidCommand",
"(",
"1",
",",
"subsystems",
")",
";",
"}",
"public",
"Command",
"getDriveCommand",
"(",
")",
"{",
"return",
"new",
"RunCommand",
"(",
"(",
")",
"->",
"subsystems",
".",
"getChassis",
"(",
")",
".",
"drive",
"(",
"subsystems",
".",
"getDriver",
"(",
")",
".",
"getY",
"(",
")",
",",
"subsystems",
".",
"getDriver",
"(",
")",
".",
"getX",
"(",
")",
")",
",",
"subsystems",
".",
"getChassis",
"(",
")",
")",
";",
"}",
"}"
] |
This class is where the bulk of the robot should be declared.
|
[
"This",
"class",
"is",
"where",
"the",
"bulk",
"of",
"the",
"robot",
"should",
"be",
"declared",
"."
] |
[
"// The robot's subsystems and commands are defined here...",
"// Subsystems",
"// ISubsystems subsystems = new frc.robot.subsystems.vex.VexSubsystems();",
"// Commands",
"// Configure the button bindings",
"// if (robotChooser.getSelected() == Robots.VEX) {",
"// subsystems = new frc.robot.subsystems.vex.VexSubsystems();",
"// } else {",
"// subsystems = new frc.robot.subsystems.romi.RomiSubsystems();",
"// }",
"// An ExampleCommand will run in autonomous",
"// return m_autoCommand;",
"// return null;",
"// return new DriveTime(0.8, 5, subsystems.getChassis());",
"// return new DriveDistance(0.8, 1, subsystems.getChassis(), subsystems.getWheelEncoders());",
"// Default operator drive command",
"// subsystems.getChassis().setDefaultCommand(",
"// new RunCommand(() -> subsystems.getChassis().drive(",
"// subsystems.getDriver().getY(),",
"// subsystems.getDriver().getX()),",
"// subsystems.getChassis()));"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 14
| 584
| 78
|
b669c0403ce8abfc4a94d5254665e0d2d0e30a96
|
leyel/BoSSS
|
src/L3-solution/BoSSS.Solution/LinearSource.cs
|
[
"Apache-2.0"
] |
C#
|
LinearSource
|
/// <summary>
/// Utility class which helps the user in creating the function matrices that are needed
/// in an implementation of <see cref="IVolumeForm"/>; The user has to override
/// <see cref="Source(double[],double[],double[])"/>, where he is able to implement the linear function as
/// an algebraic formula. All function matrices and offsets (aka. intercept) are constructed from the user-defined
/// functions by this class.
/// </summary>
|
Utility class which helps the user in creating the function matrices that are needed
in an implementation of ; The user has to override
, where he is able to implement the linear function as
an algebraic formula. All function matrices and offsets (aka. intercept) are constructed from the user-defined
functions by this class.
|
[
"Utility",
"class",
"which",
"helps",
"the",
"user",
"in",
"creating",
"the",
"function",
"matrices",
"that",
"are",
"needed",
"in",
"an",
"implementation",
"of",
";",
"The",
"user",
"has",
"to",
"override",
"where",
"he",
"is",
"able",
"to",
"implement",
"the",
"linear",
"function",
"as",
"an",
"algebraic",
"formula",
".",
"All",
"function",
"matrices",
"and",
"offsets",
"(",
"aka",
".",
"intercept",
")",
"are",
"constructed",
"from",
"the",
"user",
"-",
"defined",
"functions",
"by",
"this",
"class",
"."
] |
public abstract class LinearSource : IVolumeForm {
public virtual IList<string> ParameterOrdering {
get {
return null;
}
}
abstract public IList<string> ArgumentOrdering {
get;
}
abstract protected double Source(double[] x, double[] parameters, double[] U);
double[] m_Arguments;
private void AllocateArrays() {
if (m_Arguments == null) {
m_Arguments = new double[ArgumentOrdering.Count];
}
}
virtual public TermActivationFlags VolTerms {
get {
return TermActivationFlags.UxV | TermActivationFlags.V;
}
}
public double VolumeForm(ref CommonParamsVol cpv, double[] U, double[,] GradU, double V, double[] GradV) {
return this.Source(cpv.Xglobal, cpv.Parameters, U) * V;
}
}
|
[
"public",
"abstract",
"class",
"LinearSource",
":",
"IVolumeForm",
"{",
"public",
"virtual",
"IList",
"<",
"string",
">",
"ParameterOrdering",
"{",
"get",
"{",
"return",
"null",
";",
"}",
"}",
"abstract",
"public",
"IList",
"<",
"string",
">",
"ArgumentOrdering",
"{",
"get",
";",
"}",
"abstract",
"protected",
"double",
"Source",
"(",
"double",
"[",
"]",
"x",
",",
"double",
"[",
"]",
"parameters",
",",
"double",
"[",
"]",
"U",
")",
";",
"double",
"[",
"]",
"m_Arguments",
";",
"private",
"void",
"AllocateArrays",
"(",
")",
"{",
"if",
"(",
"m_Arguments",
"==",
"null",
")",
"{",
"m_Arguments",
"=",
"new",
"double",
"[",
"ArgumentOrdering",
".",
"Count",
"]",
";",
"}",
"}",
"virtual",
"public",
"TermActivationFlags",
"VolTerms",
"{",
"get",
"{",
"return",
"TermActivationFlags",
".",
"UxV",
"|",
"TermActivationFlags",
".",
"V",
";",
"}",
"}",
"public",
"double",
"VolumeForm",
"(",
"ref",
"CommonParamsVol",
"cpv",
",",
"double",
"[",
"]",
"U",
",",
"double",
"[",
",",
"]",
"GradU",
",",
"double",
"V",
",",
"double",
"[",
"]",
"GradV",
")",
"{",
"return",
"this",
".",
"Source",
"(",
"cpv",
".",
"Xglobal",
",",
"cpv",
".",
"Parameters",
",",
"U",
")",
"*",
"V",
";",
"}",
"}"
] |
Utility class which helps the user in creating the function matrices that are needed
in an implementation of ; The user has to override
, where he is able to implement the linear function as
an algebraic formula.
|
[
"Utility",
"class",
"which",
"helps",
"the",
"user",
"in",
"creating",
"the",
"function",
"matrices",
"that",
"are",
"needed",
"in",
"an",
"implementation",
"of",
";",
"The",
"user",
"has",
"to",
"override",
"where",
"he",
"is",
"able",
"to",
"implement",
"the",
"linear",
"function",
"as",
"an",
"algebraic",
"formula",
"."
] |
[
"/// <summary>",
"/// not in use, returning null",
"/// </summary>",
"/// <summary>",
"/// to be implemented by user ",
"/// </summary>",
"/// <summary>",
"/// override this method to implement the linear source",
"/// </summary>",
"/// <summary>",
"/// arguments used for the linear source functions to extract the function matrix",
"/// </summary>",
"/// <summary>",
"/// helper function to initialize <see cref=\"m_Arguments\"/>",
"/// </summary>",
"/// <summary>",
"/// Active terms are <see cref=\"TermActivationFlags.UxV\"/> and",
"/// <see cref=\"TermActivationFlags.V\"/>",
"/// </summary>",
"/// <summary>",
"/// translates <see cref=\"Source\"/> into <see cref=\"IVolumeForm.VolumeForm\"/>",
"/// </summary>"
] |
[
{
"param": "IVolumeForm",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "IVolumeForm",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 13
| 186
| 98
|
7483dd5537feaba4cbe5e67fd4fb489d368133a3
|
CornelSora/TeamsExtensions
|
Source/Microsoft.Teams.Apps.CompanyCommunicator.Prep.Func/PreparingToSend/GetRecipientDataBatches/Groups/GetGroupMembersActivity.cs
|
[
"MIT"
] |
C#
|
GetGroupMembersActivity
|
/// <summary>
/// This class contains the "get group member" durable activity.
/// This activity prepares the SentNotification data table by filling it with an initialized row
/// and failed row.
/// For each recipient - every member of the given group is a recipient.
/// 1). It gets the recipient data list for a group.
/// 2). It initializes or fails the sent notification data table with a row for each member in that group.
/// </summary>
|
This class contains the "get group member" durable activity.
This activity prepares the SentNotification data table by filling it with an initialized row
and failed row.
For each recipient - every member of the given group is a recipient.
1). It gets the recipient data list for a group.
2). It initializes or fails the sent notification data table with a row for each member in that group.
|
[
"This",
"class",
"contains",
"the",
"\"",
"get",
"group",
"member",
"\"",
"durable",
"activity",
".",
"This",
"activity",
"prepares",
"the",
"SentNotification",
"data",
"table",
"by",
"filling",
"it",
"with",
"an",
"initialized",
"row",
"and",
"failed",
"row",
".",
"For",
"each",
"recipient",
"-",
"every",
"member",
"of",
"the",
"given",
"group",
"is",
"a",
"recipient",
".",
"1",
")",
".",
"It",
"gets",
"the",
"recipient",
"data",
"list",
"for",
"a",
"group",
".",
"2",
")",
".",
"It",
"initializes",
"or",
"fails",
"the",
"sent",
"notification",
"data",
"table",
"with",
"a",
"row",
"for",
"each",
"member",
"in",
"that",
"group",
"."
] |
public class GetGroupMembersActivity
{
private readonly IGroupMembersService groupMembersService;
private readonly InitializeorFailGroupMembersActivity initializeorFailGroupMembersActivity;
public GetGroupMembersActivity(
IGroupMembersService groupMembersService,
InitializeorFailGroupMembersActivity initializeorFailGroupMembersActivity)
{
this.groupMembersService = groupMembersService;
this.initializeorFailGroupMembersActivity = initializeorFailGroupMembersActivity;
}
public async Task<(IGroupTransitiveMembersCollectionWithReferencesPage, string)> RunAsync(
IDurableOrchestrationContext context,
string notificationDataEntityId,
string groupId,
ILogger log)
{
var (groupMembersPage, nextPageUrl) = await context.
CallActivityWithRetryAsync
<(IGroupTransitiveMembersCollectionWithReferencesPage, string)>(
nameof(GetGroupMembersActivity.GetGroupMembersAsync),
ActivitySettings.CommonActivityRetryOptions,
groupId);
await this.initializeorFailGroupMembersActivity.
RunAsync(
context,
notificationDataEntityId,
groupMembersPage.OfType<User>(),
log);
return (groupMembersPage, nextPageUrl);
}
[FunctionName(nameof(GetGroupMembersAsync))]
public async Task<(IGroupTransitiveMembersCollectionWithReferencesPage, string)> GetGroupMembersAsync(
[ActivityTrigger] string groupId)
{
var groupMembersPage = await this.groupMembersService.
GetGroupMembersPageByIdAsync(groupId);
var nextPageUrl = groupMembersPage.AdditionalData.NextPageUrl();
return (groupMembersPage, nextPageUrl);
}
}
|
[
"public",
"class",
"GetGroupMembersActivity",
"{",
"private",
"readonly",
"IGroupMembersService",
"groupMembersService",
";",
"private",
"readonly",
"InitializeorFailGroupMembersActivity",
"initializeorFailGroupMembersActivity",
";",
"public",
"GetGroupMembersActivity",
"(",
"IGroupMembersService",
"groupMembersService",
",",
"InitializeorFailGroupMembersActivity",
"initializeorFailGroupMembersActivity",
")",
"{",
"this",
".",
"groupMembersService",
"=",
"groupMembersService",
";",
"this",
".",
"initializeorFailGroupMembersActivity",
"=",
"initializeorFailGroupMembersActivity",
";",
"}",
"public",
"async",
"Task",
"<",
"(",
"IGroupTransitiveMembersCollectionWithReferencesPage",
",",
"string",
")",
">",
"RunAsync",
"(",
"IDurableOrchestrationContext",
"context",
",",
"string",
"notificationDataEntityId",
",",
"string",
"groupId",
",",
"ILogger",
"log",
")",
"{",
"var",
"(",
"groupMembersPage",
",",
"nextPageUrl",
")",
"=",
"await",
"context",
".",
"CallActivityWithRetryAsync",
"<",
"(",
"IGroupTransitiveMembersCollectionWithReferencesPage",
",",
"string",
")",
">",
"(",
"nameof",
"(",
"GetGroupMembersActivity",
".",
"GetGroupMembersAsync",
")",
",",
"ActivitySettings",
".",
"CommonActivityRetryOptions",
",",
"groupId",
")",
";",
"await",
"this",
".",
"initializeorFailGroupMembersActivity",
".",
"RunAsync",
"(",
"context",
",",
"notificationDataEntityId",
",",
"groupMembersPage",
".",
"OfType",
"<",
"User",
">",
"(",
")",
",",
"log",
")",
";",
"return",
"(",
"groupMembersPage",
",",
"nextPageUrl",
")",
";",
"}",
"[",
"FunctionName",
"(",
"nameof",
"(",
"GetGroupMembersAsync",
")",
")",
"]",
"public",
"async",
"Task",
"<",
"(",
"IGroupTransitiveMembersCollectionWithReferencesPage",
",",
"string",
")",
">",
"GetGroupMembersAsync",
"(",
"[",
"ActivityTrigger",
"]",
"string",
"groupId",
")",
"{",
"var",
"groupMembersPage",
"=",
"await",
"this",
".",
"groupMembersService",
".",
"GetGroupMembersPageByIdAsync",
"(",
"groupId",
")",
";",
"var",
"nextPageUrl",
"=",
"groupMembersPage",
".",
"AdditionalData",
".",
"NextPageUrl",
"(",
")",
";",
"return",
"(",
"groupMembersPage",
",",
"nextPageUrl",
")",
";",
"}",
"}"
] |
This class contains the "get group member" durable activity.
|
[
"This",
"class",
"contains",
"the",
"\"",
"get",
"group",
"member",
"\"",
"durable",
"activity",
"."
] |
[
"/// <summary>",
"/// Initializes a new instance of the <see cref=\"GetGroupMembersActivity\"/> class.",
"/// </summary>",
"/// <param name=\"groupMembersService\">Group members service.</param>",
"/// <param name=\"initializeorFailGroupMembersActivity\">Initialize or Fail Group members service.</param>",
"/// <summary>",
"/// Run the activity.",
"/// Get recipient data list (group members) in parallel using fan in/fan out pattern.",
"/// </summary>",
"/// <param name=\"context\">Durable orchestration context.</param>",
"/// <param name=\"notificationDataEntityId\">Notification data entity id.</param>",
"/// <param name=\"groupId\">Group id.</param>",
"/// <param name=\"log\">Logging service.</param>",
"/// <returns>A <see cref=\"Task\"/> representing the asynchronous operation.</returns>",
"// intialize the groupMembers if app installed.",
"// fail the groupMembers if app is not installed.",
"/// <summary>",
"/// This method represents the \"get group members\" durable activity.",
"/// It gets the group members.",
"/// </summary>",
"/// <param name=\"groupId\">Group Id.</param>",
"/// <returns>It returns the group transitive members first page and next page url.</returns>"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 16
| 339
| 95
|
2c32208c4461d050cbefd28168c723d278fef85f
|
nokola/InlineColorPicker
|
InlineColorPickerShared/Support/IntraTextAdornmentTagger.cs
|
[
"MIT"
] |
C#
|
IntraTextAdornmentTagger
|
/// <summary>
/// Helper class for interspersing adornments into text.
/// </summary>
/// <remarks>
/// To avoid an issue around intra-text adornment support and its interaction with text buffer changes,
/// this tagger reacts to text and color tag changes with a delay. It waits to send out its own TagsChanged
/// event until the WPF Dispatcher is running again and it takes care to report adornments
/// that are consistent with the latest sent TagsChanged event by storing that particular snapshot
/// and using it to query for the data tags.
/// </remarks>
|
Helper class for interspersing adornments into text.
|
[
"Helper",
"class",
"for",
"interspersing",
"adornments",
"into",
"text",
"."
] |
internal abstract class IntraTextAdornmentTagger<TData, TAdornment>
: ITagger<IntraTextAdornmentTag>
where TData : ITag
where TAdornment : UIElement
{
protected readonly IWpfTextView _view;
private Dictionary<SnapshotSpan, TAdornment> _adornmentCache = new Dictionary<SnapshotSpan, TAdornment>();
protected ITextSnapshot _snapshot { get; private set; }
private readonly List<SnapshotSpan> _invalidatedSpans = new List<SnapshotSpan>();
protected IntraTextAdornmentTagger(IWpfTextView view)
{
_view = view;
_snapshot = view.TextBuffer.CurrentSnapshot;
_view.LayoutChanged += HandleLayoutChanged;
_view.TextBuffer.Changed += HandleBufferChanged;
}
protected abstract TAdornment CreateAdornment(TData dataTag);
protected abstract void UpdateAdornment(TAdornment adornment, TData dataTag);
protected abstract IEnumerable<Tuple<SnapshotSpan, TData>> GetAdorenmentData(NormalizedSnapshotSpanCollection spans);
private void HandleBufferChanged(object sender, TextContentChangedEventArgs args)
{
var editedSpans = args.Changes.Select(change => new SnapshotSpan(args.After, change.NewSpan)).ToList();
InvalidateSpans(editedSpans);
}
protected void InvalidateSpans(IList<SnapshotSpan> spans)
{
lock (_invalidatedSpans)
{
bool wasEmpty = _invalidatedSpans.Count == 0;
_invalidatedSpans.AddRange(spans);
if (wasEmpty && _invalidatedSpans.Count > 0)
{
_ = _view.VisualElement.Dispatcher.BeginInvoke(new Action(AsyncUpdate));
}
}
}
private void AsyncUpdate()
{
if (_snapshot != _view.TextBuffer.CurrentSnapshot)
{
_snapshot = _view.TextBuffer.CurrentSnapshot;
Dictionary<SnapshotSpan, TAdornment> translatedAdornmentCache = new Dictionary<SnapshotSpan, TAdornment>();
foreach (var keyValuePair in _adornmentCache)
{
translatedAdornmentCache[keyValuePair.Key.TranslateTo(_snapshot, SpanTrackingMode.EdgeExclusive)] = keyValuePair.Value;
}
_adornmentCache = translatedAdornmentCache;
}
List<SnapshotSpan> translatedSpans;
lock (_invalidatedSpans)
{
translatedSpans = _invalidatedSpans.Select(s => s.TranslateTo(_snapshot, SpanTrackingMode.EdgeInclusive)).ToList();
_invalidatedSpans.Clear();
}
if (translatedSpans.Count == 0)
return;
var start = translatedSpans.Select(span => span.Start).Min();
var end = translatedSpans.Select(span => span.End).Max();
RaiseTagsChanged(new SnapshotSpan(start, end));
}
protected void RaiseTagsChanged(SnapshotSpan span)
{
var handler = this.TagsChanged;
if (handler != null)
handler(this, new SnapshotSpanEventArgs(span));
}
private void HandleLayoutChanged(object sender, TextViewLayoutChangedEventArgs e)
{
SnapshotSpan visibleSpan = _view.TextViewLines.FormattedSpan;
List<SnapshotSpan> toRemove = new List<SnapshotSpan>(
from keyValuePair
in _adornmentCache
where !keyValuePair.Key.TranslateTo(visibleSpan.Snapshot, SpanTrackingMode.EdgeExclusive).IntersectsWith(visibleSpan)
select keyValuePair.Key);
foreach (var span in toRemove)
_adornmentCache.Remove(span);
}
public virtual IEnumerable<ITagSpan<IntraTextAdornmentTag>> GetTags(NormalizedSnapshotSpanCollection spans)
{
if (spans == null || spans.Count == 0)
yield break;
ITextSnapshot requestedSnapshot = spans[0].Snapshot;
var translatedSpans = new NormalizedSnapshotSpanCollection(spans.Select(span => span.TranslateTo(_snapshot, SpanTrackingMode.EdgeExclusive)));
foreach (var tagSpan in GetAdornmentTagsOnSnapshot(translatedSpans))
{
SnapshotSpan span = tagSpan.Span.TranslateTo(requestedSnapshot, SpanTrackingMode.EdgeExclusive);
PositionAffinity? affinity = span.Length == 0 ? (PositionAffinity?)PositionAffinity.Successor : null;
IntraTextAdornmentTag tag = new IntraTextAdornmentTag(tagSpan.Tag.Adornment, tagSpan.Tag.RemovalCallback, affinity);
yield return new TagSpan<IntraTextAdornmentTag>(span, tag);
}
}
private IEnumerable<TagSpan<IntraTextAdornmentTag>> GetAdornmentTagsOnSnapshot(NormalizedSnapshotSpanCollection spans)
{
if (spans.Count == 0)
{
yield break;
}
ITextSnapshot snapshot = spans[0].Snapshot;
System.Diagnostics.Debug.Assert(snapshot == _snapshot);
HashSet<SnapshotSpan> toRemove = new HashSet<SnapshotSpan>();
foreach (var ar in _adornmentCache)
if (spans.IntersectsWith(new NormalizedSnapshotSpanCollection(ar.Key)))
toRemove.Add(ar.Key);
foreach (var spanDataPair in GetAdorenmentData(spans))
{
TAdornment adornment;
SnapshotSpan snapshotSpan = spanDataPair.Item1;
TData adornmentData = spanDataPair.Item2;
if (_adornmentCache.TryGetValue(snapshotSpan, out adornment))
{
UpdateAdornment(adornment, adornmentData);
toRemove.Remove(snapshotSpan);
}
else
{
adornment = CreateAdornment(adornmentData);
adornment.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
_adornmentCache.Add(snapshotSpan, adornment);
}
yield return new TagSpan<IntraTextAdornmentTag>(snapshotSpan, new IntraTextAdornmentTag(adornment, null, null));
}
foreach (var snapshotSpan in toRemove)
_adornmentCache.Remove(snapshotSpan);
}
public event EventHandler<SnapshotSpanEventArgs> TagsChanged;
}
|
[
"internal",
"abstract",
"class",
"IntraTextAdornmentTagger",
"<",
"TData",
",",
"TAdornment",
">",
":",
"ITagger",
"<",
"IntraTextAdornmentTag",
">",
"where",
"TData",
":",
"ITag",
"where",
"TAdornment",
":",
"UIElement",
"{",
"protected",
"readonly",
"IWpfTextView",
"_view",
";",
"private",
"Dictionary",
"<",
"SnapshotSpan",
",",
"TAdornment",
">",
"_adornmentCache",
"=",
"new",
"Dictionary",
"<",
"SnapshotSpan",
",",
"TAdornment",
">",
"(",
")",
";",
"protected",
"ITextSnapshot",
"_snapshot",
"{",
"get",
";",
"private",
"set",
";",
"}",
"private",
"readonly",
"List",
"<",
"SnapshotSpan",
">",
"_invalidatedSpans",
"=",
"new",
"List",
"<",
"SnapshotSpan",
">",
"(",
")",
";",
"protected",
"IntraTextAdornmentTagger",
"(",
"IWpfTextView",
"view",
")",
"{",
"_view",
"=",
"view",
";",
"_snapshot",
"=",
"view",
".",
"TextBuffer",
".",
"CurrentSnapshot",
";",
"_view",
".",
"LayoutChanged",
"+=",
"HandleLayoutChanged",
";",
"_view",
".",
"TextBuffer",
".",
"Changed",
"+=",
"HandleBufferChanged",
";",
"}",
"protected",
"abstract",
"TAdornment",
"CreateAdornment",
"(",
"TData",
"dataTag",
")",
";",
"protected",
"abstract",
"void",
"UpdateAdornment",
"(",
"TAdornment",
"adornment",
",",
"TData",
"dataTag",
")",
";",
"protected",
"abstract",
"IEnumerable",
"<",
"Tuple",
"<",
"SnapshotSpan",
",",
"TData",
">",
">",
"GetAdorenmentData",
"(",
"NormalizedSnapshotSpanCollection",
"spans",
")",
";",
"private",
"void",
"HandleBufferChanged",
"(",
"object",
"sender",
",",
"TextContentChangedEventArgs",
"args",
")",
"{",
"var",
"editedSpans",
"=",
"args",
".",
"Changes",
".",
"Select",
"(",
"change",
"=>",
"new",
"SnapshotSpan",
"(",
"args",
".",
"After",
",",
"change",
".",
"NewSpan",
")",
")",
".",
"ToList",
"(",
")",
";",
"InvalidateSpans",
"(",
"editedSpans",
")",
";",
"}",
"protected",
"void",
"InvalidateSpans",
"(",
"IList",
"<",
"SnapshotSpan",
">",
"spans",
")",
"{",
"lock",
"(",
"_invalidatedSpans",
")",
"{",
"bool",
"wasEmpty",
"=",
"_invalidatedSpans",
".",
"Count",
"==",
"0",
";",
"_invalidatedSpans",
".",
"AddRange",
"(",
"spans",
")",
";",
"if",
"(",
"wasEmpty",
"&&",
"_invalidatedSpans",
".",
"Count",
">",
"0",
")",
"{",
"_",
"=",
"_view",
".",
"VisualElement",
".",
"Dispatcher",
".",
"BeginInvoke",
"(",
"new",
"Action",
"(",
"AsyncUpdate",
")",
")",
";",
"}",
"}",
"}",
"private",
"void",
"AsyncUpdate",
"(",
")",
"{",
"if",
"(",
"_snapshot",
"!=",
"_view",
".",
"TextBuffer",
".",
"CurrentSnapshot",
")",
"{",
"_snapshot",
"=",
"_view",
".",
"TextBuffer",
".",
"CurrentSnapshot",
";",
"Dictionary",
"<",
"SnapshotSpan",
",",
"TAdornment",
">",
"translatedAdornmentCache",
"=",
"new",
"Dictionary",
"<",
"SnapshotSpan",
",",
"TAdornment",
">",
"(",
")",
";",
"foreach",
"(",
"var",
"keyValuePair",
"in",
"_adornmentCache",
")",
"{",
"translatedAdornmentCache",
"[",
"keyValuePair",
".",
"Key",
".",
"TranslateTo",
"(",
"_snapshot",
",",
"SpanTrackingMode",
".",
"EdgeExclusive",
")",
"]",
"=",
"keyValuePair",
".",
"Value",
";",
"}",
"_adornmentCache",
"=",
"translatedAdornmentCache",
";",
"}",
"List",
"<",
"SnapshotSpan",
">",
"translatedSpans",
";",
"lock",
"(",
"_invalidatedSpans",
")",
"{",
"translatedSpans",
"=",
"_invalidatedSpans",
".",
"Select",
"(",
"s",
"=>",
"s",
".",
"TranslateTo",
"(",
"_snapshot",
",",
"SpanTrackingMode",
".",
"EdgeInclusive",
")",
")",
".",
"ToList",
"(",
")",
";",
"_invalidatedSpans",
".",
"Clear",
"(",
")",
";",
"}",
"if",
"(",
"translatedSpans",
".",
"Count",
"==",
"0",
")",
"return",
";",
"var",
"start",
"=",
"translatedSpans",
".",
"Select",
"(",
"span",
"=>",
"span",
".",
"Start",
")",
".",
"Min",
"(",
")",
";",
"var",
"end",
"=",
"translatedSpans",
".",
"Select",
"(",
"span",
"=>",
"span",
".",
"End",
")",
".",
"Max",
"(",
")",
";",
"RaiseTagsChanged",
"(",
"new",
"SnapshotSpan",
"(",
"start",
",",
"end",
")",
")",
";",
"}",
"protected",
"void",
"RaiseTagsChanged",
"(",
"SnapshotSpan",
"span",
")",
"{",
"var",
"handler",
"=",
"this",
".",
"TagsChanged",
";",
"if",
"(",
"handler",
"!=",
"null",
")",
"handler",
"(",
"this",
",",
"new",
"SnapshotSpanEventArgs",
"(",
"span",
")",
")",
";",
"}",
"private",
"void",
"HandleLayoutChanged",
"(",
"object",
"sender",
",",
"TextViewLayoutChangedEventArgs",
"e",
")",
"{",
"SnapshotSpan",
"visibleSpan",
"=",
"_view",
".",
"TextViewLines",
".",
"FormattedSpan",
";",
"List",
"<",
"SnapshotSpan",
">",
"toRemove",
"=",
"new",
"List",
"<",
"SnapshotSpan",
">",
"(",
"from",
"keyValuePair",
"in",
"_adornmentCache",
"where",
"!",
"keyValuePair",
".",
"Key",
".",
"TranslateTo",
"(",
"visibleSpan",
".",
"Snapshot",
",",
"SpanTrackingMode",
".",
"EdgeExclusive",
")",
".",
"IntersectsWith",
"(",
"visibleSpan",
")",
"select",
"keyValuePair",
".",
"Key",
")",
";",
"foreach",
"(",
"var",
"span",
"in",
"toRemove",
")",
"_adornmentCache",
".",
"Remove",
"(",
"span",
")",
";",
"}",
"public",
"virtual",
"IEnumerable",
"<",
"ITagSpan",
"<",
"IntraTextAdornmentTag",
">",
">",
"GetTags",
"(",
"NormalizedSnapshotSpanCollection",
"spans",
")",
"{",
"if",
"(",
"spans",
"==",
"null",
"||",
"spans",
".",
"Count",
"==",
"0",
")",
"yield",
"break",
";",
"ITextSnapshot",
"requestedSnapshot",
"=",
"spans",
"[",
"0",
"]",
".",
"Snapshot",
";",
"var",
"translatedSpans",
"=",
"new",
"NormalizedSnapshotSpanCollection",
"(",
"spans",
".",
"Select",
"(",
"span",
"=>",
"span",
".",
"TranslateTo",
"(",
"_snapshot",
",",
"SpanTrackingMode",
".",
"EdgeExclusive",
")",
")",
")",
";",
"foreach",
"(",
"var",
"tagSpan",
"in",
"GetAdornmentTagsOnSnapshot",
"(",
"translatedSpans",
")",
")",
"{",
"SnapshotSpan",
"span",
"=",
"tagSpan",
".",
"Span",
".",
"TranslateTo",
"(",
"requestedSnapshot",
",",
"SpanTrackingMode",
".",
"EdgeExclusive",
")",
";",
"PositionAffinity",
"?",
"affinity",
"=",
"span",
".",
"Length",
"==",
"0",
"?",
"(",
"PositionAffinity",
"?",
")",
"PositionAffinity",
".",
"Successor",
":",
"null",
";",
"IntraTextAdornmentTag",
"tag",
"=",
"new",
"IntraTextAdornmentTag",
"(",
"tagSpan",
".",
"Tag",
".",
"Adornment",
",",
"tagSpan",
".",
"Tag",
".",
"RemovalCallback",
",",
"affinity",
")",
";",
"yield",
"return",
"new",
"TagSpan",
"<",
"IntraTextAdornmentTag",
">",
"(",
"span",
",",
"tag",
")",
";",
"}",
"}",
"private",
"IEnumerable",
"<",
"TagSpan",
"<",
"IntraTextAdornmentTag",
">",
">",
"GetAdornmentTagsOnSnapshot",
"(",
"NormalizedSnapshotSpanCollection",
"spans",
")",
"{",
"if",
"(",
"spans",
".",
"Count",
"==",
"0",
")",
"{",
"yield",
"break",
";",
"}",
"ITextSnapshot",
"snapshot",
"=",
"spans",
"[",
"0",
"]",
".",
"Snapshot",
";",
"System",
".",
"Diagnostics",
".",
"Debug",
".",
"Assert",
"(",
"snapshot",
"==",
"_snapshot",
")",
";",
"HashSet",
"<",
"SnapshotSpan",
">",
"toRemove",
"=",
"new",
"HashSet",
"<",
"SnapshotSpan",
">",
"(",
")",
";",
"foreach",
"(",
"var",
"ar",
"in",
"_adornmentCache",
")",
"if",
"(",
"spans",
".",
"IntersectsWith",
"(",
"new",
"NormalizedSnapshotSpanCollection",
"(",
"ar",
".",
"Key",
")",
")",
")",
"toRemove",
".",
"Add",
"(",
"ar",
".",
"Key",
")",
";",
"foreach",
"(",
"var",
"spanDataPair",
"in",
"GetAdorenmentData",
"(",
"spans",
")",
")",
"{",
"TAdornment",
"adornment",
";",
"SnapshotSpan",
"snapshotSpan",
"=",
"spanDataPair",
".",
"Item1",
";",
"TData",
"adornmentData",
"=",
"spanDataPair",
".",
"Item2",
";",
"if",
"(",
"_adornmentCache",
".",
"TryGetValue",
"(",
"snapshotSpan",
",",
"out",
"adornment",
")",
")",
"{",
"UpdateAdornment",
"(",
"adornment",
",",
"adornmentData",
")",
";",
"toRemove",
".",
"Remove",
"(",
"snapshotSpan",
")",
";",
"}",
"else",
"{",
"adornment",
"=",
"CreateAdornment",
"(",
"adornmentData",
")",
";",
"adornment",
".",
"Measure",
"(",
"new",
"Size",
"(",
"double",
".",
"PositiveInfinity",
",",
"double",
".",
"PositiveInfinity",
")",
")",
";",
"_adornmentCache",
".",
"Add",
"(",
"snapshotSpan",
",",
"adornment",
")",
";",
"}",
"yield",
"return",
"new",
"TagSpan",
"<",
"IntraTextAdornmentTag",
">",
"(",
"snapshotSpan",
",",
"new",
"IntraTextAdornmentTag",
"(",
"adornment",
",",
"null",
",",
"null",
")",
")",
";",
"}",
"foreach",
"(",
"var",
"snapshotSpan",
"in",
"toRemove",
")",
"_adornmentCache",
".",
"Remove",
"(",
"snapshotSpan",
")",
";",
"}",
"public",
"event",
"EventHandler",
"<",
"SnapshotSpanEventArgs",
">",
"TagsChanged",
";",
"}"
] |
Helper class for interspersing adornments into text.
|
[
"Helper",
"class",
"for",
"interspersing",
"adornments",
"into",
"text",
"."
] |
[
"// Store the snapshot that we're now current with and send an event",
"// for the text that has changed.",
"// Filter out the adornments that are no longer visible.",
"// Produces tags on the snapshot that the tag consumer asked for.",
"// Translate the request to the snapshot that this tagger is current with.",
"// Grab the adornments.",
"// Translate each adornment to the snapshot that the tagger was asked about.",
"// Affinity is needed only for zero-length adornments.",
"// Produces tags on the snapshot that this tagger is current with.",
"// Since WPF UI objects have state (like mouse hover or animation) and are relatively expensive to create and lay out,",
"// this code tries to reuse controls as much as possible.",
"// The controls are stored in _adornmentCache between the calls.",
"// Mark which adornments fall inside the requested spans with Keep=false",
"// so that they can be removed from the cache if they no longer correspond to data tags.",
"// Look up the corresponding adornment or create one if it's new.",
"// Get the adornment to measure itself. Its DesiredSize property is used to determine",
"// how much space to leave between text for this adornment.",
"// Note: If the size of the adornment changes, the line will be reformatted to accommodate it.",
"// Note: Some adornments may change size when added to the view's visual tree due to inherited",
"// dependency properties that affect layout. Such options can include SnapsToDevicePixels,",
"// UseLayoutRounding, TextRenderingMode, TextHintingMode, and TextFormattingMode. Making sure",
"// that these properties on the adornment match the view's values before calling Measure here",
"// can help avoid the size change and the resulting unnecessary re-format."
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": [
{
"identifier": "remarks",
"docstring": "To avoid an issue around intra-text adornment support and its interaction with text buffer changes,\nthis tagger reacts to text and color tag changes with a delay. It waits to send out its own TagsChanged\nevent until the WPF Dispatcher is running again and it takes care to report adornments\nthat are consistent with the latest sent TagsChanged event by storing that particular snapshot\nand using it to query for the data tags.",
"docstring_tokens": [
"To",
"avoid",
"an",
"issue",
"around",
"intra",
"-",
"text",
"adornment",
"support",
"and",
"its",
"interaction",
"with",
"text",
"buffer",
"changes",
"this",
"tagger",
"reacts",
"to",
"text",
"and",
"color",
"tag",
"changes",
"with",
"a",
"delay",
".",
"It",
"waits",
"to",
"send",
"out",
"its",
"own",
"TagsChanged",
"event",
"until",
"the",
"WPF",
"Dispatcher",
"is",
"running",
"again",
"and",
"it",
"takes",
"care",
"to",
"report",
"adornments",
"that",
"are",
"consistent",
"with",
"the",
"latest",
"sent",
"TagsChanged",
"event",
"by",
"storing",
"that",
"particular",
"snapshot",
"and",
"using",
"it",
"to",
"query",
"for",
"the",
"data",
"tags",
"."
]
}
]
}
| false
| 20
| 1,278
| 119
|
42c3c807f53d1e6fcbacf1d1a9f923e6b5091791
|
Pritam-Biswas/Transaction-Cost-Analytics-Engine
|
Multi Process Application/clientserver/DataBaseClient.py
|
[
"MIT"
] |
Python
|
CDataBaseClient
|
Parameterised constructor for CDataBaseClient class
Input Variables:
data_list: To store the entire list of all json objects; Each json object is a row of data
params: This input contains TCA_Params to be sent by the client to the server
Member variables:
m_DataList: To store the entire list of all json objects; Each json object is a row of data
m_hashParams: To store the TCA_Params to be sent by the client to the server
m_Socket: To store the socket object created for establishing connection with server and receiving data; This has to be made a member variable as multiple functions are using it, and passing it becomes a tedious task.
m_strHost: To store the hostname of the server.
m_boolEOF_flag: To set the flag to high indicating end of feed
m_CommonFunctions_obj: To store the object of CCommonFunctions class.This has to be made a member variable as multiple functions are using it, and passing it becomes a tedious task.
|
Parameterised constructor for CDataBaseClient class
Input Variables:
data_list: To store the entire list of all json objects; Each json object is a row of data
params: This input contains TCA_Params to be sent by the client to the server
Member variables:
m_DataList: To store the entire list of all json objects; Each json object is a row of data
m_hashParams: To store the TCA_Params to be sent by the client to the server
m_Socket: To store the socket object created for establishing connection with server and receiving data; This has to be made a member variable as multiple functions are using it, and passing it becomes a tedious task.
m_strHost: To store the hostname of the server.
m_boolEOF_flag: To set the flag to high indicating end of feed
m_CommonFunctions_obj: To store the object of CCommonFunctions class.This has to be made a member variable as multiple functions are using it, and passing it becomes a tedious task.
|
[
"Parameterised",
"constructor",
"for",
"CDataBaseClient",
"class",
"Input",
"Variables",
":",
"data_list",
":",
"To",
"store",
"the",
"entire",
"list",
"of",
"all",
"json",
"objects",
";",
"Each",
"json",
"object",
"is",
"a",
"row",
"of",
"data",
"params",
":",
"This",
"input",
"contains",
"TCA_Params",
"to",
"be",
"sent",
"by",
"the",
"client",
"to",
"the",
"server",
"Member",
"variables",
":",
"m_DataList",
":",
"To",
"store",
"the",
"entire",
"list",
"of",
"all",
"json",
"objects",
";",
"Each",
"json",
"object",
"is",
"a",
"row",
"of",
"data",
"m_hashParams",
":",
"To",
"store",
"the",
"TCA_Params",
"to",
"be",
"sent",
"by",
"the",
"client",
"to",
"the",
"server",
"m_Socket",
":",
"To",
"store",
"the",
"socket",
"object",
"created",
"for",
"establishing",
"connection",
"with",
"server",
"and",
"receiving",
"data",
";",
"This",
"has",
"to",
"be",
"made",
"a",
"member",
"variable",
"as",
"multiple",
"functions",
"are",
"using",
"it",
"and",
"passing",
"it",
"becomes",
"a",
"tedious",
"task",
".",
"m_strHost",
":",
"To",
"store",
"the",
"hostname",
"of",
"the",
"server",
".",
"m_boolEOF_flag",
":",
"To",
"set",
"the",
"flag",
"to",
"high",
"indicating",
"end",
"of",
"feed",
"m_CommonFunctions_obj",
":",
"To",
"store",
"the",
"object",
"of",
"CCommonFunctions",
"class",
".",
"This",
"has",
"to",
"be",
"made",
"a",
"member",
"variable",
"as",
"multiple",
"functions",
"are",
"using",
"it",
"and",
"passing",
"it",
"becomes",
"a",
"tedious",
"task",
"."
] |
class CDataBaseClient:
'''
Parameterised constructor for CDataBaseClient class
Input Variables:
data_list: To store the entire list of all json objects; Each json object is a row of data
params: This input contains TCA_Params to be sent by the client to the server
Member variables:
m_DataList: To store the entire list of all json objects; Each json object is a row of data
m_hashParams: To store the TCA_Params to be sent by the client to the server
m_Socket: To store the socket object created for establishing connection with server and receiving data; This has to be made a member variable as multiple functions are using it, and passing it becomes a tedious task.
m_strHost: To store the hostname of the server.
m_boolEOF_flag: To set the flag to high indicating end of feed
m_CommonFunctions_obj: To store the object of CCommonFunctions class.This has to be made a member variable as multiple functions are using it, and passing it becomes a tedious task.
'''
def __init__(self, data_list, params):
self.m_DataList = data_list
self.m_hashParams = params
self.m_Socket = socket.socket()
self.m_strHost = '' # Get local machine name
self.m_boolEOF_flag = False
self.m_CommonFunctions_obj = CCommonFunctions()
'''
This function connects to the server on the port provided as the input.
Input Variables:
port: To bind to the appropriate port
'''
def Connect(self, port):
self.m_Socket.settimeout(None)
self.m_Socket.connect((self.m_strHost, port))
print "Connected to Server"
return True
'''
This function populates the m_DataList variable with the json objects list.
Input Variables:
buffer_json_list: This is an input of the json objects list.
'''
def StoreData(self, buffer_json_list):
for buffer_json in buffer_json_list:
buffer_json = json.loads(buffer_json)
# print "Receiving Market Data.."
# print buffer_json
buffer_json_formatted = self.m_CommonFunctions_obj.FormatDateJSON(buffer_json)
#print buffer_json_formatted
self.m_DataList.append(buffer_json_formatted)
if buffer_json['eof'] == True:
self.m_boolEOF_flag = True
return True
'''
This function sends the params to the server.
'''
def SendParams(self):
self.m_Socket.send(json.dumps(self.m_hashParams))
return True
'''
This function receives the incoming data from the server and stores it into a local variable, buffer_json_list.
'2 * 1024 * 1024 * 1024 - 1' below is the buffer size (2 GB - 1 byte) for the socket. So, for every client, 2 GB is the minimum RAM required. In case of lower resources at the command, reduce this buffer size. However, if the processing speed is less or the number of cores are less, then there is no guarantee for the correct execution of this entire engine. You could try increasing the duration in the time.sleep() command at the server side, which will result in less speed.
Input variables:
port: To bind to the appropriate port in case of connection loss.
'''
def ReceiveData(self, port):
while self.m_boolEOF_flag is False:
buffer_data = self.m_Socket.recv(2 * 1024 * 1024 * 1024 - 1)
##
if len(str(buffer_data)) == 0:
print "entered client if "
connected_flag = 0
while connected_flag == 0:
try:
print 'entered try'
self.m_Socket.connect(self.m_strHost, port)
connected_flag = 1
print "reconnected to server"
except Exception:
connected_flag = 0
buffer_data = self.m_Socket.recv(2 * 1024 * 1024 * 1024 - 1)
##
buffer_json_list = self.m_CommonFunctions_obj.ParseBuffer(str(buffer_data))
self.StoreData(buffer_json_list)
print "Data received"
print "total objects received :" + str(len(self.m_DataList))
return True
'''
This function disconnects the client from the server.
It also sets the eof flag indicating end of feed.
Input Variables:
data_eof: This is an input flag to indicate end of feed.
'''
def Disconnect(self, data_eof):
data_eof.set()
self.m_Socket.close()
print "socket closed"
return True
'''
This is sort of a main function to kickstart the individual clients.
Input Variables:
data_eof: This is an input flag, a multiprocessing event, to indicate end of feed.
port: This is an input to bind to the appropriate port in case of connection loss.
'''
def StartClient(self, data_eof, port):
print "Client Started"
self.Connect(port)
self.SendParams()
self.ReceiveData(port)
self.Disconnect(data_eof)
return True
|
[
"class",
"CDataBaseClient",
":",
"def",
"__init__",
"(",
"self",
",",
"data_list",
",",
"params",
")",
":",
"self",
".",
"m_DataList",
"=",
"data_list",
"self",
".",
"m_hashParams",
"=",
"params",
"self",
".",
"m_Socket",
"=",
"socket",
".",
"socket",
"(",
")",
"self",
".",
"m_strHost",
"=",
"''",
"self",
".",
"m_boolEOF_flag",
"=",
"False",
"self",
".",
"m_CommonFunctions_obj",
"=",
"CCommonFunctions",
"(",
")",
"'''\n\tThis function connects to the server on the port provided as the input.\n\tInput Variables:\n\t\tport: To bind to the appropriate port\n\t'''",
"def",
"Connect",
"(",
"self",
",",
"port",
")",
":",
"self",
".",
"m_Socket",
".",
"settimeout",
"(",
"None",
")",
"self",
".",
"m_Socket",
".",
"connect",
"(",
"(",
"self",
".",
"m_strHost",
",",
"port",
")",
")",
"print",
"\"Connected to Server\"",
"return",
"True",
"'''\n\tThis function populates the m_DataList variable with the json objects list.\n\tInput Variables:\n\t\tbuffer_json_list: This is an input of the json objects list.\n\t'''",
"def",
"StoreData",
"(",
"self",
",",
"buffer_json_list",
")",
":",
"for",
"buffer_json",
"in",
"buffer_json_list",
":",
"buffer_json",
"=",
"json",
".",
"loads",
"(",
"buffer_json",
")",
"buffer_json_formatted",
"=",
"self",
".",
"m_CommonFunctions_obj",
".",
"FormatDateJSON",
"(",
"buffer_json",
")",
"self",
".",
"m_DataList",
".",
"append",
"(",
"buffer_json_formatted",
")",
"if",
"buffer_json",
"[",
"'eof'",
"]",
"==",
"True",
":",
"self",
".",
"m_boolEOF_flag",
"=",
"True",
"return",
"True",
"'''\n\tThis function sends the params to the server.\n\t'''",
"def",
"SendParams",
"(",
"self",
")",
":",
"self",
".",
"m_Socket",
".",
"send",
"(",
"json",
".",
"dumps",
"(",
"self",
".",
"m_hashParams",
")",
")",
"return",
"True",
"'''\n\tThis function receives the incoming data from the server and stores it into a local variable, buffer_json_list.\n\t'2 * 1024 * 1024 * 1024 - 1' below is the buffer size (2 GB - 1 byte) for the socket. So, for every client, 2 GB is the minimum RAM required. In case of lower resources at the command, reduce this buffer size. However, if the processing speed is less or the number of cores are less, then there is no guarantee for the correct execution of this entire engine. You could try increasing the duration in the time.sleep() command at the server side, which will result in less speed.\n\tInput variables:\n\t\tport: To bind to the appropriate port in case of connection loss.\n\t'''",
"def",
"ReceiveData",
"(",
"self",
",",
"port",
")",
":",
"while",
"self",
".",
"m_boolEOF_flag",
"is",
"False",
":",
"buffer_data",
"=",
"self",
".",
"m_Socket",
".",
"recv",
"(",
"2",
"*",
"1024",
"*",
"1024",
"*",
"1024",
"-",
"1",
")",
"if",
"len",
"(",
"str",
"(",
"buffer_data",
")",
")",
"==",
"0",
":",
"print",
"\"entered client if \"",
"connected_flag",
"=",
"0",
"while",
"connected_flag",
"==",
"0",
":",
"try",
":",
"print",
"'entered try'",
"self",
".",
"m_Socket",
".",
"connect",
"(",
"self",
".",
"m_strHost",
",",
"port",
")",
"connected_flag",
"=",
"1",
"print",
"\"reconnected to server\"",
"except",
"Exception",
":",
"connected_flag",
"=",
"0",
"buffer_data",
"=",
"self",
".",
"m_Socket",
".",
"recv",
"(",
"2",
"*",
"1024",
"*",
"1024",
"*",
"1024",
"-",
"1",
")",
"buffer_json_list",
"=",
"self",
".",
"m_CommonFunctions_obj",
".",
"ParseBuffer",
"(",
"str",
"(",
"buffer_data",
")",
")",
"self",
".",
"StoreData",
"(",
"buffer_json_list",
")",
"print",
"\"Data received\"",
"print",
"\"total objects received :\"",
"+",
"str",
"(",
"len",
"(",
"self",
".",
"m_DataList",
")",
")",
"return",
"True",
"'''\n\tThis function disconnects the client from the server.\n\tIt also sets the eof flag indicating end of feed.\n\tInput Variables:\n\t\tdata_eof: This is an input flag to indicate end of feed.\n\t'''",
"def",
"Disconnect",
"(",
"self",
",",
"data_eof",
")",
":",
"data_eof",
".",
"set",
"(",
")",
"self",
".",
"m_Socket",
".",
"close",
"(",
")",
"print",
"\"socket closed\"",
"return",
"True",
"'''\n\tThis is sort of a main function to kickstart the individual clients.\n\tInput Variables:\n\t\tdata_eof: This is an input flag, a multiprocessing event, to indicate end of feed.\n\t\tport: This is an input to bind to the appropriate port in case of connection loss.\n\t'''",
"def",
"StartClient",
"(",
"self",
",",
"data_eof",
",",
"port",
")",
":",
"print",
"\"Client Started\"",
"self",
".",
"Connect",
"(",
"port",
")",
"self",
".",
"SendParams",
"(",
")",
"self",
".",
"ReceiveData",
"(",
"port",
")",
"self",
".",
"Disconnect",
"(",
"data_eof",
")",
"return",
"True"
] |
Parameterised constructor for CDataBaseClient class
Input Variables:
data_list: To store the entire list of all json objects; Each json object is a row of data
params: This input contains TCA_Params to be sent by the client to the server
|
[
"Parameterised",
"constructor",
"for",
"CDataBaseClient",
"class",
"Input",
"Variables",
":",
"data_list",
":",
"To",
"store",
"the",
"entire",
"list",
"of",
"all",
"json",
"objects",
";",
"Each",
"json",
"object",
"is",
"a",
"row",
"of",
"data",
"params",
":",
"This",
"input",
"contains",
"TCA_Params",
"to",
"be",
"sent",
"by",
"the",
"client",
"to",
"the",
"server"
] |
[
"'''\n\tParameterised constructor for CDataBaseClient class\n\tInput Variables:\n\t\tdata_list: To store the entire list of all json objects; Each json object is a row of data\n\t\tparams: This input contains TCA_Params to be sent by the client to the server\n\n\tMember variables:\n\t\tm_DataList: \t\t To store the entire list of all json objects; Each json object is a row of data\n\t\tm_hashParams: To store the TCA_Params to be sent by the client to the server\n\t\tm_Socket: To store the socket object created for establishing connection with server and receiving \t\t\t\t\t data; This has to be made a member variable as multiple functions are using it, and \t\t\t\t\t\t\t passing it becomes a tedious task.\n\t\tm_strHost:\t\t\t To store the hostname of the server.\n\t\tm_boolEOF_flag:\t\t To set the flag to high indicating end of feed\n\t\tm_CommonFunctions_obj: To store the object of CCommonFunctions class.This has to be made a member variable as \t\t\t\t\t\t multiple functions are using it, and passing it becomes a tedious task.\n\t'''",
"# Get local machine name",
"'''\n\tThis function connects to the server on the port provided as the input.\n\tInput Variables:\n\t\tport: To bind to the appropriate port\n\t'''",
"'''\n\tThis function populates the m_DataList variable with the json objects list.\n\tInput Variables:\n\t\tbuffer_json_list: This is an input of the json objects list.\n\t'''",
"# print \"Receiving Market Data..\"",
"# print buffer_json",
"#print buffer_json_formatted",
"'''\n\tThis function sends the params to the server.\n\t'''",
"'''\n\tThis function receives the incoming data from the server and stores it into a local variable, buffer_json_list.\n\t'2 * 1024 * 1024 * 1024 - 1' below is the buffer size (2 GB - 1 byte) for the socket. So, for every client, 2 GB is the minimum RAM required. In case of lower resources at the command, reduce this buffer size. However, if the processing speed is less or the number of cores are less, then there is no guarantee for the correct execution of this entire engine. You could try increasing the duration in the time.sleep() command at the server side, which will result in less speed.\n\tInput variables:\n\t\tport: To bind to the appropriate port in case of connection loss.\n\t'''",
"##",
"##",
"'''\n\tThis function disconnects the client from the server.\n\tIt also sets the eof flag indicating end of feed.\n\tInput Variables:\n\t\tdata_eof: This is an input flag to indicate end of feed.\n\t'''",
"'''\n\tThis is sort of a main function to kickstart the individual clients.\n\tInput Variables:\n\t\tdata_eof: This is an input flag, a multiprocessing event, to indicate end of feed.\n\t\tport: This is an input to bind to the appropriate port in case of connection loss.\n\t'''"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 17
| 1,129
| 230
|
d2d4ec89cffc91101dccefc6dcb131218c8a2088
|
ChrWeissDe/ace-maven-plugin
|
ace-maven-plugin/src/main/java/ibm/maven/plugins/ace/mojos/PrepareBarBuildWorkspaceMojo.java
|
[
"Apache-2.0"
] |
Java
|
PrepareBarBuildWorkspaceMojo
|
/**
* Unpacks the dependent WebSphere Message Broker Projects.
*
* Implemented with help from:
* https://github.com/TimMoore/mojo-executor/blob/master/README.md
*
* requiresDependencyResolution below is required for the unpack-dependencies
* goal to work correctly. See
* https://github.com/TimMoore/mojo-executor/issues/3
*/
|
Unpacks the dependent WebSphere Message Broker Projects.
requiresDependencyResolution below is required for the unpack-dependencies
goal to work correctly.
|
[
"Unpacks",
"the",
"dependent",
"WebSphere",
"Message",
"Broker",
"Projects",
".",
"requiresDependencyResolution",
"below",
"is",
"required",
"for",
"the",
"unpack",
"-",
"dependencies",
"goal",
"to",
"work",
"correctly",
"."
] |
@Mojo(name = "prepare-bar-build-workspace", requiresDependencyResolution = ResolutionScope.TEST)
public class PrepareBarBuildWorkspaceMojo extends AbstractMojo {
/**
* a comma separated list of dependency types to be unpacked
*/
private static final String UNPACK_ace_DEPENDENCY_TYPES = "zip";
private static final String UNPACK_ace_DEPENDENCY_SCOPE = "compile";
/**
* The Maven Project Object
*/
@Parameter(property = "project", required = true, readonly = true)
protected MavenProject project;
/**
* The Maven Session Object
*/
@Parameter(property = "session", required = true, readonly = true)
protected MavenSession session;
/**
* The Maven PluginManager Object
*/
@Component
protected BuildPluginManager buildPluginManager;
/**
* The path of the workspace in which the projects are extracted to be built.
*/
@Parameter(property = "ace.workspace", defaultValue = "${project.basedir}/..", required = true)
protected File workspace;
/**
* directory to unpack all dependencies
*/
@Parameter(property = "ace.unpackDependenciesDirectory", defaultValue = "${project.basedir}/../dependencies/${project.artifact.artifactId}", required = true, readonly = true)
protected File unpackDependenciesDirectory;
public void execute() throws MojoExecutionException, MojoFailureException {
unpackaceDependencies();
}
/**
* @param pomFile
* @return dummy comment
*/
private boolean isJarPackaging(File pomFile) {
try {
Model model = PomXmlUtils.unmarshallPomFile(pomFile);
// packaging "jar" is the default and may not be defined
if (model.getPackaging() == null || model.getPackaging().equals("") || model.getPackaging().equals("jar")) {
return true;
}
} catch (JAXBException e) {
getLog().debug("Exception unmarshalling ('" + pomFile.getAbsolutePath() + "')", e);
}
// this should really never happen
return false;
}
/**
* goal of the method is to create sharedLibs projects defined by Maven
* dependencies for this purpose the method performs the following tasks: -
* unpacks dependencies of scope "compile" and type "zip" to
* unpackDependencyDirectory - filter dependencies for bar files - and unpack
* them to unpackBarDirectory - filter unpacked bar files for sharedLibs and
* unpack them to the workspace directory - create a .project file for the
* sharedLibs projects
*
* @throws MojoExecutionException If an exception occurs
*/
private void unpackaceDependencies() throws MojoExecutionException {
// define the directory to be unpacked into and create it
workspace.mkdirs();
// step 1:
// unpack all dependencies that match the given scope; target: unpackDependencyDirectory
executeMojo(plugin(groupId("org.apache.maven.plugins"), artifactId("maven-dependency-plugin"), version("2.8")),
goal("unpack-dependencies"),
configuration(element(name("outputDirectory"), unpackDependenciesDirectory.getAbsolutePath()),
element(name("includeTypes"), UNPACK_ace_DEPENDENCY_TYPES),
element(name("includeScope"), UNPACK_ace_DEPENDENCY_SCOPE)),
executionEnvironment(project, session, buildPluginManager));
try {
// step 2: unpack all source files
if (unpackDependenciesDirectory.exists()) {
List<File> sourceFiles = FileUtils.getFiles(unpackDependenciesDirectory, "*sources.jar", "default.jar");
for (File sourceFile : sourceFiles) {
String[] fileParts = (FileUtils.removeExtension(sourceFile.getName())).split("-");
String projectName = fileParts[0];
getLog().info("found source for project: "+projectName);
//define target environment and unpack sources
String targetDirectory = workspace.getAbsolutePath().toString() + "/" + projectName;
File projectDirectory = new File(targetDirectory);
new ZipFile(sourceFile).extractAll(projectDirectory.getAbsolutePath());
getLog().info("unpacking " + sourceFile.getName() + " to "
+ projectDirectory.getAbsolutePath().toString());
/*
//patch .project file
//TODO: current assumption that we only handle "shared libs"
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream inStream = classloader.getResourceAsStream("templates/project.txt");
String projectFile = IOUtils.toString(inStream);
projectFile = projectFile.replace("projectname", projectName);
String targetFileName = workspace.getAbsolutePath().toString() + "/" + projectName + "/.project";
File targetFile = new File(targetFileName);
Files.write(Paths.get(targetFile.getAbsolutePath()), projectFile.getBytes(StandardCharsets.UTF_8));
*/ }
} else {
getLog().info("unpack dependency directory does not exist");
}
/*
// step 3: unpack all sharedlibs - and unpack them directly to the workspace
if (unpackBarDirectory.exists()) {
List<File> sharedLibs = FileUtils.getFiles(unpackBarDirectory, "*.shlibzip", "default.shlibzip");
for (File sharedLib : sharedLibs) {
String projectName = FileUtils.removeExtension(sharedLib.getName());
// determine the targetDirectory
String targetDirectory = workspace.getAbsolutePath().toString() + "/" + projectName;
File projectDirectory = new File(targetDirectory);
new ZipFile(sharedLib).extractAll(projectDirectory.getAbsolutePath());
getLog().info("unpacking " + sharedLib.getName() + " to "
+ projectDirectory.getAbsolutePath().toString());
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream inStream = classloader.getResourceAsStream("templates/project.txt");
String projectFile = IOUtils.toString(inStream);
projectFile = projectFile.replace("projectname", projectName);
String targetFileName = workspace.getAbsolutePath().toString() + "/" + projectName + "/.project";
File targetFile = new File(targetFileName);
Files.write(Paths.get(targetFile.getAbsolutePath()), projectFile.getBytes(StandardCharsets.UTF_8));
}
} else {
getLog().info("unpack bar directory does not exist");
}
*/
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
[
"@",
"Mojo",
"(",
"name",
"=",
"\"",
"prepare-bar-build-workspace",
"\"",
",",
"requiresDependencyResolution",
"=",
"ResolutionScope",
".",
"TEST",
")",
"public",
"class",
"PrepareBarBuildWorkspaceMojo",
"extends",
"AbstractMojo",
"{",
"/**\n\t * a comma separated list of dependency types to be unpacked\n\t */",
"private",
"static",
"final",
"String",
"UNPACK_ace_DEPENDENCY_TYPES",
"=",
"\"",
"zip",
"\"",
";",
"private",
"static",
"final",
"String",
"UNPACK_ace_DEPENDENCY_SCOPE",
"=",
"\"",
"compile",
"\"",
";",
"/**\n\t * The Maven Project Object\n\t */",
"@",
"Parameter",
"(",
"property",
"=",
"\"",
"project",
"\"",
",",
"required",
"=",
"true",
",",
"readonly",
"=",
"true",
")",
"protected",
"MavenProject",
"project",
";",
"/**\n\t * The Maven Session Object\n\t */",
"@",
"Parameter",
"(",
"property",
"=",
"\"",
"session",
"\"",
",",
"required",
"=",
"true",
",",
"readonly",
"=",
"true",
")",
"protected",
"MavenSession",
"session",
";",
"/**\n\t * The Maven PluginManager Object\n\t */",
"@",
"Component",
"protected",
"BuildPluginManager",
"buildPluginManager",
";",
"/**\n\t * The path of the workspace in which the projects are extracted to be built.\n\t */",
"@",
"Parameter",
"(",
"property",
"=",
"\"",
"ace.workspace",
"\"",
",",
"defaultValue",
"=",
"\"",
"${project.basedir}/..",
"\"",
",",
"required",
"=",
"true",
")",
"protected",
"File",
"workspace",
";",
"/**\n\t * directory to unpack all dependencies\n\t */",
"@",
"Parameter",
"(",
"property",
"=",
"\"",
"ace.unpackDependenciesDirectory",
"\"",
",",
"defaultValue",
"=",
"\"",
"${project.basedir}/../dependencies/${project.artifact.artifactId}",
"\"",
",",
"required",
"=",
"true",
",",
"readonly",
"=",
"true",
")",
"protected",
"File",
"unpackDependenciesDirectory",
";",
"public",
"void",
"execute",
"(",
")",
"throws",
"MojoExecutionException",
",",
"MojoFailureException",
"{",
"unpackaceDependencies",
"(",
")",
";",
"}",
"/**\n\t * @param pomFile\n\t * @return dummy comment\n\t */",
"private",
"boolean",
"isJarPackaging",
"(",
"File",
"pomFile",
")",
"{",
"try",
"{",
"Model",
"model",
"=",
"PomXmlUtils",
".",
"unmarshallPomFile",
"(",
"pomFile",
")",
";",
"if",
"(",
"model",
".",
"getPackaging",
"(",
")",
"==",
"null",
"||",
"model",
".",
"getPackaging",
"(",
")",
".",
"equals",
"(",
"\"",
"\"",
")",
"||",
"model",
".",
"getPackaging",
"(",
")",
".",
"equals",
"(",
"\"",
"jar",
"\"",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"catch",
"(",
"JAXBException",
"e",
")",
"{",
"getLog",
"(",
")",
".",
"debug",
"(",
"\"",
"Exception unmarshalling ('",
"\"",
"+",
"pomFile",
".",
"getAbsolutePath",
"(",
")",
"+",
"\"",
"')",
"\"",
",",
"e",
")",
";",
"}",
"return",
"false",
";",
"}",
"/**\n\t * goal of the method is to create sharedLibs projects defined by Maven\n\t * dependencies for this purpose the method performs the following tasks: -\n\t * unpacks dependencies of scope \"compile\" and type \"zip\" to\n\t * unpackDependencyDirectory - filter dependencies for bar files - and unpack\n\t * them to unpackBarDirectory - filter unpacked bar files for sharedLibs and\n\t * unpack them to the workspace directory - create a .project file for the\n\t * sharedLibs projects\n\t * \n\t * @throws MojoExecutionException If an exception occurs\n\t */",
"private",
"void",
"unpackaceDependencies",
"(",
")",
"throws",
"MojoExecutionException",
"{",
"workspace",
".",
"mkdirs",
"(",
")",
";",
"executeMojo",
"(",
"plugin",
"(",
"groupId",
"(",
"\"",
"org.apache.maven.plugins",
"\"",
")",
",",
"artifactId",
"(",
"\"",
"maven-dependency-plugin",
"\"",
")",
",",
"version",
"(",
"\"",
"2.8",
"\"",
")",
")",
",",
"goal",
"(",
"\"",
"unpack-dependencies",
"\"",
")",
",",
"configuration",
"(",
"element",
"(",
"name",
"(",
"\"",
"outputDirectory",
"\"",
")",
",",
"unpackDependenciesDirectory",
".",
"getAbsolutePath",
"(",
")",
")",
",",
"element",
"(",
"name",
"(",
"\"",
"includeTypes",
"\"",
")",
",",
"UNPACK_ace_DEPENDENCY_TYPES",
")",
",",
"element",
"(",
"name",
"(",
"\"",
"includeScope",
"\"",
")",
",",
"UNPACK_ace_DEPENDENCY_SCOPE",
")",
")",
",",
"executionEnvironment",
"(",
"project",
",",
"session",
",",
"buildPluginManager",
")",
")",
";",
"try",
"{",
"if",
"(",
"unpackDependenciesDirectory",
".",
"exists",
"(",
")",
")",
"{",
"List",
"<",
"File",
">",
"sourceFiles",
"=",
"FileUtils",
".",
"getFiles",
"(",
"unpackDependenciesDirectory",
",",
"\"",
"*sources.jar",
"\"",
",",
"\"",
"default.jar",
"\"",
")",
";",
"for",
"(",
"File",
"sourceFile",
":",
"sourceFiles",
")",
"{",
"String",
"[",
"]",
"fileParts",
"=",
"(",
"FileUtils",
".",
"removeExtension",
"(",
"sourceFile",
".",
"getName",
"(",
")",
")",
")",
".",
"split",
"(",
"\"",
"-",
"\"",
")",
";",
"String",
"projectName",
"=",
"fileParts",
"[",
"0",
"]",
";",
"getLog",
"(",
")",
".",
"info",
"(",
"\"",
"found source for project: ",
"\"",
"+",
"projectName",
")",
";",
"String",
"targetDirectory",
"=",
"workspace",
".",
"getAbsolutePath",
"(",
")",
".",
"toString",
"(",
")",
"+",
"\"",
"/",
"\"",
"+",
"projectName",
";",
"File",
"projectDirectory",
"=",
"new",
"File",
"(",
"targetDirectory",
")",
";",
"new",
"ZipFile",
"(",
"sourceFile",
")",
".",
"extractAll",
"(",
"projectDirectory",
".",
"getAbsolutePath",
"(",
")",
")",
";",
"getLog",
"(",
")",
".",
"info",
"(",
"\"",
"unpacking ",
"\"",
"+",
"sourceFile",
".",
"getName",
"(",
")",
"+",
"\"",
" to ",
"\"",
"+",
"projectDirectory",
".",
"getAbsolutePath",
"(",
")",
".",
"toString",
"(",
")",
")",
";",
"/*\n\t\t\t\t\t//patch .project file \n\t\t\t\t\t//TODO: current assumption that we only handle \"shared libs\" \n\t\t\t\t\tClassLoader classloader = Thread.currentThread().getContextClassLoader();\n\t\t\t\t\tInputStream inStream = classloader.getResourceAsStream(\"templates/project.txt\");\n\n\t\t\t\t\tString projectFile = IOUtils.toString(inStream);\n\t\t\t\t\tprojectFile = projectFile.replace(\"projectname\", projectName);\n\n\t\t\t\t\tString targetFileName = workspace.getAbsolutePath().toString() + \"/\" + projectName + \"/.project\";\n\t\t\t\t\tFile targetFile = new File(targetFileName);\n\n\t\t\t\t\tFiles.write(Paths.get(targetFile.getAbsolutePath()), projectFile.getBytes(StandardCharsets.UTF_8));\n\t\t\t\t\t\t*/",
"}",
"}",
"else",
"{",
"getLog",
"(",
")",
".",
"info",
"(",
"\"",
"unpack dependency directory does not exist",
"\"",
")",
";",
"}",
"/* \t\n\t\t\t// step 3: unpack all sharedlibs - and unpack them directly to the workspace\n\t\t\tif (unpackBarDirectory.exists()) {\n\t\t\t\tList<File> sharedLibs = FileUtils.getFiles(unpackBarDirectory, \"*.shlibzip\", \"default.shlibzip\");\n\t\t\t\tfor (File sharedLib : sharedLibs) {\n\t\t\t\t\tString projectName = FileUtils.removeExtension(sharedLib.getName());\n\n\t\t\t\t\t// determine the targetDirectory\n\t\t\t\t\tString targetDirectory = workspace.getAbsolutePath().toString() + \"/\" + projectName;\n\t\t\t\t\tFile projectDirectory = new File(targetDirectory);\n\n\t\t\t\t\tnew ZipFile(sharedLib).extractAll(projectDirectory.getAbsolutePath());\n\t\t\t\t\tgetLog().info(\"unpacking \" + sharedLib.getName() + \" to \"\n\t\t\t\t\t\t\t+ projectDirectory.getAbsolutePath().toString());\n\n\t\t\t\t\tClassLoader classloader = Thread.currentThread().getContextClassLoader();\n\t\t\t\t\tInputStream inStream = classloader.getResourceAsStream(\"templates/project.txt\");\n\n\t\t\t\t\tString projectFile = IOUtils.toString(inStream);\n\t\t\t\t\tprojectFile = projectFile.replace(\"projectname\", projectName);\n\n\t\t\t\t\tString targetFileName = workspace.getAbsolutePath().toString() + \"/\" + projectName + \"/.project\";\n\t\t\t\t\tFile targetFile = new File(targetFileName);\n\n\t\t\t\t\tFiles.write(Paths.get(targetFile.getAbsolutePath()), projectFile.getBytes(StandardCharsets.UTF_8));\n\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tgetLog().info(\"unpack bar directory does not exist\");\n\t\t\t}\n\t\t*/",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"}",
"}",
"}"
] |
Unpacks the dependent WebSphere Message Broker Projects.
|
[
"Unpacks",
"the",
"dependent",
"WebSphere",
"Message",
"Broker",
"Projects",
"."
] |
[
"// packaging \"jar\" is the default and may not be defined",
"// this should really never happen",
"// define the directory to be unpacked into and create it",
"// step 1: ",
"// unpack all dependencies that match the given scope; target: unpackDependencyDirectory ",
"// step 2: unpack all source files",
"//define target environment and unpack sources "
] |
[
{
"param": "AbstractMojo",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "AbstractMojo",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 19
| 1,354
| 83
|
c31d9ff75727bbc156e6cd30046fad5ef31f877e
|
amzn/rheoceros
|
src/intelliflow/core/signal_processing/dimension_constructs.py
|
[
"Apache-2.0",
"MIT-0"
] |
Python
|
DimensionVariantFactory
|
Factory class that provides registration API for new Variants and also an instantiation API
to help variant creation from raw data or type info.
This factory is designed to be generic (a central registrar) to allow future expansions in the variant
type system.
>>> type(DimensionVariantFactory.create_variant("2020-05-22"))
<class '...DateVariant'>
|
Factory class that provides registration API for new Variants and also an instantiation API
to help variant creation from raw data or type info.
This factory is designed to be generic (a central registrar) to allow future expansions in the variant
type system.
|
[
"Factory",
"class",
"that",
"provides",
"registration",
"API",
"for",
"new",
"Variants",
"and",
"also",
"an",
"instantiation",
"API",
"to",
"help",
"variant",
"creation",
"from",
"raw",
"data",
"or",
"type",
"info",
".",
"This",
"factory",
"is",
"designed",
"to",
"be",
"generic",
"(",
"a",
"central",
"registrar",
")",
"to",
"allow",
"future",
"expansions",
"in",
"the",
"variant",
"type",
"system",
"."
] |
class DimensionVariantFactory:
"""Factory class that provides registration API for new Variants and also an instantiation API
to help variant creation from raw data or type info.
This factory is designed to be generic (a central registrar) to allow future expansions in the variant
type system.
>>> type(DimensionVariantFactory.create_variant("2020-05-22"))
<class '...DateVariant'>
"""
_RESOLVERS: ClassVar[List[_Type[DimensionVariantResolver]]] = []
_TYPE_TO_CREATORS_MAP: ClassVar[Dict[Type, _Type[DimensionVariantCreatorMethod]]] = {}
_logger: ClassVar[logging.Logger] = logging.getLogger("DimensionVariantFactory")
MAX_RANGE_LIMIT: ClassVar[int] = 9999
def __new__(cls, *args, **kwargs):
raise TypeError(f"{cls.__class__.__name__} cannot be instantiated!")
@classmethod
def register_resolver(cls, resolver: DimensionVariantResolver) -> None:
cls._RESOLVERS.append(resolver)
@classmethod
def register_creator(cls, typ: Type, creator: DimensionVariantCreatorMethod) -> None:
cls._TYPE_TO_CREATORS_MAP[typ] = creator
@classmethod
def get_creator(cls, typ: Type) -> DimensionVariantCreatorMethod:
return cls._TYPE_TO_CREATORS_MAP[typ]
@classmethod
def create_variant_range(cls, start: Any, stop: Any, step: int, params_dict: ParamsDictType) -> List[DimensionVariant]:
start_variant = cls.create_variant(start, params_dict)
stop_variant = cls.create_variant(stop, params_dict)
range: List[DimensionVariant] = []
if type(start_variant) == type(stop_variant):
while True:
range.append(start_variant)
for i in range(step):
if start_variant.value != stop_variant.value:
start_variant = start_variant + 1
else:
break
if start_variant.value == stop_variant.value:
break
if len(range) > cls.MAX_RANGE_LIMIT:
module_logger.critical(
f"Range creation for (start: {start}, stop: {stop},"
f" step: {step}, params_dict: {params_dict}) exceeded limit {cls.MAX_RANGE_LIMIT}"
)
break
else:
raise ValueError(
f"Cannot create dimension range due to type mismatch between "
f"start: {start} (variant: {start_variant}) and stop: {stop} (variant: {stop_variant}"
)
return range
@classmethod
def create_variant(cls, raw_variant: Any, params_dict: ParamsDictType) -> DimensionVariant:
result_map: Dict[DimensionVariantResolverScore, List[DimensionVariantCreatorMethod]] = {}
for resolver in cls._RESOLVERS:
result: DimensionVariantResolver.Result = resolver.resolve(raw_variant)
if result:
result_map.setdefault(result.score, []).append(result.creator)
inferred_variant: DimensionVariant = None
decisive_matches = result_map.get(DimensionVariantResolverScore.MATCH, None)
decisive_match_count = 0
if decisive_matches:
decisive_match_count = len(decisive_matches)
if decisive_match_count == 1:
inferred_variant = decisive_matches[0].create(raw_variant, params_dict)
typ: Type = None
if params_dict:
typ = Dimension.extract_type(params_dict)
if inferred_variant:
if not typ or inferred_variant.type == typ:
# we honor resolver matches unless there is a type mismatch.
# this behaviour enables special variant types (such as any, relative, etc)
# to decorate dimension variants.
return inferred_variant
if not typ and not decisive_matches:
tentative_matches = result_map.get(DimensionVariantResolverScore.TENTATIVE, [])
if not tentative_matches:
raise ValueError(f"Cannot resolve DimensionVariant for raw dimension value: '{raw_variant}' (params_dict: '{params_dict}'")
else:
# pick the first tentative match
tentative_variant = tentative_matches[0].create(raw_variant, params_dict)
cls._logger.debug(
f"Tentatively resolved DimensionVariant ({tentative_variant}) for raw value '{raw_variant}'"
f" (params_dict: '{params_dict}'. type: {typ} and there is no decisive match."
)
return tentative_variant
elif decisive_match_count > 1:
raise TypeError(f"Type mismatch between {decisive_matches} for raw value: '{raw_variant}' (params_dict: '{params_dict}'")
else:
cls._logger.debug(
f"Could not resolve DimensionVariant for raw value '{raw_variant}' (params_dict: '{params_dict}' "
f". Creating the variant using type: {typ}."
)
return cls._TYPE_TO_CREATORS_MAP[typ].create(raw_variant, params_dict)
|
[
"class",
"DimensionVariantFactory",
":",
"_RESOLVERS",
":",
"ClassVar",
"[",
"List",
"[",
"_Type",
"[",
"DimensionVariantResolver",
"]",
"]",
"]",
"=",
"[",
"]",
"_TYPE_TO_CREATORS_MAP",
":",
"ClassVar",
"[",
"Dict",
"[",
"Type",
",",
"_Type",
"[",
"DimensionVariantCreatorMethod",
"]",
"]",
"]",
"=",
"{",
"}",
"_logger",
":",
"ClassVar",
"[",
"logging",
".",
"Logger",
"]",
"=",
"logging",
".",
"getLogger",
"(",
"\"DimensionVariantFactory\"",
")",
"MAX_RANGE_LIMIT",
":",
"ClassVar",
"[",
"int",
"]",
"=",
"9999",
"def",
"__new__",
"(",
"cls",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"raise",
"TypeError",
"(",
"f\"{cls.__class__.__name__} cannot be instantiated!\"",
")",
"@",
"classmethod",
"def",
"register_resolver",
"(",
"cls",
",",
"resolver",
":",
"DimensionVariantResolver",
")",
"->",
"None",
":",
"cls",
".",
"_RESOLVERS",
".",
"append",
"(",
"resolver",
")",
"@",
"classmethod",
"def",
"register_creator",
"(",
"cls",
",",
"typ",
":",
"Type",
",",
"creator",
":",
"DimensionVariantCreatorMethod",
")",
"->",
"None",
":",
"cls",
".",
"_TYPE_TO_CREATORS_MAP",
"[",
"typ",
"]",
"=",
"creator",
"@",
"classmethod",
"def",
"get_creator",
"(",
"cls",
",",
"typ",
":",
"Type",
")",
"->",
"DimensionVariantCreatorMethod",
":",
"return",
"cls",
".",
"_TYPE_TO_CREATORS_MAP",
"[",
"typ",
"]",
"@",
"classmethod",
"def",
"create_variant_range",
"(",
"cls",
",",
"start",
":",
"Any",
",",
"stop",
":",
"Any",
",",
"step",
":",
"int",
",",
"params_dict",
":",
"ParamsDictType",
")",
"->",
"List",
"[",
"DimensionVariant",
"]",
":",
"start_variant",
"=",
"cls",
".",
"create_variant",
"(",
"start",
",",
"params_dict",
")",
"stop_variant",
"=",
"cls",
".",
"create_variant",
"(",
"stop",
",",
"params_dict",
")",
"range",
":",
"List",
"[",
"DimensionVariant",
"]",
"=",
"[",
"]",
"if",
"type",
"(",
"start_variant",
")",
"==",
"type",
"(",
"stop_variant",
")",
":",
"while",
"True",
":",
"range",
".",
"append",
"(",
"start_variant",
")",
"for",
"i",
"in",
"range",
"(",
"step",
")",
":",
"if",
"start_variant",
".",
"value",
"!=",
"stop_variant",
".",
"value",
":",
"start_variant",
"=",
"start_variant",
"+",
"1",
"else",
":",
"break",
"if",
"start_variant",
".",
"value",
"==",
"stop_variant",
".",
"value",
":",
"break",
"if",
"len",
"(",
"range",
")",
">",
"cls",
".",
"MAX_RANGE_LIMIT",
":",
"module_logger",
".",
"critical",
"(",
"f\"Range creation for (start: {start}, stop: {stop},\"",
"f\" step: {step}, params_dict: {params_dict}) exceeded limit {cls.MAX_RANGE_LIMIT}\"",
")",
"break",
"else",
":",
"raise",
"ValueError",
"(",
"f\"Cannot create dimension range due to type mismatch between \"",
"f\"start: {start} (variant: {start_variant}) and stop: {stop} (variant: {stop_variant}\"",
")",
"return",
"range",
"@",
"classmethod",
"def",
"create_variant",
"(",
"cls",
",",
"raw_variant",
":",
"Any",
",",
"params_dict",
":",
"ParamsDictType",
")",
"->",
"DimensionVariant",
":",
"result_map",
":",
"Dict",
"[",
"DimensionVariantResolverScore",
",",
"List",
"[",
"DimensionVariantCreatorMethod",
"]",
"]",
"=",
"{",
"}",
"for",
"resolver",
"in",
"cls",
".",
"_RESOLVERS",
":",
"result",
":",
"DimensionVariantResolver",
".",
"Result",
"=",
"resolver",
".",
"resolve",
"(",
"raw_variant",
")",
"if",
"result",
":",
"result_map",
".",
"setdefault",
"(",
"result",
".",
"score",
",",
"[",
"]",
")",
".",
"append",
"(",
"result",
".",
"creator",
")",
"inferred_variant",
":",
"DimensionVariant",
"=",
"None",
"decisive_matches",
"=",
"result_map",
".",
"get",
"(",
"DimensionVariantResolverScore",
".",
"MATCH",
",",
"None",
")",
"decisive_match_count",
"=",
"0",
"if",
"decisive_matches",
":",
"decisive_match_count",
"=",
"len",
"(",
"decisive_matches",
")",
"if",
"decisive_match_count",
"==",
"1",
":",
"inferred_variant",
"=",
"decisive_matches",
"[",
"0",
"]",
".",
"create",
"(",
"raw_variant",
",",
"params_dict",
")",
"typ",
":",
"Type",
"=",
"None",
"if",
"params_dict",
":",
"typ",
"=",
"Dimension",
".",
"extract_type",
"(",
"params_dict",
")",
"if",
"inferred_variant",
":",
"if",
"not",
"typ",
"or",
"inferred_variant",
".",
"type",
"==",
"typ",
":",
"return",
"inferred_variant",
"if",
"not",
"typ",
"and",
"not",
"decisive_matches",
":",
"tentative_matches",
"=",
"result_map",
".",
"get",
"(",
"DimensionVariantResolverScore",
".",
"TENTATIVE",
",",
"[",
"]",
")",
"if",
"not",
"tentative_matches",
":",
"raise",
"ValueError",
"(",
"f\"Cannot resolve DimensionVariant for raw dimension value: '{raw_variant}' (params_dict: '{params_dict}'\"",
")",
"else",
":",
"tentative_variant",
"=",
"tentative_matches",
"[",
"0",
"]",
".",
"create",
"(",
"raw_variant",
",",
"params_dict",
")",
"cls",
".",
"_logger",
".",
"debug",
"(",
"f\"Tentatively resolved DimensionVariant ({tentative_variant}) for raw value '{raw_variant}'\"",
"f\" (params_dict: '{params_dict}'. type: {typ} and there is no decisive match.\"",
")",
"return",
"tentative_variant",
"elif",
"decisive_match_count",
">",
"1",
":",
"raise",
"TypeError",
"(",
"f\"Type mismatch between {decisive_matches} for raw value: '{raw_variant}' (params_dict: '{params_dict}'\"",
")",
"else",
":",
"cls",
".",
"_logger",
".",
"debug",
"(",
"f\"Could not resolve DimensionVariant for raw value '{raw_variant}' (params_dict: '{params_dict}' \"",
"f\". Creating the variant using type: {typ}.\"",
")",
"return",
"cls",
".",
"_TYPE_TO_CREATORS_MAP",
"[",
"typ",
"]",
".",
"create",
"(",
"raw_variant",
",",
"params_dict",
")"
] |
Factory class that provides registration API for new Variants and also an instantiation API
to help variant creation from raw data or type info.
|
[
"Factory",
"class",
"that",
"provides",
"registration",
"API",
"for",
"new",
"Variants",
"and",
"also",
"an",
"instantiation",
"API",
"to",
"help",
"variant",
"creation",
"from",
"raw",
"data",
"or",
"type",
"info",
"."
] |
[
"\"\"\"Factory class that provides registration API for new Variants and also an instantiation API\n to help variant creation from raw data or type info.\n\n This factory is designed to be generic (a central registrar) to allow future expansions in the variant\n type system.\n\n >>> type(DimensionVariantFactory.create_variant(\"2020-05-22\"))\n <class '...DateVariant'>\n \"\"\"",
"# we honor resolver matches unless there is a type mismatch.",
"# this behaviour enables special variant types (such as any, relative, etc)",
"# to decorate dimension variants.",
"# pick the first tentative match"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 19
| 1,040
| 83
|
e6997f304e7cf710ae61c7e65c66667c7c826726
|
gsantopaolo/TeamFamilyControls
|
MPCExtensions/Common/WeakEvent.cs
|
[
"Apache-2.0"
] |
C#
|
WeakEvent
|
/// <summary>
/// Implements a weak reference that allows owner to be garbage collected even with this weak handler subscribed
/// </summary>
/// <typeparam name="TInstance">Type of instance listening for the event.</typeparam>
/// <typeparam name="TSource">Type of source for the event.</typeparam>
/// <typeparam name="TEventArgs">Type of event arguments for the event.</typeparam>
|
Implements a weak reference that allows owner to be garbage collected even with this weak handler subscribed
|
[
"Implements",
"a",
"weak",
"reference",
"that",
"allows",
"owner",
"to",
"be",
"garbage",
"collected",
"even",
"with",
"this",
"weak",
"handler",
"subscribed"
] |
internal class WeakEvent<TInstance, TSource, TEventArgs> where TInstance : class
{
private WeakReference _weakInstance;
public Action<TInstance, TSource, TEventArgs> EventAction { get; set; }
public Action<TInstance, WeakEvent<TInstance, TSource, TEventArgs>> DetachAction { get; set; }
public WeakEvent(TInstance instance)
{
if (null == instance)
{
throw new ArgumentNullException("instance");
}
_weakInstance = new WeakReference(instance);
}
public void Handler(TSource source, TEventArgs eventArgs)
{
TInstance target = (TInstance)_weakInstance.Target;
if (target != null)
{
if (EventAction != null)
{
EventAction(target, source, eventArgs);
}
}
else
{
Detach();
}
}
public void Detach()
{
TInstance target = (TInstance)_weakInstance.Target;
if (null != DetachAction)
{
DetachAction(target, this);
DetachAction = null;
}
}
}
|
[
"internal",
"class",
"WeakEvent",
"<",
"TInstance",
",",
"TSource",
",",
"TEventArgs",
">",
"where",
"TInstance",
":",
"class",
"{",
"private",
"WeakReference",
"_weakInstance",
";",
"public",
"Action",
"<",
"TInstance",
",",
"TSource",
",",
"TEventArgs",
">",
"EventAction",
"{",
"get",
";",
"set",
";",
"}",
"public",
"Action",
"<",
"TInstance",
",",
"WeakEvent",
"<",
"TInstance",
",",
"TSource",
",",
"TEventArgs",
">",
">",
"DetachAction",
"{",
"get",
";",
"set",
";",
"}",
"public",
"WeakEvent",
"(",
"TInstance",
"instance",
")",
"{",
"if",
"(",
"null",
"==",
"instance",
")",
"{",
"throw",
"new",
"ArgumentNullException",
"(",
"\"",
"instance",
"\"",
")",
";",
"}",
"_weakInstance",
"=",
"new",
"WeakReference",
"(",
"instance",
")",
";",
"}",
"public",
"void",
"Handler",
"(",
"TSource",
"source",
",",
"TEventArgs",
"eventArgs",
")",
"{",
"TInstance",
"target",
"=",
"(",
"TInstance",
")",
"_weakInstance",
".",
"Target",
";",
"if",
"(",
"target",
"!=",
"null",
")",
"{",
"if",
"(",
"EventAction",
"!=",
"null",
")",
"{",
"EventAction",
"(",
"target",
",",
"source",
",",
"eventArgs",
")",
";",
"}",
"}",
"else",
"{",
"Detach",
"(",
")",
";",
"}",
"}",
"public",
"void",
"Detach",
"(",
")",
"{",
"TInstance",
"target",
"=",
"(",
"TInstance",
")",
"_weakInstance",
".",
"Target",
";",
"if",
"(",
"null",
"!=",
"DetachAction",
")",
"{",
"DetachAction",
"(",
"target",
",",
"this",
")",
";",
"DetachAction",
"=",
"null",
";",
"}",
"}",
"}"
] |
Implements a weak reference that allows owner to be garbage collected even with this weak handler subscribed
|
[
"Implements",
"a",
"weak",
"reference",
"that",
"allows",
"owner",
"to",
"be",
"garbage",
"collected",
"even",
"with",
"this",
"weak",
"handler",
"subscribed"
] |
[
"/// <summary>",
"/// WeakReference to the instance listening for the event.",
"/// </summary>",
"/// <summary>",
"/// Gets or sets the method to call when the event raises.",
"/// </summary>",
"/// <summary>",
"/// Gets or sets the method to call when detaching from the event.",
"/// </summary>",
"/// <summary>",
"/// Initializes a new instances of the WeakReference.",
"/// </summary>",
"/// <param name=\"instance\">Instance subscribing to the event.</param>",
"/// <summary>",
"/// Handler for the subscribed event, calls EventAction to handle it.",
"/// </summary>",
"/// <param name=\"source\">Event source.</param>",
"/// <param name=\"eventArgs\">Event arguments.</param>",
"// Call registered action",
"// Detach from event",
"/// <summary>",
"/// Detaches from the subscribed event.",
"/// </summary>"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": [
{
"identifier": "typeparam",
"docstring": "Type of instance listening for the event.",
"docstring_tokens": [
"Type",
"of",
"instance",
"listening",
"for",
"the",
"event",
"."
]
},
{
"identifier": "typeparam",
"docstring": "Type of source for the event.",
"docstring_tokens": [
"Type",
"of",
"source",
"for",
"the",
"event",
"."
]
},
{
"identifier": "typeparam",
"docstring": "Type of event arguments for the event.",
"docstring_tokens": [
"Type",
"of",
"event",
"arguments",
"for",
"the",
"event",
"."
]
}
]
}
| false
| 13
| 242
| 80
|
0304c131256c11d70884fcec3c2cf38436c81616
|
nicodewet/vouchertool
|
vouchserv/src/test/java/com/mayloom/vouchserv/VoucherServiceUserTest.java
|
[
"Apache-2.0"
] |
Java
|
VoucherServiceUserTest
|
/**
* In this class we test that with all applicable VoucherService requests, a User can
* only perform operations using its own VoucherBatchOwners (via the VSV-ID) and not
* that of another user, in which case we expect an Error with an appropriate code
* returned informing the user that they have used an unknown VSV-ID.
*
* It may seem odd that we do the above, but we do so since the User to VoucherBatchOwner
* mapping was added long after the then root VoucherBatchOwner came into existence (i.e.
* security aspects where added last).
*
* @author Nico
*/
|
In this class we test that with all applicable VoucherService requests, a User can
only perform operations using its own VoucherBatchOwners (via the VSV-ID) and not
that of another user, in which case we expect an Error with an appropriate code
returned informing the user that they have used an unknown VSV-ID.
It may seem odd that we do the above, but we do so since the User to VoucherBatchOwner
mapping was added long after the then root VoucherBatchOwner came into existence .
@author Nico
|
[
"In",
"this",
"class",
"we",
"test",
"that",
"with",
"all",
"applicable",
"VoucherService",
"requests",
"a",
"User",
"can",
"only",
"perform",
"operations",
"using",
"its",
"own",
"VoucherBatchOwners",
"(",
"via",
"the",
"VSV",
"-",
"ID",
")",
"and",
"not",
"that",
"of",
"another",
"user",
"in",
"which",
"case",
"we",
"expect",
"an",
"Error",
"with",
"an",
"appropriate",
"code",
"returned",
"informing",
"the",
"user",
"that",
"they",
"have",
"used",
"an",
"unknown",
"VSV",
"-",
"ID",
".",
"It",
"may",
"seem",
"odd",
"that",
"we",
"do",
"the",
"above",
"but",
"we",
"do",
"so",
"since",
"the",
"User",
"to",
"VoucherBatchOwner",
"mapping",
"was",
"added",
"long",
"after",
"the",
"then",
"root",
"VoucherBatchOwner",
"came",
"into",
"existence",
".",
"@author",
"Nico"
] |
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"spring/main-test-spring-context.xml"})
public class VoucherServiceUserTest {
private final Logger logger = LoggerFactory.getLogger(VoucherServiceGenOneHundredVouchersTest.class);
@Autowired
@Qualifier("voucherService")
private VoucherService voucherService;
@Autowired
@Qualifier("databaseHelper")
private DatabaseHelper databaseHelper;
private static boolean databaseSetup;
private static final String FIRST_USERNAME = "[email protected]";
private static final String SECOND_USERNAME = "[email protected]";
private static String firstVSVID;
private static String secondVSVID;
@Before
public void setUp() throws Exception {
/**
* Ok so here we need two Users, each with its own registration and thus VSV-ID,
* which we'll use to test that Users cannot transact with each others VSV-ID.
*/
if (!databaseSetup) {
logger.debug("=========== SETUP ===================");
databaseHelper.addNewOrdinaryUser(FIRST_USERNAME, "password");
RegisterResult registerResult = voucherService.register(FIRST_USERNAME);
assertEquals(ResultStatusCode.SUCCESS, registerResult.getResultStatusCode());
firstVSVID = registerResult.getVsvId();
databaseHelper.addNewOrdinaryUser(SECOND_USERNAME, "password");
registerResult = voucherService.register(SECOND_USERNAME);
assertEquals(ResultStatusCode.SUCCESS, registerResult.getResultStatusCode());
secondVSVID = registerResult.getVsvId();
}
databaseSetup = true;
}
@Test
public void testGenerateVoucherBatch() {
/**
* Incorrect combination that should result in failure: SECOND_USERNAME, firstVSVID
*/
BatchGenRequest req = new BatchGenRequest.Builder(SECOND_USERNAME, firstVSVID, 30, VoucherBatchType.REGULAR).
pinLength(30).pinType(PinType.ALPHANUMERIC_MIXED_CASE).build();
BatchGenResult batchGenResult = voucherService.generateVoucherBatch(SECOND_USERNAME, req);
ResultStatusCode resultStatusCode = batchGenResult.getBatchGenResultStatus();
assertEquals(ResultStatusCode.FAIL, resultStatusCode);
VoucherServError vouchServError = batchGenResult.getBatchGenErrorCode();
assertEquals(GeneralVoucherServErrorCode.VSV_ID_INVALID.getCode(), vouchServError.getCode());
}
@Test
public void testGetVoucherBatch() {
/**
* Correct firstVSVID, FIRST_USERNAME combination
*/
BatchGenRequest req = new BatchGenRequest.Builder(FIRST_USERNAME, firstVSVID, 30, VoucherBatchType.REGULAR).build();
BatchGenResult batchGenResult = voucherService.generateVoucherBatch(FIRST_USERNAME, req);
ResultStatusCode resultStatusCode = batchGenResult.getBatchGenResultStatus();
assertEquals(ResultStatusCode.SUCCESS, resultStatusCode);
/**
* Incorrect secondVSVID, FIRST_USERNAME combination in fetch ...
*/
VoucherBatch batch = voucherService.getVoucherBatch(FIRST_USERNAME, secondVSVID, batchGenResult.getBatchNumber());
assertNull(batch);
/**
* Incorrect firstVSVID, SECOND_USERNAME combination in fetch ...
*/
batch = voucherService.getVoucherBatch(SECOND_USERNAME, firstVSVID, batchGenResult.getBatchNumber());
assertNull(batch);
/**
* Correct firstVSVID, FIRST_USERNAME combination in fetch ...
*/
batch = voucherService.getVoucherBatch(FIRST_USERNAME, firstVSVID, batchGenResult.getBatchNumber());
assertNotNull(batch); // no further testing done in this class, refer to VoucherServiceTest
}
@Test
public void testActivateVoucherBatch() {
BatchGenRequest req = new BatchGenRequest.Builder(FIRST_USERNAME, firstVSVID, 30, VoucherBatchType.REGULAR).build();
BatchGenResult batchGenResult = voucherService.generateVoucherBatch(FIRST_USERNAME, req);
ResultStatusCode resultStatusCode = batchGenResult.getBatchGenResultStatus();
assertEquals(ResultStatusCode.SUCCESS, resultStatusCode);
ActivateVoucherBatchResult res = voucherService.activateVoucherBatch(FIRST_USERNAME, secondVSVID, batchGenResult.getBatchNumber());
ResultStatusCode resStatCode = res.getActivateVoucherBatchResultStatus();
assertEquals(ResultStatusCode.FAIL, resStatCode);
assertEquals(GeneralVoucherServErrorCode.VSV_ID_INVALID.getCode(), res.getActivateVoucherBatchErrorCode().getCode());
res = voucherService.activateVoucherBatch(SECOND_USERNAME, firstVSVID, batchGenResult.getBatchNumber());
resStatCode = res.getActivateVoucherBatchResultStatus();
assertEquals(ResultStatusCode.FAIL, resStatCode);
assertEquals(GeneralVoucherServErrorCode.VSV_ID_INVALID.getCode(), res.getActivateVoucherBatchErrorCode().getCode());
}
@Test
public void testRedeemVoucherWithVoucher() {
BatchGenRequest req = new BatchGenRequest.Builder(FIRST_USERNAME, firstVSVID, 30, VoucherBatchType.REGULAR).build();
BatchGenResult batchGenResult = voucherService.generateVoucherBatch(FIRST_USERNAME, req);
assertEquals(ResultStatusCode.SUCCESS, batchGenResult.getBatchGenResultStatus());
ActivateVoucherBatchResult res = voucherService.activateVoucherBatch(FIRST_USERNAME, firstVSVID, batchGenResult.getBatchNumber());
ResultStatusCode resStatCode = res.getActivateVoucherBatchResultStatus();
resStatCode = res.getActivateVoucherBatchResultStatus();
assertEquals(ResultStatusCode.SUCCESS, resStatCode);
VoucherBatch batch = voucherService.getVoucherBatch(FIRST_USERNAME, firstVSVID, batchGenResult.getBatchNumber());
assertNotNull(batch);
Voucher voucher = batch.getVouchers().get(0);
assertNotNull(voucher);
VoucherRedeemResult vouchRedeemRes = voucherService.redeemVoucher(SECOND_USERNAME, firstVSVID, voucher);
assertEquals(ResultStatusCode.FAIL, vouchRedeemRes.getRedeemVoucherResultStatus());
assertEquals(GeneralVoucherServErrorCode.VSV_ID_INVALID.getCode(), vouchRedeemRes.getVoucherRedeemErrorCode().getCode());
vouchRedeemRes = voucherService.redeemVoucher(FIRST_USERNAME, secondVSVID, voucher);
assertEquals(ResultStatusCode.FAIL, vouchRedeemRes.getRedeemVoucherResultStatus());
assertEquals(GeneralVoucherServErrorCode.VSV_ID_INVALID.getCode(), vouchRedeemRes.getVoucherRedeemErrorCode().getCode());
vouchRedeemRes = voucherService.redeemVoucher(FIRST_USERNAME, firstVSVID, voucher);
assertEquals(ResultStatusCode.SUCCESS, vouchRedeemRes.getRedeemVoucherResultStatus());
}
@Test
public void testRedeemVoucherWithPin() {
BatchGenRequest req = new BatchGenRequest.Builder(FIRST_USERNAME, firstVSVID, 30, VoucherBatchType.REGULAR).build();
BatchGenResult batchGenResult = voucherService.generateVoucherBatch(FIRST_USERNAME, req);
assertEquals(ResultStatusCode.SUCCESS, batchGenResult.getBatchGenResultStatus());
ActivateVoucherBatchResult res = voucherService.activateVoucherBatch(FIRST_USERNAME, firstVSVID, batchGenResult.getBatchNumber());
ResultStatusCode resStatCode = res.getActivateVoucherBatchResultStatus();
resStatCode = res.getActivateVoucherBatchResultStatus();
assertEquals(ResultStatusCode.SUCCESS, resStatCode);
VoucherBatch batch = voucherService.getVoucherBatch(FIRST_USERNAME, firstVSVID, batchGenResult.getBatchNumber());
assertNotNull(batch);
Voucher voucher = batch.getVouchers().get(0);
assertNotNull(voucher);
String pin = voucher.getPin();
VoucherRedeemResult vouchRedeemRes = voucherService.redeemVoucher(SECOND_USERNAME, firstVSVID, pin);
assertEquals(ResultStatusCode.FAIL, vouchRedeemRes.getRedeemVoucherResultStatus());
assertEquals(GeneralVoucherServErrorCode.VSV_ID_INVALID.getCode(), vouchRedeemRes.getVoucherRedeemErrorCode().getCode());
vouchRedeemRes = voucherService.redeemVoucher(FIRST_USERNAME, secondVSVID, pin);
assertEquals(ResultStatusCode.FAIL, vouchRedeemRes.getRedeemVoucherResultStatus());
assertEquals(GeneralVoucherServErrorCode.VSV_ID_INVALID.getCode(), vouchRedeemRes.getVoucherRedeemErrorCode().getCode());
vouchRedeemRes = voucherService.redeemVoucher(FIRST_USERNAME, firstVSVID, pin);
assertEquals(ResultStatusCode.SUCCESS, vouchRedeemRes.getRedeemVoucherResultStatus());
}
@Test
public void testDeactivateVoucherBatch() {
DeactivateVoucherBatchResult res = voucherService.deactivateVoucherbatch(FIRST_USERNAME, secondVSVID, 7);
assertEquals(ResultStatusCode.FAIL, res.getResultStatusCode());
assertEquals(GeneralVoucherServErrorCode.VSV_ID_INVALID.getCode(), res.getVoucherServError().getCode());
res = voucherService.deactivateVoucherbatch(SECOND_USERNAME, firstVSVID, 7);
assertEquals(ResultStatusCode.FAIL, res.getResultStatusCode());
assertEquals(GeneralVoucherServErrorCode.VSV_ID_INVALID.getCode(), res.getVoucherServError().getCode());
}
@Test
public void testActiveVoucherSerialRange() {
ActivateVoucherSerialRangeResult res = voucherService.activeVoucherSerialRange(FIRST_USERNAME, secondVSVID, 1, 10);
assertEquals(ResultStatusCode.FAIL, res.getResultStatusCode());
assertEquals(GeneralVoucherServErrorCode.VSV_ID_INVALID.getCode(), res.getVoucherServError().getCode());
res = voucherService.activeVoucherSerialRange(SECOND_USERNAME, firstVSVID, 1, 10);
assertEquals(ResultStatusCode.FAIL, res.getResultStatusCode());
assertEquals(GeneralVoucherServErrorCode.VSV_ID_INVALID.getCode(), res.getVoucherServError().getCode());
}
}
|
[
"@",
"RunWith",
"(",
"SpringJUnit4ClassRunner",
".",
"class",
")",
"@",
"ContextConfiguration",
"(",
"locations",
"=",
"{",
"\"",
"spring/main-test-spring-context.xml",
"\"",
"}",
")",
"public",
"class",
"VoucherServiceUserTest",
"{",
"private",
"final",
"Logger",
"logger",
"=",
"LoggerFactory",
".",
"getLogger",
"(",
"VoucherServiceGenOneHundredVouchersTest",
".",
"class",
")",
";",
"@",
"Autowired",
"@",
"Qualifier",
"(",
"\"",
"voucherService",
"\"",
")",
"private",
"VoucherService",
"voucherService",
";",
"@",
"Autowired",
"@",
"Qualifier",
"(",
"\"",
"databaseHelper",
"\"",
")",
"private",
"DatabaseHelper",
"databaseHelper",
";",
"private",
"static",
"boolean",
"databaseSetup",
";",
"private",
"static",
"final",
"String",
"FIRST_USERNAME",
"=",
"\"",
"[email protected]",
"\"",
";",
"private",
"static",
"final",
"String",
"SECOND_USERNAME",
"=",
"\"",
"[email protected]",
"\"",
";",
"private",
"static",
"String",
"firstVSVID",
";",
"private",
"static",
"String",
"secondVSVID",
";",
"@",
"Before",
"public",
"void",
"setUp",
"(",
")",
"throws",
"Exception",
"{",
"/**\r\n\t\t * Ok so here we need two Users, each with its own registration and thus VSV-ID,\r\n\t\t * which we'll use to test that Users cannot transact with each others VSV-ID.\r\n\t\t */",
"if",
"(",
"!",
"databaseSetup",
")",
"{",
"logger",
".",
"debug",
"(",
"\"",
"=========== SETUP ===================",
"\"",
")",
";",
"databaseHelper",
".",
"addNewOrdinaryUser",
"(",
"FIRST_USERNAME",
",",
"\"",
"password",
"\"",
")",
";",
"RegisterResult",
"registerResult",
"=",
"voucherService",
".",
"register",
"(",
"FIRST_USERNAME",
")",
";",
"assertEquals",
"(",
"ResultStatusCode",
".",
"SUCCESS",
",",
"registerResult",
".",
"getResultStatusCode",
"(",
")",
")",
";",
"firstVSVID",
"=",
"registerResult",
".",
"getVsvId",
"(",
")",
";",
"databaseHelper",
".",
"addNewOrdinaryUser",
"(",
"SECOND_USERNAME",
",",
"\"",
"password",
"\"",
")",
";",
"registerResult",
"=",
"voucherService",
".",
"register",
"(",
"SECOND_USERNAME",
")",
";",
"assertEquals",
"(",
"ResultStatusCode",
".",
"SUCCESS",
",",
"registerResult",
".",
"getResultStatusCode",
"(",
")",
")",
";",
"secondVSVID",
"=",
"registerResult",
".",
"getVsvId",
"(",
")",
";",
"}",
"databaseSetup",
"=",
"true",
";",
"}",
"@",
"Test",
"public",
"void",
"testGenerateVoucherBatch",
"(",
")",
"{",
"/**\r\n\t\t * Incorrect combination that should result in failure: SECOND_USERNAME, firstVSVID\r\n\t\t */",
"BatchGenRequest",
"req",
"=",
"new",
"BatchGenRequest",
".",
"Builder",
"(",
"SECOND_USERNAME",
",",
"firstVSVID",
",",
"30",
",",
"VoucherBatchType",
".",
"REGULAR",
")",
".",
"pinLength",
"(",
"30",
")",
".",
"pinType",
"(",
"PinType",
".",
"ALPHANUMERIC_MIXED_CASE",
")",
".",
"build",
"(",
")",
";",
"BatchGenResult",
"batchGenResult",
"=",
"voucherService",
".",
"generateVoucherBatch",
"(",
"SECOND_USERNAME",
",",
"req",
")",
";",
"ResultStatusCode",
"resultStatusCode",
"=",
"batchGenResult",
".",
"getBatchGenResultStatus",
"(",
")",
";",
"assertEquals",
"(",
"ResultStatusCode",
".",
"FAIL",
",",
"resultStatusCode",
")",
";",
"VoucherServError",
"vouchServError",
"=",
"batchGenResult",
".",
"getBatchGenErrorCode",
"(",
")",
";",
"assertEquals",
"(",
"GeneralVoucherServErrorCode",
".",
"VSV_ID_INVALID",
".",
"getCode",
"(",
")",
",",
"vouchServError",
".",
"getCode",
"(",
")",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testGetVoucherBatch",
"(",
")",
"{",
"/**\r\n\t\t * Correct firstVSVID, FIRST_USERNAME combination \r\n\t\t */",
"BatchGenRequest",
"req",
"=",
"new",
"BatchGenRequest",
".",
"Builder",
"(",
"FIRST_USERNAME",
",",
"firstVSVID",
",",
"30",
",",
"VoucherBatchType",
".",
"REGULAR",
")",
".",
"build",
"(",
")",
";",
"BatchGenResult",
"batchGenResult",
"=",
"voucherService",
".",
"generateVoucherBatch",
"(",
"FIRST_USERNAME",
",",
"req",
")",
";",
"ResultStatusCode",
"resultStatusCode",
"=",
"batchGenResult",
".",
"getBatchGenResultStatus",
"(",
")",
";",
"assertEquals",
"(",
"ResultStatusCode",
".",
"SUCCESS",
",",
"resultStatusCode",
")",
";",
"/**\r\n\t\t * Incorrect secondVSVID, FIRST_USERNAME combination in fetch ...\r\n\t\t */",
"VoucherBatch",
"batch",
"=",
"voucherService",
".",
"getVoucherBatch",
"(",
"FIRST_USERNAME",
",",
"secondVSVID",
",",
"batchGenResult",
".",
"getBatchNumber",
"(",
")",
")",
";",
"assertNull",
"(",
"batch",
")",
";",
"/**\r\n\t\t * Incorrect firstVSVID, SECOND_USERNAME combination in fetch ...\r\n\t\t */",
"batch",
"=",
"voucherService",
".",
"getVoucherBatch",
"(",
"SECOND_USERNAME",
",",
"firstVSVID",
",",
"batchGenResult",
".",
"getBatchNumber",
"(",
")",
")",
";",
"assertNull",
"(",
"batch",
")",
";",
"/**\r\n\t\t * Correct firstVSVID, FIRST_USERNAME combination in fetch ...\r\n\t\t */",
"batch",
"=",
"voucherService",
".",
"getVoucherBatch",
"(",
"FIRST_USERNAME",
",",
"firstVSVID",
",",
"batchGenResult",
".",
"getBatchNumber",
"(",
")",
")",
";",
"assertNotNull",
"(",
"batch",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testActivateVoucherBatch",
"(",
")",
"{",
"BatchGenRequest",
"req",
"=",
"new",
"BatchGenRequest",
".",
"Builder",
"(",
"FIRST_USERNAME",
",",
"firstVSVID",
",",
"30",
",",
"VoucherBatchType",
".",
"REGULAR",
")",
".",
"build",
"(",
")",
";",
"BatchGenResult",
"batchGenResult",
"=",
"voucherService",
".",
"generateVoucherBatch",
"(",
"FIRST_USERNAME",
",",
"req",
")",
";",
"ResultStatusCode",
"resultStatusCode",
"=",
"batchGenResult",
".",
"getBatchGenResultStatus",
"(",
")",
";",
"assertEquals",
"(",
"ResultStatusCode",
".",
"SUCCESS",
",",
"resultStatusCode",
")",
";",
"ActivateVoucherBatchResult",
"res",
"=",
"voucherService",
".",
"activateVoucherBatch",
"(",
"FIRST_USERNAME",
",",
"secondVSVID",
",",
"batchGenResult",
".",
"getBatchNumber",
"(",
")",
")",
";",
"ResultStatusCode",
"resStatCode",
"=",
"res",
".",
"getActivateVoucherBatchResultStatus",
"(",
")",
";",
"assertEquals",
"(",
"ResultStatusCode",
".",
"FAIL",
",",
"resStatCode",
")",
";",
"assertEquals",
"(",
"GeneralVoucherServErrorCode",
".",
"VSV_ID_INVALID",
".",
"getCode",
"(",
")",
",",
"res",
".",
"getActivateVoucherBatchErrorCode",
"(",
")",
".",
"getCode",
"(",
")",
")",
";",
"res",
"=",
"voucherService",
".",
"activateVoucherBatch",
"(",
"SECOND_USERNAME",
",",
"firstVSVID",
",",
"batchGenResult",
".",
"getBatchNumber",
"(",
")",
")",
";",
"resStatCode",
"=",
"res",
".",
"getActivateVoucherBatchResultStatus",
"(",
")",
";",
"assertEquals",
"(",
"ResultStatusCode",
".",
"FAIL",
",",
"resStatCode",
")",
";",
"assertEquals",
"(",
"GeneralVoucherServErrorCode",
".",
"VSV_ID_INVALID",
".",
"getCode",
"(",
")",
",",
"res",
".",
"getActivateVoucherBatchErrorCode",
"(",
")",
".",
"getCode",
"(",
")",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testRedeemVoucherWithVoucher",
"(",
")",
"{",
"BatchGenRequest",
"req",
"=",
"new",
"BatchGenRequest",
".",
"Builder",
"(",
"FIRST_USERNAME",
",",
"firstVSVID",
",",
"30",
",",
"VoucherBatchType",
".",
"REGULAR",
")",
".",
"build",
"(",
")",
";",
"BatchGenResult",
"batchGenResult",
"=",
"voucherService",
".",
"generateVoucherBatch",
"(",
"FIRST_USERNAME",
",",
"req",
")",
";",
"assertEquals",
"(",
"ResultStatusCode",
".",
"SUCCESS",
",",
"batchGenResult",
".",
"getBatchGenResultStatus",
"(",
")",
")",
";",
"ActivateVoucherBatchResult",
"res",
"=",
"voucherService",
".",
"activateVoucherBatch",
"(",
"FIRST_USERNAME",
",",
"firstVSVID",
",",
"batchGenResult",
".",
"getBatchNumber",
"(",
")",
")",
";",
"ResultStatusCode",
"resStatCode",
"=",
"res",
".",
"getActivateVoucherBatchResultStatus",
"(",
")",
";",
"resStatCode",
"=",
"res",
".",
"getActivateVoucherBatchResultStatus",
"(",
")",
";",
"assertEquals",
"(",
"ResultStatusCode",
".",
"SUCCESS",
",",
"resStatCode",
")",
";",
"VoucherBatch",
"batch",
"=",
"voucherService",
".",
"getVoucherBatch",
"(",
"FIRST_USERNAME",
",",
"firstVSVID",
",",
"batchGenResult",
".",
"getBatchNumber",
"(",
")",
")",
";",
"assertNotNull",
"(",
"batch",
")",
";",
"Voucher",
"voucher",
"=",
"batch",
".",
"getVouchers",
"(",
")",
".",
"get",
"(",
"0",
")",
";",
"assertNotNull",
"(",
"voucher",
")",
";",
"VoucherRedeemResult",
"vouchRedeemRes",
"=",
"voucherService",
".",
"redeemVoucher",
"(",
"SECOND_USERNAME",
",",
"firstVSVID",
",",
"voucher",
")",
";",
"assertEquals",
"(",
"ResultStatusCode",
".",
"FAIL",
",",
"vouchRedeemRes",
".",
"getRedeemVoucherResultStatus",
"(",
")",
")",
";",
"assertEquals",
"(",
"GeneralVoucherServErrorCode",
".",
"VSV_ID_INVALID",
".",
"getCode",
"(",
")",
",",
"vouchRedeemRes",
".",
"getVoucherRedeemErrorCode",
"(",
")",
".",
"getCode",
"(",
")",
")",
";",
"vouchRedeemRes",
"=",
"voucherService",
".",
"redeemVoucher",
"(",
"FIRST_USERNAME",
",",
"secondVSVID",
",",
"voucher",
")",
";",
"assertEquals",
"(",
"ResultStatusCode",
".",
"FAIL",
",",
"vouchRedeemRes",
".",
"getRedeemVoucherResultStatus",
"(",
")",
")",
";",
"assertEquals",
"(",
"GeneralVoucherServErrorCode",
".",
"VSV_ID_INVALID",
".",
"getCode",
"(",
")",
",",
"vouchRedeemRes",
".",
"getVoucherRedeemErrorCode",
"(",
")",
".",
"getCode",
"(",
")",
")",
";",
"vouchRedeemRes",
"=",
"voucherService",
".",
"redeemVoucher",
"(",
"FIRST_USERNAME",
",",
"firstVSVID",
",",
"voucher",
")",
";",
"assertEquals",
"(",
"ResultStatusCode",
".",
"SUCCESS",
",",
"vouchRedeemRes",
".",
"getRedeemVoucherResultStatus",
"(",
")",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testRedeemVoucherWithPin",
"(",
")",
"{",
"BatchGenRequest",
"req",
"=",
"new",
"BatchGenRequest",
".",
"Builder",
"(",
"FIRST_USERNAME",
",",
"firstVSVID",
",",
"30",
",",
"VoucherBatchType",
".",
"REGULAR",
")",
".",
"build",
"(",
")",
";",
"BatchGenResult",
"batchGenResult",
"=",
"voucherService",
".",
"generateVoucherBatch",
"(",
"FIRST_USERNAME",
",",
"req",
")",
";",
"assertEquals",
"(",
"ResultStatusCode",
".",
"SUCCESS",
",",
"batchGenResult",
".",
"getBatchGenResultStatus",
"(",
")",
")",
";",
"ActivateVoucherBatchResult",
"res",
"=",
"voucherService",
".",
"activateVoucherBatch",
"(",
"FIRST_USERNAME",
",",
"firstVSVID",
",",
"batchGenResult",
".",
"getBatchNumber",
"(",
")",
")",
";",
"ResultStatusCode",
"resStatCode",
"=",
"res",
".",
"getActivateVoucherBatchResultStatus",
"(",
")",
";",
"resStatCode",
"=",
"res",
".",
"getActivateVoucherBatchResultStatus",
"(",
")",
";",
"assertEquals",
"(",
"ResultStatusCode",
".",
"SUCCESS",
",",
"resStatCode",
")",
";",
"VoucherBatch",
"batch",
"=",
"voucherService",
".",
"getVoucherBatch",
"(",
"FIRST_USERNAME",
",",
"firstVSVID",
",",
"batchGenResult",
".",
"getBatchNumber",
"(",
")",
")",
";",
"assertNotNull",
"(",
"batch",
")",
";",
"Voucher",
"voucher",
"=",
"batch",
".",
"getVouchers",
"(",
")",
".",
"get",
"(",
"0",
")",
";",
"assertNotNull",
"(",
"voucher",
")",
";",
"String",
"pin",
"=",
"voucher",
".",
"getPin",
"(",
")",
";",
"VoucherRedeemResult",
"vouchRedeemRes",
"=",
"voucherService",
".",
"redeemVoucher",
"(",
"SECOND_USERNAME",
",",
"firstVSVID",
",",
"pin",
")",
";",
"assertEquals",
"(",
"ResultStatusCode",
".",
"FAIL",
",",
"vouchRedeemRes",
".",
"getRedeemVoucherResultStatus",
"(",
")",
")",
";",
"assertEquals",
"(",
"GeneralVoucherServErrorCode",
".",
"VSV_ID_INVALID",
".",
"getCode",
"(",
")",
",",
"vouchRedeemRes",
".",
"getVoucherRedeemErrorCode",
"(",
")",
".",
"getCode",
"(",
")",
")",
";",
"vouchRedeemRes",
"=",
"voucherService",
".",
"redeemVoucher",
"(",
"FIRST_USERNAME",
",",
"secondVSVID",
",",
"pin",
")",
";",
"assertEquals",
"(",
"ResultStatusCode",
".",
"FAIL",
",",
"vouchRedeemRes",
".",
"getRedeemVoucherResultStatus",
"(",
")",
")",
";",
"assertEquals",
"(",
"GeneralVoucherServErrorCode",
".",
"VSV_ID_INVALID",
".",
"getCode",
"(",
")",
",",
"vouchRedeemRes",
".",
"getVoucherRedeemErrorCode",
"(",
")",
".",
"getCode",
"(",
")",
")",
";",
"vouchRedeemRes",
"=",
"voucherService",
".",
"redeemVoucher",
"(",
"FIRST_USERNAME",
",",
"firstVSVID",
",",
"pin",
")",
";",
"assertEquals",
"(",
"ResultStatusCode",
".",
"SUCCESS",
",",
"vouchRedeemRes",
".",
"getRedeemVoucherResultStatus",
"(",
")",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testDeactivateVoucherBatch",
"(",
")",
"{",
"DeactivateVoucherBatchResult",
"res",
"=",
"voucherService",
".",
"deactivateVoucherbatch",
"(",
"FIRST_USERNAME",
",",
"secondVSVID",
",",
"7",
")",
";",
"assertEquals",
"(",
"ResultStatusCode",
".",
"FAIL",
",",
"res",
".",
"getResultStatusCode",
"(",
")",
")",
";",
"assertEquals",
"(",
"GeneralVoucherServErrorCode",
".",
"VSV_ID_INVALID",
".",
"getCode",
"(",
")",
",",
"res",
".",
"getVoucherServError",
"(",
")",
".",
"getCode",
"(",
")",
")",
";",
"res",
"=",
"voucherService",
".",
"deactivateVoucherbatch",
"(",
"SECOND_USERNAME",
",",
"firstVSVID",
",",
"7",
")",
";",
"assertEquals",
"(",
"ResultStatusCode",
".",
"FAIL",
",",
"res",
".",
"getResultStatusCode",
"(",
")",
")",
";",
"assertEquals",
"(",
"GeneralVoucherServErrorCode",
".",
"VSV_ID_INVALID",
".",
"getCode",
"(",
")",
",",
"res",
".",
"getVoucherServError",
"(",
")",
".",
"getCode",
"(",
")",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testActiveVoucherSerialRange",
"(",
")",
"{",
"ActivateVoucherSerialRangeResult",
"res",
"=",
"voucherService",
".",
"activeVoucherSerialRange",
"(",
"FIRST_USERNAME",
",",
"secondVSVID",
",",
"1",
",",
"10",
")",
";",
"assertEquals",
"(",
"ResultStatusCode",
".",
"FAIL",
",",
"res",
".",
"getResultStatusCode",
"(",
")",
")",
";",
"assertEquals",
"(",
"GeneralVoucherServErrorCode",
".",
"VSV_ID_INVALID",
".",
"getCode",
"(",
")",
",",
"res",
".",
"getVoucherServError",
"(",
")",
".",
"getCode",
"(",
")",
")",
";",
"res",
"=",
"voucherService",
".",
"activeVoucherSerialRange",
"(",
"SECOND_USERNAME",
",",
"firstVSVID",
",",
"1",
",",
"10",
")",
";",
"assertEquals",
"(",
"ResultStatusCode",
".",
"FAIL",
",",
"res",
".",
"getResultStatusCode",
"(",
")",
")",
";",
"assertEquals",
"(",
"GeneralVoucherServErrorCode",
".",
"VSV_ID_INVALID",
".",
"getCode",
"(",
")",
",",
"res",
".",
"getVoucherServError",
"(",
")",
".",
"getCode",
"(",
")",
")",
";",
"}",
"}"
] |
In this class we test that with all applicable VoucherService requests, a User can
only perform operations using its own VoucherBatchOwners (via the VSV-ID) and not
that of another user, in which case we expect an Error with an appropriate code
returned informing the user that they have used an unknown VSV-ID.
|
[
"In",
"this",
"class",
"we",
"test",
"that",
"with",
"all",
"applicable",
"VoucherService",
"requests",
"a",
"User",
"can",
"only",
"perform",
"operations",
"using",
"its",
"own",
"VoucherBatchOwners",
"(",
"via",
"the",
"VSV",
"-",
"ID",
")",
"and",
"not",
"that",
"of",
"another",
"user",
"in",
"which",
"case",
"we",
"expect",
"an",
"Error",
"with",
"an",
"appropriate",
"code",
"returned",
"informing",
"the",
"user",
"that",
"they",
"have",
"used",
"an",
"unknown",
"VSV",
"-",
"ID",
"."
] |
[
"// no further testing done in this class, refer to VoucherServiceTest\r"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 13
| 2,138
| 135
|
8339e044f1ca5d1931c801b5e379fd48670a5298
|
ppartarr/azure-sdk-for-java
|
sdk/storage/azure-storage-blob-changefeed/src/samples/java/com/azure/storage/blob/changefeed/ReadmeSamples.java
|
[
"MIT"
] |
Java
|
ReadmeSamples
|
/**
* WARNING: MODIFYING THIS FILE WILL REQUIRE CORRESPONDING UPDATES TO README.md FILE. LINE NUMBERS
* ARE USED TO EXTRACT APPROPRIATE CODE SEGMENTS FROM THIS FILE. ADD NEW CODE AT THE BOTTOM TO AVOID CHANGING
* LINE NUMBERS OF EXISTING CODE SAMPLES.
*
* Code samples for the README.md
*/
|
MODIFYING THIS FILE WILL REQUIRE CORRESPONDING UPDATES TO README.md FILE.
Code samples for the README.md
|
[
"MODIFYING",
"THIS",
"FILE",
"WILL",
"REQUIRE",
"CORRESPONDING",
"UPDATES",
"TO",
"README",
".",
"md",
"FILE",
".",
"Code",
"samples",
"for",
"the",
"README",
".",
"md"
] |
public class ReadmeSamples {
private BlobServiceClient blobServiceClient = new BlobServiceClientBuilder().buildClient();
private BlobChangefeedClient client = new BlobChangefeedClientBuilder(blobServiceClient).buildClient();
public void getClient() {
client = new BlobChangefeedClientBuilder(blobServiceClient).buildClient();
}
public void changefeed() {
client.getEvents().forEach(event ->
System.out.printf("Topic: %s, Subject: %s%n", event.getTopic(), event.getSubject()));
}
public void changefeedBetweenDates() {
OffsetDateTime startTime = OffsetDateTime.MIN;
OffsetDateTime endTime = OffsetDateTime.now();
client.getEvents(startTime, endTime).forEach(event ->
System.out.printf("Topic: %s, Subject: %s%n", event.getTopic(), event.getSubject()));
}
public void changefeedResumeWithCursor() {
BlobChangefeedPagedIterable iterable = client.getEvents();
Iterable<BlobChangefeedPagedResponse> pages = iterable.iterableByPage();
String cursor = null;
for (BlobChangefeedPagedResponse page : pages) {
page.getValue().forEach(event ->
System.out.printf("Topic: %s, Subject: %s%n", event.getTopic(), event.getSubject()));
/*
* Get the change feed cursor. The cursor is not required to get each page of events,
* it is intended to be saved and used to resume iterating at a later date.
*/
cursor = page.getContinuationToken();
}
/* Resume iterating from the pervious position with the cursor. */
client.getEvents(cursor).forEach(event ->
System.out.printf("Topic: %s, Subject: %s%n", event.getTopic(), event.getSubject()));
}
public void changefeedPollForEventsWithCursor() {
List<BlobChangefeedEvent> changefeedEvents = new ArrayList<BlobChangefeedEvent>();
/* Get the start time. The change feed client will round start time down to the nearest hour if you provide
an OffsetDateTime with minutes and seconds. */
OffsetDateTime startTime = OffsetDateTime.now();
/* Get your polling interval. */
long pollingInterval = 1000 * 60 * 5; /* 5 minutes. */
/* Get initial set of events. */
Iterable<BlobChangefeedPagedResponse> pages = client.getEvents(startTime, null).iterableByPage();
String continuationToken = null;
while (true) {
for (BlobChangefeedPagedResponse page : pages) {
changefeedEvents.addAll(page.getValue());
/*
* Get the change feed cursor. The cursor is not required to get each page of events,
* it is intended to be saved and used to resume iterating at a later date.
*/
continuationToken = page.getContinuationToken();
}
/* Wait before processing next batch of events. */
try {
Thread.sleep(pollingInterval);
} catch (InterruptedException e) {
e.printStackTrace();
}
/* Resume from last continuation token and fetch latest set of events. */
pages = client.getEvents(continuationToken).iterableByPage();
}
}
}
|
[
"public",
"class",
"ReadmeSamples",
"{",
"private",
"BlobServiceClient",
"blobServiceClient",
"=",
"new",
"BlobServiceClientBuilder",
"(",
")",
".",
"buildClient",
"(",
")",
";",
"private",
"BlobChangefeedClient",
"client",
"=",
"new",
"BlobChangefeedClientBuilder",
"(",
"blobServiceClient",
")",
".",
"buildClient",
"(",
")",
";",
"public",
"void",
"getClient",
"(",
")",
"{",
"client",
"=",
"new",
"BlobChangefeedClientBuilder",
"(",
"blobServiceClient",
")",
".",
"buildClient",
"(",
")",
";",
"}",
"public",
"void",
"changefeed",
"(",
")",
"{",
"client",
".",
"getEvents",
"(",
")",
".",
"forEach",
"(",
"event",
"->",
"System",
".",
"out",
".",
"printf",
"(",
"\"",
"Topic: %s, Subject: %s%n",
"\"",
",",
"event",
".",
"getTopic",
"(",
")",
",",
"event",
".",
"getSubject",
"(",
")",
")",
")",
";",
"}",
"public",
"void",
"changefeedBetweenDates",
"(",
")",
"{",
"OffsetDateTime",
"startTime",
"=",
"OffsetDateTime",
".",
"MIN",
";",
"OffsetDateTime",
"endTime",
"=",
"OffsetDateTime",
".",
"now",
"(",
")",
";",
"client",
".",
"getEvents",
"(",
"startTime",
",",
"endTime",
")",
".",
"forEach",
"(",
"event",
"->",
"System",
".",
"out",
".",
"printf",
"(",
"\"",
"Topic: %s, Subject: %s%n",
"\"",
",",
"event",
".",
"getTopic",
"(",
")",
",",
"event",
".",
"getSubject",
"(",
")",
")",
")",
";",
"}",
"public",
"void",
"changefeedResumeWithCursor",
"(",
")",
"{",
"BlobChangefeedPagedIterable",
"iterable",
"=",
"client",
".",
"getEvents",
"(",
")",
";",
"Iterable",
"<",
"BlobChangefeedPagedResponse",
">",
"pages",
"=",
"iterable",
".",
"iterableByPage",
"(",
")",
";",
"String",
"cursor",
"=",
"null",
";",
"for",
"(",
"BlobChangefeedPagedResponse",
"page",
":",
"pages",
")",
"{",
"page",
".",
"getValue",
"(",
")",
".",
"forEach",
"(",
"event",
"->",
"System",
".",
"out",
".",
"printf",
"(",
"\"",
"Topic: %s, Subject: %s%n",
"\"",
",",
"event",
".",
"getTopic",
"(",
")",
",",
"event",
".",
"getSubject",
"(",
")",
")",
")",
";",
"/*\n * Get the change feed cursor. The cursor is not required to get each page of events,\n * it is intended to be saved and used to resume iterating at a later date.\n */",
"cursor",
"=",
"page",
".",
"getContinuationToken",
"(",
")",
";",
"}",
"/* Resume iterating from the pervious position with the cursor. */",
"client",
".",
"getEvents",
"(",
"cursor",
")",
".",
"forEach",
"(",
"event",
"->",
"System",
".",
"out",
".",
"printf",
"(",
"\"",
"Topic: %s, Subject: %s%n",
"\"",
",",
"event",
".",
"getTopic",
"(",
")",
",",
"event",
".",
"getSubject",
"(",
")",
")",
")",
";",
"}",
"public",
"void",
"changefeedPollForEventsWithCursor",
"(",
")",
"{",
"List",
"<",
"BlobChangefeedEvent",
">",
"changefeedEvents",
"=",
"new",
"ArrayList",
"<",
"BlobChangefeedEvent",
">",
"(",
")",
";",
"/* Get the start time. The change feed client will round start time down to the nearest hour if you provide\n an OffsetDateTime with minutes and seconds. */",
"OffsetDateTime",
"startTime",
"=",
"OffsetDateTime",
".",
"now",
"(",
")",
";",
"/* Get your polling interval. */",
"long",
"pollingInterval",
"=",
"1000",
"*",
"60",
"*",
"5",
";",
"/* 5 minutes. */",
"/* Get initial set of events. */",
"Iterable",
"<",
"BlobChangefeedPagedResponse",
">",
"pages",
"=",
"client",
".",
"getEvents",
"(",
"startTime",
",",
"null",
")",
".",
"iterableByPage",
"(",
")",
";",
"String",
"continuationToken",
"=",
"null",
";",
"while",
"(",
"true",
")",
"{",
"for",
"(",
"BlobChangefeedPagedResponse",
"page",
":",
"pages",
")",
"{",
"changefeedEvents",
".",
"addAll",
"(",
"page",
".",
"getValue",
"(",
")",
")",
";",
"/*\n * Get the change feed cursor. The cursor is not required to get each page of events,\n * it is intended to be saved and used to resume iterating at a later date.\n */",
"continuationToken",
"=",
"page",
".",
"getContinuationToken",
"(",
")",
";",
"}",
"/* Wait before processing next batch of events. */",
"try",
"{",
"Thread",
".",
"sleep",
"(",
"pollingInterval",
")",
";",
"}",
"catch",
"(",
"InterruptedException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"}",
"/* Resume from last continuation token and fetch latest set of events. */",
"pages",
"=",
"client",
".",
"getEvents",
"(",
"continuationToken",
")",
".",
"iterableByPage",
"(",
")",
";",
"}",
"}",
"}"
] |
WARNING: MODIFYING THIS FILE WILL REQUIRE CORRESPONDING UPDATES TO README.md FILE.
|
[
"WARNING",
":",
"MODIFYING",
"THIS",
"FILE",
"WILL",
"REQUIRE",
"CORRESPONDING",
"UPDATES",
"TO",
"README",
".",
"md",
"FILE",
"."
] |
[] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 15
| 696
| 77
|
eb30e497f5b4b12cf053879eee8c912a21119759
|
rizaldoarigi/ayobeli_asp
|
ayobeli_asp/StringResource.Designer.cs
|
[
"Apache-2.0"
] |
C#
|
StringResource
|
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
|
A strongly-typed resource class, for looking up localized strings, etc.
|
[
"A",
"strongly",
"-",
"typed",
"resource",
"class",
"for",
"looking",
"up",
"localized",
"strings",
"etc",
"."
] |
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
public class StringResource {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal StringResource() {
}
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ayobeli_asp.StringResource", typeof(StringResource).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
public static string ConfirmedEmailExplanation {
get {
return ResourceManager.GetString("ConfirmedEmailExplanation", resourceCulture);
}
}
public static string ConfirmedEmailTopMessage {
get {
return ResourceManager.GetString("ConfirmedEmailTopMessage", resourceCulture);
}
}
public static string EmailAccount {
get {
return ResourceManager.GetString("EmailAccount", resourceCulture);
}
}
public static string EmailPassword {
get {
return ResourceManager.GetString("EmailPassword", resourceCulture);
}
}
public static string ErrorBadGateway {
get {
return ResourceManager.GetString("ErrorBadGateway", resourceCulture);
}
}
public static string ErrorPageNotFound {
get {
return ResourceManager.GetString("ErrorPageNotFound", resourceCulture);
}
}
public static string RegisterSuccessExplanation {
get {
return ResourceManager.GetString("RegisterSuccessExplanation", resourceCulture);
}
}
public static string RegisterSuccessTopMessage {
get {
return ResourceManager.GetString("RegisterSuccessTopMessage", resourceCulture);
}
}
public static string VerifyEmailBody {
get {
return ResourceManager.GetString("VerifyEmailBody", resourceCulture);
}
}
public static string VerifyEmailSubject {
get {
return ResourceManager.GetString("VerifyEmailSubject", resourceCulture);
}
}
}
|
[
"[",
"global",
"::",
"System",
".",
"CodeDom",
".",
"Compiler",
".",
"GeneratedCodeAttribute",
"(",
"\"",
"System.Resources.Tools.StronglyTypedResourceBuilder",
"\"",
",",
"\"",
"4.0.0.0",
"\"",
")",
"]",
"[",
"global",
"::",
"System",
".",
"Diagnostics",
".",
"DebuggerNonUserCodeAttribute",
"(",
")",
"]",
"[",
"global",
"::",
"System",
".",
"Runtime",
".",
"CompilerServices",
".",
"CompilerGeneratedAttribute",
"(",
")",
"]",
"public",
"class",
"StringResource",
"{",
"private",
"static",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"resourceMan",
";",
"private",
"static",
"global",
"::",
"System",
".",
"Globalization",
".",
"CultureInfo",
"resourceCulture",
";",
"[",
"global",
"::",
"System",
".",
"Diagnostics",
".",
"CodeAnalysis",
".",
"SuppressMessageAttribute",
"(",
"\"",
"Microsoft.Performance",
"\"",
",",
"\"",
"CA1811:AvoidUncalledPrivateCode",
"\"",
")",
"]",
"internal",
"StringResource",
"(",
")",
"{",
"}",
"[",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableAttribute",
"(",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableState",
".",
"Advanced",
")",
"]",
"public",
"static",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"ResourceManager",
"{",
"get",
"{",
"if",
"(",
"object",
".",
"ReferenceEquals",
"(",
"resourceMan",
",",
"null",
")",
")",
"{",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"temp",
"=",
"new",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"(",
"\"",
"ayobeli_asp.StringResource",
"\"",
",",
"typeof",
"(",
"StringResource",
")",
".",
"Assembly",
")",
";",
"resourceMan",
"=",
"temp",
";",
"}",
"return",
"resourceMan",
";",
"}",
"}",
"[",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableAttribute",
"(",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableState",
".",
"Advanced",
")",
"]",
"public",
"static",
"global",
"::",
"System",
".",
"Globalization",
".",
"CultureInfo",
"Culture",
"{",
"get",
"{",
"return",
"resourceCulture",
";",
"}",
"set",
"{",
"resourceCulture",
"=",
"value",
";",
"}",
"}",
"public",
"static",
"string",
"ConfirmedEmailExplanation",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"ConfirmedEmailExplanation",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"ConfirmedEmailTopMessage",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"ConfirmedEmailTopMessage",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"EmailAccount",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"EmailAccount",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"EmailPassword",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"EmailPassword",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"ErrorBadGateway",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"ErrorBadGateway",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"ErrorPageNotFound",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"ErrorPageNotFound",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"RegisterSuccessExplanation",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"RegisterSuccessExplanation",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"RegisterSuccessTopMessage",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"RegisterSuccessTopMessage",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"VerifyEmailBody",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"VerifyEmailBody",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"VerifyEmailSubject",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"VerifyEmailSubject",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"}"
] |
A strongly-typed resource class, for looking up localized strings, etc.
|
[
"A",
"strongly",
"-",
"typed",
"resource",
"class",
"for",
"looking",
"up",
"localized",
"strings",
"etc",
"."
] |
[
"/// <summary>",
"/// Returns the cached ResourceManager instance used by this class.",
"/// </summary>",
"/// <summary>",
"/// Overrides the current thread's CurrentUICulture property for all",
"/// resource lookups using this strongly typed resource class.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Selamat anda telah menjadi anggota AyoBeli! <hr class="my-4"></br> <a class="btn btn-primary btn-lg" href="#" role="button">Beranda</a>.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Alamat email anda telah dikonfirmasi.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to [email protected].",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to maxpower22.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Terdapat kesalahan pada server.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Halaman yang anda cari tidak ada.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Konfirmasi alamat email anda untuk dapat segera bertransaksi. Bila anda tidak menerima email permintaan konfirmasi, silahkan klik tombol dibawah. <hr class="my-4"></br> <a class="btn btn-primary btn-lg" href="#" role="button">Kirim email</a> .",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Alamat email anda telah berhasil didaftarkan.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to <br/><br/>Kami senang untuk memberitahukan bahwa akun AyoBeli anda telah sukses dibuat. Tolong klik tombol dibawah ini untuk memverifikasi akun anda.<br/><br/><a href="{0}" class="btn btn-primary btn-lg" role="button" aria-pressed="true">Verifikasi</a>.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Akun anda telah sukses dibuat.",
"/// </summary>"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 17
| 538
| 84
|
20b32c885af4f71346dbfe8ed1d9e1817ac09a02
|
SM-125F/google-api-dotnet-client
|
Src/Generated/Google.Apis.Recommender.v1/Google.Apis.Recommender.v1.cs
|
[
"Apache-2.0"
] |
C#
|
MarkFailedRequest
|
/// <summary>
/// Marks the Recommendation State as Failed. Users can use this method to indicate to the
/// Recommender API that they have applied the recommendation themselves, and the operation failed.
/// This stops the recommendation content from being updated. Associated insights are frozen and
/// placed in the ACCEPTED state. MarkRecommendationFailed can be applied to recommendations in
/// ACTIVE, CLAIMED, SUCCEEDED, or FAILED state. Requires the recommender.*.update IAM permission
/// for the specified recommender.
/// </summary>
|
Marks the Recommendation State as Failed. Users can use this method to indicate to the
Recommender API that they have applied the recommendation themselves, and the operation failed.
This stops the recommendation content from being updated. Associated insights are frozen and
placed in the ACCEPTED state.
|
[
"Marks",
"the",
"Recommendation",
"State",
"as",
"Failed",
".",
"Users",
"can",
"use",
"this",
"method",
"to",
"indicate",
"to",
"the",
"Recommender",
"API",
"that",
"they",
"have",
"applied",
"the",
"recommendation",
"themselves",
"and",
"the",
"operation",
"failed",
".",
"This",
"stops",
"the",
"recommendation",
"content",
"from",
"being",
"updated",
".",
"Associated",
"insights",
"are",
"frozen",
"and",
"placed",
"in",
"the",
"ACCEPTED",
"state",
"."
] |
public class MarkFailedRequest : RecommenderBaseServiceRequest<Google.Apis.Recommender.v1.Data.GoogleCloudRecommenderV1Recommendation>
{
public MarkFailedRequest(Google.Apis.Services.IClientService service, Google.Apis.Recommender.v1.Data.GoogleCloudRecommenderV1MarkRecommendationFailedRequest body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
Google.Apis.Recommender.v1.Data.GoogleCloudRecommenderV1MarkRecommendationFailedRequest Body { get; set; }
protected override object GetBody() => Body;
public override string MethodName => "markFailed";
public override string HttpMethod => "POST";
public override string RestPath => "v1/{+name}:markFailed";
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^folders/[^/]+/locations/[^/]+/recommenders/[^/]+/recommendations/[^/]+$",
});
}
}
|
[
"public",
"class",
"MarkFailedRequest",
":",
"RecommenderBaseServiceRequest",
"<",
"Google",
".",
"Apis",
".",
"Recommender",
".",
"v1",
".",
"Data",
".",
"GoogleCloudRecommenderV1Recommendation",
">",
"{",
"public",
"MarkFailedRequest",
"(",
"Google",
".",
"Apis",
".",
"Services",
".",
"IClientService",
"service",
",",
"Google",
".",
"Apis",
".",
"Recommender",
".",
"v1",
".",
"Data",
".",
"GoogleCloudRecommenderV1MarkRecommendationFailedRequest",
"body",
",",
"string",
"name",
")",
":",
"base",
"(",
"service",
")",
"{",
"Name",
"=",
"name",
";",
"Body",
"=",
"body",
";",
"InitParameters",
"(",
")",
";",
"}",
"[",
"Google",
".",
"Apis",
".",
"Util",
".",
"RequestParameterAttribute",
"(",
"\"",
"name",
"\"",
",",
"Google",
".",
"Apis",
".",
"Util",
".",
"RequestParameterType",
".",
"Path",
")",
"]",
"public",
"virtual",
"string",
"Name",
"{",
"get",
";",
"private",
"set",
";",
"}",
"Google",
".",
"Apis",
".",
"Recommender",
".",
"v1",
".",
"Data",
".",
"GoogleCloudRecommenderV1MarkRecommendationFailedRequest",
"Body",
"{",
"get",
";",
"set",
";",
"}",
"protected",
"override",
"object",
"GetBody",
"(",
")",
"=>",
"Body",
";",
"public",
"override",
"string",
"MethodName",
"=>",
"\"",
"markFailed",
"\"",
";",
"public",
"override",
"string",
"HttpMethod",
"=>",
"\"",
"POST",
"\"",
";",
"public",
"override",
"string",
"RestPath",
"=>",
"\"",
"v1/{+name}:markFailed",
"\"",
";",
"protected",
"override",
"void",
"InitParameters",
"(",
")",
"{",
"base",
".",
"InitParameters",
"(",
")",
";",
"RequestParameters",
".",
"Add",
"(",
"\"",
"name",
"\"",
",",
"new",
"Google",
".",
"Apis",
".",
"Discovery",
".",
"Parameter",
"{",
"Name",
"=",
"\"",
"name",
"\"",
",",
"IsRequired",
"=",
"true",
",",
"ParameterType",
"=",
"\"",
"path",
"\"",
",",
"DefaultValue",
"=",
"null",
",",
"Pattern",
"=",
"@\"^folders/[^/]+/locations/[^/]+/recommenders/[^/]+/recommendations/[^/]+$\"",
",",
"}",
")",
";",
"}",
"}"
] |
Marks the Recommendation State as Failed.
|
[
"Marks",
"the",
"Recommendation",
"State",
"as",
"Failed",
"."
] |
[
"/// <summary>Constructs a new MarkFailed request.</summary>",
"/// <summary>Required. Name of the recommendation.</summary>",
"/// <summary>Gets or sets the body of this request.</summary>",
"/// <summary>Returns the body of the request.</summary>",
"/// <summary>Gets the method name.</summary>",
"/// <summary>Gets the HTTP method.</summary>",
"/// <summary>Gets the REST path.</summary>",
"/// <summary>Initializes MarkFailed parameter list.</summary>"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 13
| 291
| 108
|
19df3562b4d297c805a6fc3e9ec2375555faae4d
|
elmatica/filemaker-ruby
|
lib/filemaker/model/fields.rb
|
[
"MIT"
] |
Ruby
|
Fields
|
# `Fields` help to give `Model` their perceived schema. To find out your
# fields, use `Model.fm_fields` or use Rails generator like:
#
# rails generate filemaker:model filename database layout
#
# @example
# class Model
# include Filemaker::Model
#
# string :id, identity: true
# string :title, fm_name: 'A_Title', default: 'Untitled'
# money :salary
# end
|
`Fields` help to give `Model` their perceived schema. To find out your
fields, use `Model.fm_fields` or use Rails generator like.
rails generate filemaker:model filename database layout
|
[
"`",
"Fields",
"`",
"help",
"to",
"give",
"`",
"Model",
"`",
"their",
"perceived",
"schema",
".",
"To",
"find",
"out",
"your",
"fields",
"use",
"`",
"Model",
".",
"fm_fields",
"`",
"or",
"use",
"Rails",
"generator",
"like",
".",
"rails",
"generate",
"filemaker",
":",
"model",
"filename",
"database",
"layout"
] |
module Fields
extend ActiveSupport::Concern
included do
class_attribute :fields, :identity
self.fields = {}
end
# Apply default value when you instantiate a new model.
# @See Model.new
def apply_defaults
attribute_names.each do |name|
field = fields[name]
instance_variable_set("@#{name}", field.default_value)
end
end
def attribute_names
self.class.attribute_names
end
def fm_names
fields.values.map(&:fm_name)
end
def attributes
fields.keys.each_with_object({}) do |field, hash|
# Attributes must be strings, not symbols - See
# http://api.rubyonrails.org/classes/ActiveModel/Serialization.html
hash[field.to_s] = instance_variable_get("@#{field}")
# If we use public_send(field) will encounter Stack Too Deep
end
end
module ClassMethods
def attribute_names
fields.keys
end
Filemaker::Model::Type.registry.each_key do |type|
define_method(type) do |*args|
options = args.last.is_a?(Hash) ? args.pop : {}
field_names = args
field_names.each do |name|
add_field(name, Filemaker::Model::Type.registry[type], options)
create_accessors(name)
next unless options[:max_repeat] && options[:max_repeat] > 1
# We have repeating fields
# It will create [max_repeat] number of attribute with names like:
# xxx__1, xxx__2, xxx__3
# Their fm_name will be xxx(1), xxx(2), xxx(3)
options[:max_repeat].times do |idx|
index = idx + 1
repeated_field_name = "#{name}__#{index}"
fm_name = (options.fetch(:fm_name) { name }).to_s.downcase.freeze
add_field(
repeated_field_name,
Filemaker::Model::Type.registry[type],
options.merge(fm_name: "#{fm_name}(#{index})")
)
create_accessors(repeated_field_name)
end
end
end
end
def add_field(name, type, options)
name = name.to_s.freeze
fields[name] = Filemaker::Model::Field.new(name, type, options)
self.identity = fields[name] if options[:identity]
end
def create_accessors(name)
# Normalize it so ActiveModel::Serialization can work
name = name.to_s
define_attribute_methods name
# Reader
define_method(name) do
instance_variable_get("@#{name}")
end
# Writer - We try to map to the correct type, if not we just return
# original.
define_method("#{name}=") do |value|
new_value = fields[name].serialize_for_update(value)
public_send("#{name}_will_change!") \
if new_value != public_send(name)
instance_variable_set("@#{name}", new_value)
end
# Predicate
define_method("#{name}?") do
# See ActiveRecord::AttributeMethods::Query implementation
public_send(name) == true || public_send(name).present?
end
end
# Find FileMaker's real name given either the attribute name or the real
# FileMaker name.
# FIXME - This may have ordering problem. If fm_name is the same as the
# field name.
def find_field_by_name(name)
name = name.to_s
fields.values.find do |f|
f.name == name || f.fm_name == name
# Unfortunately can't use this as builder.rb need to find field based
# on fm_name
# Always find by attribute name for now
# f.name == name
end
end
end
end
|
[
"module",
"Fields",
"extend",
"ActiveSupport",
"::",
"Concern",
"included",
"do",
"class_attribute",
":fields",
",",
":identity",
"self",
".",
"fields",
"=",
"{",
"}",
"end",
"def",
"apply_defaults",
"attribute_names",
".",
"each",
"do",
"|",
"name",
"|",
"field",
"=",
"fields",
"[",
"name",
"]",
"instance_variable_set",
"(",
"\"@#{name}\"",
",",
"field",
".",
"default_value",
")",
"end",
"end",
"def",
"attribute_names",
"self",
".",
"class",
".",
"attribute_names",
"end",
"def",
"fm_names",
"fields",
".",
"values",
".",
"map",
"(",
"&",
":fm_name",
")",
"end",
"def",
"attributes",
"fields",
".",
"keys",
".",
"each_with_object",
"(",
"{",
"}",
")",
"do",
"|",
"field",
",",
"hash",
"|",
"hash",
"[",
"field",
".",
"to_s",
"]",
"=",
"instance_variable_get",
"(",
"\"@#{field}\"",
")",
"end",
"end",
"module",
"ClassMethods",
"def",
"attribute_names",
"fields",
".",
"keys",
"end",
"Filemaker",
"::",
"Model",
"::",
"Type",
".",
"registry",
".",
"each_key",
"do",
"|",
"type",
"|",
"define_method",
"(",
"type",
")",
"do",
"|",
"*",
"args",
"|",
"options",
"=",
"args",
".",
"last",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"args",
".",
"pop",
":",
"{",
"}",
"field_names",
"=",
"args",
"field_names",
".",
"each",
"do",
"|",
"name",
"|",
"add_field",
"(",
"name",
",",
"Filemaker",
"::",
"Model",
"::",
"Type",
".",
"registry",
"[",
"type",
"]",
",",
"options",
")",
"create_accessors",
"(",
"name",
")",
"next",
"unless",
"options",
"[",
":max_repeat",
"]",
"&&",
"options",
"[",
":max_repeat",
"]",
">",
"1",
"options",
"[",
":max_repeat",
"]",
".",
"times",
"do",
"|",
"idx",
"|",
"index",
"=",
"idx",
"+",
"1",
"repeated_field_name",
"=",
"\"#{name}__#{index}\"",
"fm_name",
"=",
"(",
"options",
".",
"fetch",
"(",
":fm_name",
")",
"{",
"name",
"}",
")",
".",
"to_s",
".",
"downcase",
".",
"freeze",
"add_field",
"(",
"repeated_field_name",
",",
"Filemaker",
"::",
"Model",
"::",
"Type",
".",
"registry",
"[",
"type",
"]",
",",
"options",
".",
"merge",
"(",
"fm_name",
":",
"\"#{fm_name}(#{index})\"",
")",
")",
"create_accessors",
"(",
"repeated_field_name",
")",
"end",
"end",
"end",
"end",
"def",
"add_field",
"(",
"name",
",",
"type",
",",
"options",
")",
"name",
"=",
"name",
".",
"to_s",
".",
"freeze",
"fields",
"[",
"name",
"]",
"=",
"Filemaker",
"::",
"Model",
"::",
"Field",
".",
"new",
"(",
"name",
",",
"type",
",",
"options",
")",
"self",
".",
"identity",
"=",
"fields",
"[",
"name",
"]",
"if",
"options",
"[",
":identity",
"]",
"end",
"def",
"create_accessors",
"(",
"name",
")",
"name",
"=",
"name",
".",
"to_s",
"define_attribute_methods",
"name",
"define_method",
"(",
"name",
")",
"do",
"instance_variable_get",
"(",
"\"@#{name}\"",
")",
"end",
"define_method",
"(",
"\"#{name}=\"",
")",
"do",
"|",
"value",
"|",
"new_value",
"=",
"fields",
"[",
"name",
"]",
".",
"serialize_for_update",
"(",
"value",
")",
"public_send",
"(",
"\"#{name}_will_change!\"",
")",
"if",
"new_value",
"!=",
"public_send",
"(",
"name",
")",
"instance_variable_set",
"(",
"\"@#{name}\"",
",",
"new_value",
")",
"end",
"define_method",
"(",
"\"#{name}?\"",
")",
"do",
"public_send",
"(",
"name",
")",
"==",
"true",
"||",
"public_send",
"(",
"name",
")",
".",
"present?",
"end",
"end",
"def",
"find_field_by_name",
"(",
"name",
")",
"name",
"=",
"name",
".",
"to_s",
"fields",
".",
"values",
".",
"find",
"do",
"|",
"f",
"|",
"f",
".",
"name",
"==",
"name",
"||",
"f",
".",
"fm_name",
"==",
"name",
"end",
"end",
"end",
"end"
] |
`Fields` help to give `Model` their perceived schema.
|
[
"`",
"Fields",
"`",
"help",
"to",
"give",
"`",
"Model",
"`",
"their",
"perceived",
"schema",
"."
] |
[
"# Apply default value when you instantiate a new model.",
"# @See Model.new",
"# Attributes must be strings, not symbols - See",
"# http://api.rubyonrails.org/classes/ActiveModel/Serialization.html",
"# If we use public_send(field) will encounter Stack Too Deep",
"# We have repeating fields",
"# It will create [max_repeat] number of attribute with names like:",
"# xxx__1, xxx__2, xxx__3",
"# Their fm_name will be xxx(1), xxx(2), xxx(3)",
"# Normalize it so ActiveModel::Serialization can work",
"# Reader",
"# Writer - We try to map to the correct type, if not we just return",
"# original.",
"# Predicate",
"# See ActiveRecord::AttributeMethods::Query implementation",
"# Find FileMaker's real name given either the attribute name or the real",
"# FileMaker name.",
"# FIXME - This may have ordering problem. If fm_name is the same as the",
"# field name.",
"# Unfortunately can't use this as builder.rb need to find field based",
"# on fm_name",
"# Always find by attribute name for now",
"# f.name == name"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": [
{
"identifier": "example",
"docstring": "class Model include Filemaker::Model string :id, identity: true string :title, fm_name: 'A_Title', default: 'Untitled' money :salary end",
"docstring_tokens": [
"class",
"Model",
"include",
"Filemaker",
"::",
"Model",
"string",
":",
"id",
"identity",
":",
"true",
"string",
":",
"title",
"fm_name",
":",
"'",
"A_Title",
"'",
"default",
":",
"'",
"Untitled",
"'",
"money",
":",
"salary",
"end"
]
}
]
}
| false
| 25
| 832
| 103
|
50d6e8a79447f2e07e8885556aedb9bc1999d09d
|
bewood/OpenAdStack
|
AppNexusActivities/AppNexusActivities/AppActivities/GetCreativesActivity.cs
|
[
"Apache-2.0"
] |
C#
|
GetCreativesActivity
|
/// <summary>
/// Activity for getting creatives for an AppNexus advertiser
/// </summary>
/// <remarks>
/// Retrieves creatives for an advertiser from AppNexus
/// RequiredValues:
/// AuthUserId - The user's user id (used to call AppNexus APIs)
/// CompanyEntityId - The EntityId of the advertiser CompanyEntity
/// CampaignEntityId - The EntityId of the Campaign
/// </remarks>
|
Activity for getting creatives for an AppNexus advertiser
|
[
"Activity",
"for",
"getting",
"creatives",
"for",
"an",
"AppNexus",
"advertiser"
] |
[Name(AppNexusActivityTasks.GetCreatives)]
[RequiredValues(
EntityActivityValues.AuthUserId,
EntityActivityValues.CompanyEntityId,
EntityActivityValues.CampaignEntityId)]
public class GetCreativesActivity : AppNexusActivity
{
public override ActivityRuntimeCategory RuntimeCategory
{
get { return ActivityRuntimeCategory.InteractiveFetch; }
}
protected override ActivityResult ProcessAppNexusRequest(ActivityRequest request)
{
var context = CreateRepositoryContext(RepositoryContextType.InternalEntityGet, request);
var companyEntityId = new EntityId(request.Values[EntityActivityValues.CompanyEntityId]);
var campaignEntityId = new EntityId(request.Values[EntityActivityValues.CampaignEntityId]);
var userId = request.Values[EntityActivityValues.AuthUserId];
var user = this.Repository.GetUser(context, userId);
if (user.GetUserType() != UserType.AppNexusApp)
{
return ErrorResult(ActivityErrorId.GenericError, "Activity not supported for non-AppNexusApp users");
}
var company = this.Repository.TryGetEntity(context, companyEntityId) as CompanyEntity;
if (company == null)
{
return this.EntityNotFoundError(companyEntityId);
}
var advertiserId = ((CompanyEntity)company).GetAppNexusAdvertiserId();
if (!advertiserId.HasValue)
{
return this.ErrorResult(
ActivityErrorId.GenericError,
"The company '{0}' ({1}) does not have an AppNexus advertiser id ({2})",
company.ExternalName,
company.ExternalEntityId,
AppNexusEntityProperties.AdvertiserId);
}
var campaign = this.Repository.TryGetEntity(context, campaignEntityId) as CampaignEntity;
if (campaign == null)
{
return this.EntityNotFoundError(campaignEntityId);
}
var associatedCreatives = campaign.Associations
.Where(a => a.TargetEntityCategory == CreativeEntity.CategoryName)
.Select(a => this.Repository.TryGetEntity(context, a.TargetEntityId))
.Where(c => c != null)
.OfType<CreativeEntity>()
.Select(c => c.GetAppNexusCreativeId())
.Where(id => id != null)
.ToArray();
using (var client = CreateAppNexusClient(user.UserId))
{
var creatives = client.GetAdvertiserCreatives(advertiserId.Value);
var unassociatedCreatives = creatives
.Where(creative => !associatedCreatives.Contains((int)creative[AppNexusValues.Id]));
var creativesJson = JsonConvert.SerializeObject(unassociatedCreatives);
return this.SuccessResult(new Dictionary<string, string>
{
{ AppNexusActivityValues.Creatives, creativesJson }
});
}
}
}
|
[
"[",
"Name",
"(",
"AppNexusActivityTasks",
".",
"GetCreatives",
")",
"]",
"[",
"RequiredValues",
"(",
"EntityActivityValues",
".",
"AuthUserId",
",",
"EntityActivityValues",
".",
"CompanyEntityId",
",",
"EntityActivityValues",
".",
"CampaignEntityId",
")",
"]",
"public",
"class",
"GetCreativesActivity",
":",
"AppNexusActivity",
"{",
"public",
"override",
"ActivityRuntimeCategory",
"RuntimeCategory",
"{",
"get",
"{",
"return",
"ActivityRuntimeCategory",
".",
"InteractiveFetch",
";",
"}",
"}",
"protected",
"override",
"ActivityResult",
"ProcessAppNexusRequest",
"(",
"ActivityRequest",
"request",
")",
"{",
"var",
"context",
"=",
"CreateRepositoryContext",
"(",
"RepositoryContextType",
".",
"InternalEntityGet",
",",
"request",
")",
";",
"var",
"companyEntityId",
"=",
"new",
"EntityId",
"(",
"request",
".",
"Values",
"[",
"EntityActivityValues",
".",
"CompanyEntityId",
"]",
")",
";",
"var",
"campaignEntityId",
"=",
"new",
"EntityId",
"(",
"request",
".",
"Values",
"[",
"EntityActivityValues",
".",
"CampaignEntityId",
"]",
")",
";",
"var",
"userId",
"=",
"request",
".",
"Values",
"[",
"EntityActivityValues",
".",
"AuthUserId",
"]",
";",
"var",
"user",
"=",
"this",
".",
"Repository",
".",
"GetUser",
"(",
"context",
",",
"userId",
")",
";",
"if",
"(",
"user",
".",
"GetUserType",
"(",
")",
"!=",
"UserType",
".",
"AppNexusApp",
")",
"{",
"return",
"ErrorResult",
"(",
"ActivityErrorId",
".",
"GenericError",
",",
"\"",
"Activity not supported for non-AppNexusApp users",
"\"",
")",
";",
"}",
"var",
"company",
"=",
"this",
".",
"Repository",
".",
"TryGetEntity",
"(",
"context",
",",
"companyEntityId",
")",
"as",
"CompanyEntity",
";",
"if",
"(",
"company",
"==",
"null",
")",
"{",
"return",
"this",
".",
"EntityNotFoundError",
"(",
"companyEntityId",
")",
";",
"}",
"var",
"advertiserId",
"=",
"(",
"(",
"CompanyEntity",
")",
"company",
")",
".",
"GetAppNexusAdvertiserId",
"(",
")",
";",
"if",
"(",
"!",
"advertiserId",
".",
"HasValue",
")",
"{",
"return",
"this",
".",
"ErrorResult",
"(",
"ActivityErrorId",
".",
"GenericError",
",",
"\"",
"The company '{0}' ({1}) does not have an AppNexus advertiser id ({2})",
"\"",
",",
"company",
".",
"ExternalName",
",",
"company",
".",
"ExternalEntityId",
",",
"AppNexusEntityProperties",
".",
"AdvertiserId",
")",
";",
"}",
"var",
"campaign",
"=",
"this",
".",
"Repository",
".",
"TryGetEntity",
"(",
"context",
",",
"campaignEntityId",
")",
"as",
"CampaignEntity",
";",
"if",
"(",
"campaign",
"==",
"null",
")",
"{",
"return",
"this",
".",
"EntityNotFoundError",
"(",
"campaignEntityId",
")",
";",
"}",
"var",
"associatedCreatives",
"=",
"campaign",
".",
"Associations",
".",
"Where",
"(",
"a",
"=>",
"a",
".",
"TargetEntityCategory",
"==",
"CreativeEntity",
".",
"CategoryName",
")",
".",
"Select",
"(",
"a",
"=>",
"this",
".",
"Repository",
".",
"TryGetEntity",
"(",
"context",
",",
"a",
".",
"TargetEntityId",
")",
")",
".",
"Where",
"(",
"c",
"=>",
"c",
"!=",
"null",
")",
".",
"OfType",
"<",
"CreativeEntity",
">",
"(",
")",
".",
"Select",
"(",
"c",
"=>",
"c",
".",
"GetAppNexusCreativeId",
"(",
")",
")",
".",
"Where",
"(",
"id",
"=>",
"id",
"!=",
"null",
")",
".",
"ToArray",
"(",
")",
";",
"using",
"(",
"var",
"client",
"=",
"CreateAppNexusClient",
"(",
"user",
".",
"UserId",
")",
")",
"{",
"var",
"creatives",
"=",
"client",
".",
"GetAdvertiserCreatives",
"(",
"advertiserId",
".",
"Value",
")",
";",
"var",
"unassociatedCreatives",
"=",
"creatives",
".",
"Where",
"(",
"creative",
"=>",
"!",
"associatedCreatives",
".",
"Contains",
"(",
"(",
"int",
")",
"creative",
"[",
"AppNexusValues",
".",
"Id",
"]",
")",
")",
";",
"var",
"creativesJson",
"=",
"JsonConvert",
".",
"SerializeObject",
"(",
"unassociatedCreatives",
")",
";",
"return",
"this",
".",
"SuccessResult",
"(",
"new",
"Dictionary",
"<",
"string",
",",
"string",
">",
"{",
"{",
"AppNexusActivityValues",
".",
"Creatives",
",",
"creativesJson",
"}",
"}",
")",
";",
"}",
"}",
"}"
] |
Activity for getting creatives for an AppNexus advertiser
|
[
"Activity",
"for",
"getting",
"creatives",
"for",
"an",
"AppNexus",
"advertiser"
] |
[
"/// <summary>Gets the activity's runtime category</summary>",
"/// <summary>Processes the request and returns the result</summary>",
"/// <param name=\"request\">The request containing the activity input</param>",
"/// <returns>The result containing the output of the activity</returns>",
"// Check that user is an AppNexusApp user",
"// Get the company's AppNexus advertiser id",
"// Get the campaign to check for existing creatives",
"// Get the campaigns's existing creatives",
"// Get the advertiser's creatives (excluding those already imported)"
] |
[
{
"param": "AppNexusActivity",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "AppNexusActivity",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": [
{
"identifier": "remarks",
"docstring": "Retrieves creatives for an advertiser from AppNexus\nRequiredValues:\nAuthUserId - The user's user id (used to call AppNexus APIs)\nCompanyEntityId - The EntityId of the advertiser CompanyEntity\nCampaignEntityId - The EntityId of the Campaign",
"docstring_tokens": [
"Retrieves",
"creatives",
"for",
"an",
"advertiser",
"from",
"AppNexus",
"RequiredValues",
":",
"AuthUserId",
"-",
"The",
"user",
"'",
"s",
"user",
"id",
"(",
"used",
"to",
"call",
"AppNexus",
"APIs",
")",
"CompanyEntityId",
"-",
"The",
"EntityId",
"of",
"the",
"advertiser",
"CompanyEntity",
"CampaignEntityId",
"-",
"The",
"EntityId",
"of",
"the",
"Campaign"
]
}
]
}
| false
| 26
| 584
| 92
|
146b9d195887e032e78c4027c8fa26eb75d1b60c
|
macio-matheus/algorithms-and-data-structure-practices
|
machine_learning_kmeans.py
|
[
"Apache-2.0"
] |
Python
|
KMeans
|
1. Choose the number of clusters(K) and obtain the data points
2. Place the centroids c_1, c_2, ..... c_k randomly
3. Repeat steps 4 and 5 until convergence or until the end of a fixed number of iterations
4. for each data point x_i:
- find the nearest centroid(c_1, c_2 .. c_k)
- assign the point to that cluster
5. for each cluster j = 1..k
- new centroid = mean of all points assigned to that cluster
6. End
|
1. Choose the number of clusters(K) and obtain the data points
2.
|
[
"1",
".",
"Choose",
"the",
"number",
"of",
"clusters",
"(",
"K",
")",
"and",
"obtain",
"the",
"data",
"points",
"2",
"."
] |
class KMeans:
"""
1. Choose the number of clusters(K) and obtain the data points
2. Place the centroids c_1, c_2, ..... c_k randomly
3. Repeat steps 4 and 5 until convergence or until the end of a fixed number of iterations
4. for each data point x_i:
- find the nearest centroid(c_1, c_2 .. c_k)
- assign the point to that cluster
5. for each cluster j = 1..k
- new centroid = mean of all points assigned to that cluster
6. End
"""
def __init__(self, k: int = 5):
self.k = k
self.centers = None
self.ini_centers = None
def fit(self, data: np.array):
"""
Fits kmeans
"""
n_samples, _ = data.shape
# initialize cluster centers
self.centers = np.array(random.sample(list(data), self.k))
self.ini_centers = np.copy(self.centers)
old_data_point_assignment = None
n_iters = 0
while True:
data_point_assignment = [self.classify(datapoint) for datapoint in data]
# If data point assignments stop changing, then we find the model
if data_point_assignment == old_data_point_assignment:
print(f"Training finished.. {n_iters} iterations!")
print(f"Points assignment: {data_point_assignment}")
return
old_data_point_assignment = data_point_assignment
n_iters = n_iters + 1
# recalculate centers
for i in range(self.k):
points_idx = np.where(np.array(data_point_assignment) == i)
datapoints = data[points_idx]
self.centers[i] = datapoints.mean(axis=0)
def euclidean_distance(self, data):
return np.sqrt(np.sum((self.centers - data) ** 2, axis=1))
def classify(self, data):
"""
Return the cluster ID of that cluster.
"""
return np.argmin(self.euclidean_distance(data))
def show_clusters(self, data):
plt.figure(figsize=(10, 8))
plt.title("Initial centers in black, final centers in red")
plt.scatter(data[:, 0], data[:, 1], marker='.', c=y)
plt.scatter(self.centers[:, 0], self.centers[:, 1], c='r')
plt.scatter(self.ini_centers[:, 0], self.ini_centers[:, 1], c='k')
plt.show()
|
[
"class",
"KMeans",
":",
"def",
"__init__",
"(",
"self",
",",
"k",
":",
"int",
"=",
"5",
")",
":",
"self",
".",
"k",
"=",
"k",
"self",
".",
"centers",
"=",
"None",
"self",
".",
"ini_centers",
"=",
"None",
"def",
"fit",
"(",
"self",
",",
"data",
":",
"np",
".",
"array",
")",
":",
"\"\"\"\n Fits kmeans\n \"\"\"",
"n_samples",
",",
"_",
"=",
"data",
".",
"shape",
"self",
".",
"centers",
"=",
"np",
".",
"array",
"(",
"random",
".",
"sample",
"(",
"list",
"(",
"data",
")",
",",
"self",
".",
"k",
")",
")",
"self",
".",
"ini_centers",
"=",
"np",
".",
"copy",
"(",
"self",
".",
"centers",
")",
"old_data_point_assignment",
"=",
"None",
"n_iters",
"=",
"0",
"while",
"True",
":",
"data_point_assignment",
"=",
"[",
"self",
".",
"classify",
"(",
"datapoint",
")",
"for",
"datapoint",
"in",
"data",
"]",
"if",
"data_point_assignment",
"==",
"old_data_point_assignment",
":",
"print",
"(",
"f\"Training finished.. {n_iters} iterations!\"",
")",
"print",
"(",
"f\"Points assignment: {data_point_assignment}\"",
")",
"return",
"old_data_point_assignment",
"=",
"data_point_assignment",
"n_iters",
"=",
"n_iters",
"+",
"1",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"k",
")",
":",
"points_idx",
"=",
"np",
".",
"where",
"(",
"np",
".",
"array",
"(",
"data_point_assignment",
")",
"==",
"i",
")",
"datapoints",
"=",
"data",
"[",
"points_idx",
"]",
"self",
".",
"centers",
"[",
"i",
"]",
"=",
"datapoints",
".",
"mean",
"(",
"axis",
"=",
"0",
")",
"def",
"euclidean_distance",
"(",
"self",
",",
"data",
")",
":",
"return",
"np",
".",
"sqrt",
"(",
"np",
".",
"sum",
"(",
"(",
"self",
".",
"centers",
"-",
"data",
")",
"**",
"2",
",",
"axis",
"=",
"1",
")",
")",
"def",
"classify",
"(",
"self",
",",
"data",
")",
":",
"\"\"\"\n Return the cluster ID of that cluster.\n \"\"\"",
"return",
"np",
".",
"argmin",
"(",
"self",
".",
"euclidean_distance",
"(",
"data",
")",
")",
"def",
"show_clusters",
"(",
"self",
",",
"data",
")",
":",
"plt",
".",
"figure",
"(",
"figsize",
"=",
"(",
"10",
",",
"8",
")",
")",
"plt",
".",
"title",
"(",
"\"Initial centers in black, final centers in red\"",
")",
"plt",
".",
"scatter",
"(",
"data",
"[",
":",
",",
"0",
"]",
",",
"data",
"[",
":",
",",
"1",
"]",
",",
"marker",
"=",
"'.'",
",",
"c",
"=",
"y",
")",
"plt",
".",
"scatter",
"(",
"self",
".",
"centers",
"[",
":",
",",
"0",
"]",
",",
"self",
".",
"centers",
"[",
":",
",",
"1",
"]",
",",
"c",
"=",
"'r'",
")",
"plt",
".",
"scatter",
"(",
"self",
".",
"ini_centers",
"[",
":",
",",
"0",
"]",
",",
"self",
".",
"ini_centers",
"[",
":",
",",
"1",
"]",
",",
"c",
"=",
"'k'",
")",
"plt",
".",
"show",
"(",
")"
] |
1.
|
[
"1",
"."
] |
[
"\"\"\"\n 1. Choose the number of clusters(K) and obtain the data points\n 2. Place the centroids c_1, c_2, ..... c_k randomly\n 3. Repeat steps 4 and 5 until convergence or until the end of a fixed number of iterations\n 4. for each data point x_i:\n - find the nearest centroid(c_1, c_2 .. c_k)\n - assign the point to that cluster\n 5. for each cluster j = 1..k\n - new centroid = mean of all points assigned to that cluster\n 6. End\n \"\"\"",
"\"\"\"\n Fits kmeans\n \"\"\"",
"# initialize cluster centers",
"# If data point assignments stop changing, then we find the model",
"# recalculate centers",
"\"\"\"\n Return the cluster ID of that cluster.\n \"\"\""
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 16
| 557
| 134
|
e68c0677e87292cc5e3f188442354d7d7f61cab8
|
hyacker/eventgen
|
splunk_eventgen/lib/plugins/output/s2s.py
|
[
"Apache-2.0"
] |
Python
|
S2S
|
Encode and send events to Splunk over the S2S V2 wire protocol.
It should be noted V2 is a much older protocol and is no longer utilized by any Splunk Forwarder.
It should still work, but its a very simple protocol and we've advanced pretty far since then.
However, if you have fully cooked events, its very lightweight and very easy to implement
which is why I elected to implement this version.
|
Encode and send events to Splunk over the S2S V2 wire protocol.
It should be noted V2 is a much older protocol and is no longer utilized by any Splunk Forwarder.
It should still work, but its a very simple protocol and we've advanced pretty far since then.
However, if you have fully cooked events, its very lightweight and very easy to implement
which is why I elected to implement this version.
|
[
"Encode",
"and",
"send",
"events",
"to",
"Splunk",
"over",
"the",
"S2S",
"V2",
"wire",
"protocol",
".",
"It",
"should",
"be",
"noted",
"V2",
"is",
"a",
"much",
"older",
"protocol",
"and",
"is",
"no",
"longer",
"utilized",
"by",
"any",
"Splunk",
"Forwarder",
".",
"It",
"should",
"still",
"work",
"but",
"its",
"a",
"very",
"simple",
"protocol",
"and",
"we",
"'",
"ve",
"advanced",
"pretty",
"far",
"since",
"then",
".",
"However",
"if",
"you",
"have",
"fully",
"cooked",
"events",
"its",
"very",
"lightweight",
"and",
"very",
"easy",
"to",
"implement",
"which",
"is",
"why",
"I",
"elected",
"to",
"implement",
"this",
"version",
"."
] |
class S2S:
"""
Encode and send events to Splunk over the S2S V2 wire protocol.
It should be noted V2 is a much older protocol and is no longer utilized by any Splunk Forwarder.
It should still work, but its a very simple protocol and we've advanced pretty far since then.
However, if you have fully cooked events, its very lightweight and very easy to implement
which is why I elected to implement this version.
"""
s = None
signature_sent = None
useOutputQueue = True
def __init__(self, host='localhost', port=9997):
"""
Initialize object. Need to know Splunk host and port for the TCP Receiver
"""
self._open_connection(host, port)
self.signature_sent = False
def _open_connection(self, host='localhost', port=9997):
"""
Open a connection to Splunk and return a socket
"""
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.s.connect((host, int(port)))
def _encode_sig(self, serverName='s2s-api', mgmtPort='9997'):
"""
Create Signature element of the S2S Message. Signature is C struct:
struct S2S_Signature
{
char _signature[128];
char _serverName[256];
char _mgmtPort[16];
};
"""
if not self.signature_sent:
self.signature_sent = True
return struct.pack('!128s256s16s', '--splunk-cooked-mode-v2--', serverName, mgmtPort)
else:
return ''
def _encode_string(self, tosend=''):
"""
Encode a string to be sent across the wire to splunk
Wire protocol has an unsigned integer of the length of the string followed
by a null terminated string.
"""
tosend = str(tosend)
return struct.pack('!I%ds' % (len(tosend)+1), len(tosend)+1, tosend)
def _encode_key_value(self, key='', value=''):
"""
Encode a key/value pair to send across the wire to splunk
A key value pair is merely a concatenated set of encoded strings.
"""
return '%s%s' % (self._encode_string(key), self._encode_string(value))
def _encode_event(self, index='main', host='', source='', sourcetype='', _raw='_done', _time=None):
# Create signature
sig = self._encode_sig()
msg_size = len(struct.pack('!I', 0)) # size of unsigned 32 bit integer, which is the count of map entries
maps = 1
# May not have these, so set them first
encoded_source = False
encoded_sourcetype = False
encoded_host = False
encoded_index = False
# Encode source
if len(source) > 0:
encoded_source = self._encode_key_value('MetaData:Source', 'source::'+source)
maps += 1
msg_size += len(encoded_source)
# Encode sourcetype
if len(sourcetype) > 0:
encoded_sourcetype = self._encode_key_value('MetaData:Sourcetype', 'sourcetype::'+sourcetype)
maps += 1
msg_size += len(encoded_sourcetype)
# Encode host
if len(host) > 0:
encoded_host = self._encode_key_value('MetaData:Host', 'host::'+host)
maps += 1
msg_size += len(encoded_host)
# Encode index
encoded_index = self._encode_key_value('_MetaData:Index', index)
maps += 1
msg_size += len(encoded_index)
# Encode _raw
encoded_raw = self._encode_key_value('_raw', _raw)
msg_size += len(encoded_raw)
# Will include a 32 bit integer 0 between the end of raw and the _raw trailer
msg_size += len(struct.pack('!I', 0))
# Encode "_raw" trailer... seems to just the string '_raw' repeated again at the end of the _raw field
encoded_raw_trailer = self._encode_string('_raw')
msg_size += len(encoded_raw_trailer)
# Add _done... Not sure if there's a penalty to setting this for every event
# but otherwise we don't flush immediately
encoded_done = self._encode_key_value('_done', '_done')
maps += 1
msg_size += len(encoded_done)
# Encode _time
if _time != None:
encoded_time = self._encode_key_value('_time', _time)
msg_size += len(encoded_time)
maps += 1
# Create buffer, starting with the signature
buf = sig
# Add 32 bit integer with the size of the msg, calculated earlier
buf += struct.pack('!I', msg_size)
# Add number of map entries, which is 5, index, host, source, sourcetype, raw
buf += struct.pack('!I', maps)
# Add the map entries, index, source, sourcetype, host, raw
buf += encoded_index
buf += encoded_host if encoded_host else ''
buf += encoded_source if encoded_source else ''
buf += encoded_sourcetype if encoded_sourcetype else ''
buf += encoded_time if encoded_time else ''
buf += encoded_done
buf += encoded_raw
# Add dummy zero
buf += struct.pack('!I', 0)
# Add trailer raw
buf += encoded_raw_trailer
return buf
def send_event(self, index='main', host='', source='', sourcetype='', _raw='', _time=None):
"""
Encode and send an event to Splunk
"""
if len(_raw) > 0:
e = self._encode_event(index, host, source, sourcetype, _raw, _time)
self.s.sendall(e)
def close(self):
"""
Close connection and send final done event
"""
self.s.close()
|
[
"class",
"S2S",
":",
"s",
"=",
"None",
"signature_sent",
"=",
"None",
"useOutputQueue",
"=",
"True",
"def",
"__init__",
"(",
"self",
",",
"host",
"=",
"'localhost'",
",",
"port",
"=",
"9997",
")",
":",
"\"\"\"\n Initialize object. Need to know Splunk host and port for the TCP Receiver\n \"\"\"",
"self",
".",
"_open_connection",
"(",
"host",
",",
"port",
")",
"self",
".",
"signature_sent",
"=",
"False",
"def",
"_open_connection",
"(",
"self",
",",
"host",
"=",
"'localhost'",
",",
"port",
"=",
"9997",
")",
":",
"\"\"\"\n Open a connection to Splunk and return a socket\n \"\"\"",
"self",
".",
"s",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"self",
".",
"s",
".",
"connect",
"(",
"(",
"host",
",",
"int",
"(",
"port",
")",
")",
")",
"def",
"_encode_sig",
"(",
"self",
",",
"serverName",
"=",
"'s2s-api'",
",",
"mgmtPort",
"=",
"'9997'",
")",
":",
"\"\"\"\n Create Signature element of the S2S Message. Signature is C struct:\n\n struct S2S_Signature\n {\n char _signature[128];\n char _serverName[256];\n char _mgmtPort[16];\n };\n \"\"\"",
"if",
"not",
"self",
".",
"signature_sent",
":",
"self",
".",
"signature_sent",
"=",
"True",
"return",
"struct",
".",
"pack",
"(",
"'!128s256s16s'",
",",
"'--splunk-cooked-mode-v2--'",
",",
"serverName",
",",
"mgmtPort",
")",
"else",
":",
"return",
"''",
"def",
"_encode_string",
"(",
"self",
",",
"tosend",
"=",
"''",
")",
":",
"\"\"\"\n Encode a string to be sent across the wire to splunk\n\n Wire protocol has an unsigned integer of the length of the string followed\n by a null terminated string.\n \"\"\"",
"tosend",
"=",
"str",
"(",
"tosend",
")",
"return",
"struct",
".",
"pack",
"(",
"'!I%ds'",
"%",
"(",
"len",
"(",
"tosend",
")",
"+",
"1",
")",
",",
"len",
"(",
"tosend",
")",
"+",
"1",
",",
"tosend",
")",
"def",
"_encode_key_value",
"(",
"self",
",",
"key",
"=",
"''",
",",
"value",
"=",
"''",
")",
":",
"\"\"\"\n Encode a key/value pair to send across the wire to splunk\n\n A key value pair is merely a concatenated set of encoded strings.\n \"\"\"",
"return",
"'%s%s'",
"%",
"(",
"self",
".",
"_encode_string",
"(",
"key",
")",
",",
"self",
".",
"_encode_string",
"(",
"value",
")",
")",
"def",
"_encode_event",
"(",
"self",
",",
"index",
"=",
"'main'",
",",
"host",
"=",
"''",
",",
"source",
"=",
"''",
",",
"sourcetype",
"=",
"''",
",",
"_raw",
"=",
"'_done'",
",",
"_time",
"=",
"None",
")",
":",
"sig",
"=",
"self",
".",
"_encode_sig",
"(",
")",
"msg_size",
"=",
"len",
"(",
"struct",
".",
"pack",
"(",
"'!I'",
",",
"0",
")",
")",
"maps",
"=",
"1",
"encoded_source",
"=",
"False",
"encoded_sourcetype",
"=",
"False",
"encoded_host",
"=",
"False",
"encoded_index",
"=",
"False",
"if",
"len",
"(",
"source",
")",
">",
"0",
":",
"encoded_source",
"=",
"self",
".",
"_encode_key_value",
"(",
"'MetaData:Source'",
",",
"'source::'",
"+",
"source",
")",
"maps",
"+=",
"1",
"msg_size",
"+=",
"len",
"(",
"encoded_source",
")",
"if",
"len",
"(",
"sourcetype",
")",
">",
"0",
":",
"encoded_sourcetype",
"=",
"self",
".",
"_encode_key_value",
"(",
"'MetaData:Sourcetype'",
",",
"'sourcetype::'",
"+",
"sourcetype",
")",
"maps",
"+=",
"1",
"msg_size",
"+=",
"len",
"(",
"encoded_sourcetype",
")",
"if",
"len",
"(",
"host",
")",
">",
"0",
":",
"encoded_host",
"=",
"self",
".",
"_encode_key_value",
"(",
"'MetaData:Host'",
",",
"'host::'",
"+",
"host",
")",
"maps",
"+=",
"1",
"msg_size",
"+=",
"len",
"(",
"encoded_host",
")",
"encoded_index",
"=",
"self",
".",
"_encode_key_value",
"(",
"'_MetaData:Index'",
",",
"index",
")",
"maps",
"+=",
"1",
"msg_size",
"+=",
"len",
"(",
"encoded_index",
")",
"encoded_raw",
"=",
"self",
".",
"_encode_key_value",
"(",
"'_raw'",
",",
"_raw",
")",
"msg_size",
"+=",
"len",
"(",
"encoded_raw",
")",
"msg_size",
"+=",
"len",
"(",
"struct",
".",
"pack",
"(",
"'!I'",
",",
"0",
")",
")",
"encoded_raw_trailer",
"=",
"self",
".",
"_encode_string",
"(",
"'_raw'",
")",
"msg_size",
"+=",
"len",
"(",
"encoded_raw_trailer",
")",
"encoded_done",
"=",
"self",
".",
"_encode_key_value",
"(",
"'_done'",
",",
"'_done'",
")",
"maps",
"+=",
"1",
"msg_size",
"+=",
"len",
"(",
"encoded_done",
")",
"if",
"_time",
"!=",
"None",
":",
"encoded_time",
"=",
"self",
".",
"_encode_key_value",
"(",
"'_time'",
",",
"_time",
")",
"msg_size",
"+=",
"len",
"(",
"encoded_time",
")",
"maps",
"+=",
"1",
"buf",
"=",
"sig",
"buf",
"+=",
"struct",
".",
"pack",
"(",
"'!I'",
",",
"msg_size",
")",
"buf",
"+=",
"struct",
".",
"pack",
"(",
"'!I'",
",",
"maps",
")",
"buf",
"+=",
"encoded_index",
"buf",
"+=",
"encoded_host",
"if",
"encoded_host",
"else",
"''",
"buf",
"+=",
"encoded_source",
"if",
"encoded_source",
"else",
"''",
"buf",
"+=",
"encoded_sourcetype",
"if",
"encoded_sourcetype",
"else",
"''",
"buf",
"+=",
"encoded_time",
"if",
"encoded_time",
"else",
"''",
"buf",
"+=",
"encoded_done",
"buf",
"+=",
"encoded_raw",
"buf",
"+=",
"struct",
".",
"pack",
"(",
"'!I'",
",",
"0",
")",
"buf",
"+=",
"encoded_raw_trailer",
"return",
"buf",
"def",
"send_event",
"(",
"self",
",",
"index",
"=",
"'main'",
",",
"host",
"=",
"''",
",",
"source",
"=",
"''",
",",
"sourcetype",
"=",
"''",
",",
"_raw",
"=",
"''",
",",
"_time",
"=",
"None",
")",
":",
"\"\"\"\n Encode and send an event to Splunk\n \"\"\"",
"if",
"len",
"(",
"_raw",
")",
">",
"0",
":",
"e",
"=",
"self",
".",
"_encode_event",
"(",
"index",
",",
"host",
",",
"source",
",",
"sourcetype",
",",
"_raw",
",",
"_time",
")",
"self",
".",
"s",
".",
"sendall",
"(",
"e",
")",
"def",
"close",
"(",
"self",
")",
":",
"\"\"\"\n Close connection and send final done event\n \"\"\"",
"self",
".",
"s",
".",
"close",
"(",
")"
] |
Encode and send events to Splunk over the S2S V2 wire protocol.
|
[
"Encode",
"and",
"send",
"events",
"to",
"Splunk",
"over",
"the",
"S2S",
"V2",
"wire",
"protocol",
"."
] |
[
"\"\"\"\n Encode and send events to Splunk over the S2S V2 wire protocol.\n\n It should be noted V2 is a much older protocol and is no longer utilized by any Splunk Forwarder.\n It should still work, but its a very simple protocol and we've advanced pretty far since then.\n However, if you have fully cooked events, its very lightweight and very easy to implement\n which is why I elected to implement this version.\n \"\"\"",
"\"\"\"\n Initialize object. Need to know Splunk host and port for the TCP Receiver\n \"\"\"",
"\"\"\"\n Open a connection to Splunk and return a socket\n \"\"\"",
"\"\"\"\n Create Signature element of the S2S Message. Signature is C struct:\n\n struct S2S_Signature\n {\n char _signature[128];\n char _serverName[256];\n char _mgmtPort[16];\n };\n \"\"\"",
"\"\"\"\n Encode a string to be sent across the wire to splunk\n\n Wire protocol has an unsigned integer of the length of the string followed\n by a null terminated string.\n \"\"\"",
"\"\"\"\n Encode a key/value pair to send across the wire to splunk\n\n A key value pair is merely a concatenated set of encoded strings.\n \"\"\"",
"# Create signature",
"# size of unsigned 32 bit integer, which is the count of map entries",
"# May not have these, so set them first",
"# Encode source",
"# Encode sourcetype",
"# Encode host",
"# Encode index",
"# Encode _raw",
"# Will include a 32 bit integer 0 between the end of raw and the _raw trailer",
"# Encode \"_raw\" trailer... seems to just the string '_raw' repeated again at the end of the _raw field",
"# Add _done... Not sure if there's a penalty to setting this for every event",
"# but otherwise we don't flush immediately",
"# Encode _time",
"# Create buffer, starting with the signature",
"# Add 32 bit integer with the size of the msg, calculated earlier",
"# Add number of map entries, which is 5, index, host, source, sourcetype, raw",
"# Add the map entries, index, source, sourcetype, host, raw",
"# Add dummy zero",
"# Add trailer raw",
"\"\"\"\n Encode and send an event to Splunk\n \"\"\"",
"\"\"\"\n Close connection and send final done event\n \"\"\""
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 13
| 1,366
| 95
|
0a0606268c94efb6d2939980c85367d7365c2054
|
drhee/toxoMine
|
intermine/objectstore/main/src/org/intermine/objectstore/query/QueryObjectPathExpression.java
|
[
"PostgreSQL"
] |
Java
|
QueryObjectPathExpression
|
/**
* An element that can appear in the SELECT clause of a query, representing extra data to be
* collected for the Results - namely a object referenced by some other object in the results. In
* order to reference further into this reference, this class contains many of the features of
* Query. That is, you can add QueryFields and QueryPathExpressions to the SELECT list. You can also
* add QueryClasses to the FROM list and constraints to the WHERE clause. A default QueryClass
* corresponding to the reference is available from the getDefaultClass method. Counter-intuitively,
* this path expression may return multiple rows per original row, if extra things are added to the
* FROM list for example. In this case, this object should be on the SELECT list of the original
* Query. In the case where this object is guaranteed to return a maximum of one row per original
* row, then PathExpressionField objects should be put in the SELECT list of the original query
* instead. The definition is that if this object contains anything in the FROM element, then we
* cannot guarantee that it will only have one row per original row.
*
* @author Matthew Wakeling
*/
|
An element that can appear in the SELECT clause of a query, representing extra data to be
collected for the Results - namely a object referenced by some other object in the results. In
order to reference further into this reference, this class contains many of the features of
Query. That is, you can add QueryFields and QueryPathExpressions to the SELECT list. You can also
add QueryClasses to the FROM list and constraints to the WHERE clause. A default QueryClass
corresponding to the reference is available from the getDefaultClass method. Counter-intuitively,
this path expression may return multiple rows per original row, if extra things are added to the
FROM list for example. In this case, this object should be on the SELECT list of the original
Query. In the case where this object is guaranteed to return a maximum of one row per original
row, then PathExpressionField objects should be put in the SELECT list of the original query
instead. The definition is that if this object contains anything in the FROM element, then we
cannot guarantee that it will only have one row per original row.
@author Matthew Wakeling
|
[
"An",
"element",
"that",
"can",
"appear",
"in",
"the",
"SELECT",
"clause",
"of",
"a",
"query",
"representing",
"extra",
"data",
"to",
"be",
"collected",
"for",
"the",
"Results",
"-",
"namely",
"a",
"object",
"referenced",
"by",
"some",
"other",
"object",
"in",
"the",
"results",
".",
"In",
"order",
"to",
"reference",
"further",
"into",
"this",
"reference",
"this",
"class",
"contains",
"many",
"of",
"the",
"features",
"of",
"Query",
".",
"That",
"is",
"you",
"can",
"add",
"QueryFields",
"and",
"QueryPathExpressions",
"to",
"the",
"SELECT",
"list",
".",
"You",
"can",
"also",
"add",
"QueryClasses",
"to",
"the",
"FROM",
"list",
"and",
"constraints",
"to",
"the",
"WHERE",
"clause",
".",
"A",
"default",
"QueryClass",
"corresponding",
"to",
"the",
"reference",
"is",
"available",
"from",
"the",
"getDefaultClass",
"method",
".",
"Counter",
"-",
"intuitively",
"this",
"path",
"expression",
"may",
"return",
"multiple",
"rows",
"per",
"original",
"row",
"if",
"extra",
"things",
"are",
"added",
"to",
"the",
"FROM",
"list",
"for",
"example",
".",
"In",
"this",
"case",
"this",
"object",
"should",
"be",
"on",
"the",
"SELECT",
"list",
"of",
"the",
"original",
"Query",
".",
"In",
"the",
"case",
"where",
"this",
"object",
"is",
"guaranteed",
"to",
"return",
"a",
"maximum",
"of",
"one",
"row",
"per",
"original",
"row",
"then",
"PathExpressionField",
"objects",
"should",
"be",
"put",
"in",
"the",
"SELECT",
"list",
"of",
"the",
"original",
"query",
"instead",
".",
"The",
"definition",
"is",
"that",
"if",
"this",
"object",
"contains",
"anything",
"in",
"the",
"FROM",
"element",
"then",
"we",
"cannot",
"guarantee",
"that",
"it",
"will",
"only",
"have",
"one",
"row",
"per",
"original",
"row",
".",
"@author",
"Matthew",
"Wakeling"
] |
public class QueryObjectPathExpression implements QueryPathExpressionWithSelect, Queryable
{
private QueryClass qc;
private String fieldName;
private Class<? extends InterMineObject> type;
private Class<? extends FastPathObject> subclass = null;
private QueryClass defaultClass;
private List<QuerySelectable> selectList = new ArrayList<QuerySelectable>();
private Constraint constraint = null;
/**
* Constructs a QueryObjectPathExpression representing an object reference from the given
* QueryClass to the given fieldname.
*
* @param qc the QueryClass
* @param fieldName the name of the relevant field
* @throws IllegalArgumentException if the field is not an object reference
*/
public QueryObjectPathExpression(QueryClass qc, String fieldName) {
if (fieldName == null) {
throw new NullPointerException("Field name parameter is null");
}
if (qc == null) {
throw new NullPointerException("QueryClass parameter is null");
}
Method field = TypeUtil.getGetter(qc.getType(), fieldName);
if (field == null) {
throw new IllegalArgumentException("Field " + fieldName + " not found in "
+ qc.getType());
}
if (Collection.class.isAssignableFrom(field.getReturnType())) {
throw new IllegalArgumentException("Field " + fieldName + " is a collection type");
}
if (!InterMineObject.class.isAssignableFrom(field.getReturnType())) {
throw new IllegalArgumentException("Field " + fieldName + " is not an object reference"
+ " type - was " + field.getReturnType() + " instead");
}
this.qc = qc;
this.fieldName = fieldName;
@SuppressWarnings("unchecked") Class<? extends InterMineObject> tmpType =
(Class) field.getReturnType();
this.type = tmpType;
defaultClass = new QueryClass(type);
}
/**
* Constructs a QueryObjectPathExpression representing an object reference from the given
* QueryClass to the given fieldname, constrained to be a particular subclass.
*
* @param qc the QueryClass
* @param fieldName the name of the relevant field
* @param subclasses a Class that is a subclass of the field class
* @throws IllegalArgumentException if the field is not an object reference
*/
public QueryObjectPathExpression(QueryClass qc, String fieldName, Class<?>... subclasses) {
subclass = DynamicUtil.composeDescriptiveClass(subclasses);
if (fieldName == null) {
throw new NullPointerException("Field name parameter is null");
}
if (qc == null) {
throw new NullPointerException("QueryClass parameter is null");
}
if (subclass == null) {
throw new NullPointerException("Subclass parameter is null");
}
Method field = TypeUtil.getGetter(qc.getType(), fieldName);
if (field == null) {
throw new IllegalArgumentException("Field " + fieldName + " not found in "
+ qc.getType());
}
if (Collection.class.isAssignableFrom(field.getReturnType())) {
throw new IllegalArgumentException("Field " + fieldName + " is a collection type");
}
if (!InterMineObject.class.isAssignableFrom(field.getReturnType())) {
throw new IllegalArgumentException("Field " + fieldName + " is not an object reference"
+ " type - was " + field.getReturnType() + " instead");
}
if (!field.getReturnType().isAssignableFrom(subclass)) {
throw new IllegalArgumentException("subclass parameter " + subclass.getName()
+ " is not a subclass of reference type " + type.getName());
}
this.qc = qc;
this.fieldName = fieldName;
@SuppressWarnings("unchecked") Class<? extends InterMineObject> tmpType =
(Class) field.getReturnType();
this.type = tmpType;
defaultClass = new QueryClass(subclass);
if (subclass.equals(type)) {
subclass = null;
}
}
/**
* Returns the QueryClass of which the field is a member.
*
* @return the QueryClass
*/
public QueryClass getQueryClass() {
return qc;
}
/**
* Returns the name of the field.
*
* @return field name
*/
public String getFieldName() {
return fieldName;
}
/**
* Returns the subclass if it exists.
*
* @return the subclass
*/
public Class<? extends FastPathObject> getSubclass() {
return subclass;
}
/**
* {@inheritDoc}
*/
public Class<?> getType() {
if (selectList.isEmpty()) {
return type;
} else {
return selectList.get(0).getType();
}
}
/**
* Returns the QueryClass that represents the collection in this object.
*
* @return a QueryClass
*/
public QueryClass getDefaultClass() {
return defaultClass;
}
/**
* Adds an element to the SELECT list. If the SELECT list is left empty, then the collection
* will use default behaviour.
*
* @param selectable a QuerySelectable
*/
public void addToSelect(QuerySelectable selectable) {
selectList.add(selectable);
}
/**
* Returns the SELECT list.
*
* @return a List
*/
public List<QuerySelectable> getSelect() {
return Collections.unmodifiableList(selectList);
}
/**
* Sets the additional constraint.
*
* @param c a Constraint
*/
public void setConstraint(Constraint c) {
constraint = c;
}
/**
* Returns the additional constraint.
*
* @return a Constraint
*/
public Constraint getConstraint() {
return constraint;
}
/**
* Returns the Query that will fetch the data represented by this object, given a Collection
* of objects to fetch it for.
*
* @param bag a Collection of objects to fetch data for, or null to not constrain
* @param isNoNotXml true if the database is in missingNotXml mode
* @return a Query
*/
public Query getQuery(Collection<Integer> bag, boolean isNoNotXml) {
if (isNoNotXml && (constraint == null) && selectList.isEmpty() && (subclass == null)) {
Query q = new Query();
QueryClass newQc = new QueryClass(InterMineObject.class);
q.addFrom(newQc);
q.addToSelect(new QueryField(newQc, "id"));
q.addToSelect(newQc);
if (bag != null) {
q.setConstraint(new BagConstraint(new QueryField(newQc, "id"), ConstraintOp.IN,
bag));
}
q.setDistinct(false);
return q;
} else {
Query q = new Query();
q.addFrom(defaultClass, "default");
QueryField defaultId = new QueryField(defaultClass, "id");
q.addToSelect(defaultId);
if (selectList.isEmpty()) {
q.addToSelect(defaultClass);
} else {
for (QuerySelectable selectable : selectList) {
q.addToSelect(selectable);
}
}
if (!q.getSelect().contains(defaultClass)) {
q.addToSelect(defaultClass);
}
if (bag != null) {
if (constraint == null) {
q.setConstraint(new BagConstraint(defaultId, ConstraintOp.IN, bag));
} else {
ConstraintSet cs = new ConstraintSet(ConstraintOp.AND);
cs.addConstraint(constraint);
cs.addConstraint(new BagConstraint(defaultId, ConstraintOp.IN, bag));
q.setConstraint(cs);
}
}
q.setDistinct(false);
return q;
}
}
}
|
[
"public",
"class",
"QueryObjectPathExpression",
"implements",
"QueryPathExpressionWithSelect",
",",
"Queryable",
"{",
"private",
"QueryClass",
"qc",
";",
"private",
"String",
"fieldName",
";",
"private",
"Class",
"<",
"?",
"extends",
"InterMineObject",
">",
"type",
";",
"private",
"Class",
"<",
"?",
"extends",
"FastPathObject",
">",
"subclass",
"=",
"null",
";",
"private",
"QueryClass",
"defaultClass",
";",
"private",
"List",
"<",
"QuerySelectable",
">",
"selectList",
"=",
"new",
"ArrayList",
"<",
"QuerySelectable",
">",
"(",
")",
";",
"private",
"Constraint",
"constraint",
"=",
"null",
";",
"/**\n * Constructs a QueryObjectPathExpression representing an object reference from the given\n * QueryClass to the given fieldname.\n *\n * @param qc the QueryClass\n * @param fieldName the name of the relevant field\n * @throws IllegalArgumentException if the field is not an object reference\n */",
"public",
"QueryObjectPathExpression",
"(",
"QueryClass",
"qc",
",",
"String",
"fieldName",
")",
"{",
"if",
"(",
"fieldName",
"==",
"null",
")",
"{",
"throw",
"new",
"NullPointerException",
"(",
"\"",
"Field name parameter is null",
"\"",
")",
";",
"}",
"if",
"(",
"qc",
"==",
"null",
")",
"{",
"throw",
"new",
"NullPointerException",
"(",
"\"",
"QueryClass parameter is null",
"\"",
")",
";",
"}",
"Method",
"field",
"=",
"TypeUtil",
".",
"getGetter",
"(",
"qc",
".",
"getType",
"(",
")",
",",
"fieldName",
")",
";",
"if",
"(",
"field",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"",
"Field ",
"\"",
"+",
"fieldName",
"+",
"\"",
" not found in ",
"\"",
"+",
"qc",
".",
"getType",
"(",
")",
")",
";",
"}",
"if",
"(",
"Collection",
".",
"class",
".",
"isAssignableFrom",
"(",
"field",
".",
"getReturnType",
"(",
")",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"",
"Field ",
"\"",
"+",
"fieldName",
"+",
"\"",
" is a collection type",
"\"",
")",
";",
"}",
"if",
"(",
"!",
"InterMineObject",
".",
"class",
".",
"isAssignableFrom",
"(",
"field",
".",
"getReturnType",
"(",
")",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"",
"Field ",
"\"",
"+",
"fieldName",
"+",
"\"",
" is not an object reference",
"\"",
"+",
"\"",
" type - was ",
"\"",
"+",
"field",
".",
"getReturnType",
"(",
")",
"+",
"\"",
" instead",
"\"",
")",
";",
"}",
"this",
".",
"qc",
"=",
"qc",
";",
"this",
".",
"fieldName",
"=",
"fieldName",
";",
"@",
"SuppressWarnings",
"(",
"\"",
"unchecked",
"\"",
")",
"Class",
"<",
"?",
"extends",
"InterMineObject",
">",
"tmpType",
"=",
"(",
"Class",
")",
"field",
".",
"getReturnType",
"(",
")",
";",
"this",
".",
"type",
"=",
"tmpType",
";",
"defaultClass",
"=",
"new",
"QueryClass",
"(",
"type",
")",
";",
"}",
"/**\n * Constructs a QueryObjectPathExpression representing an object reference from the given\n * QueryClass to the given fieldname, constrained to be a particular subclass.\n *\n * @param qc the QueryClass\n * @param fieldName the name of the relevant field\n * @param subclasses a Class that is a subclass of the field class\n * @throws IllegalArgumentException if the field is not an object reference\n */",
"public",
"QueryObjectPathExpression",
"(",
"QueryClass",
"qc",
",",
"String",
"fieldName",
",",
"Class",
"<",
"?",
">",
"...",
"subclasses",
")",
"{",
"subclass",
"=",
"DynamicUtil",
".",
"composeDescriptiveClass",
"(",
"subclasses",
")",
";",
"if",
"(",
"fieldName",
"==",
"null",
")",
"{",
"throw",
"new",
"NullPointerException",
"(",
"\"",
"Field name parameter is null",
"\"",
")",
";",
"}",
"if",
"(",
"qc",
"==",
"null",
")",
"{",
"throw",
"new",
"NullPointerException",
"(",
"\"",
"QueryClass parameter is null",
"\"",
")",
";",
"}",
"if",
"(",
"subclass",
"==",
"null",
")",
"{",
"throw",
"new",
"NullPointerException",
"(",
"\"",
"Subclass parameter is null",
"\"",
")",
";",
"}",
"Method",
"field",
"=",
"TypeUtil",
".",
"getGetter",
"(",
"qc",
".",
"getType",
"(",
")",
",",
"fieldName",
")",
";",
"if",
"(",
"field",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"",
"Field ",
"\"",
"+",
"fieldName",
"+",
"\"",
" not found in ",
"\"",
"+",
"qc",
".",
"getType",
"(",
")",
")",
";",
"}",
"if",
"(",
"Collection",
".",
"class",
".",
"isAssignableFrom",
"(",
"field",
".",
"getReturnType",
"(",
")",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"",
"Field ",
"\"",
"+",
"fieldName",
"+",
"\"",
" is a collection type",
"\"",
")",
";",
"}",
"if",
"(",
"!",
"InterMineObject",
".",
"class",
".",
"isAssignableFrom",
"(",
"field",
".",
"getReturnType",
"(",
")",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"",
"Field ",
"\"",
"+",
"fieldName",
"+",
"\"",
" is not an object reference",
"\"",
"+",
"\"",
" type - was ",
"\"",
"+",
"field",
".",
"getReturnType",
"(",
")",
"+",
"\"",
" instead",
"\"",
")",
";",
"}",
"if",
"(",
"!",
"field",
".",
"getReturnType",
"(",
")",
".",
"isAssignableFrom",
"(",
"subclass",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"",
"subclass parameter ",
"\"",
"+",
"subclass",
".",
"getName",
"(",
")",
"+",
"\"",
" is not a subclass of reference type ",
"\"",
"+",
"type",
".",
"getName",
"(",
")",
")",
";",
"}",
"this",
".",
"qc",
"=",
"qc",
";",
"this",
".",
"fieldName",
"=",
"fieldName",
";",
"@",
"SuppressWarnings",
"(",
"\"",
"unchecked",
"\"",
")",
"Class",
"<",
"?",
"extends",
"InterMineObject",
">",
"tmpType",
"=",
"(",
"Class",
")",
"field",
".",
"getReturnType",
"(",
")",
";",
"this",
".",
"type",
"=",
"tmpType",
";",
"defaultClass",
"=",
"new",
"QueryClass",
"(",
"subclass",
")",
";",
"if",
"(",
"subclass",
".",
"equals",
"(",
"type",
")",
")",
"{",
"subclass",
"=",
"null",
";",
"}",
"}",
"/**\n * Returns the QueryClass of which the field is a member.\n *\n * @return the QueryClass\n */",
"public",
"QueryClass",
"getQueryClass",
"(",
")",
"{",
"return",
"qc",
";",
"}",
"/**\n * Returns the name of the field.\n *\n * @return field name\n */",
"public",
"String",
"getFieldName",
"(",
")",
"{",
"return",
"fieldName",
";",
"}",
"/**\n * Returns the subclass if it exists.\n *\n * @return the subclass\n */",
"public",
"Class",
"<",
"?",
"extends",
"FastPathObject",
">",
"getSubclass",
"(",
")",
"{",
"return",
"subclass",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"public",
"Class",
"<",
"?",
">",
"getType",
"(",
")",
"{",
"if",
"(",
"selectList",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"type",
";",
"}",
"else",
"{",
"return",
"selectList",
".",
"get",
"(",
"0",
")",
".",
"getType",
"(",
")",
";",
"}",
"}",
"/**\n * Returns the QueryClass that represents the collection in this object.\n *\n * @return a QueryClass\n */",
"public",
"QueryClass",
"getDefaultClass",
"(",
")",
"{",
"return",
"defaultClass",
";",
"}",
"/**\n * Adds an element to the SELECT list. If the SELECT list is left empty, then the collection\n * will use default behaviour.\n *\n * @param selectable a QuerySelectable\n */",
"public",
"void",
"addToSelect",
"(",
"QuerySelectable",
"selectable",
")",
"{",
"selectList",
".",
"add",
"(",
"selectable",
")",
";",
"}",
"/**\n * Returns the SELECT list.\n *\n * @return a List\n */",
"public",
"List",
"<",
"QuerySelectable",
">",
"getSelect",
"(",
")",
"{",
"return",
"Collections",
".",
"unmodifiableList",
"(",
"selectList",
")",
";",
"}",
"/**\n * Sets the additional constraint.\n *\n * @param c a Constraint\n */",
"public",
"void",
"setConstraint",
"(",
"Constraint",
"c",
")",
"{",
"constraint",
"=",
"c",
";",
"}",
"/**\n * Returns the additional constraint.\n *\n * @return a Constraint\n */",
"public",
"Constraint",
"getConstraint",
"(",
")",
"{",
"return",
"constraint",
";",
"}",
"/**\n * Returns the Query that will fetch the data represented by this object, given a Collection\n * of objects to fetch it for.\n *\n * @param bag a Collection of objects to fetch data for, or null to not constrain\n * @param isNoNotXml true if the database is in missingNotXml mode\n * @return a Query\n */",
"public",
"Query",
"getQuery",
"(",
"Collection",
"<",
"Integer",
">",
"bag",
",",
"boolean",
"isNoNotXml",
")",
"{",
"if",
"(",
"isNoNotXml",
"&&",
"(",
"constraint",
"==",
"null",
")",
"&&",
"selectList",
".",
"isEmpty",
"(",
")",
"&&",
"(",
"subclass",
"==",
"null",
")",
")",
"{",
"Query",
"q",
"=",
"new",
"Query",
"(",
")",
";",
"QueryClass",
"newQc",
"=",
"new",
"QueryClass",
"(",
"InterMineObject",
".",
"class",
")",
";",
"q",
".",
"addFrom",
"(",
"newQc",
")",
";",
"q",
".",
"addToSelect",
"(",
"new",
"QueryField",
"(",
"newQc",
",",
"\"",
"id",
"\"",
")",
")",
";",
"q",
".",
"addToSelect",
"(",
"newQc",
")",
";",
"if",
"(",
"bag",
"!=",
"null",
")",
"{",
"q",
".",
"setConstraint",
"(",
"new",
"BagConstraint",
"(",
"new",
"QueryField",
"(",
"newQc",
",",
"\"",
"id",
"\"",
")",
",",
"ConstraintOp",
".",
"IN",
",",
"bag",
")",
")",
";",
"}",
"q",
".",
"setDistinct",
"(",
"false",
")",
";",
"return",
"q",
";",
"}",
"else",
"{",
"Query",
"q",
"=",
"new",
"Query",
"(",
")",
";",
"q",
".",
"addFrom",
"(",
"defaultClass",
",",
"\"",
"default",
"\"",
")",
";",
"QueryField",
"defaultId",
"=",
"new",
"QueryField",
"(",
"defaultClass",
",",
"\"",
"id",
"\"",
")",
";",
"q",
".",
"addToSelect",
"(",
"defaultId",
")",
";",
"if",
"(",
"selectList",
".",
"isEmpty",
"(",
")",
")",
"{",
"q",
".",
"addToSelect",
"(",
"defaultClass",
")",
";",
"}",
"else",
"{",
"for",
"(",
"QuerySelectable",
"selectable",
":",
"selectList",
")",
"{",
"q",
".",
"addToSelect",
"(",
"selectable",
")",
";",
"}",
"}",
"if",
"(",
"!",
"q",
".",
"getSelect",
"(",
")",
".",
"contains",
"(",
"defaultClass",
")",
")",
"{",
"q",
".",
"addToSelect",
"(",
"defaultClass",
")",
";",
"}",
"if",
"(",
"bag",
"!=",
"null",
")",
"{",
"if",
"(",
"constraint",
"==",
"null",
")",
"{",
"q",
".",
"setConstraint",
"(",
"new",
"BagConstraint",
"(",
"defaultId",
",",
"ConstraintOp",
".",
"IN",
",",
"bag",
")",
")",
";",
"}",
"else",
"{",
"ConstraintSet",
"cs",
"=",
"new",
"ConstraintSet",
"(",
"ConstraintOp",
".",
"AND",
")",
";",
"cs",
".",
"addConstraint",
"(",
"constraint",
")",
";",
"cs",
".",
"addConstraint",
"(",
"new",
"BagConstraint",
"(",
"defaultId",
",",
"ConstraintOp",
".",
"IN",
",",
"bag",
")",
")",
";",
"q",
".",
"setConstraint",
"(",
"cs",
")",
";",
"}",
"}",
"q",
".",
"setDistinct",
"(",
"false",
")",
";",
"return",
"q",
";",
"}",
"}",
"}"
] |
An element that can appear in the SELECT clause of a query, representing extra data to be
collected for the Results - namely a object referenced by some other object in the results.
|
[
"An",
"element",
"that",
"can",
"appear",
"in",
"the",
"SELECT",
"clause",
"of",
"a",
"query",
"representing",
"extra",
"data",
"to",
"be",
"collected",
"for",
"the",
"Results",
"-",
"namely",
"a",
"object",
"referenced",
"by",
"some",
"other",
"object",
"in",
"the",
"results",
"."
] |
[] |
[
{
"param": "QueryPathExpressionWithSelect, Queryable",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "QueryPathExpressionWithSelect, Queryable",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 17
| 1,612
| 247
|
29fca9d49bb83657ada717d46a62208fb5df40a9
|
coderasha/Hyperledger-Caliper
|
packages/caliper-core/lib/worker/rate-control/linearRate.js
|
[
"ECL-2.0",
"Apache-2.0"
] |
JavaScript
|
LinearRateController
|
/**
* Rate controller for generating a linearly changing workload.
*
* @property {number} startingSleepTime The sleep time for the first transaction in milliseconds.
* @property {number} gradient The gradient of the line.
* @property {function} _interpolate Function for calculating the current time to sleep (either from TX index, or from the elapsed time).
*
* @extends RateInterface
*/
|
Rate controller for generating a linearly changing workload.
@property {number} startingSleepTime The sleep time for the first transaction in milliseconds.
@property {number} gradient The gradient of the line.
@property {function} _interpolate Function for calculating the current time to sleep (either from TX index, or from the elapsed time).
|
[
"Rate",
"controller",
"for",
"generating",
"a",
"linearly",
"changing",
"workload",
".",
"@property",
"{",
"number",
"}",
"startingSleepTime",
"The",
"sleep",
"time",
"for",
"the",
"first",
"transaction",
"in",
"milliseconds",
".",
"@property",
"{",
"number",
"}",
"gradient",
"The",
"gradient",
"of",
"the",
"line",
".",
"@property",
"{",
"function",
"}",
"_interpolate",
"Function",
"for",
"calculating",
"the",
"current",
"time",
"to",
"sleep",
"(",
"either",
"from",
"TX",
"index",
"or",
"from",
"the",
"elapsed",
"time",
")",
"."
] |
class LinearRateController extends RateInterface {
/**
* Initializes the rate controller instance.
* @param {TestMessage} testMessage The testMessage passed for the round execution
* @param {TransactionStatisticsCollector} stats The TX stats collector instance.
* @param {number} workerIndex The 0-based index of the worker node.
* @param {number} roundIndex The 0-based index of the current round.
* @param {number} numberOfWorkers The total number of worker nodes.
* @param {object} roundConfig The round configuration object.
*/
constructor(testMessage, stats, workerIndex) {
super(testMessage, stats, workerIndex);
// distributing TPS among clients
let startingTps = Number(this.options.startingTps) / this.numberOfWorkers;
let finishingTps = Number(this.options.finishingTps) / this.numberOfWorkers;
this.startingSleepTime = 1000 / startingTps;
let finishingSleepTime = 1000 / finishingTps;
// based on linear interpolation between two points with (time/index, sleep time) axes
let duration = this.testMessage.getNumberOfTxs() || (this.testMessage.getRoundDuration() * 1000);
this.gradient = (finishingSleepTime - this.startingSleepTime) / duration;
// to avoid constant if/else check with the same result
this._interpolate = this.testMessage.getNumberOfTxs() ? this._interpolateFromIndex : this._interpolateFromTime;
}
/**
* Interpolates the current sleep time from the transaction index.
* @return {number} The interpolated sleep time.
*/
_interpolateFromIndex() {
return this.startingSleepTime + this.stats.getTotalSubmittedTx() * this.gradient;
}
/**
* Interpolates the current sleep time from the elapsed time.
* @return {number} The interpolated sleep time.
*/
_interpolateFromTime() {
return this.startingSleepTime + (Date.now() - this.stats.getRoundStartTime()) * this.gradient;
}
/**
* Perform the rate control action by blocking the execution for a certain amount of time.
* @async
*/
async applyRateControl() {
let currentSleepTime = this._interpolate();
if (currentSleepTime > 5) {
await Sleep(currentSleepTime);
}
}
/**
* Notify the rate controller about the end of the round.
* @async
*/
async end() { }
}
|
[
"class",
"LinearRateController",
"extends",
"RateInterface",
"{",
"constructor",
"(",
"testMessage",
",",
"stats",
",",
"workerIndex",
")",
"{",
"super",
"(",
"testMessage",
",",
"stats",
",",
"workerIndex",
")",
";",
"let",
"startingTps",
"=",
"Number",
"(",
"this",
".",
"options",
".",
"startingTps",
")",
"/",
"this",
".",
"numberOfWorkers",
";",
"let",
"finishingTps",
"=",
"Number",
"(",
"this",
".",
"options",
".",
"finishingTps",
")",
"/",
"this",
".",
"numberOfWorkers",
";",
"this",
".",
"startingSleepTime",
"=",
"1000",
"/",
"startingTps",
";",
"let",
"finishingSleepTime",
"=",
"1000",
"/",
"finishingTps",
";",
"let",
"duration",
"=",
"this",
".",
"testMessage",
".",
"getNumberOfTxs",
"(",
")",
"||",
"(",
"this",
".",
"testMessage",
".",
"getRoundDuration",
"(",
")",
"*",
"1000",
")",
";",
"this",
".",
"gradient",
"=",
"(",
"finishingSleepTime",
"-",
"this",
".",
"startingSleepTime",
")",
"/",
"duration",
";",
"this",
".",
"_interpolate",
"=",
"this",
".",
"testMessage",
".",
"getNumberOfTxs",
"(",
")",
"?",
"this",
".",
"_interpolateFromIndex",
":",
"this",
".",
"_interpolateFromTime",
";",
"}",
"_interpolateFromIndex",
"(",
")",
"{",
"return",
"this",
".",
"startingSleepTime",
"+",
"this",
".",
"stats",
".",
"getTotalSubmittedTx",
"(",
")",
"*",
"this",
".",
"gradient",
";",
"}",
"_interpolateFromTime",
"(",
")",
"{",
"return",
"this",
".",
"startingSleepTime",
"+",
"(",
"Date",
".",
"now",
"(",
")",
"-",
"this",
".",
"stats",
".",
"getRoundStartTime",
"(",
")",
")",
"*",
"this",
".",
"gradient",
";",
"}",
"async",
"applyRateControl",
"(",
")",
"{",
"let",
"currentSleepTime",
"=",
"this",
".",
"_interpolate",
"(",
")",
";",
"if",
"(",
"currentSleepTime",
">",
"5",
")",
"{",
"await",
"Sleep",
"(",
"currentSleepTime",
")",
";",
"}",
"}",
"async",
"end",
"(",
")",
"{",
"}",
"}"
] |
Rate controller for generating a linearly changing workload.
|
[
"Rate",
"controller",
"for",
"generating",
"a",
"linearly",
"changing",
"workload",
"."
] |
[
"/**\n * Initializes the rate controller instance.\n * @param {TestMessage} testMessage The testMessage passed for the round execution\n * @param {TransactionStatisticsCollector} stats The TX stats collector instance.\n * @param {number} workerIndex The 0-based index of the worker node.\n * @param {number} roundIndex The 0-based index of the current round.\n * @param {number} numberOfWorkers The total number of worker nodes.\n * @param {object} roundConfig The round configuration object.\n */",
"// distributing TPS among clients",
"// based on linear interpolation between two points with (time/index, sleep time) axes",
"// to avoid constant if/else check with the same result",
"/**\n * Interpolates the current sleep time from the transaction index.\n * @return {number} The interpolated sleep time.\n */",
"/**\n * Interpolates the current sleep time from the elapsed time.\n * @return {number} The interpolated sleep time.\n */",
"/**\n * Perform the rate control action by blocking the execution for a certain amount of time.\n * @async\n */",
"/**\n * Notify the rate controller about the end of the round.\n * @async\n */"
] |
[
{
"param": "RateInterface",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "RateInterface",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 13
| 553
| 82
|
53f8b3eae6ab014a174c3c7c5dac4d0ea2bbd030
|
zencoder/cassandra-cql
|
lib/cassandra-cql/row.rb
|
[
"Apache-2.0"
] |
Ruby
|
CassandraCQL
|
Copyright 2011 Inside Systems, 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.
|
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.
|
[
"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",
"."
] |
module CassandraCQL
class Row
attr_reader :row
def initialize(row, schema)
@row, @schema = row, schema
@value_cache = Hash.new { |h, key|
# If it's a number and not one of our columns, assume it's an index
if key.kind_of?(Fixnum) and !column_indices.key?(key)
column_name = column_names[key]
column_index = key
else
column_name = key
column_index = column_indices[key]
end
if column_index.nil?
# Cache negative hits
h[column_name] = nil
else
h[column_name] = ColumnFamily.cast(@row.columns[column_index].value, @schema.values[@row.columns[column_index].name])
end
}
end
def [](obj)
@value_cache[obj]
end
def column_names
@names ||= @row.columns.map do |column|
ColumnFamily.cast(column.name, @schema.names[column.name])
end
end
def column_indices
@column_indices ||= Hash[column_names.each_with_index.to_a]
end
def column_values
column_names.map do |name|
@value_cache[name]
end
end
def columns
@row.columns.size
end
def to_a
column_values
end
# TODO: This should be an ordered hash
def to_hash
Hash[([column_names, column_values]).transpose]
end
end
end
|
[
"module",
"CassandraCQL",
"class",
"Row",
"attr_reader",
":row",
"def",
"initialize",
"(",
"row",
",",
"schema",
")",
"@row",
",",
"@schema",
"=",
"row",
",",
"schema",
"@value_cache",
"=",
"Hash",
".",
"new",
"{",
"|",
"h",
",",
"key",
"|",
"if",
"key",
".",
"kind_of?",
"(",
"Fixnum",
")",
"and",
"!",
"column_indices",
".",
"key?",
"(",
"key",
")",
"column_name",
"=",
"column_names",
"[",
"key",
"]",
"column_index",
"=",
"key",
"else",
"column_name",
"=",
"key",
"column_index",
"=",
"column_indices",
"[",
"key",
"]",
"end",
"if",
"column_index",
".",
"nil?",
"h",
"[",
"column_name",
"]",
"=",
"nil",
"else",
"h",
"[",
"column_name",
"]",
"=",
"ColumnFamily",
".",
"cast",
"(",
"@row",
".",
"columns",
"[",
"column_index",
"]",
".",
"value",
",",
"@schema",
".",
"values",
"[",
"@row",
".",
"columns",
"[",
"column_index",
"]",
".",
"name",
"]",
")",
"end",
"}",
"end",
"def",
"[]",
"(",
"obj",
")",
"@value_cache",
"[",
"obj",
"]",
"end",
"def",
"column_names",
"@names",
"||=",
"@row",
".",
"columns",
".",
"map",
"do",
"|",
"column",
"|",
"ColumnFamily",
".",
"cast",
"(",
"column",
".",
"name",
",",
"@schema",
".",
"names",
"[",
"column",
".",
"name",
"]",
")",
"end",
"end",
"def",
"column_indices",
"@column_indices",
"||=",
"Hash",
"[",
"column_names",
".",
"each_with_index",
".",
"to_a",
"]",
"end",
"def",
"column_values",
"column_names",
".",
"map",
"do",
"|",
"name",
"|",
"@value_cache",
"[",
"name",
"]",
"end",
"end",
"def",
"columns",
"@row",
".",
"columns",
".",
"size",
"end",
"def",
"to_a",
"column_values",
"end",
"def",
"to_hash",
"Hash",
"[",
"(",
"[",
"column_names",
",",
"column_values",
"]",
")",
".",
"transpose",
"]",
"end",
"end",
"end"
] |
Copyright 2011 Inside Systems, Inc.
|
[
"Copyright",
"2011",
"Inside",
"Systems",
"Inc",
"."
] |
[
"# If it's a number and not one of our columns, assume it's an index",
"# Cache negative hits",
"# TODO: This should be an ordered hash"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 20
| 333
| 119
|
dd8b086453a74bba9819a1dc4801a56bf48154dc
|
isikdos/N-Snake
|
N-Snake/Nartesian.py
|
[
"MIT"
] |
Python
|
Ray
|
An object for representing a ray. That is to say, a vector with a start po-
int and an end point. The start point will always be the origin, and the e-
nd point is position number of units away from the origin.
---------------------------------------------------------------------------
Properties
---------------------------------------------------------------------------
dimension: integer
Represents the dimension the ray is in
position: integer
represents the displacement from the origin along the chosen dimension.
|
An object for representing a ray. That is to say, a vector with a start po
int and an end point. The start point will always be the origin, and the e
nd point is position number of units away from the origin.
Properties
integer
Represents the dimension the ray is in
integer
represents the displacement from the origin along the chosen dimension.
|
[
"An",
"object",
"for",
"representing",
"a",
"ray",
".",
"That",
"is",
"to",
"say",
"a",
"vector",
"with",
"a",
"start",
"po",
"int",
"and",
"an",
"end",
"point",
".",
"The",
"start",
"point",
"will",
"always",
"be",
"the",
"origin",
"and",
"the",
"e",
"nd",
"point",
"is",
"position",
"number",
"of",
"units",
"away",
"from",
"the",
"origin",
".",
"Properties",
"integer",
"Represents",
"the",
"dimension",
"the",
"ray",
"is",
"in",
"integer",
"represents",
"the",
"displacement",
"from",
"the",
"origin",
"along",
"the",
"chosen",
"dimension",
"."
] |
class Ray:
"""
An object for representing a ray. That is to say, a vector with a start po-
int and an end point. The start point will always be the origin, and the e-
nd point is position number of units away from the origin.
---------------------------------------------------------------------------
Properties
---------------------------------------------------------------------------
dimension: integer
Represents the dimension the ray is in
position: integer
represents the displacement from the origin along the chosen dimension.
"""
def __init__(self, dimension, displacement):
self.dimension = dimension
self.displacement = displacement
def __eq__(self, other):
"""
Equality defintion for Ray:
NOTE!!!!!!!!!!!!!!!!!!!!
It does not care if the displacements are different, it only cares if
dimensions are different.
"""
if isinstance(self, other.__class__):
return (self.axes[0].dimension == other.dimension)
return False
|
[
"class",
"Ray",
":",
"def",
"__init__",
"(",
"self",
",",
"dimension",
",",
"displacement",
")",
":",
"self",
".",
"dimension",
"=",
"dimension",
"self",
".",
"displacement",
"=",
"displacement",
"def",
"__eq__",
"(",
"self",
",",
"other",
")",
":",
"\"\"\"\r\n Equality defintion for Ray:\r\n \r\n NOTE!!!!!!!!!!!!!!!!!!!!\r\n It does not care if the displacements are different, it only cares if\r\n dimensions are different.\r\n \"\"\"",
"if",
"isinstance",
"(",
"self",
",",
"other",
".",
"__class__",
")",
":",
"return",
"(",
"self",
".",
"axes",
"[",
"0",
"]",
".",
"dimension",
"==",
"other",
".",
"dimension",
")",
"return",
"False"
] |
An object for representing a ray.
|
[
"An",
"object",
"for",
"representing",
"a",
"ray",
"."
] |
[
"\"\"\"\r\n An object for representing a ray. That is to say, a vector with a start po-\r\n int and an end point. The start point will always be the origin, and the e-\r\n nd point is position number of units away from the origin.\r\n \r\n ---------------------------------------------------------------------------\r\n Properties\r\n ---------------------------------------------------------------------------\r\n dimension: integer\r\n Represents the dimension the ray is in\r\n \r\n position: integer\r\n represents the displacement from the origin along the chosen dimension.\r\n \"\"\"",
"\"\"\"\r\n Equality defintion for Ray:\r\n \r\n NOTE!!!!!!!!!!!!!!!!!!!!\r\n It does not care if the displacements are different, it only cares if\r\n dimensions are different.\r\n \"\"\""
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 13
| 204
| 98
|
0255afea1f233884466e0754259617457125c886
|
exjohn/rawblock
|
src/core.js
|
[
"MIT"
] |
JavaScript
|
Component
|
/**
* Component Base Class - all UI components should extend this class. This Class adds some neat stuff to parse/change options (is automatically done in constructor), listen and trigger events, react to responsive state changes and establish BEM style classes as also a11y focus management.
*
* For the live cycle features see [rb.live.register]{@link rb.live.register}.
*
* @alias rb.Component
*
* @param element
* @param [initialDefaults] {Object}
*
* @example
* //<div class="js-rb-live" data-module="my-module"></div>
* rb.live.register('my-component', class MyComponent extends rb.Component {
* static get defaults(){
* return {
* className: 'toggle-class',
* };
* }
*
* static get events(){
* return {
* 'click:closest(.change-btn)': 'changeClass',
* };
* }
*
* constructor(element, initialDefaults){
* super(element, initialDefaults);
* this.rAFs('changeClass');
* }
*
* changeClass(){
* this.$element.toggleClass(this.options.className);
* }
* });
*/
|
Component Base Class - all UI components should extend this class. This Class adds some neat stuff to parse/change options (is automatically done in constructor), listen and trigger events, react to responsive state changes and establish BEM style classes as also a11y focus management.
@param element
@param [initialDefaults] {Object}
@example
rb.live.register('my-component', class MyComponent extends rb.Component {
static get defaults(){
return {
className: 'toggle-class',
};
}
static get events(){
return {
'click:closest(.change-btn)': 'changeClass',
};
}
|
[
"Component",
"Base",
"Class",
"-",
"all",
"UI",
"components",
"should",
"extend",
"this",
"class",
".",
"This",
"Class",
"adds",
"some",
"neat",
"stuff",
"to",
"parse",
"/",
"change",
"options",
"(",
"is",
"automatically",
"done",
"in",
"constructor",
")",
"listen",
"and",
"trigger",
"events",
"react",
"to",
"responsive",
"state",
"changes",
"and",
"establish",
"BEM",
"style",
"classes",
"as",
"also",
"a11y",
"focus",
"management",
".",
"@param",
"element",
"@param",
"[",
"initialDefaults",
"]",
"{",
"Object",
"}",
"@example",
"rb",
".",
"live",
".",
"register",
"(",
"'",
"my",
"-",
"component",
"'",
"class",
"MyComponent",
"extends",
"rb",
".",
"Component",
"{",
"static",
"get",
"defaults",
"()",
"{",
"return",
"{",
"className",
":",
"'",
"toggle",
"-",
"class",
"'",
"}",
";",
"}",
"static",
"get",
"events",
"()",
"{",
"return",
"{",
"'",
"click",
":",
"closest",
"(",
".",
"change",
"-",
"btn",
")",
"'",
":",
"'",
"changeClass",
"'",
"}",
";",
"}"
] |
class Component {
constructor(element, initialDefaults){
const origName = this.name;
/**
* Reference to the main element.
* @type {Element}
*/
this.element = element;
this.$element = $(element);
/**
* Current options object constructed by defaults and overriding markup/CSS.
* @type {{}}
*/
this.options = {};
this._initialDefaults = initialDefaults;
this._stickyOpts = {};
element[componentExpando] = this;
this.origName = origName;
this.parseOptions(this.options);
this.name = this.options.name || rb.jsPrefix + origName;
this.jsName = this.options.jsName || origName;
this._evtName = this.jsName + 'changed';
this._beforeEvtName = this.jsName + 'change';
addLog(this, this.options.debug == null ? rb.isDebug : this.options.debug);
/**
* Template function or hash of template functions to be used with `this.render`. On instantiation the `rb.template['nameOfComponent']` is referenced.
* @type {Function|{}}
*/
this.templates = rb.templates[this.jsName] || rb.templates[origName] || {};
this.beforeConstruct();
_setupEventsByEvtObj(this);
}
beforeConstruct(){}
/**
* Returns the component of an element. If a string is used, uses `this.getElementsByString` or `this.query` to get the element.
*
* @param element {Element|String}
* @param [moduleName] {String}
* @param [initialOpts] {Object}
*/
component(element, moduleName, initialOpts){
if(typeof element == 'string'){
element = this.interpolateName(element);
element = rb.getElementsByString(element, this.element)[0] || this.query(element);
}
return rb.getComponent(element, moduleName, initialOpts);
}
rAFs(){
return rAFs(this, ...arguments);
}
mutationPhase(){
return mutationPhase();
}
/**
* returns the id of an element, if no id exist generates one for the element
* @param {Element} [element], if no element is given. the component element is used.
* @param {Boolean} [async=true], sets the id async in a rAF
* @returns {String} id
*/
getId(element, async) {
let id;
if(typeof element == 'boolean'){
async = element;
element = null;
}
if (!element) {
element = this.element;
}
if(async == null){
async = true;
}
if (!(id = element.id)) {
id = 'js' + rb.nameSeparator + getId();
if(async){
rAFQueue(()=> {
element.id = id;
}, true);
} else {
element.id = id;
}
}
return id;
}
/**
* Dispatches an event on the component element and returns the Event object.
* @param [type='changed'] {String|Object} The event.type that should be created. If no type is given the name 'changed' is used. Automatically prefixes the type with the name of the component. If an opbject is passed this will be used as the `event.detail` property.
* @param [detail] {Object} The value for the event.detail property to transport event related information.
* @returns {Event}
*/
trigger(type, detail) {
let opts;
if (typeof type == 'object') {
detail = type;
type = detail.type;
}
if (type == null) {
type = this._evtName;
} else if (!type.startsWith(this.jsName)) {
type = this.jsName + type;
}
opts = {detail: detail || {}};
if(detail){
if('bubbles' in detail){
opts.bubbles = detail.bubbles;
}
if('cancelable' in detail){
opts.cancelable = detail.cancelable;
}
}
return rb.events.dispatch(this.element, type, opts);
}
/**
* Dispatches an event on the component element at the next rAF.
*
* @see rb.Component.prototype.trigger
*/
triggerRaf(){
rAFQueue(() => {
this.trigger(...arguments);
}, true);
}
/**
* Uses [`rb.getElementsByString`]{@link rb.getElementsByString} with this.element as the element argument and interpolates string using `this.interpolateName`.
* @param {String} string
* @param {Element} [element=this.element]
* @returns {Element[]}
*/
getElementsByString(string, element) {
return rb.getElementsByString(this.interpolateName(string), element || this.element);
}
_trigger(){
this.logInfo('_trigger is deprecated use trigger instead');
return this.trigger.apply(this, arguments);
}
/*
* shortcut to [`rb.setFocus`]{@link rb.setFocus}
* @borrows rb.setFocus as setFocus
*/
setFocus(){
return rb.setFocus(...arguments);
}
/**
* Interpolates {name}, {jsName} and {htmlName} to the name of the component. Helps to generate BEM-style Class-Structure.
* @param {String} str
* @param {Boolean} [isJs=false]
* @returns {string}
*
* @example
* //assume the name of the component is dialog
* this.interpolateName('.{name}__button'); //return '.dialog__button'
*/
interpolateName(str, isJs) {
if(!isJs && rb.attrSel){
str = replaceHTMLSel(str);
}
return str
.replace(regName, isJs ? this.jsName : this.name)
.replace(regJsName, this.jsName)
.replace(regHtmlName, this.name)
.replace(regnameSeparator, rb.nameSeparator)
.replace(regElementSeparator, rb.elementSeparator)
.replace(regUtilPrefix, rb.utilPrefix)
.replace(regStatePrefix, rb.statePrefix)
;
}
/**
* Returns first matched element. Interpolates selector with `interpolateName`.
* @param {String} selector
* @param {Element} [context=this.element]
* @returns {Element}
*/
query(selector, context) {
return (context || this.element).querySelector(this.interpolateName(selector));
}
_qSA(selector, context){
return (context || this.element).querySelectorAll(this.interpolateName(selector));
}
/**
* Returns Array of matched elements. Interpolates selector with `interpolateName`.
* @param {String} selector
* @param {Element} [context=this.element]
* @returns {Element[]}
*/
queryAll(selector, context) {
return Array.from(this._qSA(selector, context));
}
/**
* Returns jQuery list of matched elements. Interpolates selector with `interpolateName`.
* @param {String} selector
* @param {Element} [context=this.element]
* @returns {jQueryfiedNodeList}
*/
$queryAll(selector, context) {
return $(this._qSA(selector, context));
}
/*
* Parses the Options from HTML (data-* attributes) and CSS using rb.parsePseudo. This function is automatically invoked by the init/constructor.
* @param opts
* @param initialOpts
*/
parseOptions(opts) {
const options = $.extend(true, opts || {}, this.constructor.defaults, this._initialDefaults, rb.parseComponentCss(this.element, this.origName), this.parseHTMLOptions(), this._stickyOpts);
this.setOptions(options);
}
/*
* Sets mutltiple options at once.
* @param opts
*/
setOptions(opts, isSticky) {
if(opts !== this.options){
let oldValue, newValue;
for (var prop in opts) {
newValue = opts[prop];
oldValue = this.options[prop];
if (newValue !== oldValue &&
(!oldValue || typeof newValue != 'object' || typeof oldValue != 'object' ||
JSON.stringify(newValue) != JSON.stringify(oldValue))) {
this.setOption(prop, newValue, isSticky);
}
}
}
}
/**
* Sets an option. The function should be extended to react to dynamic option changes after instantiation.
* @param name {String} Name of the option.
* @param value {*} Value of the option.
* @param isSticky=false {boolean} Whether the option can't be overwritten with CSS option.
*
* @example
* class MyComponent extends rb.Component {
* setOptions(name, value, isSticky){
* super.setOption(name, value, isSticky);
*
* if(name == 'foo'){
* this.updateFoo();
* }
* }
* }
*/
setOption(name, value, isSticky) {
this.options[name] = value;
if(isSticky){
this._stickyOpts[name] = value;
}
if (name == 'debug') {
this.isDebug = value;
} else if ((name == 'name' || name == 'jsName') && this.name && this.jsName && this.logWarn) {
this.logWarn('don\'t change name after init.');
}
}
/**
* Convenient method to render a template. Expects a template function with the given name added to the templates hash property of the component. The data will be extended with the name of the component.
* @param {String} [name]
* @param {Object} data
* @returns {String}
*
* @example
* //sources/_templates/my-component/main.ejs:
*
* //<div class="rb-<%= component %>">
* // <h1 class="<%= component %>-header">
* // <%- title ->
* // </h1>
* //</div>
*
* //require('sources/js/_templates/my-component.js');
*
* rb.live.register('my-component', class MyComponent extends rb.Component {
* renderMain(){
* this.element.innerHTML = this.render('main', {title: 'foo'});
* }
* });
*/
render(name, data) {
if (typeof name == 'object') {
data = name;
name = '';
}
if (!data.name) {
data.name = this.name;
}
if (!data.component) {
data.component = this.component;
}
return this.templates[name] ?
this.templates[name](data) :
(!name && typeof this.templates == 'function') ?
this.templates(data) :
''
;
}
/*
* parses the HTML options (data-*) of a given Element. This method is automatically invoked by the constructor or in case of a CSS option change.
* @returns {{}}
*/
parseHTMLOptions(_element) {
if(_element){
rb.logError('use `rb.parseDataAttrs` instead of parseHTMLOptions.');
return {};
}
const element = this.element;
const mainOptions = 'data-' + this.origName + '-options';
const options = rb.jsonParse(element.getAttribute(mainOptions)) || {};
return rb.parseDataAttrs(element, options, this.origName, mainOptions);
}
destroy() {
live.destroyComponent(this);
}
/**
* Passes args to `console.log` if isDebug option is `true.
* @param {...*} args
*/
log() {
}
}
|
[
"class",
"Component",
"{",
"constructor",
"(",
"element",
",",
"initialDefaults",
")",
"{",
"const",
"origName",
"=",
"this",
".",
"name",
";",
"this",
".",
"element",
"=",
"element",
";",
"this",
".",
"$element",
"=",
"$",
"(",
"element",
")",
";",
"this",
".",
"options",
"=",
"{",
"}",
";",
"this",
".",
"_initialDefaults",
"=",
"initialDefaults",
";",
"this",
".",
"_stickyOpts",
"=",
"{",
"}",
";",
"element",
"[",
"componentExpando",
"]",
"=",
"this",
";",
"this",
".",
"origName",
"=",
"origName",
";",
"this",
".",
"parseOptions",
"(",
"this",
".",
"options",
")",
";",
"this",
".",
"name",
"=",
"this",
".",
"options",
".",
"name",
"||",
"rb",
".",
"jsPrefix",
"+",
"origName",
";",
"this",
".",
"jsName",
"=",
"this",
".",
"options",
".",
"jsName",
"||",
"origName",
";",
"this",
".",
"_evtName",
"=",
"this",
".",
"jsName",
"+",
"'changed'",
";",
"this",
".",
"_beforeEvtName",
"=",
"this",
".",
"jsName",
"+",
"'change'",
";",
"addLog",
"(",
"this",
",",
"this",
".",
"options",
".",
"debug",
"==",
"null",
"?",
"rb",
".",
"isDebug",
":",
"this",
".",
"options",
".",
"debug",
")",
";",
"this",
".",
"templates",
"=",
"rb",
".",
"templates",
"[",
"this",
".",
"jsName",
"]",
"||",
"rb",
".",
"templates",
"[",
"origName",
"]",
"||",
"{",
"}",
";",
"this",
".",
"beforeConstruct",
"(",
")",
";",
"_setupEventsByEvtObj",
"(",
"this",
")",
";",
"}",
"beforeConstruct",
"(",
")",
"{",
"}",
"component",
"(",
"element",
",",
"moduleName",
",",
"initialOpts",
")",
"{",
"if",
"(",
"typeof",
"element",
"==",
"'string'",
")",
"{",
"element",
"=",
"this",
".",
"interpolateName",
"(",
"element",
")",
";",
"element",
"=",
"rb",
".",
"getElementsByString",
"(",
"element",
",",
"this",
".",
"element",
")",
"[",
"0",
"]",
"||",
"this",
".",
"query",
"(",
"element",
")",
";",
"}",
"return",
"rb",
".",
"getComponent",
"(",
"element",
",",
"moduleName",
",",
"initialOpts",
")",
";",
"}",
"rAFs",
"(",
")",
"{",
"return",
"rAFs",
"(",
"this",
",",
"...",
"arguments",
")",
";",
"}",
"mutationPhase",
"(",
")",
"{",
"return",
"mutationPhase",
"(",
")",
";",
"}",
"getId",
"(",
"element",
",",
"async",
")",
"{",
"let",
"id",
";",
"if",
"(",
"typeof",
"element",
"==",
"'boolean'",
")",
"{",
"async",
"=",
"element",
";",
"element",
"=",
"null",
";",
"}",
"if",
"(",
"!",
"element",
")",
"{",
"element",
"=",
"this",
".",
"element",
";",
"}",
"if",
"(",
"async",
"==",
"null",
")",
"{",
"async",
"=",
"true",
";",
"}",
"if",
"(",
"!",
"(",
"id",
"=",
"element",
".",
"id",
")",
")",
"{",
"id",
"=",
"'js'",
"+",
"rb",
".",
"nameSeparator",
"+",
"getId",
"(",
")",
";",
"if",
"(",
"async",
")",
"{",
"rAFQueue",
"(",
"(",
")",
"=>",
"{",
"element",
".",
"id",
"=",
"id",
";",
"}",
",",
"true",
")",
";",
"}",
"else",
"{",
"element",
".",
"id",
"=",
"id",
";",
"}",
"}",
"return",
"id",
";",
"}",
"trigger",
"(",
"type",
",",
"detail",
")",
"{",
"let",
"opts",
";",
"if",
"(",
"typeof",
"type",
"==",
"'object'",
")",
"{",
"detail",
"=",
"type",
";",
"type",
"=",
"detail",
".",
"type",
";",
"}",
"if",
"(",
"type",
"==",
"null",
")",
"{",
"type",
"=",
"this",
".",
"_evtName",
";",
"}",
"else",
"if",
"(",
"!",
"type",
".",
"startsWith",
"(",
"this",
".",
"jsName",
")",
")",
"{",
"type",
"=",
"this",
".",
"jsName",
"+",
"type",
";",
"}",
"opts",
"=",
"{",
"detail",
":",
"detail",
"||",
"{",
"}",
"}",
";",
"if",
"(",
"detail",
")",
"{",
"if",
"(",
"'bubbles'",
"in",
"detail",
")",
"{",
"opts",
".",
"bubbles",
"=",
"detail",
".",
"bubbles",
";",
"}",
"if",
"(",
"'cancelable'",
"in",
"detail",
")",
"{",
"opts",
".",
"cancelable",
"=",
"detail",
".",
"cancelable",
";",
"}",
"}",
"return",
"rb",
".",
"events",
".",
"dispatch",
"(",
"this",
".",
"element",
",",
"type",
",",
"opts",
")",
";",
"}",
"triggerRaf",
"(",
")",
"{",
"rAFQueue",
"(",
"(",
")",
"=>",
"{",
"this",
".",
"trigger",
"(",
"...",
"arguments",
")",
";",
"}",
",",
"true",
")",
";",
"}",
"getElementsByString",
"(",
"string",
",",
"element",
")",
"{",
"return",
"rb",
".",
"getElementsByString",
"(",
"this",
".",
"interpolateName",
"(",
"string",
")",
",",
"element",
"||",
"this",
".",
"element",
")",
";",
"}",
"_trigger",
"(",
")",
"{",
"this",
".",
"logInfo",
"(",
"'_trigger is deprecated use trigger instead'",
")",
";",
"return",
"this",
".",
"trigger",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"}",
"setFocus",
"(",
")",
"{",
"return",
"rb",
".",
"setFocus",
"(",
"...",
"arguments",
")",
";",
"}",
"interpolateName",
"(",
"str",
",",
"isJs",
")",
"{",
"if",
"(",
"!",
"isJs",
"&&",
"rb",
".",
"attrSel",
")",
"{",
"str",
"=",
"replaceHTMLSel",
"(",
"str",
")",
";",
"}",
"return",
"str",
".",
"replace",
"(",
"regName",
",",
"isJs",
"?",
"this",
".",
"jsName",
":",
"this",
".",
"name",
")",
".",
"replace",
"(",
"regJsName",
",",
"this",
".",
"jsName",
")",
".",
"replace",
"(",
"regHtmlName",
",",
"this",
".",
"name",
")",
".",
"replace",
"(",
"regnameSeparator",
",",
"rb",
".",
"nameSeparator",
")",
".",
"replace",
"(",
"regElementSeparator",
",",
"rb",
".",
"elementSeparator",
")",
".",
"replace",
"(",
"regUtilPrefix",
",",
"rb",
".",
"utilPrefix",
")",
".",
"replace",
"(",
"regStatePrefix",
",",
"rb",
".",
"statePrefix",
")",
";",
"}",
"query",
"(",
"selector",
",",
"context",
")",
"{",
"return",
"(",
"context",
"||",
"this",
".",
"element",
")",
".",
"querySelector",
"(",
"this",
".",
"interpolateName",
"(",
"selector",
")",
")",
";",
"}",
"_qSA",
"(",
"selector",
",",
"context",
")",
"{",
"return",
"(",
"context",
"||",
"this",
".",
"element",
")",
".",
"querySelectorAll",
"(",
"this",
".",
"interpolateName",
"(",
"selector",
")",
")",
";",
"}",
"queryAll",
"(",
"selector",
",",
"context",
")",
"{",
"return",
"Array",
".",
"from",
"(",
"this",
".",
"_qSA",
"(",
"selector",
",",
"context",
")",
")",
";",
"}",
"$queryAll",
"(",
"selector",
",",
"context",
")",
"{",
"return",
"$",
"(",
"this",
".",
"_qSA",
"(",
"selector",
",",
"context",
")",
")",
";",
"}",
"parseOptions",
"(",
"opts",
")",
"{",
"const",
"options",
"=",
"$",
".",
"extend",
"(",
"true",
",",
"opts",
"||",
"{",
"}",
",",
"this",
".",
"constructor",
".",
"defaults",
",",
"this",
".",
"_initialDefaults",
",",
"rb",
".",
"parseComponentCss",
"(",
"this",
".",
"element",
",",
"this",
".",
"origName",
")",
",",
"this",
".",
"parseHTMLOptions",
"(",
")",
",",
"this",
".",
"_stickyOpts",
")",
";",
"this",
".",
"setOptions",
"(",
"options",
")",
";",
"}",
"setOptions",
"(",
"opts",
",",
"isSticky",
")",
"{",
"if",
"(",
"opts",
"!==",
"this",
".",
"options",
")",
"{",
"let",
"oldValue",
",",
"newValue",
";",
"for",
"(",
"var",
"prop",
"in",
"opts",
")",
"{",
"newValue",
"=",
"opts",
"[",
"prop",
"]",
";",
"oldValue",
"=",
"this",
".",
"options",
"[",
"prop",
"]",
";",
"if",
"(",
"newValue",
"!==",
"oldValue",
"&&",
"(",
"!",
"oldValue",
"||",
"typeof",
"newValue",
"!=",
"'object'",
"||",
"typeof",
"oldValue",
"!=",
"'object'",
"||",
"JSON",
".",
"stringify",
"(",
"newValue",
")",
"!=",
"JSON",
".",
"stringify",
"(",
"oldValue",
")",
")",
")",
"{",
"this",
".",
"setOption",
"(",
"prop",
",",
"newValue",
",",
"isSticky",
")",
";",
"}",
"}",
"}",
"}",
"setOption",
"(",
"name",
",",
"value",
",",
"isSticky",
")",
"{",
"this",
".",
"options",
"[",
"name",
"]",
"=",
"value",
";",
"if",
"(",
"isSticky",
")",
"{",
"this",
".",
"_stickyOpts",
"[",
"name",
"]",
"=",
"value",
";",
"}",
"if",
"(",
"name",
"==",
"'debug'",
")",
"{",
"this",
".",
"isDebug",
"=",
"value",
";",
"}",
"else",
"if",
"(",
"(",
"name",
"==",
"'name'",
"||",
"name",
"==",
"'jsName'",
")",
"&&",
"this",
".",
"name",
"&&",
"this",
".",
"jsName",
"&&",
"this",
".",
"logWarn",
")",
"{",
"this",
".",
"logWarn",
"(",
"'don\\'t change name after init.'",
")",
";",
"}",
"}",
"render",
"(",
"name",
",",
"data",
")",
"{",
"if",
"(",
"typeof",
"name",
"==",
"'object'",
")",
"{",
"data",
"=",
"name",
";",
"name",
"=",
"''",
";",
"}",
"if",
"(",
"!",
"data",
".",
"name",
")",
"{",
"data",
".",
"name",
"=",
"this",
".",
"name",
";",
"}",
"if",
"(",
"!",
"data",
".",
"component",
")",
"{",
"data",
".",
"component",
"=",
"this",
".",
"component",
";",
"}",
"return",
"this",
".",
"templates",
"[",
"name",
"]",
"?",
"this",
".",
"templates",
"[",
"name",
"]",
"(",
"data",
")",
":",
"(",
"!",
"name",
"&&",
"typeof",
"this",
".",
"templates",
"==",
"'function'",
")",
"?",
"this",
".",
"templates",
"(",
"data",
")",
":",
"''",
";",
"}",
"parseHTMLOptions",
"(",
"_element",
")",
"{",
"if",
"(",
"_element",
")",
"{",
"rb",
".",
"logError",
"(",
"'use `rb.parseDataAttrs` instead of parseHTMLOptions.'",
")",
";",
"return",
"{",
"}",
";",
"}",
"const",
"element",
"=",
"this",
".",
"element",
";",
"const",
"mainOptions",
"=",
"'data-'",
"+",
"this",
".",
"origName",
"+",
"'-options'",
";",
"const",
"options",
"=",
"rb",
".",
"jsonParse",
"(",
"element",
".",
"getAttribute",
"(",
"mainOptions",
")",
")",
"||",
"{",
"}",
";",
"return",
"rb",
".",
"parseDataAttrs",
"(",
"element",
",",
"options",
",",
"this",
".",
"origName",
",",
"mainOptions",
")",
";",
"}",
"destroy",
"(",
")",
"{",
"live",
".",
"destroyComponent",
"(",
"this",
")",
";",
"}",
"log",
"(",
")",
"{",
"}",
"}"
] |
Component Base Class - all UI components should extend this class.
|
[
"Component",
"Base",
"Class",
"-",
"all",
"UI",
"components",
"should",
"extend",
"this",
"class",
"."
] |
[
"/**\n * Reference to the main element.\n * @type {Element}\n */",
"/**\n * Current options object constructed by defaults and overriding markup/CSS.\n * @type {{}}\n */",
"/**\n * Template function or hash of template functions to be used with `this.render`. On instantiation the `rb.template['nameOfComponent']` is referenced.\n * @type {Function|{}}\n */",
"/**\n * Returns the component of an element. If a string is used, uses `this.getElementsByString` or `this.query` to get the element.\n *\n * @param element {Element|String}\n * @param [moduleName] {String}\n * @param [initialOpts] {Object}\n */",
"/**\n * returns the id of an element, if no id exist generates one for the element\n * @param {Element} [element], if no element is given. the component element is used.\n * @param {Boolean} [async=true], sets the id async in a rAF\n * @returns {String} id\n */",
"/**\n * Dispatches an event on the component element and returns the Event object.\n * @param [type='changed'] {String|Object} The event.type that should be created. If no type is given the name 'changed' is used. Automatically prefixes the type with the name of the component. If an opbject is passed this will be used as the `event.detail` property.\n * @param [detail] {Object} The value for the event.detail property to transport event related information.\n * @returns {Event}\n */",
"/**\n * Dispatches an event on the component element at the next rAF.\n *\n * @see rb.Component.prototype.trigger\n */",
"/**\n * Uses [`rb.getElementsByString`]{@link rb.getElementsByString} with this.element as the element argument and interpolates string using `this.interpolateName`.\n * @param {String} string\n * @param {Element} [element=this.element]\n * @returns {Element[]}\n */",
"/*\n * shortcut to [`rb.setFocus`]{@link rb.setFocus}\n * @borrows rb.setFocus as setFocus\n */",
"/**\n * Interpolates {name}, {jsName} and {htmlName} to the name of the component. Helps to generate BEM-style Class-Structure.\n * @param {String} str\n * @param {Boolean} [isJs=false]\n * @returns {string}\n *\n * @example\n * //assume the name of the component is dialog\n * this.interpolateName('.{name}__button'); //return '.dialog__button'\n */",
"/**\n * Returns first matched element. Interpolates selector with `interpolateName`.\n * @param {String} selector\n * @param {Element} [context=this.element]\n * @returns {Element}\n */",
"/**\n * Returns Array of matched elements. Interpolates selector with `interpolateName`.\n * @param {String} selector\n * @param {Element} [context=this.element]\n * @returns {Element[]}\n */",
"/**\n * Returns jQuery list of matched elements. Interpolates selector with `interpolateName`.\n * @param {String} selector\n * @param {Element} [context=this.element]\n * @returns {jQueryfiedNodeList}\n */",
"/*\n * Parses the Options from HTML (data-* attributes) and CSS using rb.parsePseudo. This function is automatically invoked by the init/constructor.\n * @param opts\n * @param initialOpts\n */",
"/*\n * Sets mutltiple options at once.\n * @param opts\n */",
"/**\n * Sets an option. The function should be extended to react to dynamic option changes after instantiation.\n * @param name {String} Name of the option.\n * @param value {*} Value of the option.\n * @param isSticky=false {boolean} Whether the option can't be overwritten with CSS option.\n *\n * @example\n * class MyComponent extends rb.Component {\n * setOptions(name, value, isSticky){\n * super.setOption(name, value, isSticky);\n *\n * if(name == 'foo'){\n * this.updateFoo();\n * }\n * }\n * }\n */",
"/**\n * Convenient method to render a template. Expects a template function with the given name added to the templates hash property of the component. The data will be extended with the name of the component.\n * @param {String} [name]\n * @param {Object} data\n * @returns {String}\n *\n * @example\n * //sources/_templates/my-component/main.ejs:\n *\n * //<div class=\"rb-<%= component %>\">\n * // <h1 class=\"<%= component %>-header\">\n * // <%- title ->\n * // </h1>\n * //</div>\n *\n * //require('sources/js/_templates/my-component.js');\n *\n * rb.live.register('my-component', class MyComponent extends rb.Component {\n * renderMain(){\n * this.element.innerHTML = this.render('main', {title: 'foo'});\n * }\n * });\n */",
"/*\n * parses the HTML options (data-*) of a given Element. This method is automatically invoked by the constructor or in case of a CSS option change.\n * @returns {{}}\n */",
"/**\n * Passes args to `console.log` if isDebug option is `true.\n * @param {...*} args\n */"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 22
| 2,532
| 278
|
f1a723709a9dd8c0da56ad9cf0d7a064df2deb42
|
JonSnowbd/Nez
|
Ash.DefaultEC/UI/Widgets/ImageButton.cs
|
[
"MIT"
] |
C#
|
ImageButton
|
/// <summary>
/// A button with a child {@link Image} to display an image. This is useful when the button must be larger than the image and the
/// image centered on the button. If the image is the size of the button, a {@link Button} without any children can be used, where
/// the {@link Button.ButtonStyle#up}, {@link Button.ButtonStyle#down}, and {@link Button.ButtonStyle#checked} nine patches define
/// the image.
/// </summary>
|
A button with a child Image to display an image. This is useful when the button must be larger than the image and the
image centered on the button. If the image is the size of the button, a Button without any children can be used, where
the Button.ButtonStyle#up, Button.ButtonStyle#down, and Button.ButtonStyle#checked nine patches define
the image.
|
[
"A",
"button",
"with",
"a",
"child",
"Image",
"to",
"display",
"an",
"image",
".",
"This",
"is",
"useful",
"when",
"the",
"button",
"must",
"be",
"larger",
"than",
"the",
"image",
"and",
"the",
"image",
"centered",
"on",
"the",
"button",
".",
"If",
"the",
"image",
"is",
"the",
"size",
"of",
"the",
"button",
"a",
"Button",
"without",
"any",
"children",
"can",
"be",
"used",
"where",
"the",
"Button",
".",
"ButtonStyle#up",
"Button",
".",
"ButtonStyle#down",
"and",
"Button",
".",
"ButtonStyle#checked",
"nine",
"patches",
"define",
"the",
"image",
"."
] |
public class ImageButton : Button
{
Image image;
ImageButtonStyle style;
public ImageButton(ImageButtonStyle style) : base(style)
{
image = new Image();
image.SetScaling(Scaling.Fit);
Add(image);
SetStyle(style);
SetSize(PreferredWidth, PreferredHeight);
}
public ImageButton(Skin skin, string styleName = null) : this(skin.Get<ImageButtonStyle>(styleName))
{ }
public ImageButton(IDrawable imageUp) : this(new ImageButtonStyle(null, null, null, imageUp, null, null))
{ }
public ImageButton(IDrawable imageUp, IDrawable imageDown) : this(new ImageButtonStyle(null, null, null,
imageUp, imageDown, null))
{ }
public ImageButton(IDrawable imageUp, IDrawable imageDown, IDrawable imageOver) : this(
new ImageButtonStyle(null, null, null, imageUp, imageDown, imageOver))
{ }
public override void SetStyle(ButtonStyle style)
{
Insist.IsTrue(style is ImageButtonStyle, "style must be a ImageButtonStyle");
base.SetStyle(style);
this.style = (ImageButtonStyle) style;
if (image != null)
UpdateImage();
}
public new ImageButtonStyle GetStyle()
{
return style;
}
public Image GetImage()
{
return image;
}
public Cell GetImageCell()
{
return GetCell(image);
}
private void UpdateImage()
{
IDrawable drawable = null;
if (_isDisabled && style.ImageDisabled != null)
drawable = style.ImageDisabled;
else if (_mouseDown && style.ImageDown != null)
drawable = style.ImageDown;
else if (IsChecked && style.ImageChecked != null)
drawable = (style.ImageCheckedOver != null && _mouseOver) ? style.ImageCheckedOver : style.ImageChecked;
else if (_mouseOver && style.ImageOver != null)
drawable = style.ImageOver;
else if (style.ImageUp != null)
drawable = style.ImageUp;
image.SetDrawable(drawable);
}
public override void Draw(Batcher batcher, float parentAlpha)
{
UpdateImage();
base.Draw(batcher, parentAlpha);
}
}
|
[
"public",
"class",
"ImageButton",
":",
"Button",
"{",
"Image",
"image",
";",
"ImageButtonStyle",
"style",
";",
"public",
"ImageButton",
"(",
"ImageButtonStyle",
"style",
")",
":",
"base",
"(",
"style",
")",
"{",
"image",
"=",
"new",
"Image",
"(",
")",
";",
"image",
".",
"SetScaling",
"(",
"Scaling",
".",
"Fit",
")",
";",
"Add",
"(",
"image",
")",
";",
"SetStyle",
"(",
"style",
")",
";",
"SetSize",
"(",
"PreferredWidth",
",",
"PreferredHeight",
")",
";",
"}",
"public",
"ImageButton",
"(",
"Skin",
"skin",
",",
"string",
"styleName",
"=",
"null",
")",
":",
"this",
"(",
"skin",
".",
"Get",
"<",
"ImageButtonStyle",
">",
"(",
"styleName",
")",
")",
"{",
"}",
"public",
"ImageButton",
"(",
"IDrawable",
"imageUp",
")",
":",
"this",
"(",
"new",
"ImageButtonStyle",
"(",
"null",
",",
"null",
",",
"null",
",",
"imageUp",
",",
"null",
",",
"null",
")",
")",
"{",
"}",
"public",
"ImageButton",
"(",
"IDrawable",
"imageUp",
",",
"IDrawable",
"imageDown",
")",
":",
"this",
"(",
"new",
"ImageButtonStyle",
"(",
"null",
",",
"null",
",",
"null",
",",
"imageUp",
",",
"imageDown",
",",
"null",
")",
")",
"{",
"}",
"public",
"ImageButton",
"(",
"IDrawable",
"imageUp",
",",
"IDrawable",
"imageDown",
",",
"IDrawable",
"imageOver",
")",
":",
"this",
"(",
"new",
"ImageButtonStyle",
"(",
"null",
",",
"null",
",",
"null",
",",
"imageUp",
",",
"imageDown",
",",
"imageOver",
")",
")",
"{",
"}",
"public",
"override",
"void",
"SetStyle",
"(",
"ButtonStyle",
"style",
")",
"{",
"Insist",
".",
"IsTrue",
"(",
"style",
"is",
"ImageButtonStyle",
",",
"\"",
"style must be a ImageButtonStyle",
"\"",
")",
";",
"base",
".",
"SetStyle",
"(",
"style",
")",
";",
"this",
".",
"style",
"=",
"(",
"ImageButtonStyle",
")",
"style",
";",
"if",
"(",
"image",
"!=",
"null",
")",
"UpdateImage",
"(",
")",
";",
"}",
"public",
"new",
"ImageButtonStyle",
"GetStyle",
"(",
")",
"{",
"return",
"style",
";",
"}",
"public",
"Image",
"GetImage",
"(",
")",
"{",
"return",
"image",
";",
"}",
"public",
"Cell",
"GetImageCell",
"(",
")",
"{",
"return",
"GetCell",
"(",
"image",
")",
";",
"}",
"private",
"void",
"UpdateImage",
"(",
")",
"{",
"IDrawable",
"drawable",
"=",
"null",
";",
"if",
"(",
"_isDisabled",
"&&",
"style",
".",
"ImageDisabled",
"!=",
"null",
")",
"drawable",
"=",
"style",
".",
"ImageDisabled",
";",
"else",
"if",
"(",
"_mouseDown",
"&&",
"style",
".",
"ImageDown",
"!=",
"null",
")",
"drawable",
"=",
"style",
".",
"ImageDown",
";",
"else",
"if",
"(",
"IsChecked",
"&&",
"style",
".",
"ImageChecked",
"!=",
"null",
")",
"drawable",
"=",
"(",
"style",
".",
"ImageCheckedOver",
"!=",
"null",
"&&",
"_mouseOver",
")",
"?",
"style",
".",
"ImageCheckedOver",
":",
"style",
".",
"ImageChecked",
";",
"else",
"if",
"(",
"_mouseOver",
"&&",
"style",
".",
"ImageOver",
"!=",
"null",
")",
"drawable",
"=",
"style",
".",
"ImageOver",
";",
"else",
"if",
"(",
"style",
".",
"ImageUp",
"!=",
"null",
")",
"drawable",
"=",
"style",
".",
"ImageUp",
";",
"image",
".",
"SetDrawable",
"(",
"drawable",
")",
";",
"}",
"public",
"override",
"void",
"Draw",
"(",
"Batcher",
"batcher",
",",
"float",
"parentAlpha",
")",
"{",
"UpdateImage",
"(",
")",
";",
"base",
".",
"Draw",
"(",
"batcher",
",",
"parentAlpha",
")",
";",
"}",
"}"
] |
A button with a child {@link Image} to display an image.
|
[
"A",
"button",
"with",
"a",
"child",
"{",
"@link",
"Image",
"}",
"to",
"display",
"an",
"image",
"."
] |
[
"//"
] |
[
{
"param": "Button",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "Button",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 15
| 512
| 104
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.