repository_name
stringlengths 7
54
| func_path_in_repository
stringlengths 18
218
| func_name
stringlengths 5
140
| whole_func_string
stringlengths 79
3.99k
| language
stringclasses 1
value | func_code_string
stringlengths 79
3.99k
| func_code_tokens
listlengths 20
624
| func_documentation_string
stringlengths 61
1.96k
| func_documentation_tokens
listlengths 1
478
| split_name
stringclasses 1
value | func_code_url
stringlengths 107
339
|
---|---|---|---|---|---|---|---|---|---|---|
exoplatform/jcr
|
exo.jcr.component.statistics/src/main/java/org/exoplatform/services/jcr/statistics/JCRAPIAspect.java
|
JCRAPIAspect.getStatistics
|
private static Statistics getStatistics(Class<?> target, String signature)
{
initIfNeeded();
Statistics statistics = MAPPING.get(signature);
if (statistics == null)
{
synchronized (JCRAPIAspect.class)
{
Class<?> interfaceClass = findInterface(target);
if (interfaceClass != null)
{
Map<String, Statistics> allStatistics = ALL_STATISTICS.get(interfaceClass.getSimpleName());
if (allStatistics != null)
{
int index1 = signature.indexOf('(');
int index = signature.substring(0, index1).lastIndexOf('.');
String name = signature.substring(index + 1);
statistics = allStatistics.get(name);
}
}
if (statistics == null)
{
statistics = UNKNOWN;
}
Map<String, Statistics> tempMapping = new HashMap<String, Statistics>(MAPPING);
tempMapping.put(signature, statistics);
MAPPING = Collections.unmodifiableMap(tempMapping);
}
}
if (statistics == UNKNOWN) // NOSONAR
{
return null;
}
return statistics;
}
|
java
|
private static Statistics getStatistics(Class<?> target, String signature)
{
initIfNeeded();
Statistics statistics = MAPPING.get(signature);
if (statistics == null)
{
synchronized (JCRAPIAspect.class)
{
Class<?> interfaceClass = findInterface(target);
if (interfaceClass != null)
{
Map<String, Statistics> allStatistics = ALL_STATISTICS.get(interfaceClass.getSimpleName());
if (allStatistics != null)
{
int index1 = signature.indexOf('(');
int index = signature.substring(0, index1).lastIndexOf('.');
String name = signature.substring(index + 1);
statistics = allStatistics.get(name);
}
}
if (statistics == null)
{
statistics = UNKNOWN;
}
Map<String, Statistics> tempMapping = new HashMap<String, Statistics>(MAPPING);
tempMapping.put(signature, statistics);
MAPPING = Collections.unmodifiableMap(tempMapping);
}
}
if (statistics == UNKNOWN) // NOSONAR
{
return null;
}
return statistics;
}
|
[
"private",
"static",
"Statistics",
"getStatistics",
"(",
"Class",
"<",
"?",
">",
"target",
",",
"String",
"signature",
")",
"{",
"initIfNeeded",
"(",
")",
";",
"Statistics",
"statistics",
"=",
"MAPPING",
".",
"get",
"(",
"signature",
")",
";",
"if",
"(",
"statistics",
"==",
"null",
")",
"{",
"synchronized",
"(",
"JCRAPIAspect",
".",
"class",
")",
"{",
"Class",
"<",
"?",
">",
"interfaceClass",
"=",
"findInterface",
"(",
"target",
")",
";",
"if",
"(",
"interfaceClass",
"!=",
"null",
")",
"{",
"Map",
"<",
"String",
",",
"Statistics",
">",
"allStatistics",
"=",
"ALL_STATISTICS",
".",
"get",
"(",
"interfaceClass",
".",
"getSimpleName",
"(",
")",
")",
";",
"if",
"(",
"allStatistics",
"!=",
"null",
")",
"{",
"int",
"index1",
"=",
"signature",
".",
"indexOf",
"(",
"'",
"'",
")",
";",
"int",
"index",
"=",
"signature",
".",
"substring",
"(",
"0",
",",
"index1",
")",
".",
"lastIndexOf",
"(",
"'",
"'",
")",
";",
"String",
"name",
"=",
"signature",
".",
"substring",
"(",
"index",
"+",
"1",
")",
";",
"statistics",
"=",
"allStatistics",
".",
"get",
"(",
"name",
")",
";",
"}",
"}",
"if",
"(",
"statistics",
"==",
"null",
")",
"{",
"statistics",
"=",
"UNKNOWN",
";",
"}",
"Map",
"<",
"String",
",",
"Statistics",
">",
"tempMapping",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Statistics",
">",
"(",
"MAPPING",
")",
";",
"tempMapping",
".",
"put",
"(",
"signature",
",",
"statistics",
")",
";",
"MAPPING",
"=",
"Collections",
".",
"unmodifiableMap",
"(",
"tempMapping",
")",
";",
"}",
"}",
"if",
"(",
"statistics",
"==",
"UNKNOWN",
")",
"// NOSONAR",
"{",
"return",
"null",
";",
"}",
"return",
"statistics",
";",
"}"
] |
Gives the corresponding statistics for the given target class and AspectJ signature
@param target the target {@link Class}
@param signature the AspectJ signature
@return the related {@link Statistics} or <code>null</code> if it cannot be found
|
[
"Gives",
"the",
"corresponding",
"statistics",
"for",
"the",
"given",
"target",
"class",
"and",
"AspectJ",
"signature"
] |
train
|
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.statistics/src/main/java/org/exoplatform/services/jcr/statistics/JCRAPIAspect.java#L128-L162
|
UrielCh/ovh-java-sdk
|
ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java
|
ApiOvhMe.paymentMean_bankAccount_POST
|
public OvhPaymentMeanValidation paymentMean_bankAccount_POST(String bic, String description, String iban, String ownerAddress, String ownerName, Boolean setDefault) throws IOException {
String qPath = "/me/paymentMean/bankAccount";
StringBuilder sb = path(qPath);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "bic", bic);
addBody(o, "description", description);
addBody(o, "iban", iban);
addBody(o, "ownerAddress", ownerAddress);
addBody(o, "ownerName", ownerName);
addBody(o, "setDefault", setDefault);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhPaymentMeanValidation.class);
}
|
java
|
public OvhPaymentMeanValidation paymentMean_bankAccount_POST(String bic, String description, String iban, String ownerAddress, String ownerName, Boolean setDefault) throws IOException {
String qPath = "/me/paymentMean/bankAccount";
StringBuilder sb = path(qPath);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "bic", bic);
addBody(o, "description", description);
addBody(o, "iban", iban);
addBody(o, "ownerAddress", ownerAddress);
addBody(o, "ownerName", ownerName);
addBody(o, "setDefault", setDefault);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhPaymentMeanValidation.class);
}
|
[
"public",
"OvhPaymentMeanValidation",
"paymentMean_bankAccount_POST",
"(",
"String",
"bic",
",",
"String",
"description",
",",
"String",
"iban",
",",
"String",
"ownerAddress",
",",
"String",
"ownerName",
",",
"Boolean",
"setDefault",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/me/paymentMean/bankAccount\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
")",
";",
"HashMap",
"<",
"String",
",",
"Object",
">",
"o",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Object",
">",
"(",
")",
";",
"addBody",
"(",
"o",
",",
"\"bic\"",
",",
"bic",
")",
";",
"addBody",
"(",
"o",
",",
"\"description\"",
",",
"description",
")",
";",
"addBody",
"(",
"o",
",",
"\"iban\"",
",",
"iban",
")",
";",
"addBody",
"(",
"o",
",",
"\"ownerAddress\"",
",",
"ownerAddress",
")",
";",
"addBody",
"(",
"o",
",",
"\"ownerName\"",
",",
"ownerName",
")",
";",
"addBody",
"(",
"o",
",",
"\"setDefault\"",
",",
"setDefault",
")",
";",
"String",
"resp",
"=",
"exec",
"(",
"qPath",
",",
"\"POST\"",
",",
"sb",
".",
"toString",
"(",
")",
",",
"o",
")",
";",
"return",
"convertTo",
"(",
"resp",
",",
"OvhPaymentMeanValidation",
".",
"class",
")",
";",
"}"
] |
Enable payment through a new account
REST: POST /me/paymentMean/bankAccount
@param ownerAddress [required] Account owner's address
@param bic [required] Account's BIC
@param iban [required] Account's IBAN
@param ownerName [required] Account owner's name
@param setDefault [required] Set as default payment mean once validated
@param description [required] Custom description of this account
|
[
"Enable",
"payment",
"through",
"a",
"new",
"account"
] |
train
|
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java#L717-L729
|
apache/incubator-druid
|
processing/src/main/java/org/apache/druid/query/filter/JavaScriptDimFilter.java
|
JavaScriptDimFilter.getPredicateFactory
|
@EnsuresNonNull("predicateFactory")
private JavaScriptPredicateFactory getPredicateFactory()
{
// JavaScript configuration should be checked when it's actually used because someone might still want Druid
// nodes to be able to deserialize JavaScript-based objects even though JavaScript is disabled.
Preconditions.checkState(config.isEnabled(), "JavaScript is disabled");
JavaScriptPredicateFactory syncedFnPredicateFactory = predicateFactory;
if (syncedFnPredicateFactory == null) {
synchronized (config) {
syncedFnPredicateFactory = predicateFactory;
if (syncedFnPredicateFactory == null) {
syncedFnPredicateFactory = new JavaScriptPredicateFactory(function, extractionFn);
predicateFactory = syncedFnPredicateFactory;
}
}
}
return syncedFnPredicateFactory;
}
|
java
|
@EnsuresNonNull("predicateFactory")
private JavaScriptPredicateFactory getPredicateFactory()
{
// JavaScript configuration should be checked when it's actually used because someone might still want Druid
// nodes to be able to deserialize JavaScript-based objects even though JavaScript is disabled.
Preconditions.checkState(config.isEnabled(), "JavaScript is disabled");
JavaScriptPredicateFactory syncedFnPredicateFactory = predicateFactory;
if (syncedFnPredicateFactory == null) {
synchronized (config) {
syncedFnPredicateFactory = predicateFactory;
if (syncedFnPredicateFactory == null) {
syncedFnPredicateFactory = new JavaScriptPredicateFactory(function, extractionFn);
predicateFactory = syncedFnPredicateFactory;
}
}
}
return syncedFnPredicateFactory;
}
|
[
"@",
"EnsuresNonNull",
"(",
"\"predicateFactory\"",
")",
"private",
"JavaScriptPredicateFactory",
"getPredicateFactory",
"(",
")",
"{",
"// JavaScript configuration should be checked when it's actually used because someone might still want Druid",
"// nodes to be able to deserialize JavaScript-based objects even though JavaScript is disabled.",
"Preconditions",
".",
"checkState",
"(",
"config",
".",
"isEnabled",
"(",
")",
",",
"\"JavaScript is disabled\"",
")",
";",
"JavaScriptPredicateFactory",
"syncedFnPredicateFactory",
"=",
"predicateFactory",
";",
"if",
"(",
"syncedFnPredicateFactory",
"==",
"null",
")",
"{",
"synchronized",
"(",
"config",
")",
"{",
"syncedFnPredicateFactory",
"=",
"predicateFactory",
";",
"if",
"(",
"syncedFnPredicateFactory",
"==",
"null",
")",
"{",
"syncedFnPredicateFactory",
"=",
"new",
"JavaScriptPredicateFactory",
"(",
"function",
",",
"extractionFn",
")",
";",
"predicateFactory",
"=",
"syncedFnPredicateFactory",
";",
"}",
"}",
"}",
"return",
"syncedFnPredicateFactory",
";",
"}"
] |
This class can be used by multiple threads, so this function should be thread-safe to avoid extra
script compilation.
|
[
"This",
"class",
"can",
"be",
"used",
"by",
"multiple",
"threads",
"so",
"this",
"function",
"should",
"be",
"thread",
"-",
"safe",
"to",
"avoid",
"extra",
"script",
"compilation",
"."
] |
train
|
https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/processing/src/main/java/org/apache/druid/query/filter/JavaScriptDimFilter.java#L128-L146
|
Clivern/Racter
|
src/main/java/com/clivern/racter/senders/templates/ReceiptTemplate.java
|
ReceiptTemplate.setSummary
|
public void setSummary(String subtotal, String shipping_cost, String total_tax, String total_cost)
{
this.summary.put("subtotal", subtotal);
this.summary.put("shipping_cost", shipping_cost);
this.summary.put("total_tax", total_tax);
this.summary.put("total_cost", total_cost);
}
|
java
|
public void setSummary(String subtotal, String shipping_cost, String total_tax, String total_cost)
{
this.summary.put("subtotal", subtotal);
this.summary.put("shipping_cost", shipping_cost);
this.summary.put("total_tax", total_tax);
this.summary.put("total_cost", total_cost);
}
|
[
"public",
"void",
"setSummary",
"(",
"String",
"subtotal",
",",
"String",
"shipping_cost",
",",
"String",
"total_tax",
",",
"String",
"total_cost",
")",
"{",
"this",
".",
"summary",
".",
"put",
"(",
"\"subtotal\"",
",",
"subtotal",
")",
";",
"this",
".",
"summary",
".",
"put",
"(",
"\"shipping_cost\"",
",",
"shipping_cost",
")",
";",
"this",
".",
"summary",
".",
"put",
"(",
"\"total_tax\"",
",",
"total_tax",
")",
";",
"this",
".",
"summary",
".",
"put",
"(",
"\"total_cost\"",
",",
"total_cost",
")",
";",
"}"
] |
Set Summary
@param subtotal the receipt sub-total
@param shipping_cost the receipt shipping cost
@param total_tax the receipt total tax
@param total_cost the receipt total cost
|
[
"Set",
"Summary"
] |
train
|
https://github.com/Clivern/Racter/blob/bbde02f0c2a8a80653ad6b1607376d8408acd71c/src/main/java/com/clivern/racter/senders/templates/ReceiptTemplate.java#L172-L178
|
wcm-io/wcm-io-tooling
|
commons/content-package-builder/src/main/java/io/wcm/tooling/commons/contentpackagebuilder/ContentPackage.java
|
ContentPackage.writeXmlDocument
|
private void writeXmlDocument(String path, Document doc) throws IOException {
zip.putNextEntry(new ZipEntry(path));
try {
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(zip);
transformer.transform(source, result);
}
catch (TransformerException ex) {
throw new IOException("Failed to generate XML: " + ex.getMessage(), ex);
}
finally {
zip.closeEntry();
}
}
|
java
|
private void writeXmlDocument(String path, Document doc) throws IOException {
zip.putNextEntry(new ZipEntry(path));
try {
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(zip);
transformer.transform(source, result);
}
catch (TransformerException ex) {
throw new IOException("Failed to generate XML: " + ex.getMessage(), ex);
}
finally {
zip.closeEntry();
}
}
|
[
"private",
"void",
"writeXmlDocument",
"(",
"String",
"path",
",",
"Document",
"doc",
")",
"throws",
"IOException",
"{",
"zip",
".",
"putNextEntry",
"(",
"new",
"ZipEntry",
"(",
"path",
")",
")",
";",
"try",
"{",
"DOMSource",
"source",
"=",
"new",
"DOMSource",
"(",
"doc",
")",
";",
"StreamResult",
"result",
"=",
"new",
"StreamResult",
"(",
"zip",
")",
";",
"transformer",
".",
"transform",
"(",
"source",
",",
"result",
")",
";",
"}",
"catch",
"(",
"TransformerException",
"ex",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"Failed to generate XML: \"",
"+",
"ex",
".",
"getMessage",
"(",
")",
",",
"ex",
")",
";",
"}",
"finally",
"{",
"zip",
".",
"closeEntry",
"(",
")",
";",
"}",
"}"
] |
Writes an XML document as binary file entry to the ZIP output stream.
@param path Content path
@param doc XML content
@throws IOException I/O exception
|
[
"Writes",
"an",
"XML",
"document",
"as",
"binary",
"file",
"entry",
"to",
"the",
"ZIP",
"output",
"stream",
"."
] |
train
|
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/commons/content-package-builder/src/main/java/io/wcm/tooling/commons/contentpackagebuilder/ContentPackage.java#L351-L364
|
apache/incubator-druid
|
server/src/main/java/org/apache/druid/segment/realtime/appenderator/BaseAppenderatorDriver.java
|
BaseAppenderatorDriver.getAppendableSegment
|
private SegmentIdWithShardSpec getAppendableSegment(final DateTime timestamp, final String sequenceName)
{
synchronized (segments) {
final SegmentsForSequence segmentsForSequence = segments.get(sequenceName);
if (segmentsForSequence == null) {
return null;
}
final Map.Entry<Long, SegmentsOfInterval> candidateEntry = segmentsForSequence.floor(
timestamp.getMillis()
);
if (candidateEntry != null) {
final SegmentsOfInterval segmentsOfInterval = candidateEntry.getValue();
if (segmentsOfInterval.interval.contains(timestamp)) {
return segmentsOfInterval.appendingSegment == null ?
null :
segmentsOfInterval.appendingSegment.getSegmentIdentifier();
} else {
return null;
}
} else {
return null;
}
}
}
|
java
|
private SegmentIdWithShardSpec getAppendableSegment(final DateTime timestamp, final String sequenceName)
{
synchronized (segments) {
final SegmentsForSequence segmentsForSequence = segments.get(sequenceName);
if (segmentsForSequence == null) {
return null;
}
final Map.Entry<Long, SegmentsOfInterval> candidateEntry = segmentsForSequence.floor(
timestamp.getMillis()
);
if (candidateEntry != null) {
final SegmentsOfInterval segmentsOfInterval = candidateEntry.getValue();
if (segmentsOfInterval.interval.contains(timestamp)) {
return segmentsOfInterval.appendingSegment == null ?
null :
segmentsOfInterval.appendingSegment.getSegmentIdentifier();
} else {
return null;
}
} else {
return null;
}
}
}
|
[
"private",
"SegmentIdWithShardSpec",
"getAppendableSegment",
"(",
"final",
"DateTime",
"timestamp",
",",
"final",
"String",
"sequenceName",
")",
"{",
"synchronized",
"(",
"segments",
")",
"{",
"final",
"SegmentsForSequence",
"segmentsForSequence",
"=",
"segments",
".",
"get",
"(",
"sequenceName",
")",
";",
"if",
"(",
"segmentsForSequence",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"final",
"Map",
".",
"Entry",
"<",
"Long",
",",
"SegmentsOfInterval",
">",
"candidateEntry",
"=",
"segmentsForSequence",
".",
"floor",
"(",
"timestamp",
".",
"getMillis",
"(",
")",
")",
";",
"if",
"(",
"candidateEntry",
"!=",
"null",
")",
"{",
"final",
"SegmentsOfInterval",
"segmentsOfInterval",
"=",
"candidateEntry",
".",
"getValue",
"(",
")",
";",
"if",
"(",
"segmentsOfInterval",
".",
"interval",
".",
"contains",
"(",
"timestamp",
")",
")",
"{",
"return",
"segmentsOfInterval",
".",
"appendingSegment",
"==",
"null",
"?",
"null",
":",
"segmentsOfInterval",
".",
"appendingSegment",
".",
"getSegmentIdentifier",
"(",
")",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}",
"}"
] |
Find a segment in the {@link SegmentState#APPENDING} state for the given timestamp and sequenceName.
|
[
"Find",
"a",
"segment",
"in",
"the",
"{"
] |
train
|
https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/server/src/main/java/org/apache/druid/segment/realtime/appenderator/BaseAppenderatorDriver.java#L279-L305
|
ehcache/ehcache3
|
impl/src/main/java/org/ehcache/config/builders/CacheConfigurationBuilder.java
|
CacheConfigurationBuilder.withKeyCopier
|
public CacheConfigurationBuilder<K, V> withKeyCopier(Copier<K> keyCopier) {
return withCopier(new DefaultCopierConfiguration<>(requireNonNull(keyCopier, "Null key copier"), DefaultCopierConfiguration.Type.KEY));
}
|
java
|
public CacheConfigurationBuilder<K, V> withKeyCopier(Copier<K> keyCopier) {
return withCopier(new DefaultCopierConfiguration<>(requireNonNull(keyCopier, "Null key copier"), DefaultCopierConfiguration.Type.KEY));
}
|
[
"public",
"CacheConfigurationBuilder",
"<",
"K",
",",
"V",
">",
"withKeyCopier",
"(",
"Copier",
"<",
"K",
">",
"keyCopier",
")",
"{",
"return",
"withCopier",
"(",
"new",
"DefaultCopierConfiguration",
"<>",
"(",
"requireNonNull",
"(",
"keyCopier",
",",
"\"Null key copier\"",
")",
",",
"DefaultCopierConfiguration",
".",
"Type",
".",
"KEY",
")",
")",
";",
"}"
] |
Adds by-value semantic using the provided {@link Copier} for the key on heap.
<p>
{@link Copier}s are what enable control of by-reference / by-value semantics for on-heap tier.
@param keyCopier the key copier to use
@return a new builder with the added key copier
|
[
"Adds",
"by",
"-",
"value",
"semantic",
"using",
"the",
"provided",
"{",
"@link",
"Copier",
"}",
"for",
"the",
"key",
"on",
"heap",
".",
"<p",
">",
"{",
"@link",
"Copier",
"}",
"s",
"are",
"what",
"enable",
"control",
"of",
"by",
"-",
"reference",
"/",
"by",
"-",
"value",
"semantics",
"for",
"on",
"-",
"heap",
"tier",
"."
] |
train
|
https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/config/builders/CacheConfigurationBuilder.java#L408-L410
|
james-hu/jabb-core
|
src/main/java/net/sf/jabb/cache/AbstractEhCachedKeyValueRepository.java
|
AbstractEhCachedKeyValueRepository.refreshAheadNeeded
|
protected boolean refreshAheadNeeded(long accessTime, long createdTime, long expirationTime){
long ttl4 = (expirationTime - createdTime) / 4;
if (ttl4 < 0){
ttl4 = 0;
}
long start = createdTime + ttl4 * 2;
long end = expirationTime - ttl4;
return accessTime > start && accessTime < end;
}
|
java
|
protected boolean refreshAheadNeeded(long accessTime, long createdTime, long expirationTime){
long ttl4 = (expirationTime - createdTime) / 4;
if (ttl4 < 0){
ttl4 = 0;
}
long start = createdTime + ttl4 * 2;
long end = expirationTime - ttl4;
return accessTime > start && accessTime < end;
}
|
[
"protected",
"boolean",
"refreshAheadNeeded",
"(",
"long",
"accessTime",
",",
"long",
"createdTime",
",",
"long",
"expirationTime",
")",
"{",
"long",
"ttl4",
"=",
"(",
"expirationTime",
"-",
"createdTime",
")",
"/",
"4",
";",
"if",
"(",
"ttl4",
"<",
"0",
")",
"{",
"ttl4",
"=",
"0",
";",
"}",
"long",
"start",
"=",
"createdTime",
"+",
"ttl4",
"*",
"2",
";",
"long",
"end",
"=",
"expirationTime",
"-",
"ttl4",
";",
"return",
"accessTime",
">",
"start",
"&&",
"accessTime",
"<",
"end",
";",
"}"
] |
Determine if a refresh ahead is needed.
The default implementation checks if accessTime falls into the 3rd quarter of (expirationTime - createdTime)
@param accessTime last access time
@param createdTime created time
@param expirationTime end of TTL/TTI time
@return true if a refresh is needed, false otherwise
|
[
"Determine",
"if",
"a",
"refresh",
"ahead",
"is",
"needed",
".",
"The",
"default",
"implementation",
"checks",
"if",
"accessTime",
"falls",
"into",
"the",
"3rd",
"quarter",
"of",
"(",
"expirationTime",
"-",
"createdTime",
")"
] |
train
|
https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/cache/AbstractEhCachedKeyValueRepository.java#L75-L85
|
Devskiller/jfairy
|
src/main/java/com/devskiller/jfairy/producer/BaseProducer.java
|
BaseProducer.letterify
|
public String letterify(String letterString, char from, char to) {
return replaceSymbolWithCharsFromTo(letterString, '?', from, to);
}
|
java
|
public String letterify(String letterString, char from, char to) {
return replaceSymbolWithCharsFromTo(letterString, '?', from, to);
}
|
[
"public",
"String",
"letterify",
"(",
"String",
"letterString",
",",
"char",
"from",
",",
"char",
"to",
")",
"{",
"return",
"replaceSymbolWithCharsFromTo",
"(",
"letterString",
",",
"'",
"'",
",",
"from",
",",
"to",
")",
";",
"}"
] |
Replaces all {@code '?'} characters with random chars from [{@code from} - {@code to}] range
@param letterString text to process
@param from start of the range
@param to end of the range
@return text with replaced {@code '?'} chars
|
[
"Replaces",
"all",
"{",
"@code",
"?",
"}",
"characters",
"with",
"random",
"chars",
"from",
"[",
"{",
"@code",
"from",
"}",
"-",
"{",
"@code",
"to",
"}",
"]",
"range"
] |
train
|
https://github.com/Devskiller/jfairy/blob/126d1c8b1545f725afd10f969b9d27005ac520b7/src/main/java/com/devskiller/jfairy/producer/BaseProducer.java#L155-L157
|
agmip/agmip-common-functions
|
src/main/java/org/agmip/functions/PTSaxton2006.java
|
PTSaxton2006.getSKSAT
|
public static String getSKSAT(String[] soilParas) {
if (soilParas != null && soilParas.length >= 3) {
if (soilParas.length >= 4) {
return divide(calcSatBulk(soilParas[0], soilParas[1], soilParas[2], divide(soilParas[3], "100")), "10", 3);
} else {
return divide(calcSatMatric(soilParas[0], soilParas[1], soilParas[2]), "10", 3);
}
} else {
return null;
}
}
|
java
|
public static String getSKSAT(String[] soilParas) {
if (soilParas != null && soilParas.length >= 3) {
if (soilParas.length >= 4) {
return divide(calcSatBulk(soilParas[0], soilParas[1], soilParas[2], divide(soilParas[3], "100")), "10", 3);
} else {
return divide(calcSatMatric(soilParas[0], soilParas[1], soilParas[2]), "10", 3);
}
} else {
return null;
}
}
|
[
"public",
"static",
"String",
"getSKSAT",
"(",
"String",
"[",
"]",
"soilParas",
")",
"{",
"if",
"(",
"soilParas",
"!=",
"null",
"&&",
"soilParas",
".",
"length",
">=",
"3",
")",
"{",
"if",
"(",
"soilParas",
".",
"length",
">=",
"4",
")",
"{",
"return",
"divide",
"(",
"calcSatBulk",
"(",
"soilParas",
"[",
"0",
"]",
",",
"soilParas",
"[",
"1",
"]",
",",
"soilParas",
"[",
"2",
"]",
",",
"divide",
"(",
"soilParas",
"[",
"3",
"]",
",",
"\"100\"",
")",
")",
",",
"\"10\"",
",",
"3",
")",
";",
"}",
"else",
"{",
"return",
"divide",
"(",
"calcSatMatric",
"(",
"soilParas",
"[",
"0",
"]",
",",
"soilParas",
"[",
"1",
"]",
",",
"soilParas",
"[",
"2",
"]",
")",
",",
"\"10\"",
",",
"3",
")",
";",
"}",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}"
] |
For calculating SKSAT
@param soilParas should include 1. Sand weight percentage by layer
([0,100]%), 2. Clay weight percentage by layer ([0,100]%), 3. Organic
matter weight percentage by layer ([0,100]%), (= SLOC * 1.72), 4. Grave
weight percentage by layer ([0,100]%)
@return Saturated hydraulic conductivity, cm/h
|
[
"For",
"calculating",
"SKSAT"
] |
train
|
https://github.com/agmip/agmip-common-functions/blob/4efa3042178841b026ca6fba9c96da02fbfb9a8e/src/main/java/org/agmip/functions/PTSaxton2006.java#L80-L90
|
hyperledger/fabric-sdk-java
|
src/main/java/org/hyperledger/fabric/sdk/security/certgen/TLSCertificateKeyPair.java
|
TLSCertificateKeyPair.fromX509CertKeyPair
|
static TLSCertificateKeyPair fromX509CertKeyPair(X509Certificate x509Cert, KeyPair keyPair) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintWriter writer = new PrintWriter(baos);
JcaPEMWriter w = new JcaPEMWriter(writer);
w.writeObject(x509Cert);
w.flush();
w.close();
byte[] pemBytes = baos.toByteArray();
InputStreamReader isr = new InputStreamReader(new ByteArrayInputStream(pemBytes));
PemReader pr = new PemReader(isr);
PemObject pem = pr.readPemObject();
byte[] derBytes = pem.getContent();
baos = new ByteArrayOutputStream();
PrintWriter wr = new PrintWriter(baos);
wr.println("-----BEGIN PRIVATE KEY-----");
wr.println(new String(Base64.encodeBase64(keyPair.getPrivate().getEncoded())));
wr.println("-----END PRIVATE KEY-----");
wr.flush();
wr.close();
byte[] keyBytes = baos.toByteArray();
return new TLSCertificateKeyPair(pemBytes, derBytes, keyBytes);
}
|
java
|
static TLSCertificateKeyPair fromX509CertKeyPair(X509Certificate x509Cert, KeyPair keyPair) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintWriter writer = new PrintWriter(baos);
JcaPEMWriter w = new JcaPEMWriter(writer);
w.writeObject(x509Cert);
w.flush();
w.close();
byte[] pemBytes = baos.toByteArray();
InputStreamReader isr = new InputStreamReader(new ByteArrayInputStream(pemBytes));
PemReader pr = new PemReader(isr);
PemObject pem = pr.readPemObject();
byte[] derBytes = pem.getContent();
baos = new ByteArrayOutputStream();
PrintWriter wr = new PrintWriter(baos);
wr.println("-----BEGIN PRIVATE KEY-----");
wr.println(new String(Base64.encodeBase64(keyPair.getPrivate().getEncoded())));
wr.println("-----END PRIVATE KEY-----");
wr.flush();
wr.close();
byte[] keyBytes = baos.toByteArray();
return new TLSCertificateKeyPair(pemBytes, derBytes, keyBytes);
}
|
[
"static",
"TLSCertificateKeyPair",
"fromX509CertKeyPair",
"(",
"X509Certificate",
"x509Cert",
",",
"KeyPair",
"keyPair",
")",
"throws",
"IOException",
"{",
"ByteArrayOutputStream",
"baos",
"=",
"new",
"ByteArrayOutputStream",
"(",
")",
";",
"PrintWriter",
"writer",
"=",
"new",
"PrintWriter",
"(",
"baos",
")",
";",
"JcaPEMWriter",
"w",
"=",
"new",
"JcaPEMWriter",
"(",
"writer",
")",
";",
"w",
".",
"writeObject",
"(",
"x509Cert",
")",
";",
"w",
".",
"flush",
"(",
")",
";",
"w",
".",
"close",
"(",
")",
";",
"byte",
"[",
"]",
"pemBytes",
"=",
"baos",
".",
"toByteArray",
"(",
")",
";",
"InputStreamReader",
"isr",
"=",
"new",
"InputStreamReader",
"(",
"new",
"ByteArrayInputStream",
"(",
"pemBytes",
")",
")",
";",
"PemReader",
"pr",
"=",
"new",
"PemReader",
"(",
"isr",
")",
";",
"PemObject",
"pem",
"=",
"pr",
".",
"readPemObject",
"(",
")",
";",
"byte",
"[",
"]",
"derBytes",
"=",
"pem",
".",
"getContent",
"(",
")",
";",
"baos",
"=",
"new",
"ByteArrayOutputStream",
"(",
")",
";",
"PrintWriter",
"wr",
"=",
"new",
"PrintWriter",
"(",
"baos",
")",
";",
"wr",
".",
"println",
"(",
"\"-----BEGIN PRIVATE KEY-----\"",
")",
";",
"wr",
".",
"println",
"(",
"new",
"String",
"(",
"Base64",
".",
"encodeBase64",
"(",
"keyPair",
".",
"getPrivate",
"(",
")",
".",
"getEncoded",
"(",
")",
")",
")",
")",
";",
"wr",
".",
"println",
"(",
"\"-----END PRIVATE KEY-----\"",
")",
";",
"wr",
".",
"flush",
"(",
")",
";",
"wr",
".",
"close",
"(",
")",
";",
"byte",
"[",
"]",
"keyBytes",
"=",
"baos",
".",
"toByteArray",
"(",
")",
";",
"return",
"new",
"TLSCertificateKeyPair",
"(",
"pemBytes",
",",
"derBytes",
",",
"keyBytes",
")",
";",
"}"
] |
*
Creates a TLSCertificateKeyPair out of the given {@link X509Certificate} and {@link KeyPair}
encoded in PEM and also in DER for the certificate
@param x509Cert the certificate to process
@param keyPair the key pair to process
@return a TLSCertificateKeyPair
@throws IOException upon failure
|
[
"*",
"Creates",
"a",
"TLSCertificateKeyPair",
"out",
"of",
"the",
"given",
"{"
] |
train
|
https://github.com/hyperledger/fabric-sdk-java/blob/4a2d7b3408b8b0a1ed812aa36942c438159c37a0/src/main/java/org/hyperledger/fabric/sdk/security/certgen/TLSCertificateKeyPair.java#L53-L76
|
graknlabs/grakn
|
server/src/server/exception/TransactionException.java
|
TransactionException.invalidLabelStart
|
public static TransactionException invalidLabelStart(Label label) {
return create(String.format("Cannot create a label {%s} starting with character {%s} as it is a reserved starting character", label, Schema.ImplicitType.RESERVED.getValue()));
}
|
java
|
public static TransactionException invalidLabelStart(Label label) {
return create(String.format("Cannot create a label {%s} starting with character {%s} as it is a reserved starting character", label, Schema.ImplicitType.RESERVED.getValue()));
}
|
[
"public",
"static",
"TransactionException",
"invalidLabelStart",
"(",
"Label",
"label",
")",
"{",
"return",
"create",
"(",
"String",
".",
"format",
"(",
"\"Cannot create a label {%s} starting with character {%s} as it is a reserved starting character\"",
",",
"label",
",",
"Schema",
".",
"ImplicitType",
".",
"RESERVED",
".",
"getValue",
"(",
")",
")",
")",
";",
"}"
] |
Thrown when creating a label which starts with a reserved character Schema.ImplicitType#RESERVED
|
[
"Thrown",
"when",
"creating",
"a",
"label",
"which",
"starts",
"with",
"a",
"reserved",
"character",
"Schema",
".",
"ImplicitType#RESERVED"
] |
train
|
https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/server/exception/TransactionException.java#L299-L301
|
Omertron/api-themoviedb
|
src/main/java/com/omertron/themoviedbapi/methods/TmdbPeople.java
|
TmdbPeople.getPersonCombinedCredits
|
public PersonCreditList<CreditBasic> getPersonCombinedCredits(int personId, String language) throws MovieDbException {
TmdbParameters parameters = new TmdbParameters();
parameters.add(Param.ID, personId);
parameters.add(Param.LANGUAGE, language);
URL url = new ApiUrl(apiKey, MethodBase.PERSON).subMethod(MethodSub.COMBINED_CREDITS).buildUrl(parameters);
String webpage = httpTools.getRequest(url);
try {
ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(PersonCreditList.class, PersonCreditsMixIn.class);
TypeReference tr = new TypeReference<PersonCreditList<CreditBasic>>() {
};
return mapper.readValue(webpage, tr);
} catch (IOException ex) {
throw new MovieDbException(ApiExceptionType.MAPPING_FAILED, "Failed to get person combined credits", url, ex);
}
}
|
java
|
public PersonCreditList<CreditBasic> getPersonCombinedCredits(int personId, String language) throws MovieDbException {
TmdbParameters parameters = new TmdbParameters();
parameters.add(Param.ID, personId);
parameters.add(Param.LANGUAGE, language);
URL url = new ApiUrl(apiKey, MethodBase.PERSON).subMethod(MethodSub.COMBINED_CREDITS).buildUrl(parameters);
String webpage = httpTools.getRequest(url);
try {
ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(PersonCreditList.class, PersonCreditsMixIn.class);
TypeReference tr = new TypeReference<PersonCreditList<CreditBasic>>() {
};
return mapper.readValue(webpage, tr);
} catch (IOException ex) {
throw new MovieDbException(ApiExceptionType.MAPPING_FAILED, "Failed to get person combined credits", url, ex);
}
}
|
[
"public",
"PersonCreditList",
"<",
"CreditBasic",
">",
"getPersonCombinedCredits",
"(",
"int",
"personId",
",",
"String",
"language",
")",
"throws",
"MovieDbException",
"{",
"TmdbParameters",
"parameters",
"=",
"new",
"TmdbParameters",
"(",
")",
";",
"parameters",
".",
"add",
"(",
"Param",
".",
"ID",
",",
"personId",
")",
";",
"parameters",
".",
"add",
"(",
"Param",
".",
"LANGUAGE",
",",
"language",
")",
";",
"URL",
"url",
"=",
"new",
"ApiUrl",
"(",
"apiKey",
",",
"MethodBase",
".",
"PERSON",
")",
".",
"subMethod",
"(",
"MethodSub",
".",
"COMBINED_CREDITS",
")",
".",
"buildUrl",
"(",
"parameters",
")",
";",
"String",
"webpage",
"=",
"httpTools",
".",
"getRequest",
"(",
"url",
")",
";",
"try",
"{",
"ObjectMapper",
"mapper",
"=",
"new",
"ObjectMapper",
"(",
")",
";",
"mapper",
".",
"addMixIn",
"(",
"PersonCreditList",
".",
"class",
",",
"PersonCreditsMixIn",
".",
"class",
")",
";",
"TypeReference",
"tr",
"=",
"new",
"TypeReference",
"<",
"PersonCreditList",
"<",
"CreditBasic",
">",
">",
"(",
")",
"{",
"}",
";",
"return",
"mapper",
".",
"readValue",
"(",
"webpage",
",",
"tr",
")",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"throw",
"new",
"MovieDbException",
"(",
"ApiExceptionType",
".",
"MAPPING_FAILED",
",",
"\"Failed to get person combined credits\"",
",",
"url",
",",
"ex",
")",
";",
"}",
"}"
] |
Get the combined (movie and TV) credits for a specific person id.
To get the expanded details for each TV record, call the /credit method
with the provided credit_id.
This will provide details about which episode and/or season the credit is
for.
@param personId
@param language
@return
@throws MovieDbException
|
[
"Get",
"the",
"combined",
"(",
"movie",
"and",
"TV",
")",
"credits",
"for",
"a",
"specific",
"person",
"id",
"."
] |
train
|
https://github.com/Omertron/api-themoviedb/blob/bf132d7c7271734e13b58ba3bc92bba46f220118/src/main/java/com/omertron/themoviedbapi/methods/TmdbPeople.java#L169-L186
|
Azure/azure-sdk-for-java
|
network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/LocalNetworkGatewaysInner.java
|
LocalNetworkGatewaysInner.getByResourceGroupAsync
|
public Observable<LocalNetworkGatewayInner> getByResourceGroupAsync(String resourceGroupName, String localNetworkGatewayName) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, localNetworkGatewayName).map(new Func1<ServiceResponse<LocalNetworkGatewayInner>, LocalNetworkGatewayInner>() {
@Override
public LocalNetworkGatewayInner call(ServiceResponse<LocalNetworkGatewayInner> response) {
return response.body();
}
});
}
|
java
|
public Observable<LocalNetworkGatewayInner> getByResourceGroupAsync(String resourceGroupName, String localNetworkGatewayName) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, localNetworkGatewayName).map(new Func1<ServiceResponse<LocalNetworkGatewayInner>, LocalNetworkGatewayInner>() {
@Override
public LocalNetworkGatewayInner call(ServiceResponse<LocalNetworkGatewayInner> response) {
return response.body();
}
});
}
|
[
"public",
"Observable",
"<",
"LocalNetworkGatewayInner",
">",
"getByResourceGroupAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"localNetworkGatewayName",
")",
"{",
"return",
"getByResourceGroupWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"localNetworkGatewayName",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"LocalNetworkGatewayInner",
">",
",",
"LocalNetworkGatewayInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"LocalNetworkGatewayInner",
"call",
"(",
"ServiceResponse",
"<",
"LocalNetworkGatewayInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Gets the specified local network gateway in a resource group.
@param resourceGroupName The name of the resource group.
@param localNetworkGatewayName The name of the local network gateway.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the LocalNetworkGatewayInner object
|
[
"Gets",
"the",
"specified",
"local",
"network",
"gateway",
"in",
"a",
"resource",
"group",
"."
] |
train
|
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/LocalNetworkGatewaysInner.java#L310-L317
|
belaban/JGroups
|
src/org/jgroups/auth/Krb5TokenUtils.java
|
Krb5TokenUtils.validateSecurityContext
|
public static String validateSecurityContext(Subject subject, final byte[] serviceTicket) throws GSSException {
// Accept the context and return the client principal name.
return Subject.doAs(subject, (PrivilegedAction<String>)() -> {
try {
// Identify the server that communications are being made
// to.
GSSManager manager = GSSManager.getInstance();
GSSContext context = manager.createContext((GSSCredential) null);
context.acceptSecContext(serviceTicket, 0, serviceTicket.length);
return context.getSrcName().toString();
} catch (Exception e) {
log.error(Util.getMessage("Krb5TokenKerberosContextProcessingException"),e);
return null;
}
});
}
|
java
|
public static String validateSecurityContext(Subject subject, final byte[] serviceTicket) throws GSSException {
// Accept the context and return the client principal name.
return Subject.doAs(subject, (PrivilegedAction<String>)() -> {
try {
// Identify the server that communications are being made
// to.
GSSManager manager = GSSManager.getInstance();
GSSContext context = manager.createContext((GSSCredential) null);
context.acceptSecContext(serviceTicket, 0, serviceTicket.length);
return context.getSrcName().toString();
} catch (Exception e) {
log.error(Util.getMessage("Krb5TokenKerberosContextProcessingException"),e);
return null;
}
});
}
|
[
"public",
"static",
"String",
"validateSecurityContext",
"(",
"Subject",
"subject",
",",
"final",
"byte",
"[",
"]",
"serviceTicket",
")",
"throws",
"GSSException",
"{",
"// Accept the context and return the client principal name.",
"return",
"Subject",
".",
"doAs",
"(",
"subject",
",",
"(",
"PrivilegedAction",
"<",
"String",
">",
")",
"(",
")",
"->",
"{",
"try",
"{",
"// Identify the server that communications are being made",
"// to.",
"GSSManager",
"manager",
"=",
"GSSManager",
".",
"getInstance",
"(",
")",
";",
"GSSContext",
"context",
"=",
"manager",
".",
"createContext",
"(",
"(",
"GSSCredential",
")",
"null",
")",
";",
"context",
".",
"acceptSecContext",
"(",
"serviceTicket",
",",
"0",
",",
"serviceTicket",
".",
"length",
")",
";",
"return",
"context",
".",
"getSrcName",
"(",
")",
".",
"toString",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"log",
".",
"error",
"(",
"Util",
".",
"getMessage",
"(",
"\"Krb5TokenKerberosContextProcessingException\"",
")",
",",
"e",
")",
";",
"return",
"null",
";",
"}",
"}",
")",
";",
"}"
] |
Validate the service ticket by extracting the client principal name
|
[
"Validate",
"the",
"service",
"ticket",
"by",
"extracting",
"the",
"client",
"principal",
"name"
] |
train
|
https://github.com/belaban/JGroups/blob/bd3ca786aa57fed41dfbc10a94b1281e388be03b/src/org/jgroups/auth/Krb5TokenUtils.java#L87-L103
|
graknlabs/grakn
|
server/src/server/session/TransactionOLTP.java
|
TransactionOLTP.addVertexElementWithEdgeIdProperty
|
public VertexElement addVertexElementWithEdgeIdProperty(Schema.BaseType baseType, ConceptId conceptId) {
return executeLockingMethod(() -> factory().addVertexElementWithEdgeIdProperty(baseType, conceptId));
}
|
java
|
public VertexElement addVertexElementWithEdgeIdProperty(Schema.BaseType baseType, ConceptId conceptId) {
return executeLockingMethod(() -> factory().addVertexElementWithEdgeIdProperty(baseType, conceptId));
}
|
[
"public",
"VertexElement",
"addVertexElementWithEdgeIdProperty",
"(",
"Schema",
".",
"BaseType",
"baseType",
",",
"ConceptId",
"conceptId",
")",
"{",
"return",
"executeLockingMethod",
"(",
"(",
")",
"->",
"factory",
"(",
")",
".",
"addVertexElementWithEdgeIdProperty",
"(",
"baseType",
",",
"conceptId",
")",
")",
";",
"}"
] |
This is only used when reifying a Relation
@param baseType Concept BaseType which will become the VertexLabel
@param conceptId ConceptId to be set on the vertex
@return just created Vertex
|
[
"This",
"is",
"only",
"used",
"when",
"reifying",
"a",
"Relation"
] |
train
|
https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/server/session/TransactionOLTP.java#L212-L214
|
kikinteractive/ice
|
ice/src/main/java/com/kik/config/ice/internal/ConfigDescriptorFactory.java
|
ConfigDescriptorFactory.buildDescriptor
|
public ConfigDescriptor buildDescriptor(Method method, Optional<String> scopeOpt, Optional<String> overrideValue)
{
checkNotNull(method);
checkNotNull(scopeOpt);
checkNotNull(overrideValue);
StaticConfigHelper.MethodValidationState validationState = StaticConfigHelper.isValidConfigInterfaceMethod(method);
if (validationState != StaticConfigHelper.MethodValidationState.OK) {
log.debug("Configuration class {} was found to be invalid: {}",
method.getDeclaringClass().getName(), validationState.name());
throw new ConfigException("Invalid Configuration class: {}", validationState.name());
}
Optional<String> value = getMethodDefaultValue(method);
if (overrideValue.isPresent()) {
value = overrideValue;
}
return internalBuildDescriptor(method, scopeOpt, value);
}
|
java
|
public ConfigDescriptor buildDescriptor(Method method, Optional<String> scopeOpt, Optional<String> overrideValue)
{
checkNotNull(method);
checkNotNull(scopeOpt);
checkNotNull(overrideValue);
StaticConfigHelper.MethodValidationState validationState = StaticConfigHelper.isValidConfigInterfaceMethod(method);
if (validationState != StaticConfigHelper.MethodValidationState.OK) {
log.debug("Configuration class {} was found to be invalid: {}",
method.getDeclaringClass().getName(), validationState.name());
throw new ConfigException("Invalid Configuration class: {}", validationState.name());
}
Optional<String> value = getMethodDefaultValue(method);
if (overrideValue.isPresent()) {
value = overrideValue;
}
return internalBuildDescriptor(method, scopeOpt, value);
}
|
[
"public",
"ConfigDescriptor",
"buildDescriptor",
"(",
"Method",
"method",
",",
"Optional",
"<",
"String",
">",
"scopeOpt",
",",
"Optional",
"<",
"String",
">",
"overrideValue",
")",
"{",
"checkNotNull",
"(",
"method",
")",
";",
"checkNotNull",
"(",
"scopeOpt",
")",
";",
"checkNotNull",
"(",
"overrideValue",
")",
";",
"StaticConfigHelper",
".",
"MethodValidationState",
"validationState",
"=",
"StaticConfigHelper",
".",
"isValidConfigInterfaceMethod",
"(",
"method",
")",
";",
"if",
"(",
"validationState",
"!=",
"StaticConfigHelper",
".",
"MethodValidationState",
".",
"OK",
")",
"{",
"log",
".",
"debug",
"(",
"\"Configuration class {} was found to be invalid: {}\"",
",",
"method",
".",
"getDeclaringClass",
"(",
")",
".",
"getName",
"(",
")",
",",
"validationState",
".",
"name",
"(",
")",
")",
";",
"throw",
"new",
"ConfigException",
"(",
"\"Invalid Configuration class: {}\"",
",",
"validationState",
".",
"name",
"(",
")",
")",
";",
"}",
"Optional",
"<",
"String",
">",
"value",
"=",
"getMethodDefaultValue",
"(",
"method",
")",
";",
"if",
"(",
"overrideValue",
".",
"isPresent",
"(",
")",
")",
"{",
"value",
"=",
"overrideValue",
";",
"}",
"return",
"internalBuildDescriptor",
"(",
"method",
",",
"scopeOpt",
",",
"value",
")",
";",
"}"
] |
Build a {@link ConfigDescriptor} for a specific Method, given optional scope, and given override value.
@param method method to include in config descriptor
@param scopeOpt optional scope for the config descriptor
@param overrideValue optional override value used to override the static value in the config descriptor
@return a {@link ConfigDescriptor} for the given method, to be used internally in the config system.
|
[
"Build",
"a",
"{",
"@link",
"ConfigDescriptor",
"}",
"for",
"a",
"specific",
"Method",
"given",
"optional",
"scope",
"and",
"given",
"override",
"value",
"."
] |
train
|
https://github.com/kikinteractive/ice/blob/0c58d7bf2d9f6504892d0768d6022fcfa6df7514/ice/src/main/java/com/kik/config/ice/internal/ConfigDescriptorFactory.java#L123-L141
|
mikepenz/MaterialDrawer
|
library/src/main/java/com/mikepenz/materialdrawer/DrawerBuilder.java
|
DrawerBuilder.withAccountHeader
|
public DrawerBuilder withAccountHeader(@NonNull AccountHeader accountHeader, boolean accountHeaderSticky) {
this.mAccountHeader = accountHeader;
this.mAccountHeaderSticky = accountHeaderSticky;
return this;
}
|
java
|
public DrawerBuilder withAccountHeader(@NonNull AccountHeader accountHeader, boolean accountHeaderSticky) {
this.mAccountHeader = accountHeader;
this.mAccountHeaderSticky = accountHeaderSticky;
return this;
}
|
[
"public",
"DrawerBuilder",
"withAccountHeader",
"(",
"@",
"NonNull",
"AccountHeader",
"accountHeader",
",",
"boolean",
"accountHeaderSticky",
")",
"{",
"this",
".",
"mAccountHeader",
"=",
"accountHeader",
";",
"this",
".",
"mAccountHeaderSticky",
"=",
"accountHeaderSticky",
";",
"return",
"this",
";",
"}"
] |
Add a AccountSwitcherHeader which will be used in this drawer instance. Pass true if it should be sticky
NOTE: This will overwrite any set headerView or stickyHeaderView (depends on the boolean).
@param accountHeader
@param accountHeaderSticky
@return
|
[
"Add",
"a",
"AccountSwitcherHeader",
"which",
"will",
"be",
"used",
"in",
"this",
"drawer",
"instance",
".",
"Pass",
"true",
"if",
"it",
"should",
"be",
"sticky",
"NOTE",
":",
"This",
"will",
"overwrite",
"any",
"set",
"headerView",
"or",
"stickyHeaderView",
"(",
"depends",
"on",
"the",
"boolean",
")",
"."
] |
train
|
https://github.com/mikepenz/MaterialDrawer/blob/f4fb31635767edead0a01cee7b7588942b89d8d9/library/src/main/java/com/mikepenz/materialdrawer/DrawerBuilder.java#L480-L484
|
code4everything/util
|
src/main/java/com/zhazhapan/util/BeanUtils.java
|
BeanUtils.toJsonString
|
public static String toJsonString(Object object, FieldModifier modifier) throws IllegalAccessException {
return toJsonString(object, modifier, JsonMethod.AUTO);
}
|
java
|
public static String toJsonString(Object object, FieldModifier modifier) throws IllegalAccessException {
return toJsonString(object, modifier, JsonMethod.AUTO);
}
|
[
"public",
"static",
"String",
"toJsonString",
"(",
"Object",
"object",
",",
"FieldModifier",
"modifier",
")",
"throws",
"IllegalAccessException",
"{",
"return",
"toJsonString",
"(",
"object",
",",
"modifier",
",",
"JsonMethod",
".",
"AUTO",
")",
";",
"}"
] |
将Bean类指定修饰符的属性转换成JSON字符串
@param object Bean对象
@param modifier 属性的权限修饰符
@return 没有格式化的JSON字符串
@throws IllegalAccessException 异常
|
[
"将Bean类指定修饰符的属性转换成JSON字符串"
] |
train
|
https://github.com/code4everything/util/blob/1fc9f0ead1108f4d7208ba7c000df4244f708418/src/main/java/com/zhazhapan/util/BeanUtils.java#L286-L288
|
mangstadt/biweekly
|
src/main/java/biweekly/io/json/JCalRawWriter.java
|
JCalRawWriter.writeProperty
|
public void writeProperty(String propertyName, ICalDataType dataType, JCalValue value) throws IOException {
writeProperty(propertyName, new ICalParameters(), dataType, value);
}
|
java
|
public void writeProperty(String propertyName, ICalDataType dataType, JCalValue value) throws IOException {
writeProperty(propertyName, new ICalParameters(), dataType, value);
}
|
[
"public",
"void",
"writeProperty",
"(",
"String",
"propertyName",
",",
"ICalDataType",
"dataType",
",",
"JCalValue",
"value",
")",
"throws",
"IOException",
"{",
"writeProperty",
"(",
"propertyName",
",",
"new",
"ICalParameters",
"(",
")",
",",
"dataType",
",",
"value",
")",
";",
"}"
] |
Writes a property to the current component.
@param propertyName the property name (e.g. "version")
@param dataType the property's data type (e.g. "text")
@param value the property value
@throws IllegalStateException if there are no open components (
{@link #writeStartComponent(String)} must be called first) or if the last
method called was {@link #writeEndComponent()}.
@throws IOException if there's an I/O problem
|
[
"Writes",
"a",
"property",
"to",
"the",
"current",
"component",
"."
] |
train
|
https://github.com/mangstadt/biweekly/blob/2e21350f85c13dfff52fdef98fdbebe2976fcf61/src/main/java/biweekly/io/json/JCalRawWriter.java#L177-L179
|
javalite/activejdbc
|
javalite-common/src/main/java/org/javalite/http/Request.java
|
Request.text
|
public String text() {
try {
connect();
return responseCode() >= 400 ? read(connection.getErrorStream()) : read(connection.getInputStream());
} catch (IOException e) {
throw new HttpException("Failed URL: " + url, e);
}finally {
dispose();
}
}
|
java
|
public String text() {
try {
connect();
return responseCode() >= 400 ? read(connection.getErrorStream()) : read(connection.getInputStream());
} catch (IOException e) {
throw new HttpException("Failed URL: " + url, e);
}finally {
dispose();
}
}
|
[
"public",
"String",
"text",
"(",
")",
"{",
"try",
"{",
"connect",
"(",
")",
";",
"return",
"responseCode",
"(",
")",
">=",
"400",
"?",
"read",
"(",
"connection",
".",
"getErrorStream",
"(",
")",
")",
":",
"read",
"(",
"connection",
".",
"getInputStream",
"(",
")",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"HttpException",
"(",
"\"Failed URL: \"",
"+",
"url",
",",
"e",
")",
";",
"}",
"finally",
"{",
"dispose",
"(",
")",
";",
"}",
"}"
] |
Fetches response content from server as String.
@return response content from server as String.
|
[
"Fetches",
"response",
"content",
"from",
"server",
"as",
"String",
"."
] |
train
|
https://github.com/javalite/activejdbc/blob/ffcf5457cace19622a8f71e856cbbbe9e7dd5fcc/javalite-common/src/main/java/org/javalite/http/Request.java#L163-L172
|
cogroo/cogroo4
|
lang/pt_br/cogroo-addon/src/org/cogroo/addon/dialogs/reporterror/ErrorReportDialog.java
|
ErrorReportDialog.setIsStepEnabled
|
private void setIsStepEnabled(int step, boolean isEnabled) {
try {
Object oRoadmapItem = m_xRMIndexCont.getByIndex(step - 1);
XPropertySet xRMItemPSet = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, oRoadmapItem);
xRMItemPSet.setPropertyValue("Enabled", new Boolean(isEnabled));
} catch (com.sun.star.uno.Exception e) {
LOGGER.log(Level.SEVERE, "Error in setIsStepEnabled", e);
throw new CogrooRuntimeException(e);
}
}
|
java
|
private void setIsStepEnabled(int step, boolean isEnabled) {
try {
Object oRoadmapItem = m_xRMIndexCont.getByIndex(step - 1);
XPropertySet xRMItemPSet = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, oRoadmapItem);
xRMItemPSet.setPropertyValue("Enabled", new Boolean(isEnabled));
} catch (com.sun.star.uno.Exception e) {
LOGGER.log(Level.SEVERE, "Error in setIsStepEnabled", e);
throw new CogrooRuntimeException(e);
}
}
|
[
"private",
"void",
"setIsStepEnabled",
"(",
"int",
"step",
",",
"boolean",
"isEnabled",
")",
"{",
"try",
"{",
"Object",
"oRoadmapItem",
"=",
"m_xRMIndexCont",
".",
"getByIndex",
"(",
"step",
"-",
"1",
")",
";",
"XPropertySet",
"xRMItemPSet",
"=",
"(",
"XPropertySet",
")",
"UnoRuntime",
".",
"queryInterface",
"(",
"XPropertySet",
".",
"class",
",",
"oRoadmapItem",
")",
";",
"xRMItemPSet",
".",
"setPropertyValue",
"(",
"\"Enabled\"",
",",
"new",
"Boolean",
"(",
"isEnabled",
")",
")",
";",
"}",
"catch",
"(",
"com",
".",
"sun",
".",
"star",
".",
"uno",
".",
"Exception",
"e",
")",
"{",
"LOGGER",
".",
"log",
"(",
"Level",
".",
"SEVERE",
",",
"\"Error in setIsStepEnabled\"",
",",
"e",
")",
";",
"throw",
"new",
"CogrooRuntimeException",
"(",
"e",
")",
";",
"}",
"}"
] |
Configure the steps that are enabled.
@param step step to configure
@param isEnabled if it is enabled
|
[
"Configure",
"the",
"steps",
"that",
"are",
"enabled",
"."
] |
train
|
https://github.com/cogroo/cogroo4/blob/b6228900c20c6b37eac10a03708a9669dd562f52/lang/pt_br/cogroo-addon/src/org/cogroo/addon/dialogs/reporterror/ErrorReportDialog.java#L524-L533
|
google/error-prone-javac
|
src/java.compiler/share/classes/javax/lang/model/util/ElementFilter.java
|
ElementFilter.methodsIn
|
public static List<ExecutableElement>
methodsIn(Iterable<? extends Element> elements) {
return listFilter(elements, METHOD_KIND, ExecutableElement.class);
}
|
java
|
public static List<ExecutableElement>
methodsIn(Iterable<? extends Element> elements) {
return listFilter(elements, METHOD_KIND, ExecutableElement.class);
}
|
[
"public",
"static",
"List",
"<",
"ExecutableElement",
">",
"methodsIn",
"(",
"Iterable",
"<",
"?",
"extends",
"Element",
">",
"elements",
")",
"{",
"return",
"listFilter",
"(",
"elements",
",",
"METHOD_KIND",
",",
"ExecutableElement",
".",
"class",
")",
";",
"}"
] |
Returns a list of methods in {@code elements}.
@return a list of methods in {@code elements}
@param elements the elements to filter
|
[
"Returns",
"a",
"list",
"of",
"methods",
"in",
"{"
] |
train
|
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/java.compiler/share/classes/javax/lang/model/util/ElementFilter.java#L132-L135
|
webmetrics/browsermob-proxy
|
src/main/java/org/xbill/DNS/TSIG.java
|
TSIG.fromString
|
static public TSIG
fromString(String str) {
String [] parts = str.split("[:/]");
if (parts.length < 2 || parts.length > 3)
throw new IllegalArgumentException("Invalid TSIG key " +
"specification");
if (parts.length == 3)
return new TSIG(parts[0], parts[1], parts[2]);
else
return new TSIG(HMAC_MD5, parts[0], parts[1]);
}
|
java
|
static public TSIG
fromString(String str) {
String [] parts = str.split("[:/]");
if (parts.length < 2 || parts.length > 3)
throw new IllegalArgumentException("Invalid TSIG key " +
"specification");
if (parts.length == 3)
return new TSIG(parts[0], parts[1], parts[2]);
else
return new TSIG(HMAC_MD5, parts[0], parts[1]);
}
|
[
"static",
"public",
"TSIG",
"fromString",
"(",
"String",
"str",
")",
"{",
"String",
"[",
"]",
"parts",
"=",
"str",
".",
"split",
"(",
"\"[:/]\"",
")",
";",
"if",
"(",
"parts",
".",
"length",
"<",
"2",
"||",
"parts",
".",
"length",
">",
"3",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Invalid TSIG key \"",
"+",
"\"specification\"",
")",
";",
"if",
"(",
"parts",
".",
"length",
"==",
"3",
")",
"return",
"new",
"TSIG",
"(",
"parts",
"[",
"0",
"]",
",",
"parts",
"[",
"1",
"]",
",",
"parts",
"[",
"2",
"]",
")",
";",
"else",
"return",
"new",
"TSIG",
"(",
"HMAC_MD5",
",",
"parts",
"[",
"0",
"]",
",",
"parts",
"[",
"1",
"]",
")",
";",
"}"
] |
Creates a new TSIG object with the hmac-md5 algorithm, which can be used to
sign or verify a message.
@param str The TSIG key, in the form name:secret, name/secret,
alg:name:secret, or alg/name/secret. If an algorithm is specified, it must
be "hmac-md5", "hmac-sha1", or "hmac-sha256".
@throws IllegalArgumentException The string does not contain both a name
and secret.
@throws IllegalArgumentException The key name is an invalid name
@throws IllegalArgumentException The key data is improperly encoded
|
[
"Creates",
"a",
"new",
"TSIG",
"object",
"with",
"the",
"hmac",
"-",
"md5",
"algorithm",
"which",
"can",
"be",
"used",
"to",
"sign",
"or",
"verify",
"a",
"message",
"."
] |
train
|
https://github.com/webmetrics/browsermob-proxy/blob/a9252e62246ac33d55d51b993ba1159404e7d389/src/main/java/org/xbill/DNS/TSIG.java#L151-L161
|
hawkular/hawkular-agent
|
hawkular-dmr-client/src/main/java/org/hawkular/dmrclient/WebJBossASClient.java
|
WebJBossASClient.getConnector
|
public ModelNode getConnector(String name) throws Exception {
final Address address = Address.root().add(SUBSYSTEM, SUBSYSTEM_WEB, CONNECTOR, name);
return readResource(address, true);
}
|
java
|
public ModelNode getConnector(String name) throws Exception {
final Address address = Address.root().add(SUBSYSTEM, SUBSYSTEM_WEB, CONNECTOR, name);
return readResource(address, true);
}
|
[
"public",
"ModelNode",
"getConnector",
"(",
"String",
"name",
")",
"throws",
"Exception",
"{",
"final",
"Address",
"address",
"=",
"Address",
".",
"root",
"(",
")",
".",
"add",
"(",
"SUBSYSTEM",
",",
"SUBSYSTEM_WEB",
",",
"CONNECTOR",
",",
"name",
")",
";",
"return",
"readResource",
"(",
"address",
",",
"true",
")",
";",
"}"
] |
Returns the connector node with all its attributes. Will be null if it doesn't exist.
@param name the name of the connector whose node is to be returned
@return the node if there is a connector with the given name already in existence, null otherwise
@throws Exception any error
|
[
"Returns",
"the",
"connector",
"node",
"with",
"all",
"its",
"attributes",
".",
"Will",
"be",
"null",
"if",
"it",
"doesn",
"t",
"exist",
"."
] |
train
|
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-dmr-client/src/main/java/org/hawkular/dmrclient/WebJBossASClient.java#L90-L93
|
raphw/byte-buddy
|
byte-buddy-dep/src/main/java/net/bytebuddy/dynamic/loading/InjectionClassLoader.java
|
InjectionClassLoader.defineClass
|
public Class<?> defineClass(String name, byte[] binaryRepresentation) throws ClassNotFoundException {
return defineClasses(Collections.singletonMap(name, binaryRepresentation)).get(name);
}
|
java
|
public Class<?> defineClass(String name, byte[] binaryRepresentation) throws ClassNotFoundException {
return defineClasses(Collections.singletonMap(name, binaryRepresentation)).get(name);
}
|
[
"public",
"Class",
"<",
"?",
">",
"defineClass",
"(",
"String",
"name",
",",
"byte",
"[",
"]",
"binaryRepresentation",
")",
"throws",
"ClassNotFoundException",
"{",
"return",
"defineClasses",
"(",
"Collections",
".",
"singletonMap",
"(",
"name",
",",
"binaryRepresentation",
")",
")",
".",
"get",
"(",
"name",
")",
";",
"}"
] |
Defines a new type to be loaded by this class loader.
@param name The name of the type.
@param binaryRepresentation The type's binary representation.
@return The defined class or a previously defined class.
@throws ClassNotFoundException If the class could not be loaded.
|
[
"Defines",
"a",
"new",
"type",
"to",
"be",
"loaded",
"by",
"this",
"class",
"loader",
"."
] |
train
|
https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-dep/src/main/java/net/bytebuddy/dynamic/loading/InjectionClassLoader.java#L68-L70
|
liferay/com-liferay-commerce
|
commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceShipmentPersistenceImpl.java
|
CommerceShipmentPersistenceImpl.removeByG_S
|
@Override
public void removeByG_S(long groupId, int status) {
for (CommerceShipment commerceShipment : findByG_S(groupId, status,
QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
remove(commerceShipment);
}
}
|
java
|
@Override
public void removeByG_S(long groupId, int status) {
for (CommerceShipment commerceShipment : findByG_S(groupId, status,
QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
remove(commerceShipment);
}
}
|
[
"@",
"Override",
"public",
"void",
"removeByG_S",
"(",
"long",
"groupId",
",",
"int",
"status",
")",
"{",
"for",
"(",
"CommerceShipment",
"commerceShipment",
":",
"findByG_S",
"(",
"groupId",
",",
"status",
",",
"QueryUtil",
".",
"ALL_POS",
",",
"QueryUtil",
".",
"ALL_POS",
",",
"null",
")",
")",
"{",
"remove",
"(",
"commerceShipment",
")",
";",
"}",
"}"
] |
Removes all the commerce shipments where groupId = ? and status = ? from the database.
@param groupId the group ID
@param status the status
|
[
"Removes",
"all",
"the",
"commerce",
"shipments",
"where",
"groupId",
"=",
"?",
";",
"and",
"status",
"=",
"?",
";",
"from",
"the",
"database",
"."
] |
train
|
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceShipmentPersistenceImpl.java#L1080-L1086
|
kuali/ojb-1.0.4
|
src/java/org/apache/ojb/broker/core/PersistenceBrokerImpl.java
|
PersistenceBrokerImpl.refreshInstance
|
private void refreshInstance(Object cachedInstance, Identity oid, ClassDescriptor cld)
{
// read in fresh copy from the db, but do not cache it
Object freshInstance = getPlainDBObject(cld, oid);
// update all primitive typed attributes
FieldDescriptor[] fields = cld.getFieldDescriptions();
FieldDescriptor fmd;
PersistentField fld;
for (int i = 0; i < fields.length; i++)
{
fmd = fields[i];
fld = fmd.getPersistentField();
fld.set(cachedInstance, fld.get(freshInstance));
}
}
|
java
|
private void refreshInstance(Object cachedInstance, Identity oid, ClassDescriptor cld)
{
// read in fresh copy from the db, but do not cache it
Object freshInstance = getPlainDBObject(cld, oid);
// update all primitive typed attributes
FieldDescriptor[] fields = cld.getFieldDescriptions();
FieldDescriptor fmd;
PersistentField fld;
for (int i = 0; i < fields.length; i++)
{
fmd = fields[i];
fld = fmd.getPersistentField();
fld.set(cachedInstance, fld.get(freshInstance));
}
}
|
[
"private",
"void",
"refreshInstance",
"(",
"Object",
"cachedInstance",
",",
"Identity",
"oid",
",",
"ClassDescriptor",
"cld",
")",
"{",
"// read in fresh copy from the db, but do not cache it",
"Object",
"freshInstance",
"=",
"getPlainDBObject",
"(",
"cld",
",",
"oid",
")",
";",
"// update all primitive typed attributes",
"FieldDescriptor",
"[",
"]",
"fields",
"=",
"cld",
".",
"getFieldDescriptions",
"(",
")",
";",
"FieldDescriptor",
"fmd",
";",
"PersistentField",
"fld",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"fields",
".",
"length",
";",
"i",
"++",
")",
"{",
"fmd",
"=",
"fields",
"[",
"i",
"]",
";",
"fld",
"=",
"fmd",
".",
"getPersistentField",
"(",
")",
";",
"fld",
".",
"set",
"(",
"cachedInstance",
",",
"fld",
".",
"get",
"(",
"freshInstance",
")",
")",
";",
"}",
"}"
] |
refresh all primitive typed attributes of a cached instance
with the current values from the database.
refreshing of reference and collection attributes is not done
here.
@param cachedInstance the cached instance to be refreshed
@param oid the Identity of the cached instance
@param cld the ClassDescriptor of cachedInstance
|
[
"refresh",
"all",
"primitive",
"typed",
"attributes",
"of",
"a",
"cached",
"instance",
"with",
"the",
"current",
"values",
"from",
"the",
"database",
".",
"refreshing",
"of",
"reference",
"and",
"collection",
"attributes",
"is",
"not",
"done",
"here",
"."
] |
train
|
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/core/PersistenceBrokerImpl.java#L1743-L1758
|
Azure/azure-sdk-for-java
|
servicebus/data-plane/azure-servicebus/src/main/java/com/microsoft/azure/servicebus/ClientFactory.java
|
ClientFactory.createMessageReceiverFromEntityPathAsync
|
public static CompletableFuture<IMessageReceiver> createMessageReceiverFromEntityPathAsync(MessagingFactory messagingFactory, String entityPath) {
return createMessageReceiverFromEntityPathAsync(messagingFactory, entityPath, DEFAULTRECEIVEMODE);
}
|
java
|
public static CompletableFuture<IMessageReceiver> createMessageReceiverFromEntityPathAsync(MessagingFactory messagingFactory, String entityPath) {
return createMessageReceiverFromEntityPathAsync(messagingFactory, entityPath, DEFAULTRECEIVEMODE);
}
|
[
"public",
"static",
"CompletableFuture",
"<",
"IMessageReceiver",
">",
"createMessageReceiverFromEntityPathAsync",
"(",
"MessagingFactory",
"messagingFactory",
",",
"String",
"entityPath",
")",
"{",
"return",
"createMessageReceiverFromEntityPathAsync",
"(",
"messagingFactory",
",",
"entityPath",
",",
"DEFAULTRECEIVEMODE",
")",
";",
"}"
] |
Asynchronously creates a new message receiver to the entity on the messagingFactory.
@param messagingFactory messaging factory (which represents a connection) on which receiver needs to be created.
@param entityPath path of entity
@return a CompletableFuture representing the pending creation of message receiver
|
[
"Asynchronously",
"creates",
"a",
"new",
"message",
"receiver",
"to",
"the",
"entity",
"on",
"the",
"messagingFactory",
"."
] |
train
|
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/servicebus/data-plane/azure-servicebus/src/main/java/com/microsoft/azure/servicebus/ClientFactory.java#L455-L457
|
bladecoder/blade-ink
|
src/main/java/com/bladecoder/ink/runtime/Story.java
|
Story.evaluateFunction
|
public Object evaluateFunction(String functionName, Object[] arguments) throws Exception {
return evaluateFunction(functionName, null, arguments);
}
|
java
|
public Object evaluateFunction(String functionName, Object[] arguments) throws Exception {
return evaluateFunction(functionName, null, arguments);
}
|
[
"public",
"Object",
"evaluateFunction",
"(",
"String",
"functionName",
",",
"Object",
"[",
"]",
"arguments",
")",
"throws",
"Exception",
"{",
"return",
"evaluateFunction",
"(",
"functionName",
",",
"null",
",",
"arguments",
")",
";",
"}"
] |
Evaluates a function defined in ink.
@param functionName
The name of the function as declared in ink.
@param arguments
The arguments that the ink function takes, if any. Note that we
don't (can't) do any validation on the number of arguments right
now, so make sure you get it right!
@return The return value as returned from the ink function with `~ return
myValue`, or null if nothing is returned.
@throws Exception
|
[
"Evaluates",
"a",
"function",
"defined",
"in",
"ink",
"."
] |
train
|
https://github.com/bladecoder/blade-ink/blob/930922099f7073f50f956479adaa3cbd47c70225/src/main/java/com/bladecoder/ink/runtime/Story.java#L2378-L2380
|
joniles/mpxj
|
src/main/java/net/sf/mpxj/mpp/MPP12Reader.java
|
MPP12Reader.processCustomValueLists
|
private void processCustomValueLists() throws IOException
{
DirectoryEntry taskDir = (DirectoryEntry) m_projectDir.getEntry("TBkndTask");
Props taskProps = new Props12(m_inputStreamFactory.getInstance(taskDir, "Props"));
CustomFieldValueReader12 reader = new CustomFieldValueReader12(m_file.getProjectProperties(), m_file.getCustomFields(), m_outlineCodeVarMeta, m_outlineCodeVarData, m_outlineCodeFixedData, m_outlineCodeFixedData2, taskProps);
reader.process();
}
|
java
|
private void processCustomValueLists() throws IOException
{
DirectoryEntry taskDir = (DirectoryEntry) m_projectDir.getEntry("TBkndTask");
Props taskProps = new Props12(m_inputStreamFactory.getInstance(taskDir, "Props"));
CustomFieldValueReader12 reader = new CustomFieldValueReader12(m_file.getProjectProperties(), m_file.getCustomFields(), m_outlineCodeVarMeta, m_outlineCodeVarData, m_outlineCodeFixedData, m_outlineCodeFixedData2, taskProps);
reader.process();
}
|
[
"private",
"void",
"processCustomValueLists",
"(",
")",
"throws",
"IOException",
"{",
"DirectoryEntry",
"taskDir",
"=",
"(",
"DirectoryEntry",
")",
"m_projectDir",
".",
"getEntry",
"(",
"\"TBkndTask\"",
")",
";",
"Props",
"taskProps",
"=",
"new",
"Props12",
"(",
"m_inputStreamFactory",
".",
"getInstance",
"(",
"taskDir",
",",
"\"Props\"",
")",
")",
";",
"CustomFieldValueReader12",
"reader",
"=",
"new",
"CustomFieldValueReader12",
"(",
"m_file",
".",
"getProjectProperties",
"(",
")",
",",
"m_file",
".",
"getCustomFields",
"(",
")",
",",
"m_outlineCodeVarMeta",
",",
"m_outlineCodeVarData",
",",
"m_outlineCodeFixedData",
",",
"m_outlineCodeFixedData2",
",",
"taskProps",
")",
";",
"reader",
".",
"process",
"(",
")",
";",
"}"
] |
This method extracts and collates the value list information
for custom column value lists.
|
[
"This",
"method",
"extracts",
"and",
"collates",
"the",
"value",
"list",
"information",
"for",
"custom",
"column",
"value",
"lists",
"."
] |
train
|
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpp/MPP12Reader.java#L199-L206
|
jpaoletti/java-presentation-manager
|
modules/jpm-core/src/main/java/jpaoletti/jpm/core/PMContext.java
|
PMContext.getParameter
|
public Object getParameter(String paramid, Object def) {
final Object v = getParameter(paramid);
if (v == null) {
return def;
} else {
return v;
}
}
|
java
|
public Object getParameter(String paramid, Object def) {
final Object v = getParameter(paramid);
if (v == null) {
return def;
} else {
return v;
}
}
|
[
"public",
"Object",
"getParameter",
"(",
"String",
"paramid",
",",
"Object",
"def",
")",
"{",
"final",
"Object",
"v",
"=",
"getParameter",
"(",
"paramid",
")",
";",
"if",
"(",
"v",
"==",
"null",
")",
"{",
"return",
"def",
";",
"}",
"else",
"{",
"return",
"v",
";",
"}",
"}"
] |
Look for a parameter in the context with the given name. If parmeter is
null, return def
@param paramid parameter id
@param def default value
@return parameter value or def if null
|
[
"Look",
"for",
"a",
"parameter",
"in",
"the",
"context",
"with",
"the",
"given",
"name",
".",
"If",
"parmeter",
"is",
"null",
"return",
"def"
] |
train
|
https://github.com/jpaoletti/java-presentation-manager/blob/d5aab55638383695db244744b4bfe27c5200e04f/modules/jpm-core/src/main/java/jpaoletti/jpm/core/PMContext.java#L276-L283
|
nguillaumin/slick2d-maven
|
slick2d-peditor/src/main/java/org/newdawn/slick/tools/peditor/GradientEditor.java
|
GradientEditor.checkPoint
|
private boolean checkPoint(int mx, int my, ControlPoint pt) {
int dx = (int) Math.abs((10+(width * pt.pos)) - mx);
int dy = Math.abs((y+barHeight+7)-my);
if ((dx < 5) && (dy < 7)) {
return true;
}
return false;
}
|
java
|
private boolean checkPoint(int mx, int my, ControlPoint pt) {
int dx = (int) Math.abs((10+(width * pt.pos)) - mx);
int dy = Math.abs((y+barHeight+7)-my);
if ((dx < 5) && (dy < 7)) {
return true;
}
return false;
}
|
[
"private",
"boolean",
"checkPoint",
"(",
"int",
"mx",
",",
"int",
"my",
",",
"ControlPoint",
"pt",
")",
"{",
"int",
"dx",
"=",
"(",
"int",
")",
"Math",
".",
"abs",
"(",
"(",
"10",
"+",
"(",
"width",
"*",
"pt",
".",
"pos",
")",
")",
"-",
"mx",
")",
";",
"int",
"dy",
"=",
"Math",
".",
"abs",
"(",
"(",
"y",
"+",
"barHeight",
"+",
"7",
")",
"-",
"my",
")",
";",
"if",
"(",
"(",
"dx",
"<",
"5",
")",
"&&",
"(",
"dy",
"<",
"7",
")",
")",
"{",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] |
Check if there is a control point at the specified mouse location
@param mx The mouse x coordinate
@param my The mouse y coordinate
@param pt The point to check agianst
@return True if the mouse point conincides with the control point
|
[
"Check",
"if",
"there",
"is",
"a",
"control",
"point",
"at",
"the",
"specified",
"mouse",
"location"
] |
train
|
https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-peditor/src/main/java/org/newdawn/slick/tools/peditor/GradientEditor.java#L164-L173
|
code4everything/util
|
src/main/java/com/zhazhapan/util/Checker.java
|
Checker.checkNull
|
public static Double checkNull(Double value, Double elseValue) {
return isNull(value) ? elseValue : value;
}
|
java
|
public static Double checkNull(Double value, Double elseValue) {
return isNull(value) ? elseValue : value;
}
|
[
"public",
"static",
"Double",
"checkNull",
"(",
"Double",
"value",
",",
"Double",
"elseValue",
")",
"{",
"return",
"isNull",
"(",
"value",
")",
"?",
"elseValue",
":",
"value",
";",
"}"
] |
检查Double是否为null
@param value 值
@param elseValue 为null返回的值
@return {@link Double}
@since 1.0.8
|
[
"检查Double是否为null"
] |
train
|
https://github.com/code4everything/util/blob/1fc9f0ead1108f4d7208ba7c000df4244f708418/src/main/java/com/zhazhapan/util/Checker.java#L1171-L1173
|
querydsl/querydsl
|
querydsl-sql/src/main/java/com/querydsl/sql/Configuration.java
|
Configuration.registerNumeric
|
public void registerNumeric(int beginTotal, int endTotal, int beginDecimal, int endDecimal, Class <?> javaType) {
for (int total = beginTotal; total <= endTotal; total++) {
for (int decimal = beginDecimal; decimal <= endDecimal; decimal++) {
registerNumeric(total, decimal, javaType);
}
}
}
|
java
|
public void registerNumeric(int beginTotal, int endTotal, int beginDecimal, int endDecimal, Class <?> javaType) {
for (int total = beginTotal; total <= endTotal; total++) {
for (int decimal = beginDecimal; decimal <= endDecimal; decimal++) {
registerNumeric(total, decimal, javaType);
}
}
}
|
[
"public",
"void",
"registerNumeric",
"(",
"int",
"beginTotal",
",",
"int",
"endTotal",
",",
"int",
"beginDecimal",
",",
"int",
"endDecimal",
",",
"Class",
"<",
"?",
">",
"javaType",
")",
"{",
"for",
"(",
"int",
"total",
"=",
"beginTotal",
";",
"total",
"<=",
"endTotal",
";",
"total",
"++",
")",
"{",
"for",
"(",
"int",
"decimal",
"=",
"beginDecimal",
";",
"decimal",
"<=",
"endDecimal",
";",
"decimal",
"++",
")",
"{",
"registerNumeric",
"(",
"total",
",",
"decimal",
",",
"javaType",
")",
";",
"}",
"}",
"}"
] |
Override multiple numeric bindings, both begin and end are inclusive
@param beginTotal inclusive start of range
@param endTotal inclusive end of range
@param beginDecimal inclusive start of range
@param endDecimal inclusive end of range
@param javaType java type
|
[
"Override",
"multiple",
"numeric",
"bindings",
"both",
"begin",
"and",
"end",
"are",
"inclusive"
] |
train
|
https://github.com/querydsl/querydsl/blob/2bf234caf78549813a1e0f44d9c30ecc5ef734e3/querydsl-sql/src/main/java/com/querydsl/sql/Configuration.java#L458-L464
|
pravega/pravega
|
controller/src/main/java/io/pravega/controller/server/rest/resources/StreamMetadataResourceImpl.java
|
StreamMetadataResourceImpl.listScopes
|
@Override
public void listScopes(final SecurityContext securityContext, final AsyncResponse asyncResponse) {
long traceId = LoggerHelpers.traceEnter(log, "listScopes");
final Principal principal;
final List<String> authHeader = getAuthorizationHeader();
try {
principal = restAuthHelper.authenticate(authHeader);
restAuthHelper.authorize(authHeader, AuthResourceRepresentation.ofScopes(), principal, READ);
} catch (AuthException e) {
log.warn("Get scopes failed due to authentication failure.", e);
asyncResponse.resume(Response.status(Status.fromStatusCode(e.getResponseCode())).build());
LoggerHelpers.traceLeave(log, "listScopes", traceId);
return;
}
controllerService.listScopes()
.thenApply(scopesList -> {
ScopesList scopes = new ScopesList();
scopesList.forEach(scope -> {
try {
if (restAuthHelper.isAuthorized(authHeader,
AuthResourceRepresentation.ofScope(scope),
principal, READ)) {
scopes.addScopesItem(new ScopeProperty().scopeName(scope));
}
} catch (AuthException e) {
log.warn(e.getMessage(), e);
// Ignore. This exception occurs under abnormal circumstances and not to determine
// whether the user is authorized. In case it does occur, we assume that the user
// is unauthorized.
}
});
return Response.status(Status.OK).entity(scopes).build(); })
.exceptionally(exception -> {
log.warn("listScopes failed with exception: ", exception);
return Response.status(Status.INTERNAL_SERVER_ERROR).build(); })
.thenApply(response -> {
asyncResponse.resume(response);
LoggerHelpers.traceLeave(log, "listScopes", traceId);
return response;
});
}
|
java
|
@Override
public void listScopes(final SecurityContext securityContext, final AsyncResponse asyncResponse) {
long traceId = LoggerHelpers.traceEnter(log, "listScopes");
final Principal principal;
final List<String> authHeader = getAuthorizationHeader();
try {
principal = restAuthHelper.authenticate(authHeader);
restAuthHelper.authorize(authHeader, AuthResourceRepresentation.ofScopes(), principal, READ);
} catch (AuthException e) {
log.warn("Get scopes failed due to authentication failure.", e);
asyncResponse.resume(Response.status(Status.fromStatusCode(e.getResponseCode())).build());
LoggerHelpers.traceLeave(log, "listScopes", traceId);
return;
}
controllerService.listScopes()
.thenApply(scopesList -> {
ScopesList scopes = new ScopesList();
scopesList.forEach(scope -> {
try {
if (restAuthHelper.isAuthorized(authHeader,
AuthResourceRepresentation.ofScope(scope),
principal, READ)) {
scopes.addScopesItem(new ScopeProperty().scopeName(scope));
}
} catch (AuthException e) {
log.warn(e.getMessage(), e);
// Ignore. This exception occurs under abnormal circumstances and not to determine
// whether the user is authorized. In case it does occur, we assume that the user
// is unauthorized.
}
});
return Response.status(Status.OK).entity(scopes).build(); })
.exceptionally(exception -> {
log.warn("listScopes failed with exception: ", exception);
return Response.status(Status.INTERNAL_SERVER_ERROR).build(); })
.thenApply(response -> {
asyncResponse.resume(response);
LoggerHelpers.traceLeave(log, "listScopes", traceId);
return response;
});
}
|
[
"@",
"Override",
"public",
"void",
"listScopes",
"(",
"final",
"SecurityContext",
"securityContext",
",",
"final",
"AsyncResponse",
"asyncResponse",
")",
"{",
"long",
"traceId",
"=",
"LoggerHelpers",
".",
"traceEnter",
"(",
"log",
",",
"\"listScopes\"",
")",
";",
"final",
"Principal",
"principal",
";",
"final",
"List",
"<",
"String",
">",
"authHeader",
"=",
"getAuthorizationHeader",
"(",
")",
";",
"try",
"{",
"principal",
"=",
"restAuthHelper",
".",
"authenticate",
"(",
"authHeader",
")",
";",
"restAuthHelper",
".",
"authorize",
"(",
"authHeader",
",",
"AuthResourceRepresentation",
".",
"ofScopes",
"(",
")",
",",
"principal",
",",
"READ",
")",
";",
"}",
"catch",
"(",
"AuthException",
"e",
")",
"{",
"log",
".",
"warn",
"(",
"\"Get scopes failed due to authentication failure.\"",
",",
"e",
")",
";",
"asyncResponse",
".",
"resume",
"(",
"Response",
".",
"status",
"(",
"Status",
".",
"fromStatusCode",
"(",
"e",
".",
"getResponseCode",
"(",
")",
")",
")",
".",
"build",
"(",
")",
")",
";",
"LoggerHelpers",
".",
"traceLeave",
"(",
"log",
",",
"\"listScopes\"",
",",
"traceId",
")",
";",
"return",
";",
"}",
"controllerService",
".",
"listScopes",
"(",
")",
".",
"thenApply",
"(",
"scopesList",
"->",
"{",
"ScopesList",
"scopes",
"=",
"new",
"ScopesList",
"(",
")",
";",
"scopesList",
".",
"forEach",
"(",
"scope",
"->",
"{",
"try",
"{",
"if",
"(",
"restAuthHelper",
".",
"isAuthorized",
"(",
"authHeader",
",",
"AuthResourceRepresentation",
".",
"ofScope",
"(",
"scope",
")",
",",
"principal",
",",
"READ",
")",
")",
"{",
"scopes",
".",
"addScopesItem",
"(",
"new",
"ScopeProperty",
"(",
")",
".",
"scopeName",
"(",
"scope",
")",
")",
";",
"}",
"}",
"catch",
"(",
"AuthException",
"e",
")",
"{",
"log",
".",
"warn",
"(",
"e",
".",
"getMessage",
"(",
")",
",",
"e",
")",
";",
"// Ignore. This exception occurs under abnormal circumstances and not to determine",
"// whether the user is authorized. In case it does occur, we assume that the user",
"// is unauthorized.",
"}",
"}",
")",
";",
"return",
"Response",
".",
"status",
"(",
"Status",
".",
"OK",
")",
".",
"entity",
"(",
"scopes",
")",
".",
"build",
"(",
")",
";",
"}",
")",
".",
"exceptionally",
"(",
"exception",
"->",
"{",
"log",
".",
"warn",
"(",
"\"listScopes failed with exception: \"",
",",
"exception",
")",
";",
"return",
"Response",
".",
"status",
"(",
"Status",
".",
"INTERNAL_SERVER_ERROR",
")",
".",
"build",
"(",
")",
";",
"}",
")",
".",
"thenApply",
"(",
"response",
"->",
"{",
"asyncResponse",
".",
"resume",
"(",
"response",
")",
";",
"LoggerHelpers",
".",
"traceLeave",
"(",
"log",
",",
"\"listScopes\"",
",",
"traceId",
")",
";",
"return",
"response",
";",
"}",
")",
";",
"}"
] |
Implementation of listScopes REST API.
@param securityContext The security for API access.
@param asyncResponse AsyncResponse provides means for asynchronous server side response processing.
|
[
"Implementation",
"of",
"listScopes",
"REST",
"API",
"."
] |
train
|
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/controller/src/main/java/io/pravega/controller/server/rest/resources/StreamMetadataResourceImpl.java#L466-L509
|
overturetool/overture
|
ide/debug/src/main/java/org/overture/ide/debug/ui/propertypages/VdmBreakpointPropertyPage.java
|
VdmBreakpointPropertyPage.createCheckButton
|
protected Button createCheckButton(Composite parent, String text)
{
return SWTFactory.createCheckButton(parent, text, null, false, 1);
}
|
java
|
protected Button createCheckButton(Composite parent, String text)
{
return SWTFactory.createCheckButton(parent, text, null, false, 1);
}
|
[
"protected",
"Button",
"createCheckButton",
"(",
"Composite",
"parent",
",",
"String",
"text",
")",
"{",
"return",
"SWTFactory",
".",
"createCheckButton",
"(",
"parent",
",",
"text",
",",
"null",
",",
"false",
",",
"1",
")",
";",
"}"
] |
Creates a fully configured check button with the given text.
@param parent
the parent composite
@param text
the label of the returned check button
@return a fully configured check button
|
[
"Creates",
"a",
"fully",
"configured",
"check",
"button",
"with",
"the",
"given",
"text",
"."
] |
train
|
https://github.com/overturetool/overture/blob/83175dc6c24fa171cde4fcf61ecb648eba3bdbc1/ide/debug/src/main/java/org/overture/ide/debug/ui/propertypages/VdmBreakpointPropertyPage.java#L504-L507
|
alkacon/opencms-core
|
src/org/opencms/db/CmsDriverManager.java
|
CmsDriverManager.setSubscribedResourceAsDeleted
|
public void setSubscribedResourceAsDeleted(CmsDbContext dbc, String poolName, CmsResource resource)
throws CmsException {
getSubscriptionDriver().setSubscribedResourceAsDeleted(dbc, poolName, resource);
}
|
java
|
public void setSubscribedResourceAsDeleted(CmsDbContext dbc, String poolName, CmsResource resource)
throws CmsException {
getSubscriptionDriver().setSubscribedResourceAsDeleted(dbc, poolName, resource);
}
|
[
"public",
"void",
"setSubscribedResourceAsDeleted",
"(",
"CmsDbContext",
"dbc",
",",
"String",
"poolName",
",",
"CmsResource",
"resource",
")",
"throws",
"CmsException",
"{",
"getSubscriptionDriver",
"(",
")",
".",
"setSubscribedResourceAsDeleted",
"(",
"dbc",
",",
"poolName",
",",
"resource",
")",
";",
"}"
] |
Marks a subscribed resource as deleted.<p>
@param dbc the database context
@param poolName the name of the database pool to use
@param resource the subscribed resource to mark as deleted
@throws CmsException if something goes wrong
|
[
"Marks",
"a",
"subscribed",
"resource",
"as",
"deleted",
".",
"<p",
">"
] |
train
|
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsDriverManager.java#L9021-L9025
|
Azure/azure-sdk-for-java
|
sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/RecommendedElasticPoolsInner.java
|
RecommendedElasticPoolsInner.listMetricsAsync
|
public Observable<List<RecommendedElasticPoolMetricInner>> listMetricsAsync(String resourceGroupName, String serverName, String recommendedElasticPoolName) {
return listMetricsWithServiceResponseAsync(resourceGroupName, serverName, recommendedElasticPoolName).map(new Func1<ServiceResponse<List<RecommendedElasticPoolMetricInner>>, List<RecommendedElasticPoolMetricInner>>() {
@Override
public List<RecommendedElasticPoolMetricInner> call(ServiceResponse<List<RecommendedElasticPoolMetricInner>> response) {
return response.body();
}
});
}
|
java
|
public Observable<List<RecommendedElasticPoolMetricInner>> listMetricsAsync(String resourceGroupName, String serverName, String recommendedElasticPoolName) {
return listMetricsWithServiceResponseAsync(resourceGroupName, serverName, recommendedElasticPoolName).map(new Func1<ServiceResponse<List<RecommendedElasticPoolMetricInner>>, List<RecommendedElasticPoolMetricInner>>() {
@Override
public List<RecommendedElasticPoolMetricInner> call(ServiceResponse<List<RecommendedElasticPoolMetricInner>> response) {
return response.body();
}
});
}
|
[
"public",
"Observable",
"<",
"List",
"<",
"RecommendedElasticPoolMetricInner",
">",
">",
"listMetricsAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"serverName",
",",
"String",
"recommendedElasticPoolName",
")",
"{",
"return",
"listMetricsWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"serverName",
",",
"recommendedElasticPoolName",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"List",
"<",
"RecommendedElasticPoolMetricInner",
">",
">",
",",
"List",
"<",
"RecommendedElasticPoolMetricInner",
">",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"List",
"<",
"RecommendedElasticPoolMetricInner",
">",
"call",
"(",
"ServiceResponse",
"<",
"List",
"<",
"RecommendedElasticPoolMetricInner",
">",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Returns recommented elastic pool metrics.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@param recommendedElasticPoolName The name of the recommended elastic pool to be retrieved.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the List<RecommendedElasticPoolMetricInner> object
|
[
"Returns",
"recommented",
"elastic",
"pool",
"metrics",
"."
] |
train
|
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/RecommendedElasticPoolsInner.java#L291-L298
|
casbin/jcasbin
|
src/main/java/org/casbin/jcasbin/util/BuiltInFunctions.java
|
BuiltInFunctions.ipMatch
|
public static boolean ipMatch(String ip1, String ip2) {
IPAddressString ipas1 = new IPAddressString(ip1);
try {
ipas1.validateIPv4();
} catch (AddressStringException e) {
e.printStackTrace();
throw new Error("invalid argument: ip1 in IPMatch() function is not an IP address.");
}
IPAddressString ipas2 = new IPAddressString(ip2);
try {
ipas2.validate();
} catch (AddressStringException e) {
e.printStackTrace();
throw new Error("invalid argument: ip2 in IPMatch() function is neither an IP address nor a CIDR.");
}
if (ipas1.equals(ipas2)) {
return true;
}
IPAddress ipa1;
IPAddress ipa2;
try {
ipa1 = ipas1.toAddress();
ipa2 = ipas2.toAddress();
} catch (AddressStringException e) {
e.printStackTrace();
throw new Error("invalid argument: ip1 or ip2 in IPMatch() function is not an IP address.");
}
Integer prefix = ipa2.getNetworkPrefixLength();
IPAddress mask = ipa2.getNetwork().getNetworkMask(prefix, false);
return ipa1.mask(mask).equals(ipas2.getHostAddress());
}
|
java
|
public static boolean ipMatch(String ip1, String ip2) {
IPAddressString ipas1 = new IPAddressString(ip1);
try {
ipas1.validateIPv4();
} catch (AddressStringException e) {
e.printStackTrace();
throw new Error("invalid argument: ip1 in IPMatch() function is not an IP address.");
}
IPAddressString ipas2 = new IPAddressString(ip2);
try {
ipas2.validate();
} catch (AddressStringException e) {
e.printStackTrace();
throw new Error("invalid argument: ip2 in IPMatch() function is neither an IP address nor a CIDR.");
}
if (ipas1.equals(ipas2)) {
return true;
}
IPAddress ipa1;
IPAddress ipa2;
try {
ipa1 = ipas1.toAddress();
ipa2 = ipas2.toAddress();
} catch (AddressStringException e) {
e.printStackTrace();
throw new Error("invalid argument: ip1 or ip2 in IPMatch() function is not an IP address.");
}
Integer prefix = ipa2.getNetworkPrefixLength();
IPAddress mask = ipa2.getNetwork().getNetworkMask(prefix, false);
return ipa1.mask(mask).equals(ipas2.getHostAddress());
}
|
[
"public",
"static",
"boolean",
"ipMatch",
"(",
"String",
"ip1",
",",
"String",
"ip2",
")",
"{",
"IPAddressString",
"ipas1",
"=",
"new",
"IPAddressString",
"(",
"ip1",
")",
";",
"try",
"{",
"ipas1",
".",
"validateIPv4",
"(",
")",
";",
"}",
"catch",
"(",
"AddressStringException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"throw",
"new",
"Error",
"(",
"\"invalid argument: ip1 in IPMatch() function is not an IP address.\"",
")",
";",
"}",
"IPAddressString",
"ipas2",
"=",
"new",
"IPAddressString",
"(",
"ip2",
")",
";",
"try",
"{",
"ipas2",
".",
"validate",
"(",
")",
";",
"}",
"catch",
"(",
"AddressStringException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"throw",
"new",
"Error",
"(",
"\"invalid argument: ip2 in IPMatch() function is neither an IP address nor a CIDR.\"",
")",
";",
"}",
"if",
"(",
"ipas1",
".",
"equals",
"(",
"ipas2",
")",
")",
"{",
"return",
"true",
";",
"}",
"IPAddress",
"ipa1",
";",
"IPAddress",
"ipa2",
";",
"try",
"{",
"ipa1",
"=",
"ipas1",
".",
"toAddress",
"(",
")",
";",
"ipa2",
"=",
"ipas2",
".",
"toAddress",
"(",
")",
";",
"}",
"catch",
"(",
"AddressStringException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"throw",
"new",
"Error",
"(",
"\"invalid argument: ip1 or ip2 in IPMatch() function is not an IP address.\"",
")",
";",
"}",
"Integer",
"prefix",
"=",
"ipa2",
".",
"getNetworkPrefixLength",
"(",
")",
";",
"IPAddress",
"mask",
"=",
"ipa2",
".",
"getNetwork",
"(",
")",
".",
"getNetworkMask",
"(",
"prefix",
",",
"false",
")",
";",
"return",
"ipa1",
".",
"mask",
"(",
"mask",
")",
".",
"equals",
"(",
"ipas2",
".",
"getHostAddress",
"(",
")",
")",
";",
"}"
] |
ipMatch determines whether IP address ip1 matches the pattern of IP address ip2, ip2 can be an IP address or a CIDR pattern.
For example, "192.168.2.123" matches "192.168.2.0/24"
@param ip1 the first argument.
@param ip2 the second argument.
@return whether ip1 matches ip2.
|
[
"ipMatch",
"determines",
"whether",
"IP",
"address",
"ip1",
"matches",
"the",
"pattern",
"of",
"IP",
"address",
"ip2",
"ip2",
"can",
"be",
"an",
"IP",
"address",
"or",
"a",
"CIDR",
"pattern",
".",
"For",
"example",
"192",
".",
"168",
".",
"2",
".",
"123",
"matches",
"192",
".",
"168",
".",
"2",
".",
"0",
"/",
"24"
] |
train
|
https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/util/BuiltInFunctions.java#L116-L150
|
ktoso/janbanery
|
janbanery-core/src/main/java/pl/project13/janbanery/core/rest/AsyncHttpClientRestClient.java
|
AsyncHttpClientRestClient.doGet
|
@Override
@SuppressWarnings("unchecked")
public <T> T doGet(String url, Type returnType) throws ServerCommunicationException {
RestClientResponse response = doGet(url);
String responseBody = response.getResponseBody();
return (T) gson.fromJson(responseBody, returnType);
}
|
java
|
@Override
@SuppressWarnings("unchecked")
public <T> T doGet(String url, Type returnType) throws ServerCommunicationException {
RestClientResponse response = doGet(url);
String responseBody = response.getResponseBody();
return (T) gson.fromJson(responseBody, returnType);
}
|
[
"@",
"Override",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"<",
"T",
">",
"T",
"doGet",
"(",
"String",
"url",
",",
"Type",
"returnType",
")",
"throws",
"ServerCommunicationException",
"{",
"RestClientResponse",
"response",
"=",
"doGet",
"(",
"url",
")",
";",
"String",
"responseBody",
"=",
"response",
".",
"getResponseBody",
"(",
")",
";",
"return",
"(",
"T",
")",
"gson",
".",
"fromJson",
"(",
"responseBody",
",",
"returnType",
")",
";",
"}"
] |
Delegate to {@link AsyncHttpClientRestClient#doGet(String)} and also use {@link Gson} to parse the returned json
into the requested object
@param url url to call
@param returnType taskType to parse the returned json into
@param <T> the return taskType, should match returnType
@return the KanbaneryResource created by parsing the retrieved json
@throws ServerCommunicationException if the response body could not be fetched
|
[
"Delegate",
"to",
"{",
"@link",
"AsyncHttpClientRestClient#doGet",
"(",
"String",
")",
"}",
"and",
"also",
"use",
"{",
"@link",
"Gson",
"}",
"to",
"parse",
"the",
"returned",
"json",
"into",
"the",
"requested",
"object"
] |
train
|
https://github.com/ktoso/janbanery/blob/cd77b774814c7fbb2a0c9c55d4c3f7e76affa636/janbanery-core/src/main/java/pl/project13/janbanery/core/rest/AsyncHttpClientRestClient.java#L134-L141
|
lessthanoptimal/BoofCV
|
main/boofcv-geo/src/main/java/boofcv/alg/geo/PerspectiveOps.java
|
PerspectiveOps.createIntrinsic
|
public static CameraPinholeBrown createIntrinsic(int width, int height, double hfov) {
CameraPinholeBrown intrinsic = new CameraPinholeBrown();
intrinsic.width = width;
intrinsic.height = height;
intrinsic.cx = width / 2;
intrinsic.cy = height / 2;
intrinsic.fx = intrinsic.cx / Math.tan(UtilAngle.degreeToRadian(hfov/2.0));
intrinsic.fy = intrinsic.fx;
return intrinsic;
}
|
java
|
public static CameraPinholeBrown createIntrinsic(int width, int height, double hfov) {
CameraPinholeBrown intrinsic = new CameraPinholeBrown();
intrinsic.width = width;
intrinsic.height = height;
intrinsic.cx = width / 2;
intrinsic.cy = height / 2;
intrinsic.fx = intrinsic.cx / Math.tan(UtilAngle.degreeToRadian(hfov/2.0));
intrinsic.fy = intrinsic.fx;
return intrinsic;
}
|
[
"public",
"static",
"CameraPinholeBrown",
"createIntrinsic",
"(",
"int",
"width",
",",
"int",
"height",
",",
"double",
"hfov",
")",
"{",
"CameraPinholeBrown",
"intrinsic",
"=",
"new",
"CameraPinholeBrown",
"(",
")",
";",
"intrinsic",
".",
"width",
"=",
"width",
";",
"intrinsic",
".",
"height",
"=",
"height",
";",
"intrinsic",
".",
"cx",
"=",
"width",
"/",
"2",
";",
"intrinsic",
".",
"cy",
"=",
"height",
"/",
"2",
";",
"intrinsic",
".",
"fx",
"=",
"intrinsic",
".",
"cx",
"/",
"Math",
".",
"tan",
"(",
"UtilAngle",
".",
"degreeToRadian",
"(",
"hfov",
"/",
"2.0",
")",
")",
";",
"intrinsic",
".",
"fy",
"=",
"intrinsic",
".",
"fx",
";",
"return",
"intrinsic",
";",
"}"
] |
Creates a set of intrinsic parameters, without distortion, for a camera with the specified characteristics.
The focal length is assumed to be the same for x and y.
@param width Image width
@param height Image height
@param hfov Horizontal FOV in degrees
@return guess camera parameters
|
[
"Creates",
"a",
"set",
"of",
"intrinsic",
"parameters",
"without",
"distortion",
"for",
"a",
"camera",
"with",
"the",
"specified",
"characteristics",
".",
"The",
"focal",
"length",
"is",
"assumed",
"to",
"be",
"the",
"same",
"for",
"x",
"and",
"y",
"."
] |
train
|
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/PerspectiveOps.java#L118-L128
|
roboconf/roboconf-platform
|
core/roboconf-dm-rest-services/src/main/java/net/roboconf/dm/rest/services/internal/resources/impl/DebugResource.java
|
DebugResource.createDiagnostic
|
Diagnostic createDiagnostic( Instance instance ) {
Diagnostic result = new Diagnostic( InstanceHelpers.computeInstancePath( instance ));
for( Map.Entry<String,Boolean> entry : ComponentHelpers.findComponentDependenciesFor( instance.getComponent()).entrySet()) {
String facetOrComponentName = entry.getKey();
Collection<Import> imports = instance.getImports().get( facetOrComponentName );
boolean resolved = imports != null && ! imports.isEmpty();
boolean optional = entry.getValue();
result.getDependenciesInformation().add( new DependencyInformation( facetOrComponentName, optional, resolved ));
}
return result;
}
|
java
|
Diagnostic createDiagnostic( Instance instance ) {
Diagnostic result = new Diagnostic( InstanceHelpers.computeInstancePath( instance ));
for( Map.Entry<String,Boolean> entry : ComponentHelpers.findComponentDependenciesFor( instance.getComponent()).entrySet()) {
String facetOrComponentName = entry.getKey();
Collection<Import> imports = instance.getImports().get( facetOrComponentName );
boolean resolved = imports != null && ! imports.isEmpty();
boolean optional = entry.getValue();
result.getDependenciesInformation().add( new DependencyInformation( facetOrComponentName, optional, resolved ));
}
return result;
}
|
[
"Diagnostic",
"createDiagnostic",
"(",
"Instance",
"instance",
")",
"{",
"Diagnostic",
"result",
"=",
"new",
"Diagnostic",
"(",
"InstanceHelpers",
".",
"computeInstancePath",
"(",
"instance",
")",
")",
";",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"Boolean",
">",
"entry",
":",
"ComponentHelpers",
".",
"findComponentDependenciesFor",
"(",
"instance",
".",
"getComponent",
"(",
")",
")",
".",
"entrySet",
"(",
")",
")",
"{",
"String",
"facetOrComponentName",
"=",
"entry",
".",
"getKey",
"(",
")",
";",
"Collection",
"<",
"Import",
">",
"imports",
"=",
"instance",
".",
"getImports",
"(",
")",
".",
"get",
"(",
"facetOrComponentName",
")",
";",
"boolean",
"resolved",
"=",
"imports",
"!=",
"null",
"&&",
"!",
"imports",
".",
"isEmpty",
"(",
")",
";",
"boolean",
"optional",
"=",
"entry",
".",
"getValue",
"(",
")",
";",
"result",
".",
"getDependenciesInformation",
"(",
")",
".",
"add",
"(",
"new",
"DependencyInformation",
"(",
"facetOrComponentName",
",",
"optional",
",",
"resolved",
")",
")",
";",
"}",
"return",
"result",
";",
"}"
] |
Creates a diagnostic for an instance.
@param instance a non-null instance
@return a non-null diagnostic
|
[
"Creates",
"a",
"diagnostic",
"for",
"an",
"instance",
"."
] |
train
|
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-dm-rest-services/src/main/java/net/roboconf/dm/rest/services/internal/resources/impl/DebugResource.java#L184-L198
|
Carbonado/Carbonado
|
src/main/java/com/amazon/carbonado/raw/DataDecoder.java
|
DataDecoder.decodeSingleNullable
|
public static byte[] decodeSingleNullable(byte[] src, int prefixPadding, int suffixPadding)
throws CorruptEncodingException
{
try {
byte b = src[prefixPadding];
if (b == NULL_BYTE_HIGH || b == NULL_BYTE_LOW) {
return null;
}
int length = src.length - suffixPadding - 1 - prefixPadding;
if (length == 0) {
return EMPTY_BYTE_ARRAY;
}
byte[] value = new byte[length];
System.arraycopy(src, 1 + prefixPadding, value, 0, length);
return value;
} catch (IndexOutOfBoundsException e) {
throw new CorruptEncodingException(null, e);
}
}
|
java
|
public static byte[] decodeSingleNullable(byte[] src, int prefixPadding, int suffixPadding)
throws CorruptEncodingException
{
try {
byte b = src[prefixPadding];
if (b == NULL_BYTE_HIGH || b == NULL_BYTE_LOW) {
return null;
}
int length = src.length - suffixPadding - 1 - prefixPadding;
if (length == 0) {
return EMPTY_BYTE_ARRAY;
}
byte[] value = new byte[length];
System.arraycopy(src, 1 + prefixPadding, value, 0, length);
return value;
} catch (IndexOutOfBoundsException e) {
throw new CorruptEncodingException(null, e);
}
}
|
[
"public",
"static",
"byte",
"[",
"]",
"decodeSingleNullable",
"(",
"byte",
"[",
"]",
"src",
",",
"int",
"prefixPadding",
",",
"int",
"suffixPadding",
")",
"throws",
"CorruptEncodingException",
"{",
"try",
"{",
"byte",
"b",
"=",
"src",
"[",
"prefixPadding",
"]",
";",
"if",
"(",
"b",
"==",
"NULL_BYTE_HIGH",
"||",
"b",
"==",
"NULL_BYTE_LOW",
")",
"{",
"return",
"null",
";",
"}",
"int",
"length",
"=",
"src",
".",
"length",
"-",
"suffixPadding",
"-",
"1",
"-",
"prefixPadding",
";",
"if",
"(",
"length",
"==",
"0",
")",
"{",
"return",
"EMPTY_BYTE_ARRAY",
";",
"}",
"byte",
"[",
"]",
"value",
"=",
"new",
"byte",
"[",
"length",
"]",
";",
"System",
".",
"arraycopy",
"(",
"src",
",",
"1",
"+",
"prefixPadding",
",",
"value",
",",
"0",
",",
"length",
")",
";",
"return",
"value",
";",
"}",
"catch",
"(",
"IndexOutOfBoundsException",
"e",
")",
"{",
"throw",
"new",
"CorruptEncodingException",
"(",
"null",
",",
"e",
")",
";",
"}",
"}"
] |
Decodes the given byte array which was encoded by {@link
DataEncoder#encodeSingleNullable}. Always returns a new byte array
instance.
@param prefixPadding amount of extra bytes to skip from start of encoded byte array
@param suffixPadding amount of extra bytes to skip at end of encoded byte array
|
[
"Decodes",
"the",
"given",
"byte",
"array",
"which",
"was",
"encoded",
"by",
"{",
"@link",
"DataEncoder#encodeSingleNullable",
"}",
".",
"Always",
"returns",
"a",
"new",
"byte",
"array",
"instance",
"."
] |
train
|
https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/raw/DataDecoder.java#L703-L721
|
Whiley/WhileyCompiler
|
src/main/java/wyil/check/FlowTypeCheck.java
|
FlowTypeCheck.checkWhile
|
private Environment checkWhile(Stmt.While stmt, Environment environment, EnclosingScope scope) {
// Type loop invariant(s).
checkConditions(stmt.getInvariant(), true, environment);
// Type condition assuming its true to represent inside a loop
// iteration.
// Important if condition contains a type test, as we'll know it holds.
Environment trueEnvironment = checkCondition(stmt.getCondition(), true, environment);
// Type condition assuming its false to represent the terminated loop.
// Important if condition contains a type test, as we'll know it doesn't
// hold.
Environment falseEnvironment = checkCondition(stmt.getCondition(), false, environment);
// Type loop body using true environment
checkBlock(stmt.getBody(), trueEnvironment, scope);
// Determine and update modified variables
Tuple<Decl.Variable> modified = FlowTypeUtils.determineModifiedVariables(stmt.getBody());
stmt.setModified(stmt.getHeap().allocate(modified));
// Return false environment to represent flow after loop.
return falseEnvironment;
}
|
java
|
private Environment checkWhile(Stmt.While stmt, Environment environment, EnclosingScope scope) {
// Type loop invariant(s).
checkConditions(stmt.getInvariant(), true, environment);
// Type condition assuming its true to represent inside a loop
// iteration.
// Important if condition contains a type test, as we'll know it holds.
Environment trueEnvironment = checkCondition(stmt.getCondition(), true, environment);
// Type condition assuming its false to represent the terminated loop.
// Important if condition contains a type test, as we'll know it doesn't
// hold.
Environment falseEnvironment = checkCondition(stmt.getCondition(), false, environment);
// Type loop body using true environment
checkBlock(stmt.getBody(), trueEnvironment, scope);
// Determine and update modified variables
Tuple<Decl.Variable> modified = FlowTypeUtils.determineModifiedVariables(stmt.getBody());
stmt.setModified(stmt.getHeap().allocate(modified));
// Return false environment to represent flow after loop.
return falseEnvironment;
}
|
[
"private",
"Environment",
"checkWhile",
"(",
"Stmt",
".",
"While",
"stmt",
",",
"Environment",
"environment",
",",
"EnclosingScope",
"scope",
")",
"{",
"// Type loop invariant(s).",
"checkConditions",
"(",
"stmt",
".",
"getInvariant",
"(",
")",
",",
"true",
",",
"environment",
")",
";",
"// Type condition assuming its true to represent inside a loop",
"// iteration.",
"// Important if condition contains a type test, as we'll know it holds.",
"Environment",
"trueEnvironment",
"=",
"checkCondition",
"(",
"stmt",
".",
"getCondition",
"(",
")",
",",
"true",
",",
"environment",
")",
";",
"// Type condition assuming its false to represent the terminated loop.",
"// Important if condition contains a type test, as we'll know it doesn't",
"// hold.",
"Environment",
"falseEnvironment",
"=",
"checkCondition",
"(",
"stmt",
".",
"getCondition",
"(",
")",
",",
"false",
",",
"environment",
")",
";",
"// Type loop body using true environment",
"checkBlock",
"(",
"stmt",
".",
"getBody",
"(",
")",
",",
"trueEnvironment",
",",
"scope",
")",
";",
"// Determine and update modified variables",
"Tuple",
"<",
"Decl",
".",
"Variable",
">",
"modified",
"=",
"FlowTypeUtils",
".",
"determineModifiedVariables",
"(",
"stmt",
".",
"getBody",
"(",
")",
")",
";",
"stmt",
".",
"setModified",
"(",
"stmt",
".",
"getHeap",
"(",
")",
".",
"allocate",
"(",
"modified",
")",
")",
";",
"// Return false environment to represent flow after loop.",
"return",
"falseEnvironment",
";",
"}"
] |
Type check a <code>whiley</code> statement.
@param stmt
Statement to type check
@param environment
Determines the type of all variables immediately going into this
block
@return
@throws ResolveError
If a named type within this statement cannot be resolved within
the enclosing project.
|
[
"Type",
"check",
"a",
"<code",
">",
"whiley<",
"/",
"code",
">",
"statement",
"."
] |
train
|
https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyil/check/FlowTypeCheck.java#L757-L775
|
docusign/docusign-java-client
|
src/main/java/com/docusign/esign/api/WorkspacesApi.java
|
WorkspacesApi.listWorkspaceFilePages
|
public PageImages listWorkspaceFilePages(String accountId, String workspaceId, String folderId, String fileId, WorkspacesApi.ListWorkspaceFilePagesOptions options) throws ApiException {
Object localVarPostBody = "{}";
// verify the required parameter 'accountId' is set
if (accountId == null) {
throw new ApiException(400, "Missing the required parameter 'accountId' when calling listWorkspaceFilePages");
}
// verify the required parameter 'workspaceId' is set
if (workspaceId == null) {
throw new ApiException(400, "Missing the required parameter 'workspaceId' when calling listWorkspaceFilePages");
}
// verify the required parameter 'folderId' is set
if (folderId == null) {
throw new ApiException(400, "Missing the required parameter 'folderId' when calling listWorkspaceFilePages");
}
// verify the required parameter 'fileId' is set
if (fileId == null) {
throw new ApiException(400, "Missing the required parameter 'fileId' when calling listWorkspaceFilePages");
}
// create path and map variables
String localVarPath = "/v2/accounts/{accountId}/workspaces/{workspaceId}/folders/{folderId}/files/{fileId}/pages".replaceAll("\\{format\\}","json")
.replaceAll("\\{" + "accountId" + "\\}", apiClient.escapeString(accountId.toString()))
.replaceAll("\\{" + "workspaceId" + "\\}", apiClient.escapeString(workspaceId.toString()))
.replaceAll("\\{" + "folderId" + "\\}", apiClient.escapeString(folderId.toString()))
.replaceAll("\\{" + "fileId" + "\\}", apiClient.escapeString(fileId.toString()));
// query params
java.util.List<Pair> localVarQueryParams = new java.util.ArrayList<Pair>();
java.util.Map<String, String> localVarHeaderParams = new java.util.HashMap<String, String>();
java.util.Map<String, Object> localVarFormParams = new java.util.HashMap<String, Object>();
if (options != null) {
localVarQueryParams.addAll(apiClient.parameterToPairs("", "count", options.count));
localVarQueryParams.addAll(apiClient.parameterToPairs("", "dpi", options.dpi));
localVarQueryParams.addAll(apiClient.parameterToPairs("", "max_height", options.maxHeight));
localVarQueryParams.addAll(apiClient.parameterToPairs("", "max_width", options.maxWidth));
localVarQueryParams.addAll(apiClient.parameterToPairs("", "start_position", options.startPosition));
}
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
final String[] localVarContentTypes = {
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
String[] localVarAuthNames = new String[] { "docusignAccessCode" }; //{ };
GenericType<PageImages> localVarReturnType = new GenericType<PageImages>() {};
return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);
}
|
java
|
public PageImages listWorkspaceFilePages(String accountId, String workspaceId, String folderId, String fileId, WorkspacesApi.ListWorkspaceFilePagesOptions options) throws ApiException {
Object localVarPostBody = "{}";
// verify the required parameter 'accountId' is set
if (accountId == null) {
throw new ApiException(400, "Missing the required parameter 'accountId' when calling listWorkspaceFilePages");
}
// verify the required parameter 'workspaceId' is set
if (workspaceId == null) {
throw new ApiException(400, "Missing the required parameter 'workspaceId' when calling listWorkspaceFilePages");
}
// verify the required parameter 'folderId' is set
if (folderId == null) {
throw new ApiException(400, "Missing the required parameter 'folderId' when calling listWorkspaceFilePages");
}
// verify the required parameter 'fileId' is set
if (fileId == null) {
throw new ApiException(400, "Missing the required parameter 'fileId' when calling listWorkspaceFilePages");
}
// create path and map variables
String localVarPath = "/v2/accounts/{accountId}/workspaces/{workspaceId}/folders/{folderId}/files/{fileId}/pages".replaceAll("\\{format\\}","json")
.replaceAll("\\{" + "accountId" + "\\}", apiClient.escapeString(accountId.toString()))
.replaceAll("\\{" + "workspaceId" + "\\}", apiClient.escapeString(workspaceId.toString()))
.replaceAll("\\{" + "folderId" + "\\}", apiClient.escapeString(folderId.toString()))
.replaceAll("\\{" + "fileId" + "\\}", apiClient.escapeString(fileId.toString()));
// query params
java.util.List<Pair> localVarQueryParams = new java.util.ArrayList<Pair>();
java.util.Map<String, String> localVarHeaderParams = new java.util.HashMap<String, String>();
java.util.Map<String, Object> localVarFormParams = new java.util.HashMap<String, Object>();
if (options != null) {
localVarQueryParams.addAll(apiClient.parameterToPairs("", "count", options.count));
localVarQueryParams.addAll(apiClient.parameterToPairs("", "dpi", options.dpi));
localVarQueryParams.addAll(apiClient.parameterToPairs("", "max_height", options.maxHeight));
localVarQueryParams.addAll(apiClient.parameterToPairs("", "max_width", options.maxWidth));
localVarQueryParams.addAll(apiClient.parameterToPairs("", "start_position", options.startPosition));
}
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
final String[] localVarContentTypes = {
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
String[] localVarAuthNames = new String[] { "docusignAccessCode" }; //{ };
GenericType<PageImages> localVarReturnType = new GenericType<PageImages>() {};
return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);
}
|
[
"public",
"PageImages",
"listWorkspaceFilePages",
"(",
"String",
"accountId",
",",
"String",
"workspaceId",
",",
"String",
"folderId",
",",
"String",
"fileId",
",",
"WorkspacesApi",
".",
"ListWorkspaceFilePagesOptions",
"options",
")",
"throws",
"ApiException",
"{",
"Object",
"localVarPostBody",
"=",
"\"{}\"",
";",
"// verify the required parameter 'accountId' is set",
"if",
"(",
"accountId",
"==",
"null",
")",
"{",
"throw",
"new",
"ApiException",
"(",
"400",
",",
"\"Missing the required parameter 'accountId' when calling listWorkspaceFilePages\"",
")",
";",
"}",
"// verify the required parameter 'workspaceId' is set",
"if",
"(",
"workspaceId",
"==",
"null",
")",
"{",
"throw",
"new",
"ApiException",
"(",
"400",
",",
"\"Missing the required parameter 'workspaceId' when calling listWorkspaceFilePages\"",
")",
";",
"}",
"// verify the required parameter 'folderId' is set",
"if",
"(",
"folderId",
"==",
"null",
")",
"{",
"throw",
"new",
"ApiException",
"(",
"400",
",",
"\"Missing the required parameter 'folderId' when calling listWorkspaceFilePages\"",
")",
";",
"}",
"// verify the required parameter 'fileId' is set",
"if",
"(",
"fileId",
"==",
"null",
")",
"{",
"throw",
"new",
"ApiException",
"(",
"400",
",",
"\"Missing the required parameter 'fileId' when calling listWorkspaceFilePages\"",
")",
";",
"}",
"// create path and map variables",
"String",
"localVarPath",
"=",
"\"/v2/accounts/{accountId}/workspaces/{workspaceId}/folders/{folderId}/files/{fileId}/pages\"",
".",
"replaceAll",
"(",
"\"\\\\{format\\\\}\"",
",",
"\"json\"",
")",
".",
"replaceAll",
"(",
"\"\\\\{\"",
"+",
"\"accountId\"",
"+",
"\"\\\\}\"",
",",
"apiClient",
".",
"escapeString",
"(",
"accountId",
".",
"toString",
"(",
")",
")",
")",
".",
"replaceAll",
"(",
"\"\\\\{\"",
"+",
"\"workspaceId\"",
"+",
"\"\\\\}\"",
",",
"apiClient",
".",
"escapeString",
"(",
"workspaceId",
".",
"toString",
"(",
")",
")",
")",
".",
"replaceAll",
"(",
"\"\\\\{\"",
"+",
"\"folderId\"",
"+",
"\"\\\\}\"",
",",
"apiClient",
".",
"escapeString",
"(",
"folderId",
".",
"toString",
"(",
")",
")",
")",
".",
"replaceAll",
"(",
"\"\\\\{\"",
"+",
"\"fileId\"",
"+",
"\"\\\\}\"",
",",
"apiClient",
".",
"escapeString",
"(",
"fileId",
".",
"toString",
"(",
")",
")",
")",
";",
"// query params",
"java",
".",
"util",
".",
"List",
"<",
"Pair",
">",
"localVarQueryParams",
"=",
"new",
"java",
".",
"util",
".",
"ArrayList",
"<",
"Pair",
">",
"(",
")",
";",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"localVarHeaderParams",
"=",
"new",
"java",
".",
"util",
".",
"HashMap",
"<",
"String",
",",
"String",
">",
"(",
")",
";",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"Object",
">",
"localVarFormParams",
"=",
"new",
"java",
".",
"util",
".",
"HashMap",
"<",
"String",
",",
"Object",
">",
"(",
")",
";",
"if",
"(",
"options",
"!=",
"null",
")",
"{",
"localVarQueryParams",
".",
"addAll",
"(",
"apiClient",
".",
"parameterToPairs",
"(",
"\"\"",
",",
"\"count\"",
",",
"options",
".",
"count",
")",
")",
";",
"localVarQueryParams",
".",
"addAll",
"(",
"apiClient",
".",
"parameterToPairs",
"(",
"\"\"",
",",
"\"dpi\"",
",",
"options",
".",
"dpi",
")",
")",
";",
"localVarQueryParams",
".",
"addAll",
"(",
"apiClient",
".",
"parameterToPairs",
"(",
"\"\"",
",",
"\"max_height\"",
",",
"options",
".",
"maxHeight",
")",
")",
";",
"localVarQueryParams",
".",
"addAll",
"(",
"apiClient",
".",
"parameterToPairs",
"(",
"\"\"",
",",
"\"max_width\"",
",",
"options",
".",
"maxWidth",
")",
")",
";",
"localVarQueryParams",
".",
"addAll",
"(",
"apiClient",
".",
"parameterToPairs",
"(",
"\"\"",
",",
"\"start_position\"",
",",
"options",
".",
"startPosition",
")",
")",
";",
"}",
"final",
"String",
"[",
"]",
"localVarAccepts",
"=",
"{",
"\"application/json\"",
"}",
";",
"final",
"String",
"localVarAccept",
"=",
"apiClient",
".",
"selectHeaderAccept",
"(",
"localVarAccepts",
")",
";",
"final",
"String",
"[",
"]",
"localVarContentTypes",
"=",
"{",
"}",
";",
"final",
"String",
"localVarContentType",
"=",
"apiClient",
".",
"selectHeaderContentType",
"(",
"localVarContentTypes",
")",
";",
"String",
"[",
"]",
"localVarAuthNames",
"=",
"new",
"String",
"[",
"]",
"{",
"\"docusignAccessCode\"",
"}",
";",
"//{ };",
"GenericType",
"<",
"PageImages",
">",
"localVarReturnType",
"=",
"new",
"GenericType",
"<",
"PageImages",
">",
"(",
")",
"{",
"}",
";",
"return",
"apiClient",
".",
"invokeAPI",
"(",
"localVarPath",
",",
"\"GET\"",
",",
"localVarQueryParams",
",",
"localVarPostBody",
",",
"localVarHeaderParams",
",",
"localVarFormParams",
",",
"localVarAccept",
",",
"localVarContentType",
",",
"localVarAuthNames",
",",
"localVarReturnType",
")",
";",
"}"
] |
List File Pages
Retrieves a workspace file as rasterized pages.
@param accountId The external account number (int) or account ID Guid. (required)
@param workspaceId Specifies the workspace ID GUID. (required)
@param folderId The ID of the folder being accessed. (required)
@param fileId Specifies the room file ID GUID. (required)
@param options for modifying the method behavior.
@return PageImages
@throws ApiException if fails to make API call
|
[
"List",
"File",
"Pages",
"Retrieves",
"a",
"workspace",
"file",
"as",
"rasterized",
"pages",
"."
] |
train
|
https://github.com/docusign/docusign-java-client/blob/17ae82ace0f023e98edf813be832950568212e34/src/main/java/com/docusign/esign/api/WorkspacesApi.java#L492-L550
|
medallia/Word2VecJava
|
src/main/java/com/medallia/word2vec/util/IO.java
|
IO.copyAndCloseBoth
|
public static int copyAndCloseBoth(Reader input, Writer output) throws IOException {
try {
return copyAndCloseOutput(input, output);
} finally {
input.close();
}
}
|
java
|
public static int copyAndCloseBoth(Reader input, Writer output) throws IOException {
try {
return copyAndCloseOutput(input, output);
} finally {
input.close();
}
}
|
[
"public",
"static",
"int",
"copyAndCloseBoth",
"(",
"Reader",
"input",
",",
"Writer",
"output",
")",
"throws",
"IOException",
"{",
"try",
"{",
"return",
"copyAndCloseOutput",
"(",
"input",
",",
"output",
")",
";",
"}",
"finally",
"{",
"input",
".",
"close",
"(",
")",
";",
"}",
"}"
] |
Copy input to output and close both the input and output streams before returning
|
[
"Copy",
"input",
"to",
"output",
"and",
"close",
"both",
"the",
"input",
"and",
"output",
"streams",
"before",
"returning"
] |
train
|
https://github.com/medallia/Word2VecJava/blob/eb31fbb99ac6bbab82d7f807b3e2240edca50eb7/src/main/java/com/medallia/word2vec/util/IO.java#L105-L111
|
finmath/finmath-lib
|
src/main/java/net/finmath/montecarlo/interestrate/products/CMSOption.java
|
CMSOption.getValue
|
@Override
public RandomVariable getValue(double evaluationTime, LIBORModelMonteCarloSimulationModel model) throws CalculationException {
/*
* Calculate value of the swap at exercise date on each path (beware of perfect forsight - all rates are simulationTime=exerciseDate)
*/
RandomVariable valueFixLeg = new RandomVariableFromDoubleArray(fixingDates[fixingDates.length-1], 0.0);
RandomVariable valueFloatLeg = new RandomVariableFromDoubleArray(paymentDates[paymentDates.length-1], -1.0);
// Calculate the value of the swap by working backward through all periods
for(int period=fixingDates.length-1; period>=0; period--)
{
double fixingDate = fixingDates[period];
double paymentDate = paymentDates[period];
double periodLength = periodLengths != null ? periodLengths[period] : paymentDate - fixingDate;
// Get random variables - note that this is the rate at simulation time = exerciseDate
RandomVariable libor = model.getLIBOR(exerciseDate, fixingDate, paymentDate);
// Add payment received at end of period
RandomVariable payoff = new RandomVariableFromDoubleArray(paymentDate, 1.0 * periodLength);
valueFixLeg = valueFixLeg.add(payoff);
// Discount back to beginning of period
valueFloatLeg = valueFloatLeg.discount(libor, periodLength);
valueFixLeg = valueFixLeg.discount(libor, periodLength);
}
valueFloatLeg = valueFloatLeg.add(1.0);
RandomVariable parSwapRate = valueFloatLeg.div(valueFixLeg);
RandomVariable payoffUnit = new RandomVariableFromDoubleArray(paymentDates[0], periodLengths[0]);
payoffUnit = payoffUnit.discount(model.getLIBOR(exerciseDate, fixingDates[0], paymentDates[0]),paymentDates[0]-fixingDates[0]);
RandomVariable value = parSwapRate.sub(strike).floor(0.0).mult(payoffUnit);
// If the exercise date is not the first periods start date, then discount back to the exercise date (calculate the forward starting swap)
if(fixingDates[0] != exerciseDate) {
RandomVariable libor = model.getLIBOR(exerciseDate, exerciseDate, fixingDates[0]);
double periodLength = fixingDates[0] - exerciseDate;
// Discount back to beginning of period
value = value.discount(libor, periodLength);
}
/*
* Calculate value
*/
RandomVariable numeraire = model.getNumeraire(exerciseDate);
RandomVariable monteCarloProbabilities = model.getMonteCarloWeights(model.getTimeIndex(exerciseDate));
value = value.div(numeraire).mult(monteCarloProbabilities);
RandomVariable numeraireAtZero = model.getNumeraire(evaluationTime);
RandomVariable monteCarloProbabilitiesAtZero = model.getMonteCarloWeights(evaluationTime);
value = value.mult(numeraireAtZero).div(monteCarloProbabilitiesAtZero);
return value;
}
|
java
|
@Override
public RandomVariable getValue(double evaluationTime, LIBORModelMonteCarloSimulationModel model) throws CalculationException {
/*
* Calculate value of the swap at exercise date on each path (beware of perfect forsight - all rates are simulationTime=exerciseDate)
*/
RandomVariable valueFixLeg = new RandomVariableFromDoubleArray(fixingDates[fixingDates.length-1], 0.0);
RandomVariable valueFloatLeg = new RandomVariableFromDoubleArray(paymentDates[paymentDates.length-1], -1.0);
// Calculate the value of the swap by working backward through all periods
for(int period=fixingDates.length-1; period>=0; period--)
{
double fixingDate = fixingDates[period];
double paymentDate = paymentDates[period];
double periodLength = periodLengths != null ? periodLengths[period] : paymentDate - fixingDate;
// Get random variables - note that this is the rate at simulation time = exerciseDate
RandomVariable libor = model.getLIBOR(exerciseDate, fixingDate, paymentDate);
// Add payment received at end of period
RandomVariable payoff = new RandomVariableFromDoubleArray(paymentDate, 1.0 * periodLength);
valueFixLeg = valueFixLeg.add(payoff);
// Discount back to beginning of period
valueFloatLeg = valueFloatLeg.discount(libor, periodLength);
valueFixLeg = valueFixLeg.discount(libor, periodLength);
}
valueFloatLeg = valueFloatLeg.add(1.0);
RandomVariable parSwapRate = valueFloatLeg.div(valueFixLeg);
RandomVariable payoffUnit = new RandomVariableFromDoubleArray(paymentDates[0], periodLengths[0]);
payoffUnit = payoffUnit.discount(model.getLIBOR(exerciseDate, fixingDates[0], paymentDates[0]),paymentDates[0]-fixingDates[0]);
RandomVariable value = parSwapRate.sub(strike).floor(0.0).mult(payoffUnit);
// If the exercise date is not the first periods start date, then discount back to the exercise date (calculate the forward starting swap)
if(fixingDates[0] != exerciseDate) {
RandomVariable libor = model.getLIBOR(exerciseDate, exerciseDate, fixingDates[0]);
double periodLength = fixingDates[0] - exerciseDate;
// Discount back to beginning of period
value = value.discount(libor, periodLength);
}
/*
* Calculate value
*/
RandomVariable numeraire = model.getNumeraire(exerciseDate);
RandomVariable monteCarloProbabilities = model.getMonteCarloWeights(model.getTimeIndex(exerciseDate));
value = value.div(numeraire).mult(monteCarloProbabilities);
RandomVariable numeraireAtZero = model.getNumeraire(evaluationTime);
RandomVariable monteCarloProbabilitiesAtZero = model.getMonteCarloWeights(evaluationTime);
value = value.mult(numeraireAtZero).div(monteCarloProbabilitiesAtZero);
return value;
}
|
[
"@",
"Override",
"public",
"RandomVariable",
"getValue",
"(",
"double",
"evaluationTime",
",",
"LIBORModelMonteCarloSimulationModel",
"model",
")",
"throws",
"CalculationException",
"{",
"/*\n\t\t * Calculate value of the swap at exercise date on each path (beware of perfect forsight - all rates are simulationTime=exerciseDate)\n\t\t */",
"RandomVariable",
"valueFixLeg",
"=",
"new",
"RandomVariableFromDoubleArray",
"(",
"fixingDates",
"[",
"fixingDates",
".",
"length",
"-",
"1",
"]",
",",
"0.0",
")",
";",
"RandomVariable",
"valueFloatLeg",
"=",
"new",
"RandomVariableFromDoubleArray",
"(",
"paymentDates",
"[",
"paymentDates",
".",
"length",
"-",
"1",
"]",
",",
"-",
"1.0",
")",
";",
"// Calculate the value of the swap by working backward through all periods",
"for",
"(",
"int",
"period",
"=",
"fixingDates",
".",
"length",
"-",
"1",
";",
"period",
">=",
"0",
";",
"period",
"--",
")",
"{",
"double",
"fixingDate",
"=",
"fixingDates",
"[",
"period",
"]",
";",
"double",
"paymentDate",
"=",
"paymentDates",
"[",
"period",
"]",
";",
"double",
"periodLength",
"=",
"periodLengths",
"!=",
"null",
"?",
"periodLengths",
"[",
"period",
"]",
":",
"paymentDate",
"-",
"fixingDate",
";",
"// Get random variables - note that this is the rate at simulation time = exerciseDate",
"RandomVariable",
"libor",
"=",
"model",
".",
"getLIBOR",
"(",
"exerciseDate",
",",
"fixingDate",
",",
"paymentDate",
")",
";",
"// Add payment received at end of period",
"RandomVariable",
"payoff",
"=",
"new",
"RandomVariableFromDoubleArray",
"(",
"paymentDate",
",",
"1.0",
"*",
"periodLength",
")",
";",
"valueFixLeg",
"=",
"valueFixLeg",
".",
"add",
"(",
"payoff",
")",
";",
"// Discount back to beginning of period",
"valueFloatLeg",
"=",
"valueFloatLeg",
".",
"discount",
"(",
"libor",
",",
"periodLength",
")",
";",
"valueFixLeg",
"=",
"valueFixLeg",
".",
"discount",
"(",
"libor",
",",
"periodLength",
")",
";",
"}",
"valueFloatLeg",
"=",
"valueFloatLeg",
".",
"add",
"(",
"1.0",
")",
";",
"RandomVariable",
"parSwapRate",
"=",
"valueFloatLeg",
".",
"div",
"(",
"valueFixLeg",
")",
";",
"RandomVariable",
"payoffUnit",
"=",
"new",
"RandomVariableFromDoubleArray",
"(",
"paymentDates",
"[",
"0",
"]",
",",
"periodLengths",
"[",
"0",
"]",
")",
";",
"payoffUnit",
"=",
"payoffUnit",
".",
"discount",
"(",
"model",
".",
"getLIBOR",
"(",
"exerciseDate",
",",
"fixingDates",
"[",
"0",
"]",
",",
"paymentDates",
"[",
"0",
"]",
")",
",",
"paymentDates",
"[",
"0",
"]",
"-",
"fixingDates",
"[",
"0",
"]",
")",
";",
"RandomVariable",
"value",
"=",
"parSwapRate",
".",
"sub",
"(",
"strike",
")",
".",
"floor",
"(",
"0.0",
")",
".",
"mult",
"(",
"payoffUnit",
")",
";",
"// If the exercise date is not the first periods start date, then discount back to the exercise date (calculate the forward starting swap)",
"if",
"(",
"fixingDates",
"[",
"0",
"]",
"!=",
"exerciseDate",
")",
"{",
"RandomVariable",
"libor",
"=",
"model",
".",
"getLIBOR",
"(",
"exerciseDate",
",",
"exerciseDate",
",",
"fixingDates",
"[",
"0",
"]",
")",
";",
"double",
"periodLength",
"=",
"fixingDates",
"[",
"0",
"]",
"-",
"exerciseDate",
";",
"// Discount back to beginning of period",
"value",
"=",
"value",
".",
"discount",
"(",
"libor",
",",
"periodLength",
")",
";",
"}",
"/*\n\t\t * Calculate value\n\t\t */",
"RandomVariable",
"numeraire",
"=",
"model",
".",
"getNumeraire",
"(",
"exerciseDate",
")",
";",
"RandomVariable",
"monteCarloProbabilities",
"=",
"model",
".",
"getMonteCarloWeights",
"(",
"model",
".",
"getTimeIndex",
"(",
"exerciseDate",
")",
")",
";",
"value",
"=",
"value",
".",
"div",
"(",
"numeraire",
")",
".",
"mult",
"(",
"monteCarloProbabilities",
")",
";",
"RandomVariable",
"numeraireAtZero",
"=",
"model",
".",
"getNumeraire",
"(",
"evaluationTime",
")",
";",
"RandomVariable",
"monteCarloProbabilitiesAtZero",
"=",
"model",
".",
"getMonteCarloWeights",
"(",
"evaluationTime",
")",
";",
"value",
"=",
"value",
".",
"mult",
"(",
"numeraireAtZero",
")",
".",
"div",
"(",
"monteCarloProbabilitiesAtZero",
")",
";",
"return",
"value",
";",
"}"
] |
This method returns the value random variable of the product within the specified model, evaluated at a given evalutationTime.
Note: For a lattice this is often the value conditional to evalutationTime, for a Monte-Carlo simulation this is the (sum of) value discounted to evaluation time.
Cashflows prior evaluationTime are not considered.
@param evaluationTime The time on which this products value should be observed.
@param model The model used to price the product.
@return The random variable representing the value of the product discounted to evaluation time
@throws net.finmath.exception.CalculationException Thrown if the valuation fails, specific cause may be available via the <code>cause()</code> method.
|
[
"This",
"method",
"returns",
"the",
"value",
"random",
"variable",
"of",
"the",
"product",
"within",
"the",
"specified",
"model",
"evaluated",
"at",
"a",
"given",
"evalutationTime",
".",
"Note",
":",
"For",
"a",
"lattice",
"this",
"is",
"often",
"the",
"value",
"conditional",
"to",
"evalutationTime",
"for",
"a",
"Monte",
"-",
"Carlo",
"simulation",
"this",
"is",
"the",
"(",
"sum",
"of",
")",
"value",
"discounted",
"to",
"evaluation",
"time",
".",
"Cashflows",
"prior",
"evaluationTime",
"are",
"not",
"considered",
"."
] |
train
|
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/montecarlo/interestrate/products/CMSOption.java#L65-L122
|
MTDdk/jawn
|
jawn-server/src/main/java/net/javapla/jawn/server/CookieHelper.java
|
CookieHelper.setHttpOnlyReflect
|
static void setHttpOnlyReflect(net.javapla.jawn.core.http.Cookie awCookie, javax.servlet.http.Cookie servletCookie){
try {
servletCookie.getClass().getMethod("setHttpOnly", boolean.class).invoke(servletCookie, awCookie.isHttpOnly());
} catch (Exception e) {
// Cookie.logger.warn("You are trying to set HttpOnly on a cookie, but it appears you are running on Servlet version before 3.0.");
}
}
|
java
|
static void setHttpOnlyReflect(net.javapla.jawn.core.http.Cookie awCookie, javax.servlet.http.Cookie servletCookie){
try {
servletCookie.getClass().getMethod("setHttpOnly", boolean.class).invoke(servletCookie, awCookie.isHttpOnly());
} catch (Exception e) {
// Cookie.logger.warn("You are trying to set HttpOnly on a cookie, but it appears you are running on Servlet version before 3.0.");
}
}
|
[
"static",
"void",
"setHttpOnlyReflect",
"(",
"net",
".",
"javapla",
".",
"jawn",
".",
"core",
".",
"http",
".",
"Cookie",
"awCookie",
",",
"javax",
".",
"servlet",
".",
"http",
".",
"Cookie",
"servletCookie",
")",
"{",
"try",
"{",
"servletCookie",
".",
"getClass",
"(",
")",
".",
"getMethod",
"(",
"\"setHttpOnly\"",
",",
"boolean",
".",
"class",
")",
".",
"invoke",
"(",
"servletCookie",
",",
"awCookie",
".",
"isHttpOnly",
"(",
")",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"// Cookie.logger.warn(\"You are trying to set HttpOnly on a cookie, but it appears you are running on Servlet version before 3.0.\");",
"}",
"}"
] |
Need to call this by reflection for backwards compatibility with Servlet 2.5
|
[
"Need",
"to",
"call",
"this",
"by",
"reflection",
"for",
"backwards",
"compatibility",
"with",
"Servlet",
"2",
".",
"5"
] |
train
|
https://github.com/MTDdk/jawn/blob/4ec2d09b97d413efdead7487e6075e5bfd13b925/jawn-server/src/main/java/net/javapla/jawn/server/CookieHelper.java#L44-L50
|
wcm-io/wcm-io-wcm
|
commons/src/main/java/io/wcm/wcm/commons/util/Template.java
|
Template.forPage
|
public static TemplatePathInfo forPage(@NotNull Page page, @NotNull TemplatePathInfo @NotNull... templates) {
if (page == null || templates == null) {
return null;
}
String templatePath = page.getProperties().get(NameConstants.PN_TEMPLATE, String.class);
return forTemplatePath(templatePath, templates);
}
|
java
|
public static TemplatePathInfo forPage(@NotNull Page page, @NotNull TemplatePathInfo @NotNull... templates) {
if (page == null || templates == null) {
return null;
}
String templatePath = page.getProperties().get(NameConstants.PN_TEMPLATE, String.class);
return forTemplatePath(templatePath, templates);
}
|
[
"public",
"static",
"TemplatePathInfo",
"forPage",
"(",
"@",
"NotNull",
"Page",
"page",
",",
"@",
"NotNull",
"TemplatePathInfo",
"@",
"NotNull",
".",
".",
".",
"templates",
")",
"{",
"if",
"(",
"page",
"==",
"null",
"||",
"templates",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"String",
"templatePath",
"=",
"page",
".",
"getProperties",
"(",
")",
".",
"get",
"(",
"NameConstants",
".",
"PN_TEMPLATE",
",",
"String",
".",
"class",
")",
";",
"return",
"forTemplatePath",
"(",
"templatePath",
",",
"templates",
")",
";",
"}"
] |
Lookup template for given page.
@param page Page
@param templates Templates
@return The {@link TemplatePathInfo} instance or null for unknown template paths
|
[
"Lookup",
"template",
"for",
"given",
"page",
"."
] |
train
|
https://github.com/wcm-io/wcm-io-wcm/blob/8eff9434f2f4b6462fdb718f8769ad793c55b8d7/commons/src/main/java/io/wcm/wcm/commons/util/Template.java#L158-L164
|
magik6k/JWWF
|
src/main/java/net/magik6k/jwwf/core/JwwfServer.java
|
JwwfServer.bindWebapp
|
public JwwfServer bindWebapp(final Class<? extends User> user, String url) {
if (!url.endsWith("/"))
url = url + "/";
context.addServlet(new ServletHolder(new WebClientServelt(clientCreator)), url + "");
context.addServlet(new ServletHolder(new SkinServlet()), url + "__jwwf/skins/*");
ServletHolder fontServletHolder = new ServletHolder(new ResourceServlet());
fontServletHolder.setInitParameter("basePackage", "net/magik6k/jwwf/assets/fonts");
context.addServlet(fontServletHolder, url + "__jwwf/fonts/*");
context.addServlet(new ServletHolder(new APISocketServlet(new UserFactory() {
@Override
public User createUser() {
try {
User u = user.getDeclaredConstructor().newInstance();
u.setServer(jwwfServer);
return u;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
})), url + "__jwwf/socket");
for (JwwfPlugin plugin : plugins) {
if (plugin instanceof IPluginWebapp)
((IPluginWebapp) plugin).onWebappBound(this, url);
}
return this;
}
|
java
|
public JwwfServer bindWebapp(final Class<? extends User> user, String url) {
if (!url.endsWith("/"))
url = url + "/";
context.addServlet(new ServletHolder(new WebClientServelt(clientCreator)), url + "");
context.addServlet(new ServletHolder(new SkinServlet()), url + "__jwwf/skins/*");
ServletHolder fontServletHolder = new ServletHolder(new ResourceServlet());
fontServletHolder.setInitParameter("basePackage", "net/magik6k/jwwf/assets/fonts");
context.addServlet(fontServletHolder, url + "__jwwf/fonts/*");
context.addServlet(new ServletHolder(new APISocketServlet(new UserFactory() {
@Override
public User createUser() {
try {
User u = user.getDeclaredConstructor().newInstance();
u.setServer(jwwfServer);
return u;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
})), url + "__jwwf/socket");
for (JwwfPlugin plugin : plugins) {
if (plugin instanceof IPluginWebapp)
((IPluginWebapp) plugin).onWebappBound(this, url);
}
return this;
}
|
[
"public",
"JwwfServer",
"bindWebapp",
"(",
"final",
"Class",
"<",
"?",
"extends",
"User",
">",
"user",
",",
"String",
"url",
")",
"{",
"if",
"(",
"!",
"url",
".",
"endsWith",
"(",
"\"/\"",
")",
")",
"url",
"=",
"url",
"+",
"\"/\"",
";",
"context",
".",
"addServlet",
"(",
"new",
"ServletHolder",
"(",
"new",
"WebClientServelt",
"(",
"clientCreator",
")",
")",
",",
"url",
"+",
"\"\"",
")",
";",
"context",
".",
"addServlet",
"(",
"new",
"ServletHolder",
"(",
"new",
"SkinServlet",
"(",
")",
")",
",",
"url",
"+",
"\"__jwwf/skins/*\"",
")",
";",
"ServletHolder",
"fontServletHolder",
"=",
"new",
"ServletHolder",
"(",
"new",
"ResourceServlet",
"(",
")",
")",
";",
"fontServletHolder",
".",
"setInitParameter",
"(",
"\"basePackage\"",
",",
"\"net/magik6k/jwwf/assets/fonts\"",
")",
";",
"context",
".",
"addServlet",
"(",
"fontServletHolder",
",",
"url",
"+",
"\"__jwwf/fonts/*\"",
")",
";",
"context",
".",
"addServlet",
"(",
"new",
"ServletHolder",
"(",
"new",
"APISocketServlet",
"(",
"new",
"UserFactory",
"(",
")",
"{",
"@",
"Override",
"public",
"User",
"createUser",
"(",
")",
"{",
"try",
"{",
"User",
"u",
"=",
"user",
".",
"getDeclaredConstructor",
"(",
")",
".",
"newInstance",
"(",
")",
";",
"u",
".",
"setServer",
"(",
"jwwfServer",
")",
";",
"return",
"u",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"}",
"return",
"null",
";",
"}",
"}",
")",
")",
",",
"url",
"+",
"\"__jwwf/socket\"",
")",
";",
"for",
"(",
"JwwfPlugin",
"plugin",
":",
"plugins",
")",
"{",
"if",
"(",
"plugin",
"instanceof",
"IPluginWebapp",
")",
"(",
"(",
"IPluginWebapp",
")",
"plugin",
")",
".",
"onWebappBound",
"(",
"this",
",",
"url",
")",
";",
"}",
"return",
"this",
";",
"}"
] |
Binds webapp to address
@param user User class for the web application
@param url Url to bind to, myst begin and end with /, like /foo/bar/
@return This JwwfServer
|
[
"Binds",
"webapp",
"to",
"address"
] |
train
|
https://github.com/magik6k/JWWF/blob/8ba334501396c3301495da8708733f6014f20665/src/main/java/net/magik6k/jwwf/core/JwwfServer.java#L53-L83
|
lievendoclo/Valkyrie-RCP
|
valkyrie-rcp-core/src/main/java/org/valkyriercp/binding/beans/AbstractMemberPropertyAccessor.java
|
AbstractMemberPropertyAccessor.getPropertyName
|
protected String getPropertyName(String methodName, int prefixLength) {
return Character.toLowerCase(methodName.charAt(prefixLength)) + methodName.substring(prefixLength + 1);
}
|
java
|
protected String getPropertyName(String methodName, int prefixLength) {
return Character.toLowerCase(methodName.charAt(prefixLength)) + methodName.substring(prefixLength + 1);
}
|
[
"protected",
"String",
"getPropertyName",
"(",
"String",
"methodName",
",",
"int",
"prefixLength",
")",
"{",
"return",
"Character",
".",
"toLowerCase",
"(",
"methodName",
".",
"charAt",
"(",
"prefixLength",
")",
")",
"+",
"methodName",
".",
"substring",
"(",
"prefixLength",
"+",
"1",
")",
";",
"}"
] |
Returns the propertyName based on the methodName. Cuts of the prefix and
removes first capital.
@param methodName name of method to convert.
@param prefixLength length of prefix to cut of.
@return property name.
|
[
"Returns",
"the",
"propertyName",
"based",
"on",
"the",
"methodName",
".",
"Cuts",
"of",
"the",
"prefix",
"and",
"removes",
"first",
"capital",
"."
] |
train
|
https://github.com/lievendoclo/Valkyrie-RCP/blob/6aad6e640b348cda8f3b0841f6e42025233f1eb8/valkyrie-rcp-core/src/main/java/org/valkyriercp/binding/beans/AbstractMemberPropertyAccessor.java#L370-L372
|
kiegroup/drools
|
drools-templates/src/main/java/org/drools/template/DataProviderCompiler.java
|
DataProviderCompiler.compile
|
public String compile(final DataProvider dataProvider,
final TemplateDataListener listener) {
return compile(dataProvider, listener, true);
}
|
java
|
public String compile(final DataProvider dataProvider,
final TemplateDataListener listener) {
return compile(dataProvider, listener, true);
}
|
[
"public",
"String",
"compile",
"(",
"final",
"DataProvider",
"dataProvider",
",",
"final",
"TemplateDataListener",
"listener",
")",
"{",
"return",
"compile",
"(",
"dataProvider",
",",
"listener",
",",
"true",
")",
";",
"}"
] |
Generates DRL from a data provider for the spreadsheet data and templates.
@param dataProvider the data provider for the spreadsheet data
@param listener a template data listener
@return the generated DRL text as a String
|
[
"Generates",
"DRL",
"from",
"a",
"data",
"provider",
"for",
"the",
"spreadsheet",
"data",
"and",
"templates",
"."
] |
train
|
https://github.com/kiegroup/drools/blob/22b0275d6dbe93070b8090948502cf46eda543c4/drools-templates/src/main/java/org/drools/template/DataProviderCompiler.java#L67-L70
|
alkacon/opencms-core
|
src/org/opencms/db/CmsSubscriptionManager.java
|
CmsSubscriptionManager.unsubscribeResourceFor
|
public void unsubscribeResourceFor(CmsObject cms, CmsPrincipal principal, CmsResource resource)
throws CmsException {
if (!isEnabled()) {
throw new CmsRuntimeException(Messages.get().container(Messages.ERR_SUBSCRIPTION_MANAGER_DISABLED_0));
}
m_securityManager.unsubscribeResourceFor(cms.getRequestContext(), getPoolName(), principal, resource);
}
|
java
|
public void unsubscribeResourceFor(CmsObject cms, CmsPrincipal principal, CmsResource resource)
throws CmsException {
if (!isEnabled()) {
throw new CmsRuntimeException(Messages.get().container(Messages.ERR_SUBSCRIPTION_MANAGER_DISABLED_0));
}
m_securityManager.unsubscribeResourceFor(cms.getRequestContext(), getPoolName(), principal, resource);
}
|
[
"public",
"void",
"unsubscribeResourceFor",
"(",
"CmsObject",
"cms",
",",
"CmsPrincipal",
"principal",
",",
"CmsResource",
"resource",
")",
"throws",
"CmsException",
"{",
"if",
"(",
"!",
"isEnabled",
"(",
")",
")",
"{",
"throw",
"new",
"CmsRuntimeException",
"(",
"Messages",
".",
"get",
"(",
")",
".",
"container",
"(",
"Messages",
".",
"ERR_SUBSCRIPTION_MANAGER_DISABLED_0",
")",
")",
";",
"}",
"m_securityManager",
".",
"unsubscribeResourceFor",
"(",
"cms",
".",
"getRequestContext",
"(",
")",
",",
"getPoolName",
"(",
")",
",",
"principal",
",",
"resource",
")",
";",
"}"
] |
Unsubscribes the principal from the resource.<p>
@param cms the current users context
@param principal the principal that unsubscribes from the resource
@param resource the resource to unsubscribe from
@throws CmsException if something goes wrong
|
[
"Unsubscribes",
"the",
"principal",
"from",
"the",
"resource",
".",
"<p",
">"
] |
train
|
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsSubscriptionManager.java#L443-L450
|
molgenis/molgenis
|
molgenis-navigator/src/main/java/org/molgenis/navigator/copy/service/RelationTransformer.java
|
RelationTransformer.transformPackage
|
static void transformPackage(EntityType entityType, Map<String, Package> newPackages) {
if (newPackages.isEmpty()) {
return;
}
Package entityTypePackage = entityType.getPackage();
if (entityTypePackage != null) {
String packageId = entityTypePackage.getId();
if (newPackages.containsKey(packageId)) {
entityType.setPackage(newPackages.get(packageId));
}
}
}
|
java
|
static void transformPackage(EntityType entityType, Map<String, Package> newPackages) {
if (newPackages.isEmpty()) {
return;
}
Package entityTypePackage = entityType.getPackage();
if (entityTypePackage != null) {
String packageId = entityTypePackage.getId();
if (newPackages.containsKey(packageId)) {
entityType.setPackage(newPackages.get(packageId));
}
}
}
|
[
"static",
"void",
"transformPackage",
"(",
"EntityType",
"entityType",
",",
"Map",
"<",
"String",
",",
"Package",
">",
"newPackages",
")",
"{",
"if",
"(",
"newPackages",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
";",
"}",
"Package",
"entityTypePackage",
"=",
"entityType",
".",
"getPackage",
"(",
")",
";",
"if",
"(",
"entityTypePackage",
"!=",
"null",
")",
"{",
"String",
"packageId",
"=",
"entityTypePackage",
".",
"getId",
"(",
")",
";",
"if",
"(",
"newPackages",
".",
"containsKey",
"(",
"packageId",
")",
")",
"{",
"entityType",
".",
"setPackage",
"(",
"newPackages",
".",
"get",
"(",
"packageId",
")",
")",
";",
"}",
"}",
"}"
] |
Changes the {@link Package} of an {@link EntityType} to another Package if it was present in
the supplied Map. Does nothing if the Map does not contain the ID of the current Package.
@param entityType the EntityType to update
@param newPackages a Map of (old) Package IDs and new Packages
|
[
"Changes",
"the",
"{",
"@link",
"Package",
"}",
"of",
"an",
"{",
"@link",
"EntityType",
"}",
"to",
"another",
"Package",
"if",
"it",
"was",
"present",
"in",
"the",
"supplied",
"Map",
".",
"Does",
"nothing",
"if",
"the",
"Map",
"does",
"not",
"contain",
"the",
"ID",
"of",
"the",
"current",
"Package",
"."
] |
train
|
https://github.com/molgenis/molgenis/blob/b4d0d6b27e6f6c8d7505a3863dc03b589601f987/molgenis-navigator/src/main/java/org/molgenis/navigator/copy/service/RelationTransformer.java#L29-L41
|
square/okhttp
|
okhttp/src/main/java/okhttp3/internal/Util.java
|
Util.skipLeadingAsciiWhitespace
|
public static int skipLeadingAsciiWhitespace(String input, int pos, int limit) {
for (int i = pos; i < limit; i++) {
switch (input.charAt(i)) {
case '\t':
case '\n':
case '\f':
case '\r':
case ' ':
continue;
default:
return i;
}
}
return limit;
}
|
java
|
public static int skipLeadingAsciiWhitespace(String input, int pos, int limit) {
for (int i = pos; i < limit; i++) {
switch (input.charAt(i)) {
case '\t':
case '\n':
case '\f':
case '\r':
case ' ':
continue;
default:
return i;
}
}
return limit;
}
|
[
"public",
"static",
"int",
"skipLeadingAsciiWhitespace",
"(",
"String",
"input",
",",
"int",
"pos",
",",
"int",
"limit",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"pos",
";",
"i",
"<",
"limit",
";",
"i",
"++",
")",
"{",
"switch",
"(",
"input",
".",
"charAt",
"(",
"i",
")",
")",
"{",
"case",
"'",
"'",
":",
"case",
"'",
"'",
":",
"case",
"'",
"'",
":",
"case",
"'",
"'",
":",
"case",
"'",
"'",
":",
"continue",
";",
"default",
":",
"return",
"i",
";",
"}",
"}",
"return",
"limit",
";",
"}"
] |
Increments {@code pos} until {@code input[pos]} is not ASCII whitespace. Stops at {@code
limit}.
|
[
"Increments",
"{"
] |
train
|
https://github.com/square/okhttp/blob/a8c65a822dd6cadd2de7d115bf94adf312e67868/okhttp/src/main/java/okhttp3/internal/Util.java#L296-L310
|
rjeschke/txtmark
|
src/main/java/com/github/rjeschke/txtmark/Utils.java
|
Utils.readUntil
|
public final static int readUntil(final StringBuilder out, final String in, final int start, final char... end)
{
int pos = start;
while (pos < in.length())
{
final char ch = in.charAt(pos);
if (ch == '\\' && pos + 1 < in.length())
{
pos = escape(out, in.charAt(pos + 1), pos);
}
else
{
boolean endReached = false;
for (int n = 0; n < end.length; n++)
{
if (ch == end[n])
{
endReached = true;
break;
}
}
if (endReached)
{
break;
}
out.append(ch);
}
pos++;
}
return (pos == in.length()) ? -1 : pos;
}
|
java
|
public final static int readUntil(final StringBuilder out, final String in, final int start, final char... end)
{
int pos = start;
while (pos < in.length())
{
final char ch = in.charAt(pos);
if (ch == '\\' && pos + 1 < in.length())
{
pos = escape(out, in.charAt(pos + 1), pos);
}
else
{
boolean endReached = false;
for (int n = 0; n < end.length; n++)
{
if (ch == end[n])
{
endReached = true;
break;
}
}
if (endReached)
{
break;
}
out.append(ch);
}
pos++;
}
return (pos == in.length()) ? -1 : pos;
}
|
[
"public",
"final",
"static",
"int",
"readUntil",
"(",
"final",
"StringBuilder",
"out",
",",
"final",
"String",
"in",
",",
"final",
"int",
"start",
",",
"final",
"char",
"...",
"end",
")",
"{",
"int",
"pos",
"=",
"start",
";",
"while",
"(",
"pos",
"<",
"in",
".",
"length",
"(",
")",
")",
"{",
"final",
"char",
"ch",
"=",
"in",
".",
"charAt",
"(",
"pos",
")",
";",
"if",
"(",
"ch",
"==",
"'",
"'",
"&&",
"pos",
"+",
"1",
"<",
"in",
".",
"length",
"(",
")",
")",
"{",
"pos",
"=",
"escape",
"(",
"out",
",",
"in",
".",
"charAt",
"(",
"pos",
"+",
"1",
")",
",",
"pos",
")",
";",
"}",
"else",
"{",
"boolean",
"endReached",
"=",
"false",
";",
"for",
"(",
"int",
"n",
"=",
"0",
";",
"n",
"<",
"end",
".",
"length",
";",
"n",
"++",
")",
"{",
"if",
"(",
"ch",
"==",
"end",
"[",
"n",
"]",
")",
"{",
"endReached",
"=",
"true",
";",
"break",
";",
"}",
"}",
"if",
"(",
"endReached",
")",
"{",
"break",
";",
"}",
"out",
".",
"append",
"(",
"ch",
")",
";",
"}",
"pos",
"++",
";",
"}",
"return",
"(",
"pos",
"==",
"in",
".",
"length",
"(",
")",
")",
"?",
"-",
"1",
":",
"pos",
";",
"}"
] |
Reads characters until any 'end' character is encountered.
@param out
The StringBuilder to write to.
@param in
The Input String.
@param start
Starting position.
@param end
End characters.
@return The new position or -1 if no 'end' char was found.
|
[
"Reads",
"characters",
"until",
"any",
"end",
"character",
"is",
"encountered",
"."
] |
train
|
https://github.com/rjeschke/txtmark/blob/108cee6b209a362843729c032c2d982625d12d98/src/main/java/com/github/rjeschke/txtmark/Utils.java#L113-L144
|
aboutsip/pkts
|
pkts-core/src/main/java/io/pkts/Pcap.java
|
Pcap.openStream
|
public static Pcap openStream(final InputStream is, final int bufferCapacity) throws IOException {
final Buffer stream = new BoundedInputStreamBuffer(bufferCapacity, is);
final PcapGlobalHeader header = PcapGlobalHeader.parse(stream);
return new Pcap(header, stream);
}
|
java
|
public static Pcap openStream(final InputStream is, final int bufferCapacity) throws IOException {
final Buffer stream = new BoundedInputStreamBuffer(bufferCapacity, is);
final PcapGlobalHeader header = PcapGlobalHeader.parse(stream);
return new Pcap(header, stream);
}
|
[
"public",
"static",
"Pcap",
"openStream",
"(",
"final",
"InputStream",
"is",
",",
"final",
"int",
"bufferCapacity",
")",
"throws",
"IOException",
"{",
"final",
"Buffer",
"stream",
"=",
"new",
"BoundedInputStreamBuffer",
"(",
"bufferCapacity",
",",
"is",
")",
";",
"final",
"PcapGlobalHeader",
"header",
"=",
"PcapGlobalHeader",
".",
"parse",
"(",
"stream",
")",
";",
"return",
"new",
"Pcap",
"(",
"header",
",",
"stream",
")",
";",
"}"
] |
Capture packets from the input stream
@param is
@param bufferCapacity Size of buffer, must be larger than PCAPs largest framesize. See SNAPLENGTH for tcpdump, et.al.
@return
@throws IOException
|
[
"Capture",
"packets",
"from",
"the",
"input",
"stream"
] |
train
|
https://github.com/aboutsip/pkts/blob/0f06bb0dac76c812187829f580a8d476ca99a1a1/pkts-core/src/main/java/io/pkts/Pcap.java#L135-L139
|
Harium/keel
|
src/main/java/com/harium/keel/catalano/math/distance/Distance.java
|
Distance.TopsoeDivergence
|
public static double TopsoeDivergence(double[] p, double[] q) {
double r = 0;
for (int i = 0; i < p.length; i++) {
if (p[i] != 0 && q[i] != 0) {
double den = p[i] + q[i];
r += p[i] * Math.log(2 * p[i] / den) + q[i] * Math.log(2 * q[i] / den);
}
}
return r;
}
|
java
|
public static double TopsoeDivergence(double[] p, double[] q) {
double r = 0;
for (int i = 0; i < p.length; i++) {
if (p[i] != 0 && q[i] != 0) {
double den = p[i] + q[i];
r += p[i] * Math.log(2 * p[i] / den) + q[i] * Math.log(2 * q[i] / den);
}
}
return r;
}
|
[
"public",
"static",
"double",
"TopsoeDivergence",
"(",
"double",
"[",
"]",
"p",
",",
"double",
"[",
"]",
"q",
")",
"{",
"double",
"r",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"p",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"p",
"[",
"i",
"]",
"!=",
"0",
"&&",
"q",
"[",
"i",
"]",
"!=",
"0",
")",
"{",
"double",
"den",
"=",
"p",
"[",
"i",
"]",
"+",
"q",
"[",
"i",
"]",
";",
"r",
"+=",
"p",
"[",
"i",
"]",
"*",
"Math",
".",
"log",
"(",
"2",
"*",
"p",
"[",
"i",
"]",
"/",
"den",
")",
"+",
"q",
"[",
"i",
"]",
"*",
"Math",
".",
"log",
"(",
"2",
"*",
"q",
"[",
"i",
"]",
"/",
"den",
")",
";",
"}",
"}",
"return",
"r",
";",
"}"
] |
Gets the Topsoe divergence.
@param p P vector.
@param q Q vector.
@return The Topsoe divergence between p and q.
|
[
"Gets",
"the",
"Topsoe",
"divergence",
"."
] |
train
|
https://github.com/Harium/keel/blob/0369ae674f9e664bccc5f9e161ae7e7a3b949a1e/src/main/java/com/harium/keel/catalano/math/distance/Distance.java#L907-L916
|
ops4j/org.ops4j.pax.logging
|
pax-logging-api/src/main/java/org/jboss/logging/Logger.java
|
Logger.fatalf
|
public void fatalf(String format, Object... params) {
doLogf(Level.FATAL, FQCN, format, params, null);
}
|
java
|
public void fatalf(String format, Object... params) {
doLogf(Level.FATAL, FQCN, format, params, null);
}
|
[
"public",
"void",
"fatalf",
"(",
"String",
"format",
",",
"Object",
"...",
"params",
")",
"{",
"doLogf",
"(",
"Level",
".",
"FATAL",
",",
"FQCN",
",",
"format",
",",
"params",
",",
"null",
")",
";",
"}"
] |
Issue a formatted log message with a level of FATAL.
@param format the format string as per {@link String#format(String, Object...)} or resource bundle key therefor
@param params the parameters
|
[
"Issue",
"a",
"formatted",
"log",
"message",
"with",
"a",
"level",
"of",
"FATAL",
"."
] |
train
|
https://github.com/ops4j/org.ops4j.pax.logging/blob/493de4e1db4fe9f981f3dd78b8e40e5bf2b2e59d/pax-logging-api/src/main/java/org/jboss/logging/Logger.java#L1937-L1939
|
m-m-m/util
|
gwt/src/main/resources/net/sf/mmm/util/gwt/supersource/net/sf/mmm/util/exception/api/NlsRuntimeException.java
|
NlsRuntimeException.printStackTrace
|
static void printStackTrace(NlsThrowable throwable, Locale locale, Appendable buffer) {
try {
synchronized (buffer) {
buffer.append(throwable.getClass().getName());
buffer.append(": ");
throwable.getLocalizedMessage(locale, buffer);
buffer.append('\n');
UUID uuid = throwable.getUuid();
if (uuid != null) {
buffer.append(uuid.toString());
buffer.append('\n');
}
StackTraceElement[] trace = throwable.getStackTrace();
for (int i = 0; i < trace.length; i++) {
buffer.append("\tat ");
buffer.append(trace[i].toString());
buffer.append('\n');
}
for (Throwable suppressed : ((Throwable) throwable).getSuppressed()) {
buffer.append("Suppressed: ");
buffer.append('\n');
printStackTraceCause(suppressed, locale, buffer);
}
Throwable cause = throwable.getCause();
if (cause != null) {
buffer.append("Caused by: ");
buffer.append('\n');
printStackTraceCause(cause, locale, buffer);
}
}
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
|
java
|
static void printStackTrace(NlsThrowable throwable, Locale locale, Appendable buffer) {
try {
synchronized (buffer) {
buffer.append(throwable.getClass().getName());
buffer.append(": ");
throwable.getLocalizedMessage(locale, buffer);
buffer.append('\n');
UUID uuid = throwable.getUuid();
if (uuid != null) {
buffer.append(uuid.toString());
buffer.append('\n');
}
StackTraceElement[] trace = throwable.getStackTrace();
for (int i = 0; i < trace.length; i++) {
buffer.append("\tat ");
buffer.append(trace[i].toString());
buffer.append('\n');
}
for (Throwable suppressed : ((Throwable) throwable).getSuppressed()) {
buffer.append("Suppressed: ");
buffer.append('\n');
printStackTraceCause(suppressed, locale, buffer);
}
Throwable cause = throwable.getCause();
if (cause != null) {
buffer.append("Caused by: ");
buffer.append('\n');
printStackTraceCause(cause, locale, buffer);
}
}
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
|
[
"static",
"void",
"printStackTrace",
"(",
"NlsThrowable",
"throwable",
",",
"Locale",
"locale",
",",
"Appendable",
"buffer",
")",
"{",
"try",
"{",
"synchronized",
"(",
"buffer",
")",
"{",
"buffer",
".",
"append",
"(",
"throwable",
".",
"getClass",
"(",
")",
".",
"getName",
"(",
")",
")",
";",
"buffer",
".",
"append",
"(",
"\": \"",
")",
";",
"throwable",
".",
"getLocalizedMessage",
"(",
"locale",
",",
"buffer",
")",
";",
"buffer",
".",
"append",
"(",
"'",
"'",
")",
";",
"UUID",
"uuid",
"=",
"throwable",
".",
"getUuid",
"(",
")",
";",
"if",
"(",
"uuid",
"!=",
"null",
")",
"{",
"buffer",
".",
"append",
"(",
"uuid",
".",
"toString",
"(",
")",
")",
";",
"buffer",
".",
"append",
"(",
"'",
"'",
")",
";",
"}",
"StackTraceElement",
"[",
"]",
"trace",
"=",
"throwable",
".",
"getStackTrace",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"trace",
".",
"length",
";",
"i",
"++",
")",
"{",
"buffer",
".",
"append",
"(",
"\"\\tat \"",
")",
";",
"buffer",
".",
"append",
"(",
"trace",
"[",
"i",
"]",
".",
"toString",
"(",
")",
")",
";",
"buffer",
".",
"append",
"(",
"'",
"'",
")",
";",
"}",
"for",
"(",
"Throwable",
"suppressed",
":",
"(",
"(",
"Throwable",
")",
"throwable",
")",
".",
"getSuppressed",
"(",
")",
")",
"{",
"buffer",
".",
"append",
"(",
"\"Suppressed: \"",
")",
";",
"buffer",
".",
"append",
"(",
"'",
"'",
")",
";",
"printStackTraceCause",
"(",
"suppressed",
",",
"locale",
",",
"buffer",
")",
";",
"}",
"Throwable",
"cause",
"=",
"throwable",
".",
"getCause",
"(",
")",
";",
"if",
"(",
"cause",
"!=",
"null",
")",
"{",
"buffer",
".",
"append",
"(",
"\"Caused by: \"",
")",
";",
"buffer",
".",
"append",
"(",
"'",
"'",
")",
";",
"printStackTraceCause",
"(",
"cause",
",",
"locale",
",",
"buffer",
")",
";",
"}",
"}",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"e",
")",
";",
"}",
"}"
] |
@see NlsThrowable#printStackTrace(Locale, Appendable)
@param throwable is the {@link NlsThrowable} to print.
@param locale is the {@link Locale} to translate to.
@param buffer is where to write the stack trace to.
|
[
"@see",
"NlsThrowable#printStackTrace",
"(",
"Locale",
"Appendable",
")"
] |
train
|
https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/gwt/src/main/resources/net/sf/mmm/util/gwt/supersource/net/sf/mmm/util/exception/api/NlsRuntimeException.java#L139-L174
|
threerings/gwt-utils
|
src/main/java/com/threerings/gwt/ui/FormSupport.java
|
FormSupport.setPlaceholderText
|
public <B extends TextBoxBase> B setPlaceholderText (B box, String placeholder)
{
box.getElement().setAttribute("placeholder", placeholder);
return box;
}
|
java
|
public <B extends TextBoxBase> B setPlaceholderText (B box, String placeholder)
{
box.getElement().setAttribute("placeholder", placeholder);
return box;
}
|
[
"public",
"<",
"B",
"extends",
"TextBoxBase",
">",
"B",
"setPlaceholderText",
"(",
"B",
"box",
",",
"String",
"placeholder",
")",
"{",
"box",
".",
"getElement",
"(",
")",
".",
"setAttribute",
"(",
"\"placeholder\"",
",",
"placeholder",
")",
";",
"return",
"box",
";",
"}"
] |
Set the placeholder text to use on the specified form field.
This text will be shown when the field is blank and unfocused.
|
[
"Set",
"the",
"placeholder",
"text",
"to",
"use",
"on",
"the",
"specified",
"form",
"field",
".",
"This",
"text",
"will",
"be",
"shown",
"when",
"the",
"field",
"is",
"blank",
"and",
"unfocused",
"."
] |
train
|
https://github.com/threerings/gwt-utils/blob/31b31a23b667f2a9c683160d77646db259f2aae5/src/main/java/com/threerings/gwt/ui/FormSupport.java#L35-L39
|
aboutsip/pkts
|
pkts-sip/src/main/java/io/pkts/packet/sip/impl/PreConditions.java
|
PreConditions.ifNull
|
public static <T> T ifNull(final T reference, final T defaultValue) {
if (reference == null) {
return defaultValue;
}
return reference;
}
|
java
|
public static <T> T ifNull(final T reference, final T defaultValue) {
if (reference == null) {
return defaultValue;
}
return reference;
}
|
[
"public",
"static",
"<",
"T",
">",
"T",
"ifNull",
"(",
"final",
"T",
"reference",
",",
"final",
"T",
"defaultValue",
")",
"{",
"if",
"(",
"reference",
"==",
"null",
")",
"{",
"return",
"defaultValue",
";",
"}",
"return",
"reference",
";",
"}"
] |
If our reference is null then return a default value instead.
@param reference the thing to check.
@param defaultValue the default value to return if the above reference is null.
@return the reference if not null, otherwise the default value. Note, if your default value
is null as well then you will get back null, since that is what you asked. Chain with
{@link #assertNotNull(Object, String)} if you want to make sure you have a non-null
value for the default value.
|
[
"If",
"our",
"reference",
"is",
"null",
"then",
"return",
"a",
"default",
"value",
"instead",
"."
] |
train
|
https://github.com/aboutsip/pkts/blob/0f06bb0dac76c812187829f580a8d476ca99a1a1/pkts-sip/src/main/java/io/pkts/packet/sip/impl/PreConditions.java#L132-L137
|
google/j2objc
|
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/BasicTimeZone.java
|
BasicTimeZone.hasEquivalentTransitions
|
public boolean hasEquivalentTransitions(TimeZone tz, long start, long end) {
return hasEquivalentTransitions(tz, start, end, false);
}
|
java
|
public boolean hasEquivalentTransitions(TimeZone tz, long start, long end) {
return hasEquivalentTransitions(tz, start, end, false);
}
|
[
"public",
"boolean",
"hasEquivalentTransitions",
"(",
"TimeZone",
"tz",
",",
"long",
"start",
",",
"long",
"end",
")",
"{",
"return",
"hasEquivalentTransitions",
"(",
"tz",
",",
"start",
",",
"end",
",",
"false",
")",
";",
"}"
] |
<strong>[icu]</strong> Checks if the time zone has equivalent transitions in the time range.
This method returns true when all of transition times, from/to standard
offsets and DST savings used by this time zone match the other in the
time range.
<p>Example code:{{@literal @}.jcite android.icu.samples.util.timezone.BasicTimeZoneExample:---hasEquivalentTransitionsExample}
@param tz The instance of <code>TimeZone</code>
@param start The start time of the evaluated time range (inclusive)
@param end The end time of the evaluated time range (inclusive)
@return true if the other time zone has the equivalent transitions in the
time range. When tz is not a <code>BasicTimeZone</code>, this method
returns false.
|
[
"<strong",
">",
"[",
"icu",
"]",
"<",
"/",
"strong",
">",
"Checks",
"if",
"the",
"time",
"zone",
"has",
"equivalent",
"transitions",
"in",
"the",
"time",
"range",
".",
"This",
"method",
"returns",
"true",
"when",
"all",
"of",
"transition",
"times",
"from",
"/",
"to",
"standard",
"offsets",
"and",
"DST",
"savings",
"used",
"by",
"this",
"time",
"zone",
"match",
"the",
"other",
"in",
"the",
"time",
"range",
".",
"<p",
">",
"Example",
"code",
":",
"{{",
"@literal",
"@",
"}",
".",
"jcite",
"android",
".",
"icu",
".",
"samples",
".",
"util",
".",
"timezone",
".",
"BasicTimeZoneExample",
":",
"---",
"hasEquivalentTransitionsExample",
"}"
] |
train
|
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/BasicTimeZone.java#L78-L80
|
Appendium/objectlabkit
|
utils/src/main/java/net/objectlab/kit/console/ConsoleMenu.java
|
ConsoleMenu.getInt
|
public static int getInt(final String title, final int defaultValue) {
int opt;
do {
try {
final String val = ConsoleMenu.getString(title + DEFAULT_TITLE + defaultValue + ")");
if (val.length() == 0) {
opt = defaultValue;
} else {
opt = Integer.parseInt(val);
}
} catch (final NumberFormatException e) {
opt = -1;
}
} while (opt == -1);
return opt;
}
|
java
|
public static int getInt(final String title, final int defaultValue) {
int opt;
do {
try {
final String val = ConsoleMenu.getString(title + DEFAULT_TITLE + defaultValue + ")");
if (val.length() == 0) {
opt = defaultValue;
} else {
opt = Integer.parseInt(val);
}
} catch (final NumberFormatException e) {
opt = -1;
}
} while (opt == -1);
return opt;
}
|
[
"public",
"static",
"int",
"getInt",
"(",
"final",
"String",
"title",
",",
"final",
"int",
"defaultValue",
")",
"{",
"int",
"opt",
";",
"do",
"{",
"try",
"{",
"final",
"String",
"val",
"=",
"ConsoleMenu",
".",
"getString",
"(",
"title",
"+",
"DEFAULT_TITLE",
"+",
"defaultValue",
"+",
"\")\"",
")",
";",
"if",
"(",
"val",
".",
"length",
"(",
")",
"==",
"0",
")",
"{",
"opt",
"=",
"defaultValue",
";",
"}",
"else",
"{",
"opt",
"=",
"Integer",
".",
"parseInt",
"(",
"val",
")",
";",
"}",
"}",
"catch",
"(",
"final",
"NumberFormatException",
"e",
")",
"{",
"opt",
"=",
"-",
"1",
";",
"}",
"}",
"while",
"(",
"opt",
"==",
"-",
"1",
")",
";",
"return",
"opt",
";",
"}"
] |
Gets an int from the System.in
@param title for the command line
@param defaultValue defaultValue if title not found
@return int as entered by the user of the console app
|
[
"Gets",
"an",
"int",
"from",
"the",
"System",
".",
"in"
] |
train
|
https://github.com/Appendium/objectlabkit/blob/cd649bce7a32e4e926520e62cb765f3b1d451594/utils/src/main/java/net/objectlab/kit/console/ConsoleMenu.java#L218-L235
|
threerings/nenya
|
core/src/main/java/com/threerings/miso/util/MisoUtil.java
|
MisoUtil.screenToFull
|
public static Point screenToFull (
MisoSceneMetrics metrics, int sx, int sy, Point fpos)
{
// get the tile coordinates
Point tpos = new Point();
screenToTile(metrics, sx, sy, tpos);
// get the screen coordinates for the containing tile
Point spos = tileToScreen(metrics, tpos.x, tpos.y, new Point());
// Log.info("Screen to full " +
// "[screen=" + StringUtil.coordsToString(sx, sy) +
// ", tpos=" + StringUtil.toString(tpos) +
// ", spos=" + StringUtil.toString(spos) +
// ", fpix=" + StringUtil.coordsToString(
// sx-spos.x, sy-spos.y) + "].");
// get the fine coordinates within the containing tile
pixelToFine(metrics, sx - spos.x, sy - spos.y, fpos);
// toss in the tile coordinates for good measure
fpos.x += (tpos.x * FULL_TILE_FACTOR);
fpos.y += (tpos.y * FULL_TILE_FACTOR);
return fpos;
}
|
java
|
public static Point screenToFull (
MisoSceneMetrics metrics, int sx, int sy, Point fpos)
{
// get the tile coordinates
Point tpos = new Point();
screenToTile(metrics, sx, sy, tpos);
// get the screen coordinates for the containing tile
Point spos = tileToScreen(metrics, tpos.x, tpos.y, new Point());
// Log.info("Screen to full " +
// "[screen=" + StringUtil.coordsToString(sx, sy) +
// ", tpos=" + StringUtil.toString(tpos) +
// ", spos=" + StringUtil.toString(spos) +
// ", fpix=" + StringUtil.coordsToString(
// sx-spos.x, sy-spos.y) + "].");
// get the fine coordinates within the containing tile
pixelToFine(metrics, sx - spos.x, sy - spos.y, fpos);
// toss in the tile coordinates for good measure
fpos.x += (tpos.x * FULL_TILE_FACTOR);
fpos.y += (tpos.y * FULL_TILE_FACTOR);
return fpos;
}
|
[
"public",
"static",
"Point",
"screenToFull",
"(",
"MisoSceneMetrics",
"metrics",
",",
"int",
"sx",
",",
"int",
"sy",
",",
"Point",
"fpos",
")",
"{",
"// get the tile coordinates",
"Point",
"tpos",
"=",
"new",
"Point",
"(",
")",
";",
"screenToTile",
"(",
"metrics",
",",
"sx",
",",
"sy",
",",
"tpos",
")",
";",
"// get the screen coordinates for the containing tile",
"Point",
"spos",
"=",
"tileToScreen",
"(",
"metrics",
",",
"tpos",
".",
"x",
",",
"tpos",
".",
"y",
",",
"new",
"Point",
"(",
")",
")",
";",
"// Log.info(\"Screen to full \" +",
"// \"[screen=\" + StringUtil.coordsToString(sx, sy) +",
"// \", tpos=\" + StringUtil.toString(tpos) +",
"// \", spos=\" + StringUtil.toString(spos) +",
"// \", fpix=\" + StringUtil.coordsToString(",
"// sx-spos.x, sy-spos.y) + \"].\");",
"// get the fine coordinates within the containing tile",
"pixelToFine",
"(",
"metrics",
",",
"sx",
"-",
"spos",
".",
"x",
",",
"sy",
"-",
"spos",
".",
"y",
",",
"fpos",
")",
";",
"// toss in the tile coordinates for good measure",
"fpos",
".",
"x",
"+=",
"(",
"tpos",
".",
"x",
"*",
"FULL_TILE_FACTOR",
")",
";",
"fpos",
".",
"y",
"+=",
"(",
"tpos",
".",
"y",
"*",
"FULL_TILE_FACTOR",
")",
";",
"return",
"fpos",
";",
"}"
] |
Convert the given screen-based pixel coordinates to full
scene-based coordinates that include both the tile coordinates
and the fine coordinates in each dimension. Converted
coordinates are placed in the given point object.
@param sx the screen x-position pixel coordinate.
@param sy the screen y-position pixel coordinate.
@param fpos the point object to place coordinates in.
@return the point passed in to receive the coordinates.
|
[
"Convert",
"the",
"given",
"screen",
"-",
"based",
"pixel",
"coordinates",
"to",
"full",
"scene",
"-",
"based",
"coordinates",
"that",
"include",
"both",
"the",
"tile",
"coordinates",
"and",
"the",
"fine",
"coordinates",
"in",
"each",
"dimension",
".",
"Converted",
"coordinates",
"are",
"placed",
"in",
"the",
"given",
"point",
"object",
"."
] |
train
|
https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/miso/util/MisoUtil.java#L317-L342
|
shrinkwrap/shrinkwrap
|
impl-base/src/main/java/org/jboss/shrinkwrap/impl/base/io/tar/TarBuffer.java
|
TarBuffer.writeRecord
|
public void writeRecord(byte[] buf, int offset) throws IOException {
if (this.debug) {
System.err.println("WriteRecord: recIdx = " + this.currRecIdx + " blkIdx = " + this.currBlkIdx);
}
if (this.outStream == null) {
throw new IOException("writing to an input buffer");
}
if ((offset + this.recordSize) > buf.length) {
throw new IOException("record has length '" + buf.length + "' with offset '" + offset
+ "' which is less than the record size of '" + this.recordSize + "'");
}
if (this.currRecIdx >= this.recsPerBlock) {
this.writeBlock();
}
System.arraycopy(buf, offset, this.blockBuffer, (this.currRecIdx * this.recordSize), this.recordSize);
this.currRecIdx++;
}
|
java
|
public void writeRecord(byte[] buf, int offset) throws IOException {
if (this.debug) {
System.err.println("WriteRecord: recIdx = " + this.currRecIdx + " blkIdx = " + this.currBlkIdx);
}
if (this.outStream == null) {
throw new IOException("writing to an input buffer");
}
if ((offset + this.recordSize) > buf.length) {
throw new IOException("record has length '" + buf.length + "' with offset '" + offset
+ "' which is less than the record size of '" + this.recordSize + "'");
}
if (this.currRecIdx >= this.recsPerBlock) {
this.writeBlock();
}
System.arraycopy(buf, offset, this.blockBuffer, (this.currRecIdx * this.recordSize), this.recordSize);
this.currRecIdx++;
}
|
[
"public",
"void",
"writeRecord",
"(",
"byte",
"[",
"]",
"buf",
",",
"int",
"offset",
")",
"throws",
"IOException",
"{",
"if",
"(",
"this",
".",
"debug",
")",
"{",
"System",
".",
"err",
".",
"println",
"(",
"\"WriteRecord: recIdx = \"",
"+",
"this",
".",
"currRecIdx",
"+",
"\" blkIdx = \"",
"+",
"this",
".",
"currBlkIdx",
")",
";",
"}",
"if",
"(",
"this",
".",
"outStream",
"==",
"null",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"writing to an input buffer\"",
")",
";",
"}",
"if",
"(",
"(",
"offset",
"+",
"this",
".",
"recordSize",
")",
">",
"buf",
".",
"length",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"record has length '\"",
"+",
"buf",
".",
"length",
"+",
"\"' with offset '\"",
"+",
"offset",
"+",
"\"' which is less than the record size of '\"",
"+",
"this",
".",
"recordSize",
"+",
"\"'\"",
")",
";",
"}",
"if",
"(",
"this",
".",
"currRecIdx",
">=",
"this",
".",
"recsPerBlock",
")",
"{",
"this",
".",
"writeBlock",
"(",
")",
";",
"}",
"System",
".",
"arraycopy",
"(",
"buf",
",",
"offset",
",",
"this",
".",
"blockBuffer",
",",
"(",
"this",
".",
"currRecIdx",
"*",
"this",
".",
"recordSize",
")",
",",
"this",
".",
"recordSize",
")",
";",
"this",
".",
"currRecIdx",
"++",
";",
"}"
] |
Write an archive record to the archive, where the record may be inside of a larger array buffer. The buffer must
be "offset plus record size" long.
@param buf
The buffer containing the record data to write.
@param offset
The offset of the record data within buf.
|
[
"Write",
"an",
"archive",
"record",
"to",
"the",
"archive",
"where",
"the",
"record",
"may",
"be",
"inside",
"of",
"a",
"larger",
"array",
"buffer",
".",
"The",
"buffer",
"must",
"be",
"offset",
"plus",
"record",
"size",
"long",
"."
] |
train
|
https://github.com/shrinkwrap/shrinkwrap/blob/3f8a1a6d344651428c709a63ebb52d35343c5387/impl-base/src/main/java/org/jboss/shrinkwrap/impl/base/io/tar/TarBuffer.java#L302-L323
|
cloudinary/cloudinary_java
|
cloudinary-core/src/main/java/com/cloudinary/Api.java
|
Api.updateResourcesAccessModeByIds
|
public ApiResponse updateResourcesAccessModeByIds(String accessMode, Iterable<String> publicIds, Map options) throws Exception {
return updateResourcesAccessMode(accessMode, "public_ids", publicIds, options);
}
|
java
|
public ApiResponse updateResourcesAccessModeByIds(String accessMode, Iterable<String> publicIds, Map options) throws Exception {
return updateResourcesAccessMode(accessMode, "public_ids", publicIds, options);
}
|
[
"public",
"ApiResponse",
"updateResourcesAccessModeByIds",
"(",
"String",
"accessMode",
",",
"Iterable",
"<",
"String",
">",
"publicIds",
",",
"Map",
"options",
")",
"throws",
"Exception",
"{",
"return",
"updateResourcesAccessMode",
"(",
"accessMode",
",",
"\"public_ids\"",
",",
"publicIds",
",",
"options",
")",
";",
"}"
] |
Update access mode of one or more resources by publicIds
@param accessMode The new access mode, "public" or "authenticated"
@param publicIds A list of public ids of resources to be updated
@param options additional options
<ul>
<li>resource_type - (default "image") - the type of resources to modify</li>
<li>max_results - optional - the maximum resources to process in a single invocation</li>
<li>next_cursor - optional - provided by a previous call to the method</li>
</ul>
@return a map of the returned values
<ul>
<li>updated - an array of resources</li>
<li>next_cursor - optional - provided if more resources can be processed</li>
</ul>
@throws ApiException an API exception
|
[
"Update",
"access",
"mode",
"of",
"one",
"or",
"more",
"resources",
"by",
"publicIds"
] |
train
|
https://github.com/cloudinary/cloudinary_java/blob/58ee1823180da2dea6a2eb7e5cf00d5a760f8aef/cloudinary-core/src/main/java/com/cloudinary/Api.java#L540-L542
|
groupon/odo
|
proxylib/src/main/java/com/groupon/odo/proxylib/PathOverrideService.java
|
PathOverrideService.setResponseEnabled
|
public void setResponseEnabled(int pathId, boolean enabled, String clientUUID) throws Exception {
PreparedStatement statement = null;
int profileId = EditService.getProfileIdFromPathID(pathId);
try (Connection sqlConnection = sqlService.getConnection()) {
statement = sqlConnection.prepareStatement(
"UPDATE " + Constants.DB_TABLE_REQUEST_RESPONSE +
" SET " + Constants.DB_TABLE_PATH_RESPONSE_ENABLED + "= ?" +
" WHERE " + Constants.GENERIC_PROFILE_ID + "= ?" +
" AND " + Constants.GENERIC_CLIENT_UUID + "= ?" +
" AND " + Constants.REQUEST_RESPONSE_PATH_ID + "= ?"
);
statement.setBoolean(1, enabled);
statement.setInt(2, profileId);
statement.setString(3, clientUUID);
statement.setInt(4, pathId);
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (statement != null) {
statement.close();
}
} catch (Exception e) {
}
}
}
|
java
|
public void setResponseEnabled(int pathId, boolean enabled, String clientUUID) throws Exception {
PreparedStatement statement = null;
int profileId = EditService.getProfileIdFromPathID(pathId);
try (Connection sqlConnection = sqlService.getConnection()) {
statement = sqlConnection.prepareStatement(
"UPDATE " + Constants.DB_TABLE_REQUEST_RESPONSE +
" SET " + Constants.DB_TABLE_PATH_RESPONSE_ENABLED + "= ?" +
" WHERE " + Constants.GENERIC_PROFILE_ID + "= ?" +
" AND " + Constants.GENERIC_CLIENT_UUID + "= ?" +
" AND " + Constants.REQUEST_RESPONSE_PATH_ID + "= ?"
);
statement.setBoolean(1, enabled);
statement.setInt(2, profileId);
statement.setString(3, clientUUID);
statement.setInt(4, pathId);
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (statement != null) {
statement.close();
}
} catch (Exception e) {
}
}
}
|
[
"public",
"void",
"setResponseEnabled",
"(",
"int",
"pathId",
",",
"boolean",
"enabled",
",",
"String",
"clientUUID",
")",
"throws",
"Exception",
"{",
"PreparedStatement",
"statement",
"=",
"null",
";",
"int",
"profileId",
"=",
"EditService",
".",
"getProfileIdFromPathID",
"(",
"pathId",
")",
";",
"try",
"(",
"Connection",
"sqlConnection",
"=",
"sqlService",
".",
"getConnection",
"(",
")",
")",
"{",
"statement",
"=",
"sqlConnection",
".",
"prepareStatement",
"(",
"\"UPDATE \"",
"+",
"Constants",
".",
"DB_TABLE_REQUEST_RESPONSE",
"+",
"\" SET \"",
"+",
"Constants",
".",
"DB_TABLE_PATH_RESPONSE_ENABLED",
"+",
"\"= ?\"",
"+",
"\" WHERE \"",
"+",
"Constants",
".",
"GENERIC_PROFILE_ID",
"+",
"\"= ?\"",
"+",
"\" AND \"",
"+",
"Constants",
".",
"GENERIC_CLIENT_UUID",
"+",
"\"= ?\"",
"+",
"\" AND \"",
"+",
"Constants",
".",
"REQUEST_RESPONSE_PATH_ID",
"+",
"\"= ?\"",
")",
";",
"statement",
".",
"setBoolean",
"(",
"1",
",",
"enabled",
")",
";",
"statement",
".",
"setInt",
"(",
"2",
",",
"profileId",
")",
";",
"statement",
".",
"setString",
"(",
"3",
",",
"clientUUID",
")",
";",
"statement",
".",
"setInt",
"(",
"4",
",",
"pathId",
")",
";",
"statement",
".",
"executeUpdate",
"(",
")",
";",
"}",
"catch",
"(",
"SQLException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"}",
"finally",
"{",
"try",
"{",
"if",
"(",
"statement",
"!=",
"null",
")",
"{",
"statement",
".",
"close",
"(",
")",
";",
"}",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"}",
"}",
"}"
] |
Sets enabled/disabled for a response
@param pathId ID of path
@param enabled 1 for enabled, 0 for disabled
@param clientUUID client ID
@throws Exception exception
|
[
"Sets",
"enabled",
"/",
"disabled",
"for",
"a",
"response"
] |
train
|
https://github.com/groupon/odo/blob/3bae43d5eca8ace036775e5b2d3ed9af1a9ff9b1/proxylib/src/main/java/com/groupon/odo/proxylib/PathOverrideService.java#L1351-L1377
|
icode/ameba
|
src/main/java/ameba/mvc/template/internal/TemplateHelper.java
|
TemplateHelper.getTemplateOutputEncoding
|
public static Charset getTemplateOutputEncoding(Configuration configuration, String suffix) {
final String enc = PropertiesHelper.getValue(configuration.getProperties(), MvcFeature.ENCODING + suffix,
String.class, null);
if (enc == null) {
return DEFAULT_ENCODING;
} else {
return Charset.forName(enc);
}
}
|
java
|
public static Charset getTemplateOutputEncoding(Configuration configuration, String suffix) {
final String enc = PropertiesHelper.getValue(configuration.getProperties(), MvcFeature.ENCODING + suffix,
String.class, null);
if (enc == null) {
return DEFAULT_ENCODING;
} else {
return Charset.forName(enc);
}
}
|
[
"public",
"static",
"Charset",
"getTemplateOutputEncoding",
"(",
"Configuration",
"configuration",
",",
"String",
"suffix",
")",
"{",
"final",
"String",
"enc",
"=",
"PropertiesHelper",
".",
"getValue",
"(",
"configuration",
".",
"getProperties",
"(",
")",
",",
"MvcFeature",
".",
"ENCODING",
"+",
"suffix",
",",
"String",
".",
"class",
",",
"null",
")",
";",
"if",
"(",
"enc",
"==",
"null",
")",
"{",
"return",
"DEFAULT_ENCODING",
";",
"}",
"else",
"{",
"return",
"Charset",
".",
"forName",
"(",
"enc",
")",
";",
"}",
"}"
] |
Get output encoding from configuration.
@param configuration Configuration.
@param suffix Template processor suffix of the
to configuration property {@link org.glassfish.jersey.server.mvc.MvcFeature#ENCODING}.
@return Encoding read from configuration properties or a default encoding if no encoding is configured.
|
[
"Get",
"output",
"encoding",
"from",
"configuration",
"."
] |
train
|
https://github.com/icode/ameba/blob/9d4956e935898e41331b2745e400ef869cd265e0/src/main/java/ameba/mvc/template/internal/TemplateHelper.java#L152-L160
|
google/closure-templates
|
java/src/com/google/template/soy/exprtree/AbstractOperatorNode.java
|
AbstractOperatorNode.getOperandProtectedForPrecHelper
|
private String getOperandProtectedForPrecHelper(int index, boolean shouldProtectEqualPrec) {
int thisOpPrec = operator.getPrecedence();
ExprNode child = getChild(index);
boolean shouldProtect;
if (child instanceof OperatorNode) {
int childOpPrec = ((OperatorNode) child).getOperator().getPrecedence();
shouldProtect = shouldProtectEqualPrec ? childOpPrec <= thisOpPrec : childOpPrec < thisOpPrec;
} else {
shouldProtect = false;
}
if (shouldProtect) {
return "(" + child.toSourceString() + ")";
} else {
return child.toSourceString();
}
}
|
java
|
private String getOperandProtectedForPrecHelper(int index, boolean shouldProtectEqualPrec) {
int thisOpPrec = operator.getPrecedence();
ExprNode child = getChild(index);
boolean shouldProtect;
if (child instanceof OperatorNode) {
int childOpPrec = ((OperatorNode) child).getOperator().getPrecedence();
shouldProtect = shouldProtectEqualPrec ? childOpPrec <= thisOpPrec : childOpPrec < thisOpPrec;
} else {
shouldProtect = false;
}
if (shouldProtect) {
return "(" + child.toSourceString() + ")";
} else {
return child.toSourceString();
}
}
|
[
"private",
"String",
"getOperandProtectedForPrecHelper",
"(",
"int",
"index",
",",
"boolean",
"shouldProtectEqualPrec",
")",
"{",
"int",
"thisOpPrec",
"=",
"operator",
".",
"getPrecedence",
"(",
")",
";",
"ExprNode",
"child",
"=",
"getChild",
"(",
"index",
")",
";",
"boolean",
"shouldProtect",
";",
"if",
"(",
"child",
"instanceof",
"OperatorNode",
")",
"{",
"int",
"childOpPrec",
"=",
"(",
"(",
"OperatorNode",
")",
"child",
")",
".",
"getOperator",
"(",
")",
".",
"getPrecedence",
"(",
")",
";",
"shouldProtect",
"=",
"shouldProtectEqualPrec",
"?",
"childOpPrec",
"<=",
"thisOpPrec",
":",
"childOpPrec",
"<",
"thisOpPrec",
";",
"}",
"else",
"{",
"shouldProtect",
"=",
"false",
";",
"}",
"if",
"(",
"shouldProtect",
")",
"{",
"return",
"\"(\"",
"+",
"child",
".",
"toSourceString",
"(",
")",
"+",
"\")\"",
";",
"}",
"else",
"{",
"return",
"child",
".",
"toSourceString",
"(",
")",
";",
"}",
"}"
] |
Helper for getOperandProtectedForLowerPrec() and getOperandProtectedForLowerOrEqualPrec().
@param index The index of the operand to get.
@param shouldProtectEqualPrec Whether to proect the operand if it is an operator with equal
precedence to this operator.
@return The source string for the operand at the given index, possibly protected by surrounding
parentheses.
|
[
"Helper",
"for",
"getOperandProtectedForLowerPrec",
"()",
"and",
"getOperandProtectedForLowerOrEqualPrec",
"()",
"."
] |
train
|
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/exprtree/AbstractOperatorNode.java#L128-L147
|
ow2-chameleon/fuchsia
|
bases/knx/calimero/src/main/java/tuwien/auto/calimero/dptxlator/DPTXlator.java
|
DPTXlator.setTypeID
|
protected void setTypeID(Map availableTypes, String dptID) throws KNXFormatException
{
final DPT t = (DPT) availableTypes.get(dptID);
if (t == null) {
// don't call logThrow since dpt is not set yet
final String s = "DPT " + dptID + " is not available";
logger.warn(s);
throw new KNXFormatException(s, dptID);
}
dpt = t;
}
|
java
|
protected void setTypeID(Map availableTypes, String dptID) throws KNXFormatException
{
final DPT t = (DPT) availableTypes.get(dptID);
if (t == null) {
// don't call logThrow since dpt is not set yet
final String s = "DPT " + dptID + " is not available";
logger.warn(s);
throw new KNXFormatException(s, dptID);
}
dpt = t;
}
|
[
"protected",
"void",
"setTypeID",
"(",
"Map",
"availableTypes",
",",
"String",
"dptID",
")",
"throws",
"KNXFormatException",
"{",
"final",
"DPT",
"t",
"=",
"(",
"DPT",
")",
"availableTypes",
".",
"get",
"(",
"dptID",
")",
";",
"if",
"(",
"t",
"==",
"null",
")",
"{",
"// don't call logThrow since dpt is not set yet\r",
"final",
"String",
"s",
"=",
"\"DPT \"",
"+",
"dptID",
"+",
"\" is not available\"",
";",
"logger",
".",
"warn",
"(",
"s",
")",
";",
"throw",
"new",
"KNXFormatException",
"(",
"s",
",",
"dptID",
")",
";",
"}",
"dpt",
"=",
"t",
";",
"}"
] |
Sets the DPT for the translator to use for translation, doing a lookup before in
the translator's map containing the available, implemented datapoint types.
<p>
@param availableTypes map of the translator with available, implemented DPTs; the
map key is a dptID string, map value is of type {@link DPT}
@param dptID the ID as string of the datapoint type to set
@throws KNXFormatException on DPT not available
|
[
"Sets",
"the",
"DPT",
"for",
"the",
"translator",
"to",
"use",
"for",
"translation",
"doing",
"a",
"lookup",
"before",
"in",
"the",
"translator",
"s",
"map",
"containing",
"the",
"available",
"implemented",
"datapoint",
"types",
".",
"<p",
">"
] |
train
|
https://github.com/ow2-chameleon/fuchsia/blob/4e9318eadbdeb945e529789f573b45386e619bed/bases/knx/calimero/src/main/java/tuwien/auto/calimero/dptxlator/DPTXlator.java#L405-L415
|
Azure/azure-sdk-for-java
|
cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ListManagementImagesImpl.java
|
ListManagementImagesImpl.addImageUrlInput
|
public Image addImageUrlInput(String listId, String contentType, BodyModelModel imageUrl, AddImageUrlInputOptionalParameter addImageUrlInputOptionalParameter) {
return addImageUrlInputWithServiceResponseAsync(listId, contentType, imageUrl, addImageUrlInputOptionalParameter).toBlocking().single().body();
}
|
java
|
public Image addImageUrlInput(String listId, String contentType, BodyModelModel imageUrl, AddImageUrlInputOptionalParameter addImageUrlInputOptionalParameter) {
return addImageUrlInputWithServiceResponseAsync(listId, contentType, imageUrl, addImageUrlInputOptionalParameter).toBlocking().single().body();
}
|
[
"public",
"Image",
"addImageUrlInput",
"(",
"String",
"listId",
",",
"String",
"contentType",
",",
"BodyModelModel",
"imageUrl",
",",
"AddImageUrlInputOptionalParameter",
"addImageUrlInputOptionalParameter",
")",
"{",
"return",
"addImageUrlInputWithServiceResponseAsync",
"(",
"listId",
",",
"contentType",
",",
"imageUrl",
",",
"addImageUrlInputOptionalParameter",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
"body",
"(",
")",
";",
"}"
] |
Add an image to the list with list Id equal to list Id passed.
@param listId List Id of the image list.
@param contentType The content type.
@param imageUrl The image url.
@param addImageUrlInputOptionalParameter the object representing the optional parameters to be set before calling this API
@throws IllegalArgumentException thrown if parameters fail the validation
@throws APIErrorException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the Image object if successful.
|
[
"Add",
"an",
"image",
"to",
"the",
"list",
"with",
"list",
"Id",
"equal",
"to",
"list",
"Id",
"passed",
"."
] |
train
|
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ListManagementImagesImpl.java#L505-L507
|
Samsung/GearVRf
|
GVRf/Extensions/widgetLib/src/org/gearvrf/widgetlib/widget/layout/basic/LinearLayout.java
|
LinearLayout.isValidLayout
|
protected boolean isValidLayout(Gravity gravity, Orientation orientation) {
boolean isValid = true;
switch (gravity) {
case TOP:
case BOTTOM:
isValid = (!isUnlimitedSize() && orientation == Orientation.VERTICAL);
break;
case LEFT:
case RIGHT:
isValid = (!isUnlimitedSize() && orientation == Orientation.HORIZONTAL);
break;
case FRONT:
case BACK:
isValid = (!isUnlimitedSize() && orientation == Orientation.STACK);
break;
case FILL:
isValid = !isUnlimitedSize();
break;
case CENTER:
break;
default:
isValid = false;
break;
}
if (!isValid) {
Log.w(TAG, "Cannot set the gravity %s and orientation %s - " +
"due to unlimited bounds or incompatibility", gravity, orientation);
}
return isValid;
}
|
java
|
protected boolean isValidLayout(Gravity gravity, Orientation orientation) {
boolean isValid = true;
switch (gravity) {
case TOP:
case BOTTOM:
isValid = (!isUnlimitedSize() && orientation == Orientation.VERTICAL);
break;
case LEFT:
case RIGHT:
isValid = (!isUnlimitedSize() && orientation == Orientation.HORIZONTAL);
break;
case FRONT:
case BACK:
isValid = (!isUnlimitedSize() && orientation == Orientation.STACK);
break;
case FILL:
isValid = !isUnlimitedSize();
break;
case CENTER:
break;
default:
isValid = false;
break;
}
if (!isValid) {
Log.w(TAG, "Cannot set the gravity %s and orientation %s - " +
"due to unlimited bounds or incompatibility", gravity, orientation);
}
return isValid;
}
|
[
"protected",
"boolean",
"isValidLayout",
"(",
"Gravity",
"gravity",
",",
"Orientation",
"orientation",
")",
"{",
"boolean",
"isValid",
"=",
"true",
";",
"switch",
"(",
"gravity",
")",
"{",
"case",
"TOP",
":",
"case",
"BOTTOM",
":",
"isValid",
"=",
"(",
"!",
"isUnlimitedSize",
"(",
")",
"&&",
"orientation",
"==",
"Orientation",
".",
"VERTICAL",
")",
";",
"break",
";",
"case",
"LEFT",
":",
"case",
"RIGHT",
":",
"isValid",
"=",
"(",
"!",
"isUnlimitedSize",
"(",
")",
"&&",
"orientation",
"==",
"Orientation",
".",
"HORIZONTAL",
")",
";",
"break",
";",
"case",
"FRONT",
":",
"case",
"BACK",
":",
"isValid",
"=",
"(",
"!",
"isUnlimitedSize",
"(",
")",
"&&",
"orientation",
"==",
"Orientation",
".",
"STACK",
")",
";",
"break",
";",
"case",
"FILL",
":",
"isValid",
"=",
"!",
"isUnlimitedSize",
"(",
")",
";",
"break",
";",
"case",
"CENTER",
":",
"break",
";",
"default",
":",
"isValid",
"=",
"false",
";",
"break",
";",
"}",
"if",
"(",
"!",
"isValid",
")",
"{",
"Log",
".",
"w",
"(",
"TAG",
",",
"\"Cannot set the gravity %s and orientation %s - \"",
"+",
"\"due to unlimited bounds or incompatibility\"",
",",
"gravity",
",",
"orientation",
")",
";",
"}",
"return",
"isValid",
";",
"}"
] |
Check if the gravity and orientation are not in conflict one with other.
@param gravity
@param orientation
@return true if orientation and gravity can be applied together, false - otherwise
|
[
"Check",
"if",
"the",
"gravity",
"and",
"orientation",
"are",
"not",
"in",
"conflict",
"one",
"with",
"other",
"."
] |
train
|
https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Extensions/widgetLib/src/org/gearvrf/widgetlib/widget/layout/basic/LinearLayout.java#L278-L308
|
inkstand-io/scribble
|
scribble-net/src/main/java/io/inkstand/scribble/net/NetworkMatchers.java
|
NetworkMatchers.remoteDatagramPort
|
public static NetworkPort remoteDatagramPort(String hostname, int port){
return new RemoteNetworkPort(hostname, port, NetworkPort.Type.UDP);
}
|
java
|
public static NetworkPort remoteDatagramPort(String hostname, int port){
return new RemoteNetworkPort(hostname, port, NetworkPort.Type.UDP);
}
|
[
"public",
"static",
"NetworkPort",
"remoteDatagramPort",
"(",
"String",
"hostname",
",",
"int",
"port",
")",
"{",
"return",
"new",
"RemoteNetworkPort",
"(",
"hostname",
",",
"port",
",",
"NetworkPort",
".",
"Type",
".",
"UDP",
")",
";",
"}"
] |
Creates a type-safe udp port pointing ot a remote host and port.
@param hostname
the hostname of the remote host
@param port
the port of the remote host
@return a {@link NetworkPort} instance describing the udp port
|
[
"Creates",
"a",
"type",
"-",
"safe",
"udp",
"port",
"pointing",
"ot",
"a",
"remote",
"host",
"and",
"port",
"."
] |
train
|
https://github.com/inkstand-io/scribble/blob/66e67553bad4b1ff817e1715fd1d3dd833406744/scribble-net/src/main/java/io/inkstand/scribble/net/NetworkMatchers.java#L102-L104
|
google/j2objc
|
jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/AlgorithmId.java
|
AlgorithmId.makeSigAlg
|
public static String makeSigAlg(String digAlg, String encAlg) {
digAlg = digAlg.replace("-", "").toUpperCase(Locale.ENGLISH);
if (digAlg.equalsIgnoreCase("SHA")) digAlg = "SHA1";
encAlg = encAlg.toUpperCase(Locale.ENGLISH);
if (encAlg.equals("EC")) encAlg = "ECDSA";
return digAlg + "with" + encAlg;
}
|
java
|
public static String makeSigAlg(String digAlg, String encAlg) {
digAlg = digAlg.replace("-", "").toUpperCase(Locale.ENGLISH);
if (digAlg.equalsIgnoreCase("SHA")) digAlg = "SHA1";
encAlg = encAlg.toUpperCase(Locale.ENGLISH);
if (encAlg.equals("EC")) encAlg = "ECDSA";
return digAlg + "with" + encAlg;
}
|
[
"public",
"static",
"String",
"makeSigAlg",
"(",
"String",
"digAlg",
",",
"String",
"encAlg",
")",
"{",
"digAlg",
"=",
"digAlg",
".",
"replace",
"(",
"\"-\"",
",",
"\"\"",
")",
".",
"toUpperCase",
"(",
"Locale",
".",
"ENGLISH",
")",
";",
"if",
"(",
"digAlg",
".",
"equalsIgnoreCase",
"(",
"\"SHA\"",
")",
")",
"digAlg",
"=",
"\"SHA1\"",
";",
"encAlg",
"=",
"encAlg",
".",
"toUpperCase",
"(",
"Locale",
".",
"ENGLISH",
")",
";",
"if",
"(",
"encAlg",
".",
"equals",
"(",
"\"EC\"",
")",
")",
"encAlg",
"=",
"\"ECDSA\"",
";",
"return",
"digAlg",
"+",
"\"with\"",
"+",
"encAlg",
";",
"}"
] |
Creates a signature algorithm name from a digest algorithm
name and a encryption algorithm name.
|
[
"Creates",
"a",
"signature",
"algorithm",
"name",
"from",
"a",
"digest",
"algorithm",
"name",
"and",
"a",
"encryption",
"algorithm",
"name",
"."
] |
train
|
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/AlgorithmId.java#L947-L955
|
Crab2died/Excel4J
|
src/main/java/com/github/crab2died/utils/DateUtils.java
|
DateUtils.date2Str
|
public static String date2Str(Date date, String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(date);
}
|
java
|
public static String date2Str(Date date, String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(date);
}
|
[
"public",
"static",
"String",
"date2Str",
"(",
"Date",
"date",
",",
"String",
"format",
")",
"{",
"SimpleDateFormat",
"sdf",
"=",
"new",
"SimpleDateFormat",
"(",
"format",
")",
";",
"return",
"sdf",
".",
"format",
"(",
"date",
")",
";",
"}"
] |
<p>将{@link Date}类型转换为指定格式的字符串</p>
author : Crab2Died
date : 2017年06月02日 15:32:04
@param date {@link Date}类型的时间
@param format 指定格式化类型
@return 返回格式化后的时间字符串
|
[
"<p",
">",
"将",
"{",
"@link",
"Date",
"}",
"类型转换为指定格式的字符串<",
"/",
"p",
">",
"author",
":",
"Crab2Died",
"date",
":",
"2017年06月02日",
"15",
":",
"32",
":",
"04"
] |
train
|
https://github.com/Crab2died/Excel4J/blob/2ab0a3b8226a69ff868c3ead6e724f3a774f5f77/src/main/java/com/github/crab2died/utils/DateUtils.java#L96-L99
|
gosu-lang/gosu-lang
|
gosu-core/src/main/java/gw/internal/gosu/parser/BeanAccess.java
|
BeanAccess.areBeansEqual
|
public static boolean areBeansEqual( Object bean1, Object bean2 )
{
if( bean1 == bean2 )
{
return true;
}
if( bean1 == null || bean2 == null )
{
return false;
}
IType class1 = TypeLoaderAccess.instance().getIntrinsicTypeFromObject( bean1 );
IType class2 = TypeLoaderAccess.instance().getIntrinsicTypeFromObject( bean2 );
if( class1.isAssignableFrom( class2 ) || class2.isAssignableFrom( class1 ) )
{
return bean1.equals( bean2 );
}
if( CommonServices.getEntityAccess().isDomainInstance( bean1 ) ||
CommonServices.getEntityAccess().isDomainInstance( bean2 ) )
{
return CommonServices.getEntityAccess().areBeansEqual( bean1, bean2 );
}
return bean1.equals( bean2 );
}
|
java
|
public static boolean areBeansEqual( Object bean1, Object bean2 )
{
if( bean1 == bean2 )
{
return true;
}
if( bean1 == null || bean2 == null )
{
return false;
}
IType class1 = TypeLoaderAccess.instance().getIntrinsicTypeFromObject( bean1 );
IType class2 = TypeLoaderAccess.instance().getIntrinsicTypeFromObject( bean2 );
if( class1.isAssignableFrom( class2 ) || class2.isAssignableFrom( class1 ) )
{
return bean1.equals( bean2 );
}
if( CommonServices.getEntityAccess().isDomainInstance( bean1 ) ||
CommonServices.getEntityAccess().isDomainInstance( bean2 ) )
{
return CommonServices.getEntityAccess().areBeansEqual( bean1, bean2 );
}
return bean1.equals( bean2 );
}
|
[
"public",
"static",
"boolean",
"areBeansEqual",
"(",
"Object",
"bean1",
",",
"Object",
"bean2",
")",
"{",
"if",
"(",
"bean1",
"==",
"bean2",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"bean1",
"==",
"null",
"||",
"bean2",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"IType",
"class1",
"=",
"TypeLoaderAccess",
".",
"instance",
"(",
")",
".",
"getIntrinsicTypeFromObject",
"(",
"bean1",
")",
";",
"IType",
"class2",
"=",
"TypeLoaderAccess",
".",
"instance",
"(",
")",
".",
"getIntrinsicTypeFromObject",
"(",
"bean2",
")",
";",
"if",
"(",
"class1",
".",
"isAssignableFrom",
"(",
"class2",
")",
"||",
"class2",
".",
"isAssignableFrom",
"(",
"class1",
")",
")",
"{",
"return",
"bean1",
".",
"equals",
"(",
"bean2",
")",
";",
"}",
"if",
"(",
"CommonServices",
".",
"getEntityAccess",
"(",
")",
".",
"isDomainInstance",
"(",
"bean1",
")",
"||",
"CommonServices",
".",
"getEntityAccess",
"(",
")",
".",
"isDomainInstance",
"(",
"bean2",
")",
")",
"{",
"return",
"CommonServices",
".",
"getEntityAccess",
"(",
")",
".",
"areBeansEqual",
"(",
"bean1",
",",
"bean2",
")",
";",
"}",
"return",
"bean1",
".",
"equals",
"(",
"bean2",
")",
";",
"}"
] |
Test for equality between two BeanType values. Note this method is not entirely appropriate for
non-BeanType value i.e., it's not as intelligent as EqualityExpression comparing primitive types,
TypeKeys, etc.
<p/>
Msotly this method is for handling conversion of KeyableBean and Key for comparison.
@param bean1 A value having an IType of BeanType
@param bean2 A value having an IType of BeanType
@return True if the beans are equal
|
[
"Test",
"for",
"equality",
"between",
"two",
"BeanType",
"values",
".",
"Note",
"this",
"method",
"is",
"not",
"entirely",
"appropriate",
"for",
"non",
"-",
"BeanType",
"value",
"i",
".",
"e",
".",
"it",
"s",
"not",
"as",
"intelligent",
"as",
"EqualityExpression",
"comparing",
"primitive",
"types",
"TypeKeys",
"etc",
".",
"<p",
"/",
">",
"Msotly",
"this",
"method",
"is",
"for",
"handling",
"conversion",
"of",
"KeyableBean",
"and",
"Key",
"for",
"comparison",
"."
] |
train
|
https://github.com/gosu-lang/gosu-lang/blob/d6e9261b137ce66fef3726cabe7826d4a1f946b7/gosu-core/src/main/java/gw/internal/gosu/parser/BeanAccess.java#L299-L325
|
Esri/geometry-api-java
|
src/main/java/com/esri/core/geometry/IndexMultiDCList.java
|
IndexMultiDCList.deleteElement
|
int deleteElement(int list, int node) {
int prev = getPrev(node);
int next = getNext(node);
if (prev != nullNode())
setNext_(prev, next);
else
m_lists.setField(list, 0, next);// change head
if (next != nullNode())
setPrev_(next, prev);
else
m_lists.setField(list, 1, prev);// change tail
freeNode_(node);
setListSize_(list, getListSize(list) - 1);
return next;
}
|
java
|
int deleteElement(int list, int node) {
int prev = getPrev(node);
int next = getNext(node);
if (prev != nullNode())
setNext_(prev, next);
else
m_lists.setField(list, 0, next);// change head
if (next != nullNode())
setPrev_(next, prev);
else
m_lists.setField(list, 1, prev);// change tail
freeNode_(node);
setListSize_(list, getListSize(list) - 1);
return next;
}
|
[
"int",
"deleteElement",
"(",
"int",
"list",
",",
"int",
"node",
")",
"{",
"int",
"prev",
"=",
"getPrev",
"(",
"node",
")",
";",
"int",
"next",
"=",
"getNext",
"(",
"node",
")",
";",
"if",
"(",
"prev",
"!=",
"nullNode",
"(",
")",
")",
"setNext_",
"(",
"prev",
",",
"next",
")",
";",
"else",
"m_lists",
".",
"setField",
"(",
"list",
",",
"0",
",",
"next",
")",
";",
"// change head",
"if",
"(",
"next",
"!=",
"nullNode",
"(",
")",
")",
"setPrev_",
"(",
"next",
",",
"prev",
")",
";",
"else",
"m_lists",
".",
"setField",
"(",
"list",
",",
"1",
",",
"prev",
")",
";",
"// change tail",
"freeNode_",
"(",
"node",
")",
";",
"setListSize_",
"(",
"list",
",",
"getListSize",
"(",
"list",
")",
"-",
"1",
")",
";",
"return",
"next",
";",
"}"
] |
Deletes a node from a list. Returns the next node after the deleted one.
|
[
"Deletes",
"a",
"node",
"from",
"a",
"list",
".",
"Returns",
"the",
"next",
"node",
"after",
"the",
"deleted",
"one",
"."
] |
train
|
https://github.com/Esri/geometry-api-java/blob/494da8ec953d76e7c6072afbc081abfe48ff07cf/src/main/java/com/esri/core/geometry/IndexMultiDCList.java#L199-L214
|
ineunetOS/knife-commons
|
knife-commons-utils/src/main/java/com/ineunet/knife/util/DateUtils.java
|
DateUtils.getPeriodDays
|
public static int getPeriodDays(Date start, Date end) {
try {
start = FORMAT_DATE_.parse(FORMAT_DATE_.format(start));
end = FORMAT_DATE_.parse(FORMAT_DATE_.format(end));
Calendar cal = Calendar.getInstance();
cal.setTime(start);
long time1 = cal.getTimeInMillis();
cal.setTime(end);
long time2 = cal.getTimeInMillis();
long between_days = (time2 - time1) / (1000 * 3600 * 24);
return Integer.parseInt(String.valueOf(between_days));
} catch (Exception e) {
throw new KnifeUtilsException(e);
}
}
|
java
|
public static int getPeriodDays(Date start, Date end) {
try {
start = FORMAT_DATE_.parse(FORMAT_DATE_.format(start));
end = FORMAT_DATE_.parse(FORMAT_DATE_.format(end));
Calendar cal = Calendar.getInstance();
cal.setTime(start);
long time1 = cal.getTimeInMillis();
cal.setTime(end);
long time2 = cal.getTimeInMillis();
long between_days = (time2 - time1) / (1000 * 3600 * 24);
return Integer.parseInt(String.valueOf(between_days));
} catch (Exception e) {
throw new KnifeUtilsException(e);
}
}
|
[
"public",
"static",
"int",
"getPeriodDays",
"(",
"Date",
"start",
",",
"Date",
"end",
")",
"{",
"try",
"{",
"start",
"=",
"FORMAT_DATE_",
".",
"parse",
"(",
"FORMAT_DATE_",
".",
"format",
"(",
"start",
")",
")",
";",
"end",
"=",
"FORMAT_DATE_",
".",
"parse",
"(",
"FORMAT_DATE_",
".",
"format",
"(",
"end",
")",
")",
";",
"Calendar",
"cal",
"=",
"Calendar",
".",
"getInstance",
"(",
")",
";",
"cal",
".",
"setTime",
"(",
"start",
")",
";",
"long",
"time1",
"=",
"cal",
".",
"getTimeInMillis",
"(",
")",
";",
"cal",
".",
"setTime",
"(",
"end",
")",
";",
"long",
"time2",
"=",
"cal",
".",
"getTimeInMillis",
"(",
")",
";",
"long",
"between_days",
"=",
"(",
"time2",
"-",
"time1",
")",
"/",
"(",
"1000",
"*",
"3600",
"*",
"24",
")",
";",
"return",
"Integer",
".",
"parseInt",
"(",
"String",
".",
"valueOf",
"(",
"between_days",
")",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"KnifeUtilsException",
"(",
"e",
")",
";",
"}",
"}"
] |
计算两个日期之间相差的天数
@param start 较小的时间
@param end 较大的时间
@return 相差天数
@since 2.0.2
|
[
"计算两个日期之间相差的天数"
] |
train
|
https://github.com/ineunetOS/knife-commons/blob/eae9e59afa020a00ae8977c10d43ac8ae46ae236/knife-commons-utils/src/main/java/com/ineunet/knife/util/DateUtils.java#L244-L258
|
palatable/lambda
|
src/main/java/com/jnape/palatable/lambda/adt/Maybe.java
|
Maybe.orElseThrow
|
public final <E extends Throwable> A orElseThrow(Supplier<E> throwableSupplier) throws E {
return orElseGet((CheckedSupplier<E, A>) () -> {
throw throwableSupplier.get();
});
}
|
java
|
public final <E extends Throwable> A orElseThrow(Supplier<E> throwableSupplier) throws E {
return orElseGet((CheckedSupplier<E, A>) () -> {
throw throwableSupplier.get();
});
}
|
[
"public",
"final",
"<",
"E",
"extends",
"Throwable",
">",
"A",
"orElseThrow",
"(",
"Supplier",
"<",
"E",
">",
"throwableSupplier",
")",
"throws",
"E",
"{",
"return",
"orElseGet",
"(",
"(",
"CheckedSupplier",
"<",
"E",
",",
"A",
">",
")",
"(",
")",
"->",
"{",
"throw",
"throwableSupplier",
".",
"get",
"(",
")",
";",
"}",
")",
";",
"}"
] |
If the value is present, return it; otherwise, throw the {@link Throwable} supplied by
<code>throwableSupplier</code>.
@param throwableSupplier the supplier of the potentially thrown {@link Throwable}
@param <E> the Throwable type
@return the value, if present
@throws E the throwable, if the value is absent
|
[
"If",
"the",
"value",
"is",
"present",
"return",
"it",
";",
"otherwise",
"throw",
"the",
"{",
"@link",
"Throwable",
"}",
"supplied",
"by",
"<code",
">",
"throwableSupplier<",
"/",
"code",
">",
"."
] |
train
|
https://github.com/palatable/lambda/blob/b643ba836c5916d1d8193822e5efb4e7b40c489a/src/main/java/com/jnape/palatable/lambda/adt/Maybe.java#L72-L76
|
streamsets/datacollector-api
|
src/main/java/com/streamsets/pipeline/api/impl/Utils.java
|
Utils.checkArgument
|
public static void checkArgument(boolean expression, @Nullable Object msg) {
if (!expression) {
throw new IllegalArgumentException(String.valueOf(msg));
}
}
|
java
|
public static void checkArgument(boolean expression, @Nullable Object msg) {
if (!expression) {
throw new IllegalArgumentException(String.valueOf(msg));
}
}
|
[
"public",
"static",
"void",
"checkArgument",
"(",
"boolean",
"expression",
",",
"@",
"Nullable",
"Object",
"msg",
")",
"{",
"if",
"(",
"!",
"expression",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"String",
".",
"valueOf",
"(",
"msg",
")",
")",
";",
"}",
"}"
] |
Ensures the truth of an expression involving one or more parameters to the calling method.
@param expression a boolean expression
@param msg the exception message to use if the check fails; will be converted to a
string using {@link String#valueOf(Object)}
@throws IllegalArgumentException if {@code expression} is false
|
[
"Ensures",
"the",
"truth",
"of",
"an",
"expression",
"involving",
"one",
"or",
"more",
"parameters",
"to",
"the",
"calling",
"method",
"."
] |
train
|
https://github.com/streamsets/datacollector-api/blob/ac832a97bea2fcef11f50fac6746e85019adad58/src/main/java/com/streamsets/pipeline/api/impl/Utils.java#L70-L74
|
omadahealth/TypefaceView
|
lib/src/main/java/com/github/omadahealth/typefaceview/TypefaceEditText.java
|
TypefaceEditText.setCustomTypeface
|
@BindingAdapter("bind:tv_typeface")
public static void setCustomTypeface(TypefaceEditText editText, String type) {
editText.mCurrentTypeface = TypefaceType.getTypeface(type != null ? type : "");
Typeface typeface = getFont(editText.getContext(), editText.mCurrentTypeface.getAssetFileName());
editText.setTypeface(typeface);
}
|
java
|
@BindingAdapter("bind:tv_typeface")
public static void setCustomTypeface(TypefaceEditText editText, String type) {
editText.mCurrentTypeface = TypefaceType.getTypeface(type != null ? type : "");
Typeface typeface = getFont(editText.getContext(), editText.mCurrentTypeface.getAssetFileName());
editText.setTypeface(typeface);
}
|
[
"@",
"BindingAdapter",
"(",
"\"bind:tv_typeface\"",
")",
"public",
"static",
"void",
"setCustomTypeface",
"(",
"TypefaceEditText",
"editText",
",",
"String",
"type",
")",
"{",
"editText",
".",
"mCurrentTypeface",
"=",
"TypefaceType",
".",
"getTypeface",
"(",
"type",
"!=",
"null",
"?",
"type",
":",
"\"\"",
")",
";",
"Typeface",
"typeface",
"=",
"getFont",
"(",
"editText",
".",
"getContext",
"(",
")",
",",
"editText",
".",
"mCurrentTypeface",
".",
"getAssetFileName",
"(",
")",
")",
";",
"editText",
".",
"setTypeface",
"(",
"typeface",
")",
";",
"}"
] |
Data-binding method for custom attribute bind:tv_typeface to be set
@param editText The instance of the object to set value on
@param type The string name of the typeface, same as in xml
|
[
"Data",
"-",
"binding",
"method",
"for",
"custom",
"attribute",
"bind",
":",
"tv_typeface",
"to",
"be",
"set"
] |
train
|
https://github.com/omadahealth/TypefaceView/blob/9a36a67b0fb26584c3e20a24f8f0bafad6a0badd/lib/src/main/java/com/github/omadahealth/typefaceview/TypefaceEditText.java#L120-L125
|
algolia/instantsearch-android
|
core/src/main/java/com/algolia/instantsearch/core/helpers/Searcher.java
|
Searcher.updateFacetRefinement
|
@NonNull
public Searcher updateFacetRefinement(@NonNull String attribute, @NonNull String value, boolean active) {
if (active) {
addFacetRefinement(attribute, value);
} else {
removeFacetRefinement(attribute, value);
}
return this;
}
|
java
|
@NonNull
public Searcher updateFacetRefinement(@NonNull String attribute, @NonNull String value, boolean active) {
if (active) {
addFacetRefinement(attribute, value);
} else {
removeFacetRefinement(attribute, value);
}
return this;
}
|
[
"@",
"NonNull",
"public",
"Searcher",
"updateFacetRefinement",
"(",
"@",
"NonNull",
"String",
"attribute",
",",
"@",
"NonNull",
"String",
"value",
",",
"boolean",
"active",
")",
"{",
"if",
"(",
"active",
")",
"{",
"addFacetRefinement",
"(",
"attribute",
",",
"value",
")",
";",
"}",
"else",
"{",
"removeFacetRefinement",
"(",
"attribute",
",",
"value",
")",
";",
"}",
"return",
"this",
";",
"}"
] |
Adds or removes this facet refinement for the next queries according to its enabled status.
@param attribute the attribute to facet on.
@param value the value for this attribute.
@param active if {@code true}, this facet value is currently refined on.
@return this {@link Searcher} for chaining.
|
[
"Adds",
"or",
"removes",
"this",
"facet",
"refinement",
"for",
"the",
"next",
"queries",
"according",
"to",
"its",
"enabled",
"status",
"."
] |
train
|
https://github.com/algolia/instantsearch-android/blob/12092ec30140df9ffc2bf916339b433372034616/core/src/main/java/com/algolia/instantsearch/core/helpers/Searcher.java#L607-L615
|
Deep-Symmetry/beat-link
|
src/main/java/org/deepsymmetry/beatlink/data/MetadataFinder.java
|
MetadataFinder.requestMetadataFrom
|
@SuppressWarnings("WeakerAccess")
public TrackMetadata requestMetadataFrom(final DataReference track, final CdjStatus.TrackType trackType) {
return requestMetadataInternal(track, trackType, false);
}
|
java
|
@SuppressWarnings("WeakerAccess")
public TrackMetadata requestMetadataFrom(final DataReference track, final CdjStatus.TrackType trackType) {
return requestMetadataInternal(track, trackType, false);
}
|
[
"@",
"SuppressWarnings",
"(",
"\"WeakerAccess\"",
")",
"public",
"TrackMetadata",
"requestMetadataFrom",
"(",
"final",
"DataReference",
"track",
",",
"final",
"CdjStatus",
".",
"TrackType",
"trackType",
")",
"{",
"return",
"requestMetadataInternal",
"(",
"track",
",",
"trackType",
",",
"false",
")",
";",
"}"
] |
Ask the specified player for metadata about the track in the specified slot with the specified rekordbox ID,
unless we have a metadata cache available for the specified media slot, in which case that will be used instead.
@param track uniquely identifies the track whose metadata is desired
@param trackType identifies the type of track being requested, which affects the type of metadata request
message that must be used
@return the metadata, if any
|
[
"Ask",
"the",
"specified",
"player",
"for",
"metadata",
"about",
"the",
"track",
"in",
"the",
"specified",
"slot",
"with",
"the",
"specified",
"rekordbox",
"ID",
"unless",
"we",
"have",
"a",
"metadata",
"cache",
"available",
"for",
"the",
"specified",
"media",
"slot",
"in",
"which",
"case",
"that",
"will",
"be",
"used",
"instead",
"."
] |
train
|
https://github.com/Deep-Symmetry/beat-link/blob/f958a2a70e8a87a31a75326d7b4db77c2f0b4212/src/main/java/org/deepsymmetry/beatlink/data/MetadataFinder.java#L73-L76
|
gmessner/gitlab4j-api
|
src/main/java/org/gitlab4j/api/RepositoryFileApi.java
|
RepositoryFileApi.getRawFile
|
public InputStream getRawFile(Object projectIdOrPath, String commitOrBranchName, String filepath) throws GitLabApiException {
if (isApiVersion(ApiVersion.V3)) {
Form formData = new GitLabApiForm().withParam("file_path", filepath, true);
Response response = getWithAccepts(Response.Status.OK, formData.asMap(), MediaType.MEDIA_TYPE_WILDCARD,
"projects", getProjectIdOrPath(projectIdOrPath), "repository", "blobs", commitOrBranchName);
return (response.readEntity(InputStream.class));
} else {
Form formData = new GitLabApiForm().withParam("ref", commitOrBranchName, true);
Response response = getWithAccepts(Response.Status.OK, formData.asMap(), MediaType.MEDIA_TYPE_WILDCARD,
"projects", getProjectIdOrPath(projectIdOrPath), "repository", "files", urlEncode(filepath), "raw");
return (response.readEntity(InputStream.class));
}
}
|
java
|
public InputStream getRawFile(Object projectIdOrPath, String commitOrBranchName, String filepath) throws GitLabApiException {
if (isApiVersion(ApiVersion.V3)) {
Form formData = new GitLabApiForm().withParam("file_path", filepath, true);
Response response = getWithAccepts(Response.Status.OK, formData.asMap(), MediaType.MEDIA_TYPE_WILDCARD,
"projects", getProjectIdOrPath(projectIdOrPath), "repository", "blobs", commitOrBranchName);
return (response.readEntity(InputStream.class));
} else {
Form formData = new GitLabApiForm().withParam("ref", commitOrBranchName, true);
Response response = getWithAccepts(Response.Status.OK, formData.asMap(), MediaType.MEDIA_TYPE_WILDCARD,
"projects", getProjectIdOrPath(projectIdOrPath), "repository", "files", urlEncode(filepath), "raw");
return (response.readEntity(InputStream.class));
}
}
|
[
"public",
"InputStream",
"getRawFile",
"(",
"Object",
"projectIdOrPath",
",",
"String",
"commitOrBranchName",
",",
"String",
"filepath",
")",
"throws",
"GitLabApiException",
"{",
"if",
"(",
"isApiVersion",
"(",
"ApiVersion",
".",
"V3",
")",
")",
"{",
"Form",
"formData",
"=",
"new",
"GitLabApiForm",
"(",
")",
".",
"withParam",
"(",
"\"file_path\"",
",",
"filepath",
",",
"true",
")",
";",
"Response",
"response",
"=",
"getWithAccepts",
"(",
"Response",
".",
"Status",
".",
"OK",
",",
"formData",
".",
"asMap",
"(",
")",
",",
"MediaType",
".",
"MEDIA_TYPE_WILDCARD",
",",
"\"projects\"",
",",
"getProjectIdOrPath",
"(",
"projectIdOrPath",
")",
",",
"\"repository\"",
",",
"\"blobs\"",
",",
"commitOrBranchName",
")",
";",
"return",
"(",
"response",
".",
"readEntity",
"(",
"InputStream",
".",
"class",
")",
")",
";",
"}",
"else",
"{",
"Form",
"formData",
"=",
"new",
"GitLabApiForm",
"(",
")",
".",
"withParam",
"(",
"\"ref\"",
",",
"commitOrBranchName",
",",
"true",
")",
";",
"Response",
"response",
"=",
"getWithAccepts",
"(",
"Response",
".",
"Status",
".",
"OK",
",",
"formData",
".",
"asMap",
"(",
")",
",",
"MediaType",
".",
"MEDIA_TYPE_WILDCARD",
",",
"\"projects\"",
",",
"getProjectIdOrPath",
"(",
"projectIdOrPath",
")",
",",
"\"repository\"",
",",
"\"files\"",
",",
"urlEncode",
"(",
"filepath",
")",
",",
"\"raw\"",
")",
";",
"return",
"(",
"response",
".",
"readEntity",
"(",
"InputStream",
".",
"class",
")",
")",
";",
"}",
"}"
] |
Get the raw file contents for a file by commit sha and path.
V3:
<pre><code>GitLab Endpoint: GET /projects/:id/repository/blobs/:sha</code></pre>
V4:
<pre><code>GitLab Endpoint: GET /projects/:id/repository/files/:filepath</code></pre>
@param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
@param commitOrBranchName the commit or branch name to get the file contents for
@param filepath the path of the file to get
@return an InputStream to read the raw file from
@throws GitLabApiException if any exception occurs
|
[
"Get",
"the",
"raw",
"file",
"contents",
"for",
"a",
"file",
"by",
"commit",
"sha",
"and",
"path",
"."
] |
train
|
https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/RepositoryFileApi.java#L415-L428
|
sarl/sarl
|
sre/io.janusproject/io.janusproject.plugin/src/io/janusproject/kernel/services/jdk/contextspace/SpaceRepository.java
|
SpaceRepository.fireSpaceAdded
|
protected void fireSpaceAdded(Space space, boolean isLocalCreation) {
if (this.externalListener != null) {
this.externalListener.spaceCreated(space, isLocalCreation);
}
}
|
java
|
protected void fireSpaceAdded(Space space, boolean isLocalCreation) {
if (this.externalListener != null) {
this.externalListener.spaceCreated(space, isLocalCreation);
}
}
|
[
"protected",
"void",
"fireSpaceAdded",
"(",
"Space",
"space",
",",
"boolean",
"isLocalCreation",
")",
"{",
"if",
"(",
"this",
".",
"externalListener",
"!=",
"null",
")",
"{",
"this",
".",
"externalListener",
".",
"spaceCreated",
"(",
"space",
",",
"isLocalCreation",
")",
";",
"}",
"}"
] |
Notifies the listeners on the space creation.
@param space the created space.
@param isLocalCreation indicates if the creation of the space was initiated on the current kernel.
|
[
"Notifies",
"the",
"listeners",
"on",
"the",
"space",
"creation",
"."
] |
train
|
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/sre/io.janusproject/io.janusproject.plugin/src/io/janusproject/kernel/services/jdk/contextspace/SpaceRepository.java#L383-L387
|
fnklabs/draenei
|
src/main/java/com/fnklabs/draenei/orm/EntityMetadata.java
|
EntityMetadata.buildEntityMetadata
|
static <V> EntityMetadata buildEntityMetadata(@NotNull Class<V> clazz, @NotNull CassandraClient cassandraClient) throws MetadataException {
Table tableAnnotation = clazz.getAnnotation(Table.class);
if (tableAnnotation == null) {
throw new MetadataException(String.format("Table annotation is missing for %s", clazz.getName()));
}
String tableKeyspace = StringUtils.isEmpty(tableAnnotation.keyspace()) ? cassandraClient.getDefaultKeyspace() : tableAnnotation.keyspace();
String tableName = tableAnnotation.name();
TableMetadata tableMetadata = cassandraClient.getTableMetadata(tableKeyspace, tableName);
EntityMetadata entityMetadata = new EntityMetadata(
tableName,
tableKeyspace,
tableAnnotation.compactStorage(),
tableAnnotation.fetchSize(),
tableAnnotation.readConsistencyLevel(),
tableAnnotation.writeConsistencyLevel(),
tableMetadata
);
try {
BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
for (PropertyDescriptor propertyDescriptor : beanInfo.getPropertyDescriptors()) {
ColumnMetadata columnMetadata = buildColumnMetadata(propertyDescriptor, clazz, cassandraClient, tableMetadata);
if (columnMetadata != null) {
entityMetadata.addColumnMetadata(columnMetadata);
}
LOGGER.debug("Property descriptor: {} {}", propertyDescriptor.getName(), propertyDescriptor.getDisplayName());
}
} catch (IntrospectionException e) {
LOGGER.warn("Can't build column metadata", e);
}
EntityMetadata.validate(entityMetadata);
return entityMetadata;
}
|
java
|
static <V> EntityMetadata buildEntityMetadata(@NotNull Class<V> clazz, @NotNull CassandraClient cassandraClient) throws MetadataException {
Table tableAnnotation = clazz.getAnnotation(Table.class);
if (tableAnnotation == null) {
throw new MetadataException(String.format("Table annotation is missing for %s", clazz.getName()));
}
String tableKeyspace = StringUtils.isEmpty(tableAnnotation.keyspace()) ? cassandraClient.getDefaultKeyspace() : tableAnnotation.keyspace();
String tableName = tableAnnotation.name();
TableMetadata tableMetadata = cassandraClient.getTableMetadata(tableKeyspace, tableName);
EntityMetadata entityMetadata = new EntityMetadata(
tableName,
tableKeyspace,
tableAnnotation.compactStorage(),
tableAnnotation.fetchSize(),
tableAnnotation.readConsistencyLevel(),
tableAnnotation.writeConsistencyLevel(),
tableMetadata
);
try {
BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
for (PropertyDescriptor propertyDescriptor : beanInfo.getPropertyDescriptors()) {
ColumnMetadata columnMetadata = buildColumnMetadata(propertyDescriptor, clazz, cassandraClient, tableMetadata);
if (columnMetadata != null) {
entityMetadata.addColumnMetadata(columnMetadata);
}
LOGGER.debug("Property descriptor: {} {}", propertyDescriptor.getName(), propertyDescriptor.getDisplayName());
}
} catch (IntrospectionException e) {
LOGGER.warn("Can't build column metadata", e);
}
EntityMetadata.validate(entityMetadata);
return entityMetadata;
}
|
[
"static",
"<",
"V",
">",
"EntityMetadata",
"buildEntityMetadata",
"(",
"@",
"NotNull",
"Class",
"<",
"V",
">",
"clazz",
",",
"@",
"NotNull",
"CassandraClient",
"cassandraClient",
")",
"throws",
"MetadataException",
"{",
"Table",
"tableAnnotation",
"=",
"clazz",
".",
"getAnnotation",
"(",
"Table",
".",
"class",
")",
";",
"if",
"(",
"tableAnnotation",
"==",
"null",
")",
"{",
"throw",
"new",
"MetadataException",
"(",
"String",
".",
"format",
"(",
"\"Table annotation is missing for %s\"",
",",
"clazz",
".",
"getName",
"(",
")",
")",
")",
";",
"}",
"String",
"tableKeyspace",
"=",
"StringUtils",
".",
"isEmpty",
"(",
"tableAnnotation",
".",
"keyspace",
"(",
")",
")",
"?",
"cassandraClient",
".",
"getDefaultKeyspace",
"(",
")",
":",
"tableAnnotation",
".",
"keyspace",
"(",
")",
";",
"String",
"tableName",
"=",
"tableAnnotation",
".",
"name",
"(",
")",
";",
"TableMetadata",
"tableMetadata",
"=",
"cassandraClient",
".",
"getTableMetadata",
"(",
"tableKeyspace",
",",
"tableName",
")",
";",
"EntityMetadata",
"entityMetadata",
"=",
"new",
"EntityMetadata",
"(",
"tableName",
",",
"tableKeyspace",
",",
"tableAnnotation",
".",
"compactStorage",
"(",
")",
",",
"tableAnnotation",
".",
"fetchSize",
"(",
")",
",",
"tableAnnotation",
".",
"readConsistencyLevel",
"(",
")",
",",
"tableAnnotation",
".",
"writeConsistencyLevel",
"(",
")",
",",
"tableMetadata",
")",
";",
"try",
"{",
"BeanInfo",
"beanInfo",
"=",
"Introspector",
".",
"getBeanInfo",
"(",
"clazz",
")",
";",
"for",
"(",
"PropertyDescriptor",
"propertyDescriptor",
":",
"beanInfo",
".",
"getPropertyDescriptors",
"(",
")",
")",
"{",
"ColumnMetadata",
"columnMetadata",
"=",
"buildColumnMetadata",
"(",
"propertyDescriptor",
",",
"clazz",
",",
"cassandraClient",
",",
"tableMetadata",
")",
";",
"if",
"(",
"columnMetadata",
"!=",
"null",
")",
"{",
"entityMetadata",
".",
"addColumnMetadata",
"(",
"columnMetadata",
")",
";",
"}",
"LOGGER",
".",
"debug",
"(",
"\"Property descriptor: {} {}\"",
",",
"propertyDescriptor",
".",
"getName",
"(",
")",
",",
"propertyDescriptor",
".",
"getDisplayName",
"(",
")",
")",
";",
"}",
"}",
"catch",
"(",
"IntrospectionException",
"e",
")",
"{",
"LOGGER",
".",
"warn",
"(",
"\"Can't build column metadata\"",
",",
"e",
")",
";",
"}",
"EntityMetadata",
".",
"validate",
"(",
"entityMetadata",
")",
";",
"return",
"entityMetadata",
";",
"}"
] |
Build cassandra entity metadata
@param clazz Entity class
@param cassandraClient Cassandra Client from which will be retrieved table information
@param <V> Entity class type
@return Entity metadata
@throws MetadataException
|
[
"Build",
"cassandra",
"entity",
"metadata"
] |
train
|
https://github.com/fnklabs/draenei/blob/0a8cac54f1f635be3e2950375a23291d38453ae8/src/main/java/com/fnklabs/draenei/orm/EntityMetadata.java#L189-L232
|
facebookarchive/hive-dwrf
|
hive-dwrf/src/main/java/com/facebook/hive/orc/lazy/LazyTreeReader.java
|
LazyTreeReader.loadIndeces
|
public int loadIndeces(List<RowIndexEntry> rowIndexEntries, int startIndex) {
if (present != null) {
return present.loadIndeces(rowIndexEntries, startIndex);
} else {
return startIndex;
}
}
|
java
|
public int loadIndeces(List<RowIndexEntry> rowIndexEntries, int startIndex) {
if (present != null) {
return present.loadIndeces(rowIndexEntries, startIndex);
} else {
return startIndex;
}
}
|
[
"public",
"int",
"loadIndeces",
"(",
"List",
"<",
"RowIndexEntry",
">",
"rowIndexEntries",
",",
"int",
"startIndex",
")",
"{",
"if",
"(",
"present",
"!=",
"null",
")",
"{",
"return",
"present",
".",
"loadIndeces",
"(",
"rowIndexEntries",
",",
"startIndex",
")",
";",
"}",
"else",
"{",
"return",
"startIndex",
";",
"}",
"}"
] |
Read any indeces that will be needed and return a startIndex after the values that have been
read.
|
[
"Read",
"any",
"indeces",
"that",
"will",
"be",
"needed",
"and",
"return",
"a",
"startIndex",
"after",
"the",
"values",
"that",
"have",
"been",
"read",
"."
] |
train
|
https://github.com/facebookarchive/hive-dwrf/blob/a7b4fcf28a57e006a2fc041d40cf7e5ad16e6b45/hive-dwrf/src/main/java/com/facebook/hive/orc/lazy/LazyTreeReader.java#L371-L377
|
google/error-prone
|
check_api/src/main/java/com/google/errorprone/matchers/Matchers.java
|
Matchers.nestingKind
|
public static Matcher<ClassTree> nestingKind(final NestingKind kind) {
return new Matcher<ClassTree>() {
@Override
public boolean matches(ClassTree classTree, VisitorState state) {
ClassSymbol sym = ASTHelpers.getSymbol(classTree);
return sym.getNestingKind() == kind;
}
};
}
|
java
|
public static Matcher<ClassTree> nestingKind(final NestingKind kind) {
return new Matcher<ClassTree>() {
@Override
public boolean matches(ClassTree classTree, VisitorState state) {
ClassSymbol sym = ASTHelpers.getSymbol(classTree);
return sym.getNestingKind() == kind;
}
};
}
|
[
"public",
"static",
"Matcher",
"<",
"ClassTree",
">",
"nestingKind",
"(",
"final",
"NestingKind",
"kind",
")",
"{",
"return",
"new",
"Matcher",
"<",
"ClassTree",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"boolean",
"matches",
"(",
"ClassTree",
"classTree",
",",
"VisitorState",
"state",
")",
"{",
"ClassSymbol",
"sym",
"=",
"ASTHelpers",
".",
"getSymbol",
"(",
"classTree",
")",
";",
"return",
"sym",
".",
"getNestingKind",
"(",
")",
"==",
"kind",
";",
"}",
"}",
";",
"}"
] |
Matches an class based on whether it is nested in another class or method.
@param kind The kind of nesting to match, eg ANONYMOUS, LOCAL, MEMBER, TOP_LEVEL
|
[
"Matches",
"an",
"class",
"based",
"on",
"whether",
"it",
"is",
"nested",
"in",
"another",
"class",
"or",
"method",
"."
] |
train
|
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/matchers/Matchers.java#L1114-L1122
|
DDTH/ddth-commons
|
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/TypesafeConfigUtils.java
|
TypesafeConfigUtils.getDuration
|
public static Duration getDuration(Config config, String path) {
try {
return config.getDuration(path);
} catch (ConfigException.Missing | ConfigException.WrongType | ConfigException.BadValue e) {
if (e instanceof ConfigException.WrongType || e instanceof ConfigException.BadValue) {
LOGGER.warn(e.getMessage(), e);
}
return null;
}
}
|
java
|
public static Duration getDuration(Config config, String path) {
try {
return config.getDuration(path);
} catch (ConfigException.Missing | ConfigException.WrongType | ConfigException.BadValue e) {
if (e instanceof ConfigException.WrongType || e instanceof ConfigException.BadValue) {
LOGGER.warn(e.getMessage(), e);
}
return null;
}
}
|
[
"public",
"static",
"Duration",
"getDuration",
"(",
"Config",
"config",
",",
"String",
"path",
")",
"{",
"try",
"{",
"return",
"config",
".",
"getDuration",
"(",
"path",
")",
";",
"}",
"catch",
"(",
"ConfigException",
".",
"Missing",
"|",
"ConfigException",
".",
"WrongType",
"|",
"ConfigException",
".",
"BadValue",
"e",
")",
"{",
"if",
"(",
"e",
"instanceof",
"ConfigException",
".",
"WrongType",
"||",
"e",
"instanceof",
"ConfigException",
".",
"BadValue",
")",
"{",
"LOGGER",
".",
"warn",
"(",
"e",
".",
"getMessage",
"(",
")",
",",
"e",
")",
";",
"}",
"return",
"null",
";",
"}",
"}"
] |
Get a configuration as duration (parses special strings like "10s"). Return {@code null}
if missing, wrong type or bad value.
@param config
@param path
@return
|
[
"Get",
"a",
"configuration",
"as",
"duration",
"(",
"parses",
"special",
"strings",
"like",
"10s",
")",
".",
"Return",
"{",
"@code",
"null",
"}",
"if",
"missing",
"wrong",
"type",
"or",
"bad",
"value",
"."
] |
train
|
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/TypesafeConfigUtils.java#L635-L644
|
elki-project/elki
|
elki-core-distance/src/main/java/de/lmu/ifi/dbs/elki/distance/distancefunction/minkowski/LPIntegerNormDistanceFunction.java
|
LPIntegerNormDistanceFunction.preDistance
|
private double preDistance(NumberVector v1, NumberVector v2, final int start, final int end) {
double agg = 0.;
for(int d = start; d < end; d++) {
final double xd = v1.doubleValue(d), yd = v2.doubleValue(d);
final double delta = xd >= yd ? xd - yd : yd - xd;
agg += MathUtil.powi(delta, intp);
}
return agg;
}
|
java
|
private double preDistance(NumberVector v1, NumberVector v2, final int start, final int end) {
double agg = 0.;
for(int d = start; d < end; d++) {
final double xd = v1.doubleValue(d), yd = v2.doubleValue(d);
final double delta = xd >= yd ? xd - yd : yd - xd;
agg += MathUtil.powi(delta, intp);
}
return agg;
}
|
[
"private",
"double",
"preDistance",
"(",
"NumberVector",
"v1",
",",
"NumberVector",
"v2",
",",
"final",
"int",
"start",
",",
"final",
"int",
"end",
")",
"{",
"double",
"agg",
"=",
"0.",
";",
"for",
"(",
"int",
"d",
"=",
"start",
";",
"d",
"<",
"end",
";",
"d",
"++",
")",
"{",
"final",
"double",
"xd",
"=",
"v1",
".",
"doubleValue",
"(",
"d",
")",
",",
"yd",
"=",
"v2",
".",
"doubleValue",
"(",
"d",
")",
";",
"final",
"double",
"delta",
"=",
"xd",
">=",
"yd",
"?",
"xd",
"-",
"yd",
":",
"yd",
"-",
"xd",
";",
"agg",
"+=",
"MathUtil",
".",
"powi",
"(",
"delta",
",",
"intp",
")",
";",
"}",
"return",
"agg",
";",
"}"
] |
Compute unscaled distance in a range of dimensions.
@param v1 First object
@param v2 Second object
@param start First dimension
@param end Exclusive last dimension
@return Aggregated values.
|
[
"Compute",
"unscaled",
"distance",
"in",
"a",
"range",
"of",
"dimensions",
"."
] |
train
|
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-distance/src/main/java/de/lmu/ifi/dbs/elki/distance/distancefunction/minkowski/LPIntegerNormDistanceFunction.java#L74-L82
|
exoplatform/jcr
|
exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/resource/NodeRepresentationService.java
|
NodeRepresentationService.getNodeRepresentation
|
public NodeRepresentation getNodeRepresentation(Node node, String mediaTypeHint) throws RepositoryException
{
NodeRepresentationFactory factory = factory(node);
if (factory != null)
return factory.createNodeRepresentation(node, mediaTypeHint);
else
return new DocumentViewNodeRepresentation(node);
}
|
java
|
public NodeRepresentation getNodeRepresentation(Node node, String mediaTypeHint) throws RepositoryException
{
NodeRepresentationFactory factory = factory(node);
if (factory != null)
return factory.createNodeRepresentation(node, mediaTypeHint);
else
return new DocumentViewNodeRepresentation(node);
}
|
[
"public",
"NodeRepresentation",
"getNodeRepresentation",
"(",
"Node",
"node",
",",
"String",
"mediaTypeHint",
")",
"throws",
"RepositoryException",
"{",
"NodeRepresentationFactory",
"factory",
"=",
"factory",
"(",
"node",
")",
";",
"if",
"(",
"factory",
"!=",
"null",
")",
"return",
"factory",
".",
"createNodeRepresentation",
"(",
"node",
",",
"mediaTypeHint",
")",
";",
"else",
"return",
"new",
"DocumentViewNodeRepresentation",
"(",
"node",
")",
";",
"}"
] |
Get NodeRepresentation for given node. String mediaTypeHint can be used as external information
for representation. By default node will be represented as doc-view.
@param node
the jcr node.
@param mediaTypeHint
the mimetype hint or null if not known.
@return the NodeRepresentation.
@throws RepositoryException
|
[
"Get",
"NodeRepresentation",
"for",
"given",
"node",
".",
"String",
"mediaTypeHint",
"can",
"be",
"used",
"as",
"external",
"information",
"for",
"representation",
".",
"By",
"default",
"node",
"will",
"be",
"represented",
"as",
"doc",
"-",
"view",
"."
] |
train
|
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/resource/NodeRepresentationService.java#L87-L95
|
infinispan/infinispan
|
core/src/main/java/org/infinispan/util/AbstractDelegatingCacheStream.java
|
AbstractDelegatingCacheStream.mapToInt
|
@Override
public IntCacheStream mapToInt(ToIntFunction<? super R> mapper) {
return new AbstractDelegatingIntCacheStream(this, castStream(underlyingStream).mapToInt(mapper));
}
|
java
|
@Override
public IntCacheStream mapToInt(ToIntFunction<? super R> mapper) {
return new AbstractDelegatingIntCacheStream(this, castStream(underlyingStream).mapToInt(mapper));
}
|
[
"@",
"Override",
"public",
"IntCacheStream",
"mapToInt",
"(",
"ToIntFunction",
"<",
"?",
"super",
"R",
">",
"mapper",
")",
"{",
"return",
"new",
"AbstractDelegatingIntCacheStream",
"(",
"this",
",",
"castStream",
"(",
"underlyingStream",
")",
".",
"mapToInt",
"(",
"mapper",
")",
")",
";",
"}"
] |
These are methods that convert to a different AbstractDelegating*CacheStream
|
[
"These",
"are",
"methods",
"that",
"convert",
"to",
"a",
"different",
"AbstractDelegating",
"*",
"CacheStream"
] |
train
|
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/core/src/main/java/org/infinispan/util/AbstractDelegatingCacheStream.java#L51-L54
|
di2e/Argo
|
Responder/ResponderDaemon/src/main/java/ws/argo/responder/transport/AmazonSNSTransport.java
|
AmazonSNSTransport.subscribe
|
public void subscribe() throws URISyntaxException, TransportConfigException {
/*
* if this instance of the transport (as there could be several - each with
* a different topic) is in shutdown mode then don't subscribe. This is a
* side effect of when you shutdown a sns transport and the listener gets an
* UnsubscribeConfirmation. In normal operation, when the topic does
* occasional house keeping and clears out the subscriptions, running
* transports will just re-subscribe.
*/
if (_inShutdown)
return;
URI url = getBaseSubscriptionURI();
String subscriptionURL = url.toString() + "listener/sns";
LOGGER.info("Subscription URI - " + subscriptionURL);
SubscribeRequest subRequest = new SubscribeRequest(_argoTopicName, "http", subscriptionURL);
try {
getSNSClient().subscribe(subRequest);
} catch (AmazonServiceException e) {
throw new TransportConfigException("Error subscribing to SNS topic.", e);
}
// get request id for SubscribeRequest from SNS metadata
this._subscriptionArn = getSNSClient().getCachedResponseMetadata(subRequest).toString();
LOGGER.info("SubscribeRequest - " + _subscriptionArn);
}
|
java
|
public void subscribe() throws URISyntaxException, TransportConfigException {
/*
* if this instance of the transport (as there could be several - each with
* a different topic) is in shutdown mode then don't subscribe. This is a
* side effect of when you shutdown a sns transport and the listener gets an
* UnsubscribeConfirmation. In normal operation, when the topic does
* occasional house keeping and clears out the subscriptions, running
* transports will just re-subscribe.
*/
if (_inShutdown)
return;
URI url = getBaseSubscriptionURI();
String subscriptionURL = url.toString() + "listener/sns";
LOGGER.info("Subscription URI - " + subscriptionURL);
SubscribeRequest subRequest = new SubscribeRequest(_argoTopicName, "http", subscriptionURL);
try {
getSNSClient().subscribe(subRequest);
} catch (AmazonServiceException e) {
throw new TransportConfigException("Error subscribing to SNS topic.", e);
}
// get request id for SubscribeRequest from SNS metadata
this._subscriptionArn = getSNSClient().getCachedResponseMetadata(subRequest).toString();
LOGGER.info("SubscribeRequest - " + _subscriptionArn);
}
|
[
"public",
"void",
"subscribe",
"(",
")",
"throws",
"URISyntaxException",
",",
"TransportConfigException",
"{",
"/*\n * if this instance of the transport (as there could be several - each with\n * a different topic) is in shutdown mode then don't subscribe. This is a\n * side effect of when you shutdown a sns transport and the listener gets an\n * UnsubscribeConfirmation. In normal operation, when the topic does\n * occasional house keeping and clears out the subscriptions, running\n * transports will just re-subscribe.\n */",
"if",
"(",
"_inShutdown",
")",
"return",
";",
"URI",
"url",
"=",
"getBaseSubscriptionURI",
"(",
")",
";",
"String",
"subscriptionURL",
"=",
"url",
".",
"toString",
"(",
")",
"+",
"\"listener/sns\"",
";",
"LOGGER",
".",
"info",
"(",
"\"Subscription URI - \"",
"+",
"subscriptionURL",
")",
";",
"SubscribeRequest",
"subRequest",
"=",
"new",
"SubscribeRequest",
"(",
"_argoTopicName",
",",
"\"http\"",
",",
"subscriptionURL",
")",
";",
"try",
"{",
"getSNSClient",
"(",
")",
".",
"subscribe",
"(",
"subRequest",
")",
";",
"}",
"catch",
"(",
"AmazonServiceException",
"e",
")",
"{",
"throw",
"new",
"TransportConfigException",
"(",
"\"Error subscribing to SNS topic.\"",
",",
"e",
")",
";",
"}",
"// get request id for SubscribeRequest from SNS metadata",
"this",
".",
"_subscriptionArn",
"=",
"getSNSClient",
"(",
")",
".",
"getCachedResponseMetadata",
"(",
"subRequest",
")",
".",
"toString",
"(",
")",
";",
"LOGGER",
".",
"info",
"(",
"\"SubscribeRequest - \"",
"+",
"_subscriptionArn",
")",
";",
"}"
] |
Attempt to subscript to the Argo SNS topic.
@throws URISyntaxException if the subscription HTTP URL is messed up
@throws TransportConfigException if there was some Amazon specific issue
while subscribing
|
[
"Attempt",
"to",
"subscript",
"to",
"the",
"Argo",
"SNS",
"topic",
"."
] |
train
|
https://github.com/di2e/Argo/blob/f537a03d2d25fdfecda7999ec10e1da67dc3b8f3/Responder/ResponderDaemon/src/main/java/ws/argo/responder/transport/AmazonSNSTransport.java#L162-L189
|
Jasig/uPortal
|
uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/dlm/EditManager.java
|
EditManager.addPrefsDirective
|
public static void addPrefsDirective(Element plfNode, String attributeName, IPerson person)
throws PortalException {
addDirective(plfNode, attributeName, Constants.ELM_PREF, person);
}
|
java
|
public static void addPrefsDirective(Element plfNode, String attributeName, IPerson person)
throws PortalException {
addDirective(plfNode, attributeName, Constants.ELM_PREF, person);
}
|
[
"public",
"static",
"void",
"addPrefsDirective",
"(",
"Element",
"plfNode",
",",
"String",
"attributeName",
",",
"IPerson",
"person",
")",
"throws",
"PortalException",
"{",
"addDirective",
"(",
"plfNode",
",",
"attributeName",
",",
"Constants",
".",
"ELM_PREF",
",",
"person",
")",
";",
"}"
] |
Create and append a user preferences edit directive to the edit set if not there. This only
records that the attribute was changed. The value will be in the user preferences object for
the user.
|
[
"Create",
"and",
"append",
"a",
"user",
"preferences",
"edit",
"directive",
"to",
"the",
"edit",
"set",
"if",
"not",
"there",
".",
"This",
"only",
"records",
"that",
"the",
"attribute",
"was",
"changed",
".",
"The",
"value",
"will",
"be",
"in",
"the",
"user",
"preferences",
"object",
"for",
"the",
"user",
"."
] |
train
|
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/dlm/EditManager.java#L99-L102
|
google/error-prone
|
check_api/src/main/java/com/google/errorprone/fixes/SuggestedFixes.java
|
SuggestedFixes.qualifyType
|
public static String qualifyType(VisitorState state, SuggestedFix.Builder fix, String typeName) {
for (int startOfClass = typeName.indexOf('.');
startOfClass > 0;
startOfClass = typeName.indexOf('.', startOfClass + 1)) {
int endOfClass = typeName.indexOf('.', startOfClass + 1);
if (endOfClass < 0) {
endOfClass = typeName.length();
}
if (!Character.isUpperCase(typeName.charAt(startOfClass + 1))) {
continue;
}
String className = typeName.substring(startOfClass + 1);
Symbol found = FindIdentifiers.findIdent(className, state, KindSelector.VAL_TYP);
// No clashing name: import it and return.
if (found == null) {
fix.addImport(typeName.substring(0, endOfClass));
return className;
}
// Type already imported.
if (found.getQualifiedName().contentEquals(typeName)) {
return className;
}
}
return typeName;
}
|
java
|
public static String qualifyType(VisitorState state, SuggestedFix.Builder fix, String typeName) {
for (int startOfClass = typeName.indexOf('.');
startOfClass > 0;
startOfClass = typeName.indexOf('.', startOfClass + 1)) {
int endOfClass = typeName.indexOf('.', startOfClass + 1);
if (endOfClass < 0) {
endOfClass = typeName.length();
}
if (!Character.isUpperCase(typeName.charAt(startOfClass + 1))) {
continue;
}
String className = typeName.substring(startOfClass + 1);
Symbol found = FindIdentifiers.findIdent(className, state, KindSelector.VAL_TYP);
// No clashing name: import it and return.
if (found == null) {
fix.addImport(typeName.substring(0, endOfClass));
return className;
}
// Type already imported.
if (found.getQualifiedName().contentEquals(typeName)) {
return className;
}
}
return typeName;
}
|
[
"public",
"static",
"String",
"qualifyType",
"(",
"VisitorState",
"state",
",",
"SuggestedFix",
".",
"Builder",
"fix",
",",
"String",
"typeName",
")",
"{",
"for",
"(",
"int",
"startOfClass",
"=",
"typeName",
".",
"indexOf",
"(",
"'",
"'",
")",
";",
"startOfClass",
">",
"0",
";",
"startOfClass",
"=",
"typeName",
".",
"indexOf",
"(",
"'",
"'",
",",
"startOfClass",
"+",
"1",
")",
")",
"{",
"int",
"endOfClass",
"=",
"typeName",
".",
"indexOf",
"(",
"'",
"'",
",",
"startOfClass",
"+",
"1",
")",
";",
"if",
"(",
"endOfClass",
"<",
"0",
")",
"{",
"endOfClass",
"=",
"typeName",
".",
"length",
"(",
")",
";",
"}",
"if",
"(",
"!",
"Character",
".",
"isUpperCase",
"(",
"typeName",
".",
"charAt",
"(",
"startOfClass",
"+",
"1",
")",
")",
")",
"{",
"continue",
";",
"}",
"String",
"className",
"=",
"typeName",
".",
"substring",
"(",
"startOfClass",
"+",
"1",
")",
";",
"Symbol",
"found",
"=",
"FindIdentifiers",
".",
"findIdent",
"(",
"className",
",",
"state",
",",
"KindSelector",
".",
"VAL_TYP",
")",
";",
"// No clashing name: import it and return.",
"if",
"(",
"found",
"==",
"null",
")",
"{",
"fix",
".",
"addImport",
"(",
"typeName",
".",
"substring",
"(",
"0",
",",
"endOfClass",
")",
")",
";",
"return",
"className",
";",
"}",
"// Type already imported.",
"if",
"(",
"found",
".",
"getQualifiedName",
"(",
")",
".",
"contentEquals",
"(",
"typeName",
")",
")",
"{",
"return",
"className",
";",
"}",
"}",
"return",
"typeName",
";",
"}"
] |
Returns a human-friendly name of the given {@code typeName} for use in fixes.
<p>This should be used if the type may not be loaded.
|
[
"Returns",
"a",
"human",
"-",
"friendly",
"name",
"of",
"the",
"given",
"{",
"@code",
"typeName",
"}",
"for",
"use",
"in",
"fixes",
"."
] |
train
|
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/fixes/SuggestedFixes.java#L336-L360
|
google/error-prone-javac
|
src/jdk.compiler/share/classes/com/sun/tools/javah/Main.java
|
Main.run
|
public static int run(String[] args, PrintWriter out) {
JavahTask t = new JavahTask();
t.setLog(out);
return t.run(args);
}
|
java
|
public static int run(String[] args, PrintWriter out) {
JavahTask t = new JavahTask();
t.setLog(out);
return t.run(args);
}
|
[
"public",
"static",
"int",
"run",
"(",
"String",
"[",
"]",
"args",
",",
"PrintWriter",
"out",
")",
"{",
"JavahTask",
"t",
"=",
"new",
"JavahTask",
"(",
")",
";",
"t",
".",
"setLog",
"(",
"out",
")",
";",
"return",
"t",
".",
"run",
"(",
"args",
")",
";",
"}"
] |
Entry point that does <i>not</i> call System.exit.
@param args command line arguments
@param out output stream
@return an exit code. 0 means success, non-zero means an error occurred.
|
[
"Entry",
"point",
"that",
"does",
"<i",
">",
"not<",
"/",
"i",
">",
"call",
"System",
".",
"exit",
"."
] |
train
|
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javah/Main.java#L56-L60
|
micronaut-projects/micronaut-core
|
http/src/main/java/io/micronaut/http/context/ServerRequestContext.java
|
ServerRequestContext.with
|
public static <T> T with(HttpRequest request, Callable<T> callable) throws Exception {
HttpRequest existing = REQUEST.get();
boolean isSet = false;
try {
if (request != existing) {
isSet = true;
REQUEST.set(request);
}
return callable.call();
} finally {
if (isSet) {
REQUEST.remove();
}
}
}
|
java
|
public static <T> T with(HttpRequest request, Callable<T> callable) throws Exception {
HttpRequest existing = REQUEST.get();
boolean isSet = false;
try {
if (request != existing) {
isSet = true;
REQUEST.set(request);
}
return callable.call();
} finally {
if (isSet) {
REQUEST.remove();
}
}
}
|
[
"public",
"static",
"<",
"T",
">",
"T",
"with",
"(",
"HttpRequest",
"request",
",",
"Callable",
"<",
"T",
">",
"callable",
")",
"throws",
"Exception",
"{",
"HttpRequest",
"existing",
"=",
"REQUEST",
".",
"get",
"(",
")",
";",
"boolean",
"isSet",
"=",
"false",
";",
"try",
"{",
"if",
"(",
"request",
"!=",
"existing",
")",
"{",
"isSet",
"=",
"true",
";",
"REQUEST",
".",
"set",
"(",
"request",
")",
";",
"}",
"return",
"callable",
".",
"call",
"(",
")",
";",
"}",
"finally",
"{",
"if",
"(",
"isSet",
")",
"{",
"REQUEST",
".",
"remove",
"(",
")",
";",
"}",
"}",
"}"
] |
Wrap the execution of the given callable in request context processing.
@param request The request
@param callable The callable
@param <T> The return type of the callable
@return The return value of the callable
@throws Exception If the callable throws an exception
|
[
"Wrap",
"the",
"execution",
"of",
"the",
"given",
"callable",
"in",
"request",
"context",
"processing",
"."
] |
train
|
https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/http/src/main/java/io/micronaut/http/context/ServerRequestContext.java#L104-L118
|
doanduyhai/Achilles
|
achilles-core/src/main/java/info/archinnov/achilles/internals/dsl/options/AbstractOptionsForSelect.java
|
AbstractOptionsForSelect.withResultSetAsyncListeners
|
public T withResultSetAsyncListeners(List<Function<ResultSet, ResultSet>> resultSetAsyncListeners) {
getOptions().setResultSetAsyncListeners(Optional.of(resultSetAsyncListeners));
return getThis();
}
|
java
|
public T withResultSetAsyncListeners(List<Function<ResultSet, ResultSet>> resultSetAsyncListeners) {
getOptions().setResultSetAsyncListeners(Optional.of(resultSetAsyncListeners));
return getThis();
}
|
[
"public",
"T",
"withResultSetAsyncListeners",
"(",
"List",
"<",
"Function",
"<",
"ResultSet",
",",
"ResultSet",
">",
">",
"resultSetAsyncListeners",
")",
"{",
"getOptions",
"(",
")",
".",
"setResultSetAsyncListeners",
"(",
"Optional",
".",
"of",
"(",
"resultSetAsyncListeners",
")",
")",
";",
"return",
"getThis",
"(",
")",
";",
"}"
] |
Add the given list of async listeners on the {@link com.datastax.driver.core.ResultSet} object.
Example of usage:
<pre class="code"><code class="java">
.withResultSetAsyncListeners(Arrays.asList(resultSet -> {
//Do something with the resultSet object here
}))
</code></pre>
Remark: <strong>it is not allowed to consume the ResultSet values. It is strongly advised to read only meta data</strong>
|
[
"Add",
"the",
"given",
"list",
"of",
"async",
"listeners",
"on",
"the",
"{",
"@link",
"com",
".",
"datastax",
".",
"driver",
".",
"core",
".",
"ResultSet",
"}",
"object",
".",
"Example",
"of",
"usage",
":",
"<pre",
"class",
"=",
"code",
">",
"<code",
"class",
"=",
"java",
">"
] |
train
|
https://github.com/doanduyhai/Achilles/blob/8281c33100e72c993e570592ae1a5306afac6813/achilles-core/src/main/java/info/archinnov/achilles/internals/dsl/options/AbstractOptionsForSelect.java#L182-L185
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.