repository_name
stringlengths 7
58
| func_path_in_repository
stringlengths 11
218
| func_name
stringlengths 4
140
| whole_func_string
stringlengths 153
5.32k
| language
stringclasses 1
value | func_code_string
stringlengths 72
4k
| func_code_tokens
listlengths 20
832
| func_documentation_string
stringlengths 61
2k
| func_documentation_tokens
listlengths 1
647
| split_name
stringclasses 1
value | func_code_url
stringlengths 102
339
|
---|---|---|---|---|---|---|---|---|---|---|
Viascom/groundwork | foxhttp/src/main/java/ch/viascom/groundwork/foxhttp/body/request/RequestMultipartBody.java | RequestMultipartBody.addInputStreamPart | public void addInputStreamPart(String name, String inputStreamName, InputStream inputStream, String contentTransferEncoding, String contentType) {
"""
Adds an inputstream to te request
@param name
@param inputStreamName
@param inputStream
@param contentTransferEncoding usually binary
@param contentType
"""
stream.put(name, new NamedInputStream(inputStreamName, inputStream, contentTransferEncoding, contentType));
} | java | public void addInputStreamPart(String name, String inputStreamName, InputStream inputStream, String contentTransferEncoding, String contentType) {
stream.put(name, new NamedInputStream(inputStreamName, inputStream, contentTransferEncoding, contentType));
} | [
"public",
"void",
"addInputStreamPart",
"(",
"String",
"name",
",",
"String",
"inputStreamName",
",",
"InputStream",
"inputStream",
",",
"String",
"contentTransferEncoding",
",",
"String",
"contentType",
")",
"{",
"stream",
".",
"put",
"(",
"name",
",",
"new",
"NamedInputStream",
"(",
"inputStreamName",
",",
"inputStream",
",",
"contentTransferEncoding",
",",
"contentType",
")",
")",
";",
"}"
]
| Adds an inputstream to te request
@param name
@param inputStreamName
@param inputStream
@param contentTransferEncoding usually binary
@param contentType | [
"Adds",
"an",
"inputstream",
"to",
"te",
"request"
]
| train | https://github.com/Viascom/groundwork/blob/d3f7d0df65e2e75861fc7db938090683f2cdf919/foxhttp/src/main/java/ch/viascom/groundwork/foxhttp/body/request/RequestMultipartBody.java#L154-L156 |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/sampling/VarOptItemsUnion.java | VarOptItemsUnion.markMovingGadgetCoercer | private VarOptItemsSketch<T> markMovingGadgetCoercer() {
"""
This coercer directly transfers marked items from the gadget's H into the result's R.
Deciding whether that is a valid thing to do is the responsibility of the caller. Currently,
this is only used for a subcase of pseudo-exact, but later it might be used by other
subcases as well.
@return A sketch derived from the gadget, with marked items moved to the reservoir
"""
final int resultK = gadget_.getHRegionCount() + gadget_.getRRegionCount();
int resultH = 0;
int resultR = 0;
int nextRPos = resultK; // = (resultK+1)-1, to fill R region from back to front
final ArrayList<T> data = new ArrayList<>(resultK + 1);
final ArrayList<Double> weights = new ArrayList<>(resultK + 1);
// Need arrays filled to use set() and be able to fill from end forward.
// Ideally would create as arrays but trying to avoid forcing user to pass a Class<?>
for (int i = 0; i < (resultK + 1); ++i) {
data.add(null);
weights.add(null);
}
final VarOptItemsSamples<T> sketchSamples = gadget_.getSketchSamples();
// insert R region items, ignoring weights
// Currently (May 2017) this next block is unreachable; this coercer is used only in the
// pseudo-exact case in which case there are no items natively in R, only marked items in H
// that will be moved into R as part of the coercion process.
Iterator<VarOptItemsSamples<T>.WeightedSample> sketchIterator;
sketchIterator = sketchSamples.getRIterator();
while (sketchIterator.hasNext()) {
final VarOptItemsSamples<T>.WeightedSample ws = sketchIterator.next();
data.set(nextRPos, ws.getItem());
weights.set(nextRPos, -1.0);
++resultR;
--nextRPos;
}
double transferredWeight = 0;
// insert H region items
sketchIterator = sketchSamples.getHIterator();
while (sketchIterator.hasNext()) {
final VarOptItemsSamples<T>.WeightedSample ws = sketchIterator.next();
if (ws.getMark()) {
data.set(nextRPos, ws.getItem());
weights.set(nextRPos, -1.0);
transferredWeight += ws.getWeight();
++resultR;
--nextRPos;
} else {
data.set(resultH, ws.getItem());
weights.set(resultH, ws.getWeight());
++resultH;
}
}
assert (resultH + resultR) == resultK;
assert Math.abs(transferredWeight - outerTauNumer) < 1e-10;
final double resultRWeight = gadget_.getTotalWtR() + transferredWeight;
final long resultN = n_;
// explicitly set values for the gap
data.set(resultH, null);
weights.set(resultH, -1.0);
// create sketch with the new values
return newInstanceFromUnionResult(data, weights, resultK, resultN, resultH, resultR, resultRWeight);
} | java | private VarOptItemsSketch<T> markMovingGadgetCoercer() {
final int resultK = gadget_.getHRegionCount() + gadget_.getRRegionCount();
int resultH = 0;
int resultR = 0;
int nextRPos = resultK; // = (resultK+1)-1, to fill R region from back to front
final ArrayList<T> data = new ArrayList<>(resultK + 1);
final ArrayList<Double> weights = new ArrayList<>(resultK + 1);
// Need arrays filled to use set() and be able to fill from end forward.
// Ideally would create as arrays but trying to avoid forcing user to pass a Class<?>
for (int i = 0; i < (resultK + 1); ++i) {
data.add(null);
weights.add(null);
}
final VarOptItemsSamples<T> sketchSamples = gadget_.getSketchSamples();
// insert R region items, ignoring weights
// Currently (May 2017) this next block is unreachable; this coercer is used only in the
// pseudo-exact case in which case there are no items natively in R, only marked items in H
// that will be moved into R as part of the coercion process.
Iterator<VarOptItemsSamples<T>.WeightedSample> sketchIterator;
sketchIterator = sketchSamples.getRIterator();
while (sketchIterator.hasNext()) {
final VarOptItemsSamples<T>.WeightedSample ws = sketchIterator.next();
data.set(nextRPos, ws.getItem());
weights.set(nextRPos, -1.0);
++resultR;
--nextRPos;
}
double transferredWeight = 0;
// insert H region items
sketchIterator = sketchSamples.getHIterator();
while (sketchIterator.hasNext()) {
final VarOptItemsSamples<T>.WeightedSample ws = sketchIterator.next();
if (ws.getMark()) {
data.set(nextRPos, ws.getItem());
weights.set(nextRPos, -1.0);
transferredWeight += ws.getWeight();
++resultR;
--nextRPos;
} else {
data.set(resultH, ws.getItem());
weights.set(resultH, ws.getWeight());
++resultH;
}
}
assert (resultH + resultR) == resultK;
assert Math.abs(transferredWeight - outerTauNumer) < 1e-10;
final double resultRWeight = gadget_.getTotalWtR() + transferredWeight;
final long resultN = n_;
// explicitly set values for the gap
data.set(resultH, null);
weights.set(resultH, -1.0);
// create sketch with the new values
return newInstanceFromUnionResult(data, weights, resultK, resultN, resultH, resultR, resultRWeight);
} | [
"private",
"VarOptItemsSketch",
"<",
"T",
">",
"markMovingGadgetCoercer",
"(",
")",
"{",
"final",
"int",
"resultK",
"=",
"gadget_",
".",
"getHRegionCount",
"(",
")",
"+",
"gadget_",
".",
"getRRegionCount",
"(",
")",
";",
"int",
"resultH",
"=",
"0",
";",
"int",
"resultR",
"=",
"0",
";",
"int",
"nextRPos",
"=",
"resultK",
";",
"// = (resultK+1)-1, to fill R region from back to front",
"final",
"ArrayList",
"<",
"T",
">",
"data",
"=",
"new",
"ArrayList",
"<>",
"(",
"resultK",
"+",
"1",
")",
";",
"final",
"ArrayList",
"<",
"Double",
">",
"weights",
"=",
"new",
"ArrayList",
"<>",
"(",
"resultK",
"+",
"1",
")",
";",
"// Need arrays filled to use set() and be able to fill from end forward.",
"// Ideally would create as arrays but trying to avoid forcing user to pass a Class<?>",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"(",
"resultK",
"+",
"1",
")",
";",
"++",
"i",
")",
"{",
"data",
".",
"add",
"(",
"null",
")",
";",
"weights",
".",
"add",
"(",
"null",
")",
";",
"}",
"final",
"VarOptItemsSamples",
"<",
"T",
">",
"sketchSamples",
"=",
"gadget_",
".",
"getSketchSamples",
"(",
")",
";",
"// insert R region items, ignoring weights",
"// Currently (May 2017) this next block is unreachable; this coercer is used only in the",
"// pseudo-exact case in which case there are no items natively in R, only marked items in H",
"// that will be moved into R as part of the coercion process.",
"Iterator",
"<",
"VarOptItemsSamples",
"<",
"T",
">",
".",
"WeightedSample",
">",
"sketchIterator",
";",
"sketchIterator",
"=",
"sketchSamples",
".",
"getRIterator",
"(",
")",
";",
"while",
"(",
"sketchIterator",
".",
"hasNext",
"(",
")",
")",
"{",
"final",
"VarOptItemsSamples",
"<",
"T",
">",
".",
"WeightedSample",
"ws",
"=",
"sketchIterator",
".",
"next",
"(",
")",
";",
"data",
".",
"set",
"(",
"nextRPos",
",",
"ws",
".",
"getItem",
"(",
")",
")",
";",
"weights",
".",
"set",
"(",
"nextRPos",
",",
"-",
"1.0",
")",
";",
"++",
"resultR",
";",
"--",
"nextRPos",
";",
"}",
"double",
"transferredWeight",
"=",
"0",
";",
"// insert H region items",
"sketchIterator",
"=",
"sketchSamples",
".",
"getHIterator",
"(",
")",
";",
"while",
"(",
"sketchIterator",
".",
"hasNext",
"(",
")",
")",
"{",
"final",
"VarOptItemsSamples",
"<",
"T",
">",
".",
"WeightedSample",
"ws",
"=",
"sketchIterator",
".",
"next",
"(",
")",
";",
"if",
"(",
"ws",
".",
"getMark",
"(",
")",
")",
"{",
"data",
".",
"set",
"(",
"nextRPos",
",",
"ws",
".",
"getItem",
"(",
")",
")",
";",
"weights",
".",
"set",
"(",
"nextRPos",
",",
"-",
"1.0",
")",
";",
"transferredWeight",
"+=",
"ws",
".",
"getWeight",
"(",
")",
";",
"++",
"resultR",
";",
"--",
"nextRPos",
";",
"}",
"else",
"{",
"data",
".",
"set",
"(",
"resultH",
",",
"ws",
".",
"getItem",
"(",
")",
")",
";",
"weights",
".",
"set",
"(",
"resultH",
",",
"ws",
".",
"getWeight",
"(",
")",
")",
";",
"++",
"resultH",
";",
"}",
"}",
"assert",
"(",
"resultH",
"+",
"resultR",
")",
"==",
"resultK",
";",
"assert",
"Math",
".",
"abs",
"(",
"transferredWeight",
"-",
"outerTauNumer",
")",
"<",
"1e-10",
";",
"final",
"double",
"resultRWeight",
"=",
"gadget_",
".",
"getTotalWtR",
"(",
")",
"+",
"transferredWeight",
";",
"final",
"long",
"resultN",
"=",
"n_",
";",
"// explicitly set values for the gap",
"data",
".",
"set",
"(",
"resultH",
",",
"null",
")",
";",
"weights",
".",
"set",
"(",
"resultH",
",",
"-",
"1.0",
")",
";",
"// create sketch with the new values",
"return",
"newInstanceFromUnionResult",
"(",
"data",
",",
"weights",
",",
"resultK",
",",
"resultN",
",",
"resultH",
",",
"resultR",
",",
"resultRWeight",
")",
";",
"}"
]
| This coercer directly transfers marked items from the gadget's H into the result's R.
Deciding whether that is a valid thing to do is the responsibility of the caller. Currently,
this is only used for a subcase of pseudo-exact, but later it might be used by other
subcases as well.
@return A sketch derived from the gadget, with marked items moved to the reservoir | [
"This",
"coercer",
"directly",
"transfers",
"marked",
"items",
"from",
"the",
"gadget",
"s",
"H",
"into",
"the",
"result",
"s",
"R",
".",
"Deciding",
"whether",
"that",
"is",
"a",
"valid",
"thing",
"to",
"do",
"is",
"the",
"responsibility",
"of",
"the",
"caller",
".",
"Currently",
"this",
"is",
"only",
"used",
"for",
"a",
"subcase",
"of",
"pseudo",
"-",
"exact",
"but",
"later",
"it",
"might",
"be",
"used",
"by",
"other",
"subcases",
"as",
"well",
"."
]
| train | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/sampling/VarOptItemsUnion.java#L476-L538 |
UrielCh/ovh-java-sdk | ovh-java-sdk-dedicatednasha/src/main/java/net/minidev/ovh/api/ApiOvhDedicatednasha.java | ApiOvhDedicatednasha.serviceName_partition_partitionName_snapshot_POST | public OvhTask serviceName_partition_partitionName_snapshot_POST(String serviceName, String partitionName, OvhSnapshotEnum snapshotType) throws IOException {
"""
Schedule a new snapshot type
REST: POST /dedicated/nasha/{serviceName}/partition/{partitionName}/snapshot
@param snapshotType [required] Snapshot interval to add
@param serviceName [required] The internal name of your storage
@param partitionName [required] the given name of partition
"""
String qPath = "/dedicated/nasha/{serviceName}/partition/{partitionName}/snapshot";
StringBuilder sb = path(qPath, serviceName, partitionName);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "snapshotType", snapshotType);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhTask.class);
} | java | public OvhTask serviceName_partition_partitionName_snapshot_POST(String serviceName, String partitionName, OvhSnapshotEnum snapshotType) throws IOException {
String qPath = "/dedicated/nasha/{serviceName}/partition/{partitionName}/snapshot";
StringBuilder sb = path(qPath, serviceName, partitionName);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "snapshotType", snapshotType);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhTask.class);
} | [
"public",
"OvhTask",
"serviceName_partition_partitionName_snapshot_POST",
"(",
"String",
"serviceName",
",",
"String",
"partitionName",
",",
"OvhSnapshotEnum",
"snapshotType",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/dedicated/nasha/{serviceName}/partition/{partitionName}/snapshot\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"serviceName",
",",
"partitionName",
")",
";",
"HashMap",
"<",
"String",
",",
"Object",
">",
"o",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Object",
">",
"(",
")",
";",
"addBody",
"(",
"o",
",",
"\"snapshotType\"",
",",
"snapshotType",
")",
";",
"String",
"resp",
"=",
"exec",
"(",
"qPath",
",",
"\"POST\"",
",",
"sb",
".",
"toString",
"(",
")",
",",
"o",
")",
";",
"return",
"convertTo",
"(",
"resp",
",",
"OvhTask",
".",
"class",
")",
";",
"}"
]
| Schedule a new snapshot type
REST: POST /dedicated/nasha/{serviceName}/partition/{partitionName}/snapshot
@param snapshotType [required] Snapshot interval to add
@param serviceName [required] The internal name of your storage
@param partitionName [required] the given name of partition | [
"Schedule",
"a",
"new",
"snapshot",
"type"
]
| train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dedicatednasha/src/main/java/net/minidev/ovh/api/ApiOvhDedicatednasha.java#L341-L348 |
datumbox/datumbox-framework | datumbox-framework-applications/src/main/java/com/datumbox/framework/applications/nlp/TextClassifier.java | TextClassifier.fit | public void fit(Map<Object, URI> datasets) {
"""
Trains a Machine Learning modeler using the provided dataset files. The data
map should have as index the names of each class and as values the URIs
of the training files. The training files should contain one training example
per row.
@param datasets
"""
TrainingParameters tp = (TrainingParameters) knowledgeBase.getTrainingParameters();
Dataframe trainingData = Dataframe.Builder.parseTextFiles(datasets,
AbstractTextExtractor.newInstance(tp.getTextExtractorParameters()),
knowledgeBase.getConfiguration()
);
fit(trainingData);
trainingData.close();
} | java | public void fit(Map<Object, URI> datasets) {
TrainingParameters tp = (TrainingParameters) knowledgeBase.getTrainingParameters();
Dataframe trainingData = Dataframe.Builder.parseTextFiles(datasets,
AbstractTextExtractor.newInstance(tp.getTextExtractorParameters()),
knowledgeBase.getConfiguration()
);
fit(trainingData);
trainingData.close();
} | [
"public",
"void",
"fit",
"(",
"Map",
"<",
"Object",
",",
"URI",
">",
"datasets",
")",
"{",
"TrainingParameters",
"tp",
"=",
"(",
"TrainingParameters",
")",
"knowledgeBase",
".",
"getTrainingParameters",
"(",
")",
";",
"Dataframe",
"trainingData",
"=",
"Dataframe",
".",
"Builder",
".",
"parseTextFiles",
"(",
"datasets",
",",
"AbstractTextExtractor",
".",
"newInstance",
"(",
"tp",
".",
"getTextExtractorParameters",
"(",
")",
")",
",",
"knowledgeBase",
".",
"getConfiguration",
"(",
")",
")",
";",
"fit",
"(",
"trainingData",
")",
";",
"trainingData",
".",
"close",
"(",
")",
";",
"}"
]
| Trains a Machine Learning modeler using the provided dataset files. The data
map should have as index the names of each class and as values the URIs
of the training files. The training files should contain one training example
per row.
@param datasets | [
"Trains",
"a",
"Machine",
"Learning",
"modeler",
"using",
"the",
"provided",
"dataset",
"files",
".",
"The",
"data",
"map",
"should",
"have",
"as",
"index",
"the",
"names",
"of",
"each",
"class",
"and",
"as",
"values",
"the",
"URIs",
"of",
"the",
"training",
"files",
".",
"The",
"training",
"files",
"should",
"contain",
"one",
"training",
"example",
"per",
"row",
"."
]
| train | https://github.com/datumbox/datumbox-framework/blob/909dff0476e80834f05ecdde0624dd2390e9b0ca/datumbox-framework-applications/src/main/java/com/datumbox/framework/applications/nlp/TextClassifier.java#L129-L139 |
Ordinastie/MalisisCore | src/main/java/net/malisis/core/asm/AsmUtils.java | AsmUtils.typeInsnEqual | public static boolean typeInsnEqual(TypeInsnNode insn1, TypeInsnNode insn2) {
"""
Checks if two {@link TypeInsnNode} are equals.
@param insn1 the insn1
@param insn2 the insn2
@return true, if successful
"""
if (insn1.desc.equals("~") || insn2.desc.equals("~"))
return true;
return insn1.desc.equals(insn2.desc);
} | java | public static boolean typeInsnEqual(TypeInsnNode insn1, TypeInsnNode insn2)
{
if (insn1.desc.equals("~") || insn2.desc.equals("~"))
return true;
return insn1.desc.equals(insn2.desc);
} | [
"public",
"static",
"boolean",
"typeInsnEqual",
"(",
"TypeInsnNode",
"insn1",
",",
"TypeInsnNode",
"insn2",
")",
"{",
"if",
"(",
"insn1",
".",
"desc",
".",
"equals",
"(",
"\"~\"",
")",
"||",
"insn2",
".",
"desc",
".",
"equals",
"(",
"\"~\"",
")",
")",
"return",
"true",
";",
"return",
"insn1",
".",
"desc",
".",
"equals",
"(",
"insn2",
".",
"desc",
")",
";",
"}"
]
| Checks if two {@link TypeInsnNode} are equals.
@param insn1 the insn1
@param insn2 the insn2
@return true, if successful | [
"Checks",
"if",
"two",
"{",
"@link",
"TypeInsnNode",
"}",
"are",
"equals",
"."
]
| train | https://github.com/Ordinastie/MalisisCore/blob/4f8e1fa462d5c372fc23414482ba9f429881cc54/src/main/java/net/malisis/core/asm/AsmUtils.java#L234-L240 |
kuali/ojb-1.0.4 | src/xdoclet/java/src/xdoclet/modules/ojb/OjbTagsHandler.java | OjbTagsHandler.forAllForeignkeys | public void forAllForeignkeys(String template, Properties attributes) throws XDocletException {
"""
Processes the template for all foreignkeys of the current table.
@param template The template
@param attributes The attributes of the tag
@exception XDocletException if an error occurs
@doc.tag type="block"
"""
for (Iterator it = _curTableDef.getForeignkeys(); it.hasNext(); )
{
_curForeignkeyDef = (ForeignkeyDef)it.next();
generate(template);
}
_curForeignkeyDef = null;
} | java | public void forAllForeignkeys(String template, Properties attributes) throws XDocletException
{
for (Iterator it = _curTableDef.getForeignkeys(); it.hasNext(); )
{
_curForeignkeyDef = (ForeignkeyDef)it.next();
generate(template);
}
_curForeignkeyDef = null;
} | [
"public",
"void",
"forAllForeignkeys",
"(",
"String",
"template",
",",
"Properties",
"attributes",
")",
"throws",
"XDocletException",
"{",
"for",
"(",
"Iterator",
"it",
"=",
"_curTableDef",
".",
"getForeignkeys",
"(",
")",
";",
"it",
".",
"hasNext",
"(",
")",
";",
")",
"{",
"_curForeignkeyDef",
"=",
"(",
"ForeignkeyDef",
")",
"it",
".",
"next",
"(",
")",
";",
"generate",
"(",
"template",
")",
";",
"}",
"_curForeignkeyDef",
"=",
"null",
";",
"}"
]
| Processes the template for all foreignkeys of the current table.
@param template The template
@param attributes The attributes of the tag
@exception XDocletException if an error occurs
@doc.tag type="block" | [
"Processes",
"the",
"template",
"for",
"all",
"foreignkeys",
"of",
"the",
"current",
"table",
"."
]
| train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/xdoclet/java/src/xdoclet/modules/ojb/OjbTagsHandler.java#L1362-L1370 |
zhangguangyong/codes | codes-persistent-hibernate/src/main/java/com/codes/persistence/hibernate/dao/QueryParameterWrap.java | QueryParameterWrap.addParameters | public QueryParameterWrap addParameters(String name, Object first, Object second,
Object... rest) {
"""
添加命名的参数 :propertyName ->命名的参数
@param name
@param first
第一个,不能为空
@param second
第二个,不能为空
@param rest
后面的,可为空
@return
"""
List<Object> parameters = new ArrayList<Object>();
parameters.add(first);
parameters.add(second);
if (notEmpty(rest)) {
parameters.addAll(Arrays.asList(rest));
}
return addParameters(name, parameters);
} | java | public QueryParameterWrap addParameters(String name, Object first, Object second,
Object... rest) {
List<Object> parameters = new ArrayList<Object>();
parameters.add(first);
parameters.add(second);
if (notEmpty(rest)) {
parameters.addAll(Arrays.asList(rest));
}
return addParameters(name, parameters);
} | [
"public",
"QueryParameterWrap",
"addParameters",
"(",
"String",
"name",
",",
"Object",
"first",
",",
"Object",
"second",
",",
"Object",
"...",
"rest",
")",
"{",
"List",
"<",
"Object",
">",
"parameters",
"=",
"new",
"ArrayList",
"<",
"Object",
">",
"(",
")",
";",
"parameters",
".",
"add",
"(",
"first",
")",
";",
"parameters",
".",
"add",
"(",
"second",
")",
";",
"if",
"(",
"notEmpty",
"(",
"rest",
")",
")",
"{",
"parameters",
".",
"addAll",
"(",
"Arrays",
".",
"asList",
"(",
"rest",
")",
")",
";",
"}",
"return",
"addParameters",
"(",
"name",
",",
"parameters",
")",
";",
"}"
]
| 添加命名的参数 :propertyName ->命名的参数
@param name
@param first
第一个,不能为空
@param second
第二个,不能为空
@param rest
后面的,可为空
@return | [
"添加命名的参数",
":",
"propertyName",
"-",
">",
"命名的参数"
]
| train | https://github.com/zhangguangyong/codes/blob/5585c17ea46af665582734f399c05dfbba18c30d/codes-persistent-hibernate/src/main/java/com/codes/persistence/hibernate/dao/QueryParameterWrap.java#L128-L137 |
geomajas/geomajas-project-server | plugin/layer-common/layer-common/src/main/java/org/geomajas/layer/common/proxy/CachingLayerHttpService.java | CachingLayerHttpService.getStream | public InputStream getStream(String url, RasterLayer layer) throws IOException {
"""
Get the contents from the request URL.
@param url URL to get the response from
@param layer the raster layer
@return {@link InputStream} with the content
@throws IOException cannot get content
"""
if (layer instanceof ProxyLayerSupport) {
ProxyLayerSupport proxyLayer = (ProxyLayerSupport) layer;
if (proxyLayer.isUseCache() && null != cacheManagerService) {
Object cachedObject = cacheManagerService.get(proxyLayer, CacheCategory.RASTER, url);
if (null != cachedObject) {
testRecorder.record(TEST_RECORDER_GROUP, TEST_RECORDER_GET_FROM_CACHE);
return new ByteArrayInputStream((byte[]) cachedObject);
} else {
testRecorder.record(TEST_RECORDER_GROUP, TEST_RECORDER_PUT_IN_CACHE);
InputStream stream = super.getStream(url, proxyLayer);
ByteArrayOutputStream os = new ByteArrayOutputStream();
int b;
while ((b = stream.read()) >= 0) {
os.write(b);
}
cacheManagerService.put(proxyLayer, CacheCategory.RASTER, url, os.toByteArray(),
getLayerEnvelope(proxyLayer));
return new ByteArrayInputStream((byte[]) os.toByteArray());
}
}
}
return super.getStream(url, layer);
} | java | public InputStream getStream(String url, RasterLayer layer) throws IOException {
if (layer instanceof ProxyLayerSupport) {
ProxyLayerSupport proxyLayer = (ProxyLayerSupport) layer;
if (proxyLayer.isUseCache() && null != cacheManagerService) {
Object cachedObject = cacheManagerService.get(proxyLayer, CacheCategory.RASTER, url);
if (null != cachedObject) {
testRecorder.record(TEST_RECORDER_GROUP, TEST_RECORDER_GET_FROM_CACHE);
return new ByteArrayInputStream((byte[]) cachedObject);
} else {
testRecorder.record(TEST_RECORDER_GROUP, TEST_RECORDER_PUT_IN_CACHE);
InputStream stream = super.getStream(url, proxyLayer);
ByteArrayOutputStream os = new ByteArrayOutputStream();
int b;
while ((b = stream.read()) >= 0) {
os.write(b);
}
cacheManagerService.put(proxyLayer, CacheCategory.RASTER, url, os.toByteArray(),
getLayerEnvelope(proxyLayer));
return new ByteArrayInputStream((byte[]) os.toByteArray());
}
}
}
return super.getStream(url, layer);
} | [
"public",
"InputStream",
"getStream",
"(",
"String",
"url",
",",
"RasterLayer",
"layer",
")",
"throws",
"IOException",
"{",
"if",
"(",
"layer",
"instanceof",
"ProxyLayerSupport",
")",
"{",
"ProxyLayerSupport",
"proxyLayer",
"=",
"(",
"ProxyLayerSupport",
")",
"layer",
";",
"if",
"(",
"proxyLayer",
".",
"isUseCache",
"(",
")",
"&&",
"null",
"!=",
"cacheManagerService",
")",
"{",
"Object",
"cachedObject",
"=",
"cacheManagerService",
".",
"get",
"(",
"proxyLayer",
",",
"CacheCategory",
".",
"RASTER",
",",
"url",
")",
";",
"if",
"(",
"null",
"!=",
"cachedObject",
")",
"{",
"testRecorder",
".",
"record",
"(",
"TEST_RECORDER_GROUP",
",",
"TEST_RECORDER_GET_FROM_CACHE",
")",
";",
"return",
"new",
"ByteArrayInputStream",
"(",
"(",
"byte",
"[",
"]",
")",
"cachedObject",
")",
";",
"}",
"else",
"{",
"testRecorder",
".",
"record",
"(",
"TEST_RECORDER_GROUP",
",",
"TEST_RECORDER_PUT_IN_CACHE",
")",
";",
"InputStream",
"stream",
"=",
"super",
".",
"getStream",
"(",
"url",
",",
"proxyLayer",
")",
";",
"ByteArrayOutputStream",
"os",
"=",
"new",
"ByteArrayOutputStream",
"(",
")",
";",
"int",
"b",
";",
"while",
"(",
"(",
"b",
"=",
"stream",
".",
"read",
"(",
")",
")",
">=",
"0",
")",
"{",
"os",
".",
"write",
"(",
"b",
")",
";",
"}",
"cacheManagerService",
".",
"put",
"(",
"proxyLayer",
",",
"CacheCategory",
".",
"RASTER",
",",
"url",
",",
"os",
".",
"toByteArray",
"(",
")",
",",
"getLayerEnvelope",
"(",
"proxyLayer",
")",
")",
";",
"return",
"new",
"ByteArrayInputStream",
"(",
"(",
"byte",
"[",
"]",
")",
"os",
".",
"toByteArray",
"(",
")",
")",
";",
"}",
"}",
"}",
"return",
"super",
".",
"getStream",
"(",
"url",
",",
"layer",
")",
";",
"}"
]
| Get the contents from the request URL.
@param url URL to get the response from
@param layer the raster layer
@return {@link InputStream} with the content
@throws IOException cannot get content | [
"Get",
"the",
"contents",
"from",
"the",
"request",
"URL",
"."
]
| train | https://github.com/geomajas/geomajas-project-server/blob/904b7d7deed1350d28955589098dd1e0a786d76e/plugin/layer-common/layer-common/src/main/java/org/geomajas/layer/common/proxy/CachingLayerHttpService.java#L69-L92 |
elastic/elasticsearch-hadoop | mr/src/main/java/org/elasticsearch/hadoop/rest/RestRepository.java | RestRepository.scanLimit | ScrollQuery scanLimit(String query, BytesArray body, long limit, ScrollReader reader) {
"""
Returns a pageable (scan based) result to the given query.
@param query scan query
@param reader scroll reader
@return a scroll query
"""
return new ScrollQuery(this, query, body, limit, reader);
} | java | ScrollQuery scanLimit(String query, BytesArray body, long limit, ScrollReader reader) {
return new ScrollQuery(this, query, body, limit, reader);
} | [
"ScrollQuery",
"scanLimit",
"(",
"String",
"query",
",",
"BytesArray",
"body",
",",
"long",
"limit",
",",
"ScrollReader",
"reader",
")",
"{",
"return",
"new",
"ScrollQuery",
"(",
"this",
",",
"query",
",",
"body",
",",
"limit",
",",
"reader",
")",
";",
"}"
]
| Returns a pageable (scan based) result to the given query.
@param query scan query
@param reader scroll reader
@return a scroll query | [
"Returns",
"a",
"pageable",
"(",
"scan",
"based",
")",
"result",
"to",
"the",
"given",
"query",
"."
]
| train | https://github.com/elastic/elasticsearch-hadoop/blob/f3acaba268ff96efae8eb946088c748c777c22cc/mr/src/main/java/org/elasticsearch/hadoop/rest/RestRepository.java#L153-L155 |
pmwmedia/tinylog | tinylog-api/src/main/java/org/tinylog/configuration/Configuration.java | Configuration.load | private static void load(final Properties properties, final InputStream stream) throws IOException {
"""
Puts all properties from a stream to an existing properties object. Already existing properties will be
overridden.
@param properties
Read properties will be put to this properties object
@param stream
Input stream with a properties file
@throws IOException
Failed reading properties from input stream
"""
try {
properties.load(stream);
} finally {
stream.close();
}
} | java | private static void load(final Properties properties, final InputStream stream) throws IOException {
try {
properties.load(stream);
} finally {
stream.close();
}
} | [
"private",
"static",
"void",
"load",
"(",
"final",
"Properties",
"properties",
",",
"final",
"InputStream",
"stream",
")",
"throws",
"IOException",
"{",
"try",
"{",
"properties",
".",
"load",
"(",
"stream",
")",
";",
"}",
"finally",
"{",
"stream",
".",
"close",
"(",
")",
";",
"}",
"}"
]
| Puts all properties from a stream to an existing properties object. Already existing properties will be
overridden.
@param properties
Read properties will be put to this properties object
@param stream
Input stream with a properties file
@throws IOException
Failed reading properties from input stream | [
"Puts",
"all",
"properties",
"from",
"a",
"stream",
"to",
"an",
"existing",
"properties",
"object",
".",
"Already",
"existing",
"properties",
"will",
"be",
"overridden",
"."
]
| train | https://github.com/pmwmedia/tinylog/blob/d03d4ef84a1310155037e08ca8822a91697d1086/tinylog-api/src/main/java/org/tinylog/configuration/Configuration.java#L221-L227 |
samskivert/samskivert | src/main/java/com/samskivert/util/SortableArrayList.java | SortableArrayList.binarySearch | public int binarySearch (T key, Comparator<? super T> comp) {
"""
Performs a binary search, attempting to locate the specified
object. The array must be in the sort order defined by the supplied
{@link Comparator} for this to operate correctly.
@return the index of the object in question or
<code>(-(<i>insertion point</i>) - 1)</code> (always a negative
value) if the object was not found in the list.
"""
return ArrayUtil.binarySearch(_elements, 0, _size, key, comp);
} | java | public int binarySearch (T key, Comparator<? super T> comp)
{
return ArrayUtil.binarySearch(_elements, 0, _size, key, comp);
} | [
"public",
"int",
"binarySearch",
"(",
"T",
"key",
",",
"Comparator",
"<",
"?",
"super",
"T",
">",
"comp",
")",
"{",
"return",
"ArrayUtil",
".",
"binarySearch",
"(",
"_elements",
",",
"0",
",",
"_size",
",",
"key",
",",
"comp",
")",
";",
"}"
]
| Performs a binary search, attempting to locate the specified
object. The array must be in the sort order defined by the supplied
{@link Comparator} for this to operate correctly.
@return the index of the object in question or
<code>(-(<i>insertion point</i>) - 1)</code> (always a negative
value) if the object was not found in the list. | [
"Performs",
"a",
"binary",
"search",
"attempting",
"to",
"locate",
"the",
"specified",
"object",
".",
"The",
"array",
"must",
"be",
"in",
"the",
"sort",
"order",
"defined",
"by",
"the",
"supplied",
"{",
"@link",
"Comparator",
"}",
"for",
"this",
"to",
"operate",
"correctly",
"."
]
| train | https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/util/SortableArrayList.java#L67-L70 |
alkacon/opencms-core | src/org/opencms/main/CmsShellCommands.java | CmsShellCommands.exportResourcesAndUserdata | public void exportResourcesAndUserdata(String exportFile, String pathList) throws Exception {
"""
Exports a list of resources from the current site root and the user data to a ZIP file.<p>
The resource names in the list must be separated with a ";".<p>
@param exportFile the name (absolute path) of the ZIP file to export to
@param pathList the list of resource to export, separated with a ";"
@throws Exception if something goes wrong
"""
exportResourcesAndUserdata(exportFile, pathList, false);
} | java | public void exportResourcesAndUserdata(String exportFile, String pathList) throws Exception {
exportResourcesAndUserdata(exportFile, pathList, false);
} | [
"public",
"void",
"exportResourcesAndUserdata",
"(",
"String",
"exportFile",
",",
"String",
"pathList",
")",
"throws",
"Exception",
"{",
"exportResourcesAndUserdata",
"(",
"exportFile",
",",
"pathList",
",",
"false",
")",
";",
"}"
]
| Exports a list of resources from the current site root and the user data to a ZIP file.<p>
The resource names in the list must be separated with a ";".<p>
@param exportFile the name (absolute path) of the ZIP file to export to
@param pathList the list of resource to export, separated with a ";"
@throws Exception if something goes wrong | [
"Exports",
"a",
"list",
"of",
"resources",
"from",
"the",
"current",
"site",
"root",
"and",
"the",
"user",
"data",
"to",
"a",
"ZIP",
"file",
".",
"<p",
">"
]
| train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/main/CmsShellCommands.java#L723-L726 |
graknlabs/grakn | server/src/server/kb/concept/ElementFactory.java | ElementFactory.buildRelation | RelationImpl buildRelation(VertexElement vertex, RelationType type) {
"""
Used by RelationTypeImpl to create a new instance of RelationImpl
first build a ReifiedRelation and then inject it to RelationImpl
@return
"""
return getOrBuildConcept(vertex, (v) -> RelationImpl.create(buildRelationReified(v, type)));
} | java | RelationImpl buildRelation(VertexElement vertex, RelationType type) {
return getOrBuildConcept(vertex, (v) -> RelationImpl.create(buildRelationReified(v, type)));
} | [
"RelationImpl",
"buildRelation",
"(",
"VertexElement",
"vertex",
",",
"RelationType",
"type",
")",
"{",
"return",
"getOrBuildConcept",
"(",
"vertex",
",",
"(",
"v",
")",
"-",
">",
"RelationImpl",
".",
"create",
"(",
"buildRelationReified",
"(",
"v",
",",
"type",
")",
")",
")",
";",
"}"
]
| Used by RelationTypeImpl to create a new instance of RelationImpl
first build a ReifiedRelation and then inject it to RelationImpl
@return | [
"Used",
"by",
"RelationTypeImpl",
"to",
"create",
"a",
"new",
"instance",
"of",
"RelationImpl",
"first",
"build",
"a",
"ReifiedRelation",
"and",
"then",
"inject",
"it",
"to",
"RelationImpl"
]
| train | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/server/kb/concept/ElementFactory.java#L131-L133 |
vznet/mongo-jackson-mapper | src/main/java/net/vz/mongodb/jackson/DBQuery.java | DBQuery.greaterThan | public static Query greaterThan(String field, Object value) {
"""
The field is greater than the given value
@param field The field to compare
@param value The value to compare to
@return the query
"""
return new Query().greaterThan(field, value);
} | java | public static Query greaterThan(String field, Object value) {
return new Query().greaterThan(field, value);
} | [
"public",
"static",
"Query",
"greaterThan",
"(",
"String",
"field",
",",
"Object",
"value",
")",
"{",
"return",
"new",
"Query",
"(",
")",
".",
"greaterThan",
"(",
"field",
",",
"value",
")",
";",
"}"
]
| The field is greater than the given value
@param field The field to compare
@param value The value to compare to
@return the query | [
"The",
"field",
"is",
"greater",
"than",
"the",
"given",
"value"
]
| train | https://github.com/vznet/mongo-jackson-mapper/blob/ecd189aefa89636cddf70fb383f5d676be347976/src/main/java/net/vz/mongodb/jackson/DBQuery.java#L84-L86 |
wisdom-framework/wisdom | core/wisdom-vertx-engine/src/main/java/org/wisdom/framework/vertx/RequestFromVertx.java | RequestFromVertx.parameterAsInteger | @Override
public Integer parameterAsInteger(String name, Integer defaultValue) {
"""
Like {@link #parameter(String, String)}, but converts the
parameter to Integer if found.
<p/>
The parameter is decoded by default.
@param name The name of the post or query parameter
@param defaultValue A default value if parameter not found.
@return The value of the parameter of the defaultValue if not found.
"""
Integer parameter = parameterAsInteger(name);
if (parameter == null) {
return defaultValue;
}
return parameter;
} | java | @Override
public Integer parameterAsInteger(String name, Integer defaultValue) {
Integer parameter = parameterAsInteger(name);
if (parameter == null) {
return defaultValue;
}
return parameter;
} | [
"@",
"Override",
"public",
"Integer",
"parameterAsInteger",
"(",
"String",
"name",
",",
"Integer",
"defaultValue",
")",
"{",
"Integer",
"parameter",
"=",
"parameterAsInteger",
"(",
"name",
")",
";",
"if",
"(",
"parameter",
"==",
"null",
")",
"{",
"return",
"defaultValue",
";",
"}",
"return",
"parameter",
";",
"}"
]
| Like {@link #parameter(String, String)}, but converts the
parameter to Integer if found.
<p/>
The parameter is decoded by default.
@param name The name of the post or query parameter
@param defaultValue A default value if parameter not found.
@return The value of the parameter of the defaultValue if not found. | [
"Like",
"{",
"@link",
"#parameter",
"(",
"String",
"String",
")",
"}",
"but",
"converts",
"the",
"parameter",
"to",
"Integer",
"if",
"found",
".",
"<p",
"/",
">",
"The",
"parameter",
"is",
"decoded",
"by",
"default",
"."
]
| train | https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/core/wisdom-vertx-engine/src/main/java/org/wisdom/framework/vertx/RequestFromVertx.java#L439-L446 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jpa.container.core/src/com/ibm/ws/jpa/management/CapturingClassTransformer.java | CapturingClassTransformer.initialize | private void initialize(final File logDirectory, final String aaplName) {
"""
Determines the existence of the server log directory, and attempts to create a capture
directory within the log directory. If this can be accomplished, the field captureEnabled
is set to true. Otherwise, it is left to its default value false if the capture directory
cannot be used.
@param logDirectory
"""
if (logDirectory == null) {
captureEnabled = false;
return;
}
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
public Void run() {
// Create a new or reuse an existing base capture directory
String captureDirStr = "JPATransform" + "/" + ((aaplName != null) ? aaplName : "unknownapp");
captureRootDir = new File(logDirectory, captureDirStr);
captureEnabled = captureRootDir.mkdirs() || captureRootDir.isDirectory();
if (!captureEnabled) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Cannot create server instance capture directory, so enhanced entity bytecode will not be captured.");
}
} else {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Capturing enhanced bytecode for JPA entities to " + captureRootDir.getAbsolutePath());
}
}
return null;
}
});
} | java | private void initialize(final File logDirectory, final String aaplName) {
if (logDirectory == null) {
captureEnabled = false;
return;
}
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
public Void run() {
// Create a new or reuse an existing base capture directory
String captureDirStr = "JPATransform" + "/" + ((aaplName != null) ? aaplName : "unknownapp");
captureRootDir = new File(logDirectory, captureDirStr);
captureEnabled = captureRootDir.mkdirs() || captureRootDir.isDirectory();
if (!captureEnabled) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Cannot create server instance capture directory, so enhanced entity bytecode will not be captured.");
}
} else {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Capturing enhanced bytecode for JPA entities to " + captureRootDir.getAbsolutePath());
}
}
return null;
}
});
} | [
"private",
"void",
"initialize",
"(",
"final",
"File",
"logDirectory",
",",
"final",
"String",
"aaplName",
")",
"{",
"if",
"(",
"logDirectory",
"==",
"null",
")",
"{",
"captureEnabled",
"=",
"false",
";",
"return",
";",
"}",
"AccessController",
".",
"doPrivileged",
"(",
"new",
"PrivilegedAction",
"<",
"Void",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"Void",
"run",
"(",
")",
"{",
"// Create a new or reuse an existing base capture directory",
"String",
"captureDirStr",
"=",
"\"JPATransform\"",
"+",
"\"/\"",
"+",
"(",
"(",
"aaplName",
"!=",
"null",
")",
"?",
"aaplName",
":",
"\"unknownapp\"",
")",
";",
"captureRootDir",
"=",
"new",
"File",
"(",
"logDirectory",
",",
"captureDirStr",
")",
";",
"captureEnabled",
"=",
"captureRootDir",
".",
"mkdirs",
"(",
")",
"||",
"captureRootDir",
".",
"isDirectory",
"(",
")",
";",
"if",
"(",
"!",
"captureEnabled",
")",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"Tr",
".",
"debug",
"(",
"tc",
",",
"\"Cannot create server instance capture directory, so enhanced entity bytecode will not be captured.\"",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"Tr",
".",
"debug",
"(",
"tc",
",",
"\"Capturing enhanced bytecode for JPA entities to \"",
"+",
"captureRootDir",
".",
"getAbsolutePath",
"(",
")",
")",
";",
"}",
"}",
"return",
"null",
";",
"}",
"}",
")",
";",
"}"
]
| Determines the existence of the server log directory, and attempts to create a capture
directory within the log directory. If this can be accomplished, the field captureEnabled
is set to true. Otherwise, it is left to its default value false if the capture directory
cannot be used.
@param logDirectory | [
"Determines",
"the",
"existence",
"of",
"the",
"server",
"log",
"directory",
"and",
"attempts",
"to",
"create",
"a",
"capture",
"directory",
"within",
"the",
"log",
"directory",
".",
"If",
"this",
"can",
"be",
"accomplished",
"the",
"field",
"captureEnabled",
"is",
"set",
"to",
"true",
".",
"Otherwise",
"it",
"is",
"left",
"to",
"its",
"default",
"value",
"false",
"if",
"the",
"capture",
"directory",
"cannot",
"be",
"used",
"."
]
| train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jpa.container.core/src/com/ibm/ws/jpa/management/CapturingClassTransformer.java#L128-L155 |
apache/flink | flink-scala-shell/src/main/java/org/apache/flink/api/java/JarHelper.java | JarHelper.jarDir | public void jarDir(File dirOrFile2Jar, File destJar)
throws IOException {
"""
Jars a given directory or single file into a JarOutputStream.
"""
if (dirOrFile2Jar == null || destJar == null) {
throw new IllegalArgumentException();
}
mDestJarName = destJar.getCanonicalPath();
FileOutputStream fout = new FileOutputStream(destJar);
JarOutputStream jout = new JarOutputStream(fout);
//jout.setLevel(0);
try {
jarDir(dirOrFile2Jar, jout, null);
} catch (IOException ioe) {
throw ioe;
} finally {
jout.close();
fout.close();
}
} | java | public void jarDir(File dirOrFile2Jar, File destJar)
throws IOException {
if (dirOrFile2Jar == null || destJar == null) {
throw new IllegalArgumentException();
}
mDestJarName = destJar.getCanonicalPath();
FileOutputStream fout = new FileOutputStream(destJar);
JarOutputStream jout = new JarOutputStream(fout);
//jout.setLevel(0);
try {
jarDir(dirOrFile2Jar, jout, null);
} catch (IOException ioe) {
throw ioe;
} finally {
jout.close();
fout.close();
}
} | [
"public",
"void",
"jarDir",
"(",
"File",
"dirOrFile2Jar",
",",
"File",
"destJar",
")",
"throws",
"IOException",
"{",
"if",
"(",
"dirOrFile2Jar",
"==",
"null",
"||",
"destJar",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
")",
";",
"}",
"mDestJarName",
"=",
"destJar",
".",
"getCanonicalPath",
"(",
")",
";",
"FileOutputStream",
"fout",
"=",
"new",
"FileOutputStream",
"(",
"destJar",
")",
";",
"JarOutputStream",
"jout",
"=",
"new",
"JarOutputStream",
"(",
"fout",
")",
";",
"//jout.setLevel(0);",
"try",
"{",
"jarDir",
"(",
"dirOrFile2Jar",
",",
"jout",
",",
"null",
")",
";",
"}",
"catch",
"(",
"IOException",
"ioe",
")",
"{",
"throw",
"ioe",
";",
"}",
"finally",
"{",
"jout",
".",
"close",
"(",
")",
";",
"fout",
".",
"close",
"(",
")",
";",
"}",
"}"
]
| Jars a given directory or single file into a JarOutputStream. | [
"Jars",
"a",
"given",
"directory",
"or",
"single",
"file",
"into",
"a",
"JarOutputStream",
"."
]
| train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-scala-shell/src/main/java/org/apache/flink/api/java/JarHelper.java#L71-L90 |
MariaDB/mariadb-connector-j | src/main/java/org/mariadb/jdbc/internal/failover/impl/AuroraListener.java | AuroraListener.searchForMasterHostAddress | private HostAddress searchForMasterHostAddress(Protocol protocol, List<HostAddress> loopAddress)
throws SQLException {
"""
Aurora replica doesn't have the master endpoint but the master instance name. since the end
point normally use the instance name like "instance-name.some_unique_string.region.rds.amazonaws.com",
if an endpoint start with this instance name, it will be checked first. Otherwise, the endpoint
ending string is extracted and used since the writer was newly created.
@param protocol current protocol
@param loopAddress list of possible hosts
@return the probable host address or null if no valid endpoint found
@throws SQLException if any connection error occur
"""
String masterHostName;
proxy.lock.lock();
try {
Results results = new Results();
protocol.executeQuery(false, results,
"select server_id from information_schema.replica_host_status "
+ "where session_id = 'MASTER_SESSION_ID' "
+ "and last_update_timestamp > now() - INTERVAL 3 MINUTE "
+ "ORDER BY last_update_timestamp DESC LIMIT 1");
results.commandEnd();
ResultSet queryResult = results.getResultSet();
if (!queryResult.isBeforeFirst()) {
return null;
} else {
queryResult.next();
masterHostName = queryResult.getString(1);
}
} finally {
proxy.lock.unlock();
}
Matcher matcher;
if (masterHostName != null) {
for (HostAddress hostAddress : loopAddress) {
matcher = auroraDnsPattern.matcher(hostAddress.host);
if (hostAddress.host.startsWith(masterHostName) && !matcher.find()) {
return hostAddress;
}
}
HostAddress masterHostAddress;
if (clusterDnsSuffix == null && protocol.getHost().contains(".")) {
clusterDnsSuffix = protocol.getHost().substring(protocol.getHost().indexOf(".") + 1);
} else {
return null;
}
masterHostAddress = new HostAddress(masterHostName + "." + clusterDnsSuffix,
protocol.getPort(), null);
loopAddress.add(masterHostAddress);
urlParser.setHostAddresses(loopAddress);
return masterHostAddress;
}
return null;
} | java | private HostAddress searchForMasterHostAddress(Protocol protocol, List<HostAddress> loopAddress)
throws SQLException {
String masterHostName;
proxy.lock.lock();
try {
Results results = new Results();
protocol.executeQuery(false, results,
"select server_id from information_schema.replica_host_status "
+ "where session_id = 'MASTER_SESSION_ID' "
+ "and last_update_timestamp > now() - INTERVAL 3 MINUTE "
+ "ORDER BY last_update_timestamp DESC LIMIT 1");
results.commandEnd();
ResultSet queryResult = results.getResultSet();
if (!queryResult.isBeforeFirst()) {
return null;
} else {
queryResult.next();
masterHostName = queryResult.getString(1);
}
} finally {
proxy.lock.unlock();
}
Matcher matcher;
if (masterHostName != null) {
for (HostAddress hostAddress : loopAddress) {
matcher = auroraDnsPattern.matcher(hostAddress.host);
if (hostAddress.host.startsWith(masterHostName) && !matcher.find()) {
return hostAddress;
}
}
HostAddress masterHostAddress;
if (clusterDnsSuffix == null && protocol.getHost().contains(".")) {
clusterDnsSuffix = protocol.getHost().substring(protocol.getHost().indexOf(".") + 1);
} else {
return null;
}
masterHostAddress = new HostAddress(masterHostName + "." + clusterDnsSuffix,
protocol.getPort(), null);
loopAddress.add(masterHostAddress);
urlParser.setHostAddresses(loopAddress);
return masterHostAddress;
}
return null;
} | [
"private",
"HostAddress",
"searchForMasterHostAddress",
"(",
"Protocol",
"protocol",
",",
"List",
"<",
"HostAddress",
">",
"loopAddress",
")",
"throws",
"SQLException",
"{",
"String",
"masterHostName",
";",
"proxy",
".",
"lock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"Results",
"results",
"=",
"new",
"Results",
"(",
")",
";",
"protocol",
".",
"executeQuery",
"(",
"false",
",",
"results",
",",
"\"select server_id from information_schema.replica_host_status \"",
"+",
"\"where session_id = 'MASTER_SESSION_ID' \"",
"+",
"\"and last_update_timestamp > now() - INTERVAL 3 MINUTE \"",
"+",
"\"ORDER BY last_update_timestamp DESC LIMIT 1\"",
")",
";",
"results",
".",
"commandEnd",
"(",
")",
";",
"ResultSet",
"queryResult",
"=",
"results",
".",
"getResultSet",
"(",
")",
";",
"if",
"(",
"!",
"queryResult",
".",
"isBeforeFirst",
"(",
")",
")",
"{",
"return",
"null",
";",
"}",
"else",
"{",
"queryResult",
".",
"next",
"(",
")",
";",
"masterHostName",
"=",
"queryResult",
".",
"getString",
"(",
"1",
")",
";",
"}",
"}",
"finally",
"{",
"proxy",
".",
"lock",
".",
"unlock",
"(",
")",
";",
"}",
"Matcher",
"matcher",
";",
"if",
"(",
"masterHostName",
"!=",
"null",
")",
"{",
"for",
"(",
"HostAddress",
"hostAddress",
":",
"loopAddress",
")",
"{",
"matcher",
"=",
"auroraDnsPattern",
".",
"matcher",
"(",
"hostAddress",
".",
"host",
")",
";",
"if",
"(",
"hostAddress",
".",
"host",
".",
"startsWith",
"(",
"masterHostName",
")",
"&&",
"!",
"matcher",
".",
"find",
"(",
")",
")",
"{",
"return",
"hostAddress",
";",
"}",
"}",
"HostAddress",
"masterHostAddress",
";",
"if",
"(",
"clusterDnsSuffix",
"==",
"null",
"&&",
"protocol",
".",
"getHost",
"(",
")",
".",
"contains",
"(",
"\".\"",
")",
")",
"{",
"clusterDnsSuffix",
"=",
"protocol",
".",
"getHost",
"(",
")",
".",
"substring",
"(",
"protocol",
".",
"getHost",
"(",
")",
".",
"indexOf",
"(",
"\".\"",
")",
"+",
"1",
")",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"masterHostAddress",
"=",
"new",
"HostAddress",
"(",
"masterHostName",
"+",
"\".\"",
"+",
"clusterDnsSuffix",
",",
"protocol",
".",
"getPort",
"(",
")",
",",
"null",
")",
";",
"loopAddress",
".",
"add",
"(",
"masterHostAddress",
")",
";",
"urlParser",
".",
"setHostAddresses",
"(",
"loopAddress",
")",
";",
"return",
"masterHostAddress",
";",
"}",
"return",
"null",
";",
"}"
]
| Aurora replica doesn't have the master endpoint but the master instance name. since the end
point normally use the instance name like "instance-name.some_unique_string.region.rds.amazonaws.com",
if an endpoint start with this instance name, it will be checked first. Otherwise, the endpoint
ending string is extracted and used since the writer was newly created.
@param protocol current protocol
@param loopAddress list of possible hosts
@return the probable host address or null if no valid endpoint found
@throws SQLException if any connection error occur | [
"Aurora",
"replica",
"doesn",
"t",
"have",
"the",
"master",
"endpoint",
"but",
"the",
"master",
"instance",
"name",
".",
"since",
"the",
"end",
"point",
"normally",
"use",
"the",
"instance",
"name",
"like",
"instance",
"-",
"name",
".",
"some_unique_string",
".",
"region",
".",
"rds",
".",
"amazonaws",
".",
"com",
"if",
"an",
"endpoint",
"start",
"with",
"this",
"instance",
"name",
"it",
"will",
"be",
"checked",
"first",
".",
"Otherwise",
"the",
"endpoint",
"ending",
"string",
"is",
"extracted",
"and",
"used",
"since",
"the",
"writer",
"was",
"newly",
"created",
"."
]
| train | https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/failover/impl/AuroraListener.java#L378-L426 |
eurekaclinical/javautil | src/main/java/org/arp/javautil/arrays/Arrays.java | Arrays.addAll | @SafeVarargs
public static <E> void addAll(Collection<E> collection, E[]... arr) {
"""
Adds the contents of one or more arrays to a collection.
@param collection a {@link Collection}. Cannot be <code>null</code>.
@param arr zero or more <code>E[]</code>.
"""
if (collection == null) {
throw new IllegalArgumentException("collection cannot be null");
}
for (E[] oarr : arr) {
for (E o : oarr) {
collection.add(o);
}
}
} | java | @SafeVarargs
public static <E> void addAll(Collection<E> collection, E[]... arr) {
if (collection == null) {
throw new IllegalArgumentException("collection cannot be null");
}
for (E[] oarr : arr) {
for (E o : oarr) {
collection.add(o);
}
}
} | [
"@",
"SafeVarargs",
"public",
"static",
"<",
"E",
">",
"void",
"addAll",
"(",
"Collection",
"<",
"E",
">",
"collection",
",",
"E",
"[",
"]",
"...",
"arr",
")",
"{",
"if",
"(",
"collection",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"collection cannot be null\"",
")",
";",
"}",
"for",
"(",
"E",
"[",
"]",
"oarr",
":",
"arr",
")",
"{",
"for",
"(",
"E",
"o",
":",
"oarr",
")",
"{",
"collection",
".",
"add",
"(",
"o",
")",
";",
"}",
"}",
"}"
]
| Adds the contents of one or more arrays to a collection.
@param collection a {@link Collection}. Cannot be <code>null</code>.
@param arr zero or more <code>E[]</code>. | [
"Adds",
"the",
"contents",
"of",
"one",
"or",
"more",
"arrays",
"to",
"a",
"collection",
"."
]
| train | https://github.com/eurekaclinical/javautil/blob/779bbc5bf096c75f8eed4f99ca45b99c1d44df43/src/main/java/org/arp/javautil/arrays/Arrays.java#L121-L131 |
lightblue-platform/lightblue-client | http/src/main/java/com/redhat/lightblue/client/http/transport/JavaNetHttpTransport.java | JavaNetHttpTransport.readResponseStream | private String readResponseStream(InputStream responseStream, HttpURLConnection connection)
throws IOException {
"""
Tries to efficiently allocate the response string if the "Content-Length"
header is set.
"""
LOGGER.debug("Reading response stream");
InputStream decodedStream = responseStream;
if (compression == Compression.LZF && "lzf".equals(connection.getHeaderField("Content-Encoding"))) {
LOGGER.debug("Decoding lzf");
decodedStream = new LZFInputStream(responseStream);
}
int contentLength = connection.getContentLength();
if (contentLength == 0) {
return "";
} else {
return new String(ByteStreams.toByteArray(decodedStream), UTF_8);
}
} | java | private String readResponseStream(InputStream responseStream, HttpURLConnection connection)
throws IOException {
LOGGER.debug("Reading response stream");
InputStream decodedStream = responseStream;
if (compression == Compression.LZF && "lzf".equals(connection.getHeaderField("Content-Encoding"))) {
LOGGER.debug("Decoding lzf");
decodedStream = new LZFInputStream(responseStream);
}
int contentLength = connection.getContentLength();
if (contentLength == 0) {
return "";
} else {
return new String(ByteStreams.toByteArray(decodedStream), UTF_8);
}
} | [
"private",
"String",
"readResponseStream",
"(",
"InputStream",
"responseStream",
",",
"HttpURLConnection",
"connection",
")",
"throws",
"IOException",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Reading response stream\"",
")",
";",
"InputStream",
"decodedStream",
"=",
"responseStream",
";",
"if",
"(",
"compression",
"==",
"Compression",
".",
"LZF",
"&&",
"\"lzf\"",
".",
"equals",
"(",
"connection",
".",
"getHeaderField",
"(",
"\"Content-Encoding\"",
")",
")",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Decoding lzf\"",
")",
";",
"decodedStream",
"=",
"new",
"LZFInputStream",
"(",
"responseStream",
")",
";",
"}",
"int",
"contentLength",
"=",
"connection",
".",
"getContentLength",
"(",
")",
";",
"if",
"(",
"contentLength",
"==",
"0",
")",
"{",
"return",
"\"\"",
";",
"}",
"else",
"{",
"return",
"new",
"String",
"(",
"ByteStreams",
".",
"toByteArray",
"(",
"decodedStream",
")",
",",
"UTF_8",
")",
";",
"}",
"}"
]
| Tries to efficiently allocate the response string if the "Content-Length"
header is set. | [
"Tries",
"to",
"efficiently",
"allocate",
"the",
"response",
"string",
"if",
"the",
"Content",
"-",
"Length",
"header",
"is",
"set",
"."
]
| train | https://github.com/lightblue-platform/lightblue-client/blob/03790aff34e90d3889f60fd6c603c21a21dc1a40/http/src/main/java/com/redhat/lightblue/client/http/transport/JavaNetHttpTransport.java#L239-L255 |
unbescape/unbescape | src/main/java/org/unbescape/uri/UriEscape.java | UriEscape.unescapeUriPathSegment | public static void unescapeUriPathSegment(final Reader reader, final Writer writer)
throws IOException {
"""
<p>
Perform am URI path segment <strong>unescape</strong> operation
on a <tt>Reader</tt> input using <tt>UTF-8</tt> as encoding, writing results to a <tt>Writer</tt>.
</p>
<p>
This method will unescape every percent-encoded (<tt>%HH</tt>) sequences present in input,
even for those characters that do not need to be percent-encoded in this context (unreserved characters
can be percent-encoded even if/when this is not required, though it is not generally considered a
good practice).
</p>
<p>
This method will use <tt>UTF-8</tt> in order to determine the characters specified in the
percent-encoded byte sequences.
</p>
<p>
This method is <strong>thread-safe</strong>.
</p>
@param reader the <tt>Reader</tt> reading the text to be unescaped.
@param writer the <tt>java.io.Writer</tt> to which the unescaped result will be written. Nothing will
be written at all to this writer if input is <tt>null</tt>.
@throws IOException if an input/output exception occurs
@since 1.1.2
"""
unescapeUriPathSegment(reader, writer, DEFAULT_ENCODING);
} | java | public static void unescapeUriPathSegment(final Reader reader, final Writer writer)
throws IOException {
unescapeUriPathSegment(reader, writer, DEFAULT_ENCODING);
} | [
"public",
"static",
"void",
"unescapeUriPathSegment",
"(",
"final",
"Reader",
"reader",
",",
"final",
"Writer",
"writer",
")",
"throws",
"IOException",
"{",
"unescapeUriPathSegment",
"(",
"reader",
",",
"writer",
",",
"DEFAULT_ENCODING",
")",
";",
"}"
]
| <p>
Perform am URI path segment <strong>unescape</strong> operation
on a <tt>Reader</tt> input using <tt>UTF-8</tt> as encoding, writing results to a <tt>Writer</tt>.
</p>
<p>
This method will unescape every percent-encoded (<tt>%HH</tt>) sequences present in input,
even for those characters that do not need to be percent-encoded in this context (unreserved characters
can be percent-encoded even if/when this is not required, though it is not generally considered a
good practice).
</p>
<p>
This method will use <tt>UTF-8</tt> in order to determine the characters specified in the
percent-encoded byte sequences.
</p>
<p>
This method is <strong>thread-safe</strong>.
</p>
@param reader the <tt>Reader</tt> reading the text to be unescaped.
@param writer the <tt>java.io.Writer</tt> to which the unescaped result will be written. Nothing will
be written at all to this writer if input is <tt>null</tt>.
@throws IOException if an input/output exception occurs
@since 1.1.2 | [
"<p",
">",
"Perform",
"am",
"URI",
"path",
"segment",
"<strong",
">",
"unescape<",
"/",
"strong",
">",
"operation",
"on",
"a",
"<tt",
">",
"Reader<",
"/",
"tt",
">",
"input",
"using",
"<tt",
">",
"UTF",
"-",
"8<",
"/",
"tt",
">",
"as",
"encoding",
"writing",
"results",
"to",
"a",
"<tt",
">",
"Writer<",
"/",
"tt",
">",
".",
"<",
"/",
"p",
">",
"<p",
">",
"This",
"method",
"will",
"unescape",
"every",
"percent",
"-",
"encoded",
"(",
"<tt",
">",
"%HH<",
"/",
"tt",
">",
")",
"sequences",
"present",
"in",
"input",
"even",
"for",
"those",
"characters",
"that",
"do",
"not",
"need",
"to",
"be",
"percent",
"-",
"encoded",
"in",
"this",
"context",
"(",
"unreserved",
"characters",
"can",
"be",
"percent",
"-",
"encoded",
"even",
"if",
"/",
"when",
"this",
"is",
"not",
"required",
"though",
"it",
"is",
"not",
"generally",
"considered",
"a",
"good",
"practice",
")",
".",
"<",
"/",
"p",
">",
"<p",
">",
"This",
"method",
"will",
"use",
"<tt",
">",
"UTF",
"-",
"8<",
"/",
"tt",
">",
"in",
"order",
"to",
"determine",
"the",
"characters",
"specified",
"in",
"the",
"percent",
"-",
"encoded",
"byte",
"sequences",
".",
"<",
"/",
"p",
">",
"<p",
">",
"This",
"method",
"is",
"<strong",
">",
"thread",
"-",
"safe<",
"/",
"strong",
">",
".",
"<",
"/",
"p",
">"
]
| train | https://github.com/unbescape/unbescape/blob/ec5435fb3508c2eed25d8165dc27ded2602cae13/src/main/java/org/unbescape/uri/UriEscape.java#L2186-L2189 |
mojohaus/jaxb2-maven-plugin | src/main/java/org/codehaus/mojo/jaxb2/shared/arguments/ArgumentBuilder.java | ArgumentBuilder.withFlag | public ArgumentBuilder withFlag(final boolean addFlag, final String flag) {
"""
<p>Adds a flag on the form {@code -someflag} to the list of arguments contained within this ArgumentBuilder.
If the {@code flag} argument does not start with a dash ('-'), one will be prepended.</p>
<p>Typical usage:</p>
<pre><code>
argumentBuilder
.withFlag(someBooleanParameter, "foobar")
.withFlag(someOtherBooleanParameter, "gnat")
.withFlag(someThirdBooleanParameter, "gnu")
....
</code></pre>
@param addFlag if {@code true}, the flag will be added to the underlying list of arguments
within this ArgumentBuilder.
@param flag The flag/argument to add. The flag must be a complete word, implying it
cannot contain whitespace.
@return This ArgumentBuilder, for chaining.
"""
// Bail out?
if (!addFlag) {
return this;
}
// Check sanity
Validate.notEmpty(flag, "flag");
Validate.isTrue(!AbstractJaxbMojo.CONTAINS_WHITESPACE.matcher(flag).matches(),
"Flags cannot contain whitespace. Got: [" + flag + "]");
// Trim, and add the flag as an argument.
final String trimmed = flag.trim();
Validate.notEmpty(trimmed, "flag");
// Prepend the DASH if required
final String toAdd = trimmed.charAt(0) != DASH ? DASH + trimmed : trimmed;
// Assign the argument only if not already set.
if (getIndexForFlag(toAdd) == NOT_FOUND) {
synchronized (lock) {
arguments.add(toAdd);
}
}
// All done.
return this;
} | java | public ArgumentBuilder withFlag(final boolean addFlag, final String flag) {
// Bail out?
if (!addFlag) {
return this;
}
// Check sanity
Validate.notEmpty(flag, "flag");
Validate.isTrue(!AbstractJaxbMojo.CONTAINS_WHITESPACE.matcher(flag).matches(),
"Flags cannot contain whitespace. Got: [" + flag + "]");
// Trim, and add the flag as an argument.
final String trimmed = flag.trim();
Validate.notEmpty(trimmed, "flag");
// Prepend the DASH if required
final String toAdd = trimmed.charAt(0) != DASH ? DASH + trimmed : trimmed;
// Assign the argument only if not already set.
if (getIndexForFlag(toAdd) == NOT_FOUND) {
synchronized (lock) {
arguments.add(toAdd);
}
}
// All done.
return this;
} | [
"public",
"ArgumentBuilder",
"withFlag",
"(",
"final",
"boolean",
"addFlag",
",",
"final",
"String",
"flag",
")",
"{",
"// Bail out?",
"if",
"(",
"!",
"addFlag",
")",
"{",
"return",
"this",
";",
"}",
"// Check sanity",
"Validate",
".",
"notEmpty",
"(",
"flag",
",",
"\"flag\"",
")",
";",
"Validate",
".",
"isTrue",
"(",
"!",
"AbstractJaxbMojo",
".",
"CONTAINS_WHITESPACE",
".",
"matcher",
"(",
"flag",
")",
".",
"matches",
"(",
")",
",",
"\"Flags cannot contain whitespace. Got: [\"",
"+",
"flag",
"+",
"\"]\"",
")",
";",
"// Trim, and add the flag as an argument.",
"final",
"String",
"trimmed",
"=",
"flag",
".",
"trim",
"(",
")",
";",
"Validate",
".",
"notEmpty",
"(",
"trimmed",
",",
"\"flag\"",
")",
";",
"// Prepend the DASH if required",
"final",
"String",
"toAdd",
"=",
"trimmed",
".",
"charAt",
"(",
"0",
")",
"!=",
"DASH",
"?",
"DASH",
"+",
"trimmed",
":",
"trimmed",
";",
"// Assign the argument only if not already set.",
"if",
"(",
"getIndexForFlag",
"(",
"toAdd",
")",
"==",
"NOT_FOUND",
")",
"{",
"synchronized",
"(",
"lock",
")",
"{",
"arguments",
".",
"add",
"(",
"toAdd",
")",
";",
"}",
"}",
"// All done.",
"return",
"this",
";",
"}"
]
| <p>Adds a flag on the form {@code -someflag} to the list of arguments contained within this ArgumentBuilder.
If the {@code flag} argument does not start with a dash ('-'), one will be prepended.</p>
<p>Typical usage:</p>
<pre><code>
argumentBuilder
.withFlag(someBooleanParameter, "foobar")
.withFlag(someOtherBooleanParameter, "gnat")
.withFlag(someThirdBooleanParameter, "gnu")
....
</code></pre>
@param addFlag if {@code true}, the flag will be added to the underlying list of arguments
within this ArgumentBuilder.
@param flag The flag/argument to add. The flag must be a complete word, implying it
cannot contain whitespace.
@return This ArgumentBuilder, for chaining. | [
"<p",
">",
"Adds",
"a",
"flag",
"on",
"the",
"form",
"{",
"@code",
"-",
"someflag",
"}",
"to",
"the",
"list",
"of",
"arguments",
"contained",
"within",
"this",
"ArgumentBuilder",
".",
"If",
"the",
"{",
"@code",
"flag",
"}",
"argument",
"does",
"not",
"start",
"with",
"a",
"dash",
"(",
"-",
")",
"one",
"will",
"be",
"prepended",
".",
"<",
"/",
"p",
">",
"<p",
">",
"Typical",
"usage",
":",
"<",
"/",
"p",
">",
"<pre",
">",
"<code",
">",
"argumentBuilder",
".",
"withFlag",
"(",
"someBooleanParameter",
"foobar",
")",
".",
"withFlag",
"(",
"someOtherBooleanParameter",
"gnat",
")",
".",
"withFlag",
"(",
"someThirdBooleanParameter",
"gnu",
")",
"....",
"<",
"/",
"code",
">",
"<",
"/",
"pre",
">"
]
| train | https://github.com/mojohaus/jaxb2-maven-plugin/blob/e3c4e47943b15282e5a6e850bbfb1588d8452a0a/src/main/java/org/codehaus/mojo/jaxb2/shared/arguments/ArgumentBuilder.java#L74-L102 |
UrielCh/ovh-java-sdk | ovh-java-sdk-emaildomain/src/main/java/net/minidev/ovh/api/ApiOvhEmaildomain.java | ApiOvhEmaildomain.domain_account_accountName_PUT | public void domain_account_accountName_PUT(String domain, String accountName, OvhAccount body) throws IOException {
"""
Alter this object properties
REST: PUT /email/domain/{domain}/account/{accountName}
@param body [required] New object properties
@param domain [required] Name of your domain name
@param accountName [required] Name of account
"""
String qPath = "/email/domain/{domain}/account/{accountName}";
StringBuilder sb = path(qPath, domain, accountName);
exec(qPath, "PUT", sb.toString(), body);
} | java | public void domain_account_accountName_PUT(String domain, String accountName, OvhAccount body) throws IOException {
String qPath = "/email/domain/{domain}/account/{accountName}";
StringBuilder sb = path(qPath, domain, accountName);
exec(qPath, "PUT", sb.toString(), body);
} | [
"public",
"void",
"domain_account_accountName_PUT",
"(",
"String",
"domain",
",",
"String",
"accountName",
",",
"OvhAccount",
"body",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/email/domain/{domain}/account/{accountName}\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"domain",
",",
"accountName",
")",
";",
"exec",
"(",
"qPath",
",",
"\"PUT\"",
",",
"sb",
".",
"toString",
"(",
")",
",",
"body",
")",
";",
"}"
]
| Alter this object properties
REST: PUT /email/domain/{domain}/account/{accountName}
@param body [required] New object properties
@param domain [required] Name of your domain name
@param accountName [required] Name of account | [
"Alter",
"this",
"object",
"properties"
]
| train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-emaildomain/src/main/java/net/minidev/ovh/api/ApiOvhEmaildomain.java#L843-L847 |
BorderTech/wcomponents | wcomponents-core/src/main/java/com/github/bordertech/wcomponents/container/DefaultPageShell.java | DefaultPageShell.addJsHeadlines | private void addJsHeadlines(final PrintWriter writer, final List jsHeadlines) {
"""
Add a list of javascript headline entries intended to be added only once to the page.
@param writer the writer to write to.
@param jsHeadlines a list of javascript entries to be added to the page as a whole.
"""
if (jsHeadlines == null || jsHeadlines.isEmpty()) {
return;
}
writer.println();
writer.write("\n<!-- Start javascript headlines -->"
+ "\n<script type=\"" + WebUtilities.CONTENT_TYPE_JS + "\">");
for (Object line : jsHeadlines) {
writer.write("\n" + line);
}
writer.write("\n</script>"
+ "\n<!-- End javascript headlines -->");
} | java | private void addJsHeadlines(final PrintWriter writer, final List jsHeadlines) {
if (jsHeadlines == null || jsHeadlines.isEmpty()) {
return;
}
writer.println();
writer.write("\n<!-- Start javascript headlines -->"
+ "\n<script type=\"" + WebUtilities.CONTENT_TYPE_JS + "\">");
for (Object line : jsHeadlines) {
writer.write("\n" + line);
}
writer.write("\n</script>"
+ "\n<!-- End javascript headlines -->");
} | [
"private",
"void",
"addJsHeadlines",
"(",
"final",
"PrintWriter",
"writer",
",",
"final",
"List",
"jsHeadlines",
")",
"{",
"if",
"(",
"jsHeadlines",
"==",
"null",
"||",
"jsHeadlines",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
";",
"}",
"writer",
".",
"println",
"(",
")",
";",
"writer",
".",
"write",
"(",
"\"\\n<!-- Start javascript headlines -->\"",
"+",
"\"\\n<script type=\\\"\"",
"+",
"WebUtilities",
".",
"CONTENT_TYPE_JS",
"+",
"\"\\\">\"",
")",
";",
"for",
"(",
"Object",
"line",
":",
"jsHeadlines",
")",
"{",
"writer",
".",
"write",
"(",
"\"\\n\"",
"+",
"line",
")",
";",
"}",
"writer",
".",
"write",
"(",
"\"\\n</script>\"",
"+",
"\"\\n<!-- End javascript headlines -->\"",
")",
";",
"}"
]
| Add a list of javascript headline entries intended to be added only once to the page.
@param writer the writer to write to.
@param jsHeadlines a list of javascript entries to be added to the page as a whole. | [
"Add",
"a",
"list",
"of",
"javascript",
"headline",
"entries",
"intended",
"to",
"be",
"added",
"only",
"once",
"to",
"the",
"page",
"."
]
| train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/container/DefaultPageShell.java#L162-L177 |
spring-projects/spring-data-solr | src/main/java/org/springframework/data/solr/core/QueryParserBase.java | QueryParserBase.appendDefType | protected void appendDefType(SolrQuery solrQuery, @Nullable String defType) {
"""
Set {@code defType} for {@link SolrQuery}
@param solrQuery
@param defType
"""
if (StringUtils.isNotBlank(defType)) {
solrQuery.set("defType", defType);
}
} | java | protected void appendDefType(SolrQuery solrQuery, @Nullable String defType) {
if (StringUtils.isNotBlank(defType)) {
solrQuery.set("defType", defType);
}
} | [
"protected",
"void",
"appendDefType",
"(",
"SolrQuery",
"solrQuery",
",",
"@",
"Nullable",
"String",
"defType",
")",
"{",
"if",
"(",
"StringUtils",
".",
"isNotBlank",
"(",
"defType",
")",
")",
"{",
"solrQuery",
".",
"set",
"(",
"\"defType\"",
",",
"defType",
")",
";",
"}",
"}"
]
| Set {@code defType} for {@link SolrQuery}
@param solrQuery
@param defType | [
"Set",
"{",
"@code",
"defType",
"}",
"for",
"{",
"@link",
"SolrQuery",
"}"
]
| train | https://github.com/spring-projects/spring-data-solr/blob/20be5cb82498b70134dfda6c1a91ad21f8e657e0/src/main/java/org/springframework/data/solr/core/QueryParserBase.java#L487-L491 |
mebigfatguy/fb-contrib | src/main/java/com/mebigfatguy/fbcontrib/detect/CopiedOverriddenMethod.java | CopiedOverriddenMethod.visitCode | @Override
public void visitCode(Code obj) {
"""
overrides the visitor to find code blocks of methods that are the same as its parents
@param obj
the code object of the currently parsed method
"""
try {
Method m = getMethod();
if ((!m.isPublic() && !m.isProtected()) || m.isAbstract() || m.isSynthetic()) {
return;
}
CodeInfo superCode = superclassCode.remove(curMethodInfo);
if (superCode != null) {
if (sameAccess(getMethod().getAccessFlags(), superCode.getAccess()) && codeEquals(obj, superCode.getCode())) {
bugReporter.reportBug(new BugInstance(this, BugType.COM_COPIED_OVERRIDDEN_METHOD.name(), NORMAL_PRIORITY).addClass(this).addMethod(this)
.addSourceLine(classContext, this, getPC()));
return;
}
if ((getMethod().getAccessFlags() & Const.ACC_SYNCHRONIZED) != (superCode.getAccess() & Const.ACC_SYNCHRONIZED)) {
return;
}
parmTypes = getMethod().getArgumentTypes();
nextParmIndex = 0;
nextParmOffset = getMethod().isStatic() ? 0 : 1;
sawAload0 = nextParmOffset == 0;
sawParentCall = false;
super.visitCode(obj);
}
} catch (StopOpcodeParsingException e) {
// method is unique
}
} | java | @Override
public void visitCode(Code obj) {
try {
Method m = getMethod();
if ((!m.isPublic() && !m.isProtected()) || m.isAbstract() || m.isSynthetic()) {
return;
}
CodeInfo superCode = superclassCode.remove(curMethodInfo);
if (superCode != null) {
if (sameAccess(getMethod().getAccessFlags(), superCode.getAccess()) && codeEquals(obj, superCode.getCode())) {
bugReporter.reportBug(new BugInstance(this, BugType.COM_COPIED_OVERRIDDEN_METHOD.name(), NORMAL_PRIORITY).addClass(this).addMethod(this)
.addSourceLine(classContext, this, getPC()));
return;
}
if ((getMethod().getAccessFlags() & Const.ACC_SYNCHRONIZED) != (superCode.getAccess() & Const.ACC_SYNCHRONIZED)) {
return;
}
parmTypes = getMethod().getArgumentTypes();
nextParmIndex = 0;
nextParmOffset = getMethod().isStatic() ? 0 : 1;
sawAload0 = nextParmOffset == 0;
sawParentCall = false;
super.visitCode(obj);
}
} catch (StopOpcodeParsingException e) {
// method is unique
}
} | [
"@",
"Override",
"public",
"void",
"visitCode",
"(",
"Code",
"obj",
")",
"{",
"try",
"{",
"Method",
"m",
"=",
"getMethod",
"(",
")",
";",
"if",
"(",
"(",
"!",
"m",
".",
"isPublic",
"(",
")",
"&&",
"!",
"m",
".",
"isProtected",
"(",
")",
")",
"||",
"m",
".",
"isAbstract",
"(",
")",
"||",
"m",
".",
"isSynthetic",
"(",
")",
")",
"{",
"return",
";",
"}",
"CodeInfo",
"superCode",
"=",
"superclassCode",
".",
"remove",
"(",
"curMethodInfo",
")",
";",
"if",
"(",
"superCode",
"!=",
"null",
")",
"{",
"if",
"(",
"sameAccess",
"(",
"getMethod",
"(",
")",
".",
"getAccessFlags",
"(",
")",
",",
"superCode",
".",
"getAccess",
"(",
")",
")",
"&&",
"codeEquals",
"(",
"obj",
",",
"superCode",
".",
"getCode",
"(",
")",
")",
")",
"{",
"bugReporter",
".",
"reportBug",
"(",
"new",
"BugInstance",
"(",
"this",
",",
"BugType",
".",
"COM_COPIED_OVERRIDDEN_METHOD",
".",
"name",
"(",
")",
",",
"NORMAL_PRIORITY",
")",
".",
"addClass",
"(",
"this",
")",
".",
"addMethod",
"(",
"this",
")",
".",
"addSourceLine",
"(",
"classContext",
",",
"this",
",",
"getPC",
"(",
")",
")",
")",
";",
"return",
";",
"}",
"if",
"(",
"(",
"getMethod",
"(",
")",
".",
"getAccessFlags",
"(",
")",
"&",
"Const",
".",
"ACC_SYNCHRONIZED",
")",
"!=",
"(",
"superCode",
".",
"getAccess",
"(",
")",
"&",
"Const",
".",
"ACC_SYNCHRONIZED",
")",
")",
"{",
"return",
";",
"}",
"parmTypes",
"=",
"getMethod",
"(",
")",
".",
"getArgumentTypes",
"(",
")",
";",
"nextParmIndex",
"=",
"0",
";",
"nextParmOffset",
"=",
"getMethod",
"(",
")",
".",
"isStatic",
"(",
")",
"?",
"0",
":",
"1",
";",
"sawAload0",
"=",
"nextParmOffset",
"==",
"0",
";",
"sawParentCall",
"=",
"false",
";",
"super",
".",
"visitCode",
"(",
"obj",
")",
";",
"}",
"}",
"catch",
"(",
"StopOpcodeParsingException",
"e",
")",
"{",
"// method is unique",
"}",
"}"
]
| overrides the visitor to find code blocks of methods that are the same as its parents
@param obj
the code object of the currently parsed method | [
"overrides",
"the",
"visitor",
"to",
"find",
"code",
"blocks",
"of",
"methods",
"that",
"are",
"the",
"same",
"as",
"its",
"parents"
]
| train | https://github.com/mebigfatguy/fb-contrib/blob/3b5203196f627b399fbcea3c2ab2b1f4e56cc7b8/src/main/java/com/mebigfatguy/fbcontrib/detect/CopiedOverriddenMethod.java#L132-L163 |
ops4j/org.ops4j.pax.swissbox | pax-swissbox-core/src/main/java/org/ops4j/pax/swissbox/core/BundleUtils.java | BundleUtils.getBundle | public static Bundle getBundle( BundleContext bc, String symbolicName ) {
"""
Returns any bundle with the given symbolic name, or null if no such bundle exists. If there
are multiple bundles with the same symbolic name and different version, this method returns
the first bundle found.
@param bc bundle context
@param symbolicName bundle symbolic name
@return matching bundle, or null
"""
return getBundle( bc, symbolicName, null );
} | java | public static Bundle getBundle( BundleContext bc, String symbolicName )
{
return getBundle( bc, symbolicName, null );
} | [
"public",
"static",
"Bundle",
"getBundle",
"(",
"BundleContext",
"bc",
",",
"String",
"symbolicName",
")",
"{",
"return",
"getBundle",
"(",
"bc",
",",
"symbolicName",
",",
"null",
")",
";",
"}"
]
| Returns any bundle with the given symbolic name, or null if no such bundle exists. If there
are multiple bundles with the same symbolic name and different version, this method returns
the first bundle found.
@param bc bundle context
@param symbolicName bundle symbolic name
@return matching bundle, or null | [
"Returns",
"any",
"bundle",
"with",
"the",
"given",
"symbolic",
"name",
"or",
"null",
"if",
"no",
"such",
"bundle",
"exists",
".",
"If",
"there",
"are",
"multiple",
"bundles",
"with",
"the",
"same",
"symbolic",
"name",
"and",
"different",
"version",
"this",
"method",
"returns",
"the",
"first",
"bundle",
"found",
"."
]
| train | https://github.com/ops4j/org.ops4j.pax.swissbox/blob/00b0ee16cdbe8017984a4d7ba808b10d985c5b5c/pax-swissbox-core/src/main/java/org/ops4j/pax/swissbox/core/BundleUtils.java#L94-L97 |
Azure/azure-sdk-for-java | appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServicePlansInner.java | AppServicePlansInner.createOrUpdateVnetRoute | public VnetRouteInner createOrUpdateVnetRoute(String resourceGroupName, String name, String vnetName, String routeName, VnetRouteInner route) {
"""
Create or update a Virtual Network route in an App Service plan.
Create or update a Virtual Network route in an App Service plan.
@param resourceGroupName Name of the resource group to which the resource belongs.
@param name Name of the App Service plan.
@param vnetName Name of the Virtual Network.
@param routeName Name of the Virtual Network route.
@param route Definition of the Virtual Network route.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the VnetRouteInner object if successful.
"""
return createOrUpdateVnetRouteWithServiceResponseAsync(resourceGroupName, name, vnetName, routeName, route).toBlocking().single().body();
} | java | public VnetRouteInner createOrUpdateVnetRoute(String resourceGroupName, String name, String vnetName, String routeName, VnetRouteInner route) {
return createOrUpdateVnetRouteWithServiceResponseAsync(resourceGroupName, name, vnetName, routeName, route).toBlocking().single().body();
} | [
"public",
"VnetRouteInner",
"createOrUpdateVnetRoute",
"(",
"String",
"resourceGroupName",
",",
"String",
"name",
",",
"String",
"vnetName",
",",
"String",
"routeName",
",",
"VnetRouteInner",
"route",
")",
"{",
"return",
"createOrUpdateVnetRouteWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"name",
",",
"vnetName",
",",
"routeName",
",",
"route",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
"body",
"(",
")",
";",
"}"
]
| Create or update a Virtual Network route in an App Service plan.
Create or update a Virtual Network route in an App Service plan.
@param resourceGroupName Name of the resource group to which the resource belongs.
@param name Name of the App Service plan.
@param vnetName Name of the Virtual Network.
@param routeName Name of the Virtual Network route.
@param route Definition of the Virtual Network route.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the VnetRouteInner object if successful. | [
"Create",
"or",
"update",
"a",
"Virtual",
"Network",
"route",
"in",
"an",
"App",
"Service",
"plan",
".",
"Create",
"or",
"update",
"a",
"Virtual",
"Network",
"route",
"in",
"an",
"App",
"Service",
"plan",
"."
]
| train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServicePlansInner.java#L3593-L3595 |
azkaban/azkaban | azkaban-common/src/main/java/azkaban/server/MBeanRegistrationManager.java | MBeanRegistrationManager.getMBeanAttribute | public Object getMBeanAttribute(final ObjectName name, final String attribute) {
"""
Get MBean Attribute
@param name mbean name
@param attribute attribute name
@return object of MBean Attribute
"""
try {
return getMbeanServer().getAttribute(name, attribute);
} catch (final Exception e) {
logger.error(
"Retrieve MBeanServer attribute Failure. "
+ "ObjectName = " + name.toString() + ", "
+ "attribute = " + attribute,
e);
return null;
}
} | java | public Object getMBeanAttribute(final ObjectName name, final String attribute) {
try {
return getMbeanServer().getAttribute(name, attribute);
} catch (final Exception e) {
logger.error(
"Retrieve MBeanServer attribute Failure. "
+ "ObjectName = " + name.toString() + ", "
+ "attribute = " + attribute,
e);
return null;
}
} | [
"public",
"Object",
"getMBeanAttribute",
"(",
"final",
"ObjectName",
"name",
",",
"final",
"String",
"attribute",
")",
"{",
"try",
"{",
"return",
"getMbeanServer",
"(",
")",
".",
"getAttribute",
"(",
"name",
",",
"attribute",
")",
";",
"}",
"catch",
"(",
"final",
"Exception",
"e",
")",
"{",
"logger",
".",
"error",
"(",
"\"Retrieve MBeanServer attribute Failure. \"",
"+",
"\"ObjectName = \"",
"+",
"name",
".",
"toString",
"(",
")",
"+",
"\", \"",
"+",
"\"attribute = \"",
"+",
"attribute",
",",
"e",
")",
";",
"return",
"null",
";",
"}",
"}"
]
| Get MBean Attribute
@param name mbean name
@param attribute attribute name
@return object of MBean Attribute | [
"Get",
"MBean",
"Attribute"
]
| train | https://github.com/azkaban/azkaban/blob/d258ea7d6e66807c6eff79c5325d6d3443618dff/azkaban-common/src/main/java/azkaban/server/MBeanRegistrationManager.java#L106-L117 |
graknlabs/grakn | server/src/graql/gremlin/spanningtree/datastructure/FibonacciHeap.java | FibonacciHeap.cutAndMakeRoot | private void cutAndMakeRoot(Entry entry) {
"""
Cuts this entry from its parent and adds it to the root list, and then
does the same for its parent, and so on up the tree.
Runtime: O(log n)
"""
Entry oParent = entry.oParent;
if (oParent == null) return; // already a root
oParent.degree--;
entry.isMarked = false;
// update parent's `oFirstChild` pointer
Entry oFirstChild = oParent.oFirstChild;
assert oFirstChild != null;
if (oFirstChild.equals(entry)) {
if (oParent.degree == 0) {
oParent.oFirstChild = null;
}
else {
oParent.oFirstChild = entry.next;
}
}
entry.oParent = null;
unlinkFromNeighbors(entry);
// add to root list
mergeLists(entry, oMinEntry);
if (oParent.oParent != null) {
if (oParent.isMarked) {
cutAndMakeRoot(oParent);
}
else {
oParent.isMarked = true;
}
}
} | java | private void cutAndMakeRoot(Entry entry) {
Entry oParent = entry.oParent;
if (oParent == null) return; // already a root
oParent.degree--;
entry.isMarked = false;
// update parent's `oFirstChild` pointer
Entry oFirstChild = oParent.oFirstChild;
assert oFirstChild != null;
if (oFirstChild.equals(entry)) {
if (oParent.degree == 0) {
oParent.oFirstChild = null;
}
else {
oParent.oFirstChild = entry.next;
}
}
entry.oParent = null;
unlinkFromNeighbors(entry);
// add to root list
mergeLists(entry, oMinEntry);
if (oParent.oParent != null) {
if (oParent.isMarked) {
cutAndMakeRoot(oParent);
}
else {
oParent.isMarked = true;
}
}
} | [
"private",
"void",
"cutAndMakeRoot",
"(",
"Entry",
"entry",
")",
"{",
"Entry",
"oParent",
"=",
"entry",
".",
"oParent",
";",
"if",
"(",
"oParent",
"==",
"null",
")",
"return",
";",
"// already a root",
"oParent",
".",
"degree",
"--",
";",
"entry",
".",
"isMarked",
"=",
"false",
";",
"// update parent's `oFirstChild` pointer",
"Entry",
"oFirstChild",
"=",
"oParent",
".",
"oFirstChild",
";",
"assert",
"oFirstChild",
"!=",
"null",
";",
"if",
"(",
"oFirstChild",
".",
"equals",
"(",
"entry",
")",
")",
"{",
"if",
"(",
"oParent",
".",
"degree",
"==",
"0",
")",
"{",
"oParent",
".",
"oFirstChild",
"=",
"null",
";",
"}",
"else",
"{",
"oParent",
".",
"oFirstChild",
"=",
"entry",
".",
"next",
";",
"}",
"}",
"entry",
".",
"oParent",
"=",
"null",
";",
"unlinkFromNeighbors",
"(",
"entry",
")",
";",
"// add to root list",
"mergeLists",
"(",
"entry",
",",
"oMinEntry",
")",
";",
"if",
"(",
"oParent",
".",
"oParent",
"!=",
"null",
")",
"{",
"if",
"(",
"oParent",
".",
"isMarked",
")",
"{",
"cutAndMakeRoot",
"(",
"oParent",
")",
";",
"}",
"else",
"{",
"oParent",
".",
"isMarked",
"=",
"true",
";",
"}",
"}",
"}"
]
| Cuts this entry from its parent and adds it to the root list, and then
does the same for its parent, and so on up the tree.
Runtime: O(log n) | [
"Cuts",
"this",
"entry",
"from",
"its",
"parent",
"and",
"adds",
"it",
"to",
"the",
"root",
"list",
"and",
"then",
"does",
"the",
"same",
"for",
"its",
"parent",
"and",
"so",
"on",
"up",
"the",
"tree",
".",
"Runtime",
":",
"O",
"(",
"log",
"n",
")"
]
| train | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/gremlin/spanningtree/datastructure/FibonacciHeap.java#L285-L318 |
baidubce/bce-sdk-java | src/main/java/com/baidubce/services/media/MediaClient.java | MediaClient.listTranscodingJobs | public ListTranscodingJobsResponse listTranscodingJobs(ListTranscodingJobsRequest request) {
"""
List all transcoder jobs on specified pipeline.
@param request The request object containing all options for list jobs.
@return The list of job IDs.
"""
checkNotNull(request, "The parameter request should NOT be null.");
checkStringNotEmpty(request.getPipelineName(),
"The parameter pipelineName should NOT be null or empty string.");
InternalRequest internalRequest = createRequest(HttpMethodName.GET, request, TRANSCODE_JOB);
internalRequest.addParameter("pipelineName", request.getPipelineName());
return invokeHttpClient(internalRequest, ListTranscodingJobsResponse.class);
} | java | public ListTranscodingJobsResponse listTranscodingJobs(ListTranscodingJobsRequest request) {
checkNotNull(request, "The parameter request should NOT be null.");
checkStringNotEmpty(request.getPipelineName(),
"The parameter pipelineName should NOT be null or empty string.");
InternalRequest internalRequest = createRequest(HttpMethodName.GET, request, TRANSCODE_JOB);
internalRequest.addParameter("pipelineName", request.getPipelineName());
return invokeHttpClient(internalRequest, ListTranscodingJobsResponse.class);
} | [
"public",
"ListTranscodingJobsResponse",
"listTranscodingJobs",
"(",
"ListTranscodingJobsRequest",
"request",
")",
"{",
"checkNotNull",
"(",
"request",
",",
"\"The parameter request should NOT be null.\"",
")",
";",
"checkStringNotEmpty",
"(",
"request",
".",
"getPipelineName",
"(",
")",
",",
"\"The parameter pipelineName should NOT be null or empty string.\"",
")",
";",
"InternalRequest",
"internalRequest",
"=",
"createRequest",
"(",
"HttpMethodName",
".",
"GET",
",",
"request",
",",
"TRANSCODE_JOB",
")",
";",
"internalRequest",
".",
"addParameter",
"(",
"\"pipelineName\"",
",",
"request",
".",
"getPipelineName",
"(",
")",
")",
";",
"return",
"invokeHttpClient",
"(",
"internalRequest",
",",
"ListTranscodingJobsResponse",
".",
"class",
")",
";",
"}"
]
| List all transcoder jobs on specified pipeline.
@param request The request object containing all options for list jobs.
@return The list of job IDs. | [
"List",
"all",
"transcoder",
"jobs",
"on",
"specified",
"pipeline",
"."
]
| train | https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/media/MediaClient.java#L459-L466 |
ginere/ginere-base | src/main/java/eu/ginere/base/util/properties/old/GlobalFileProperties.java | GlobalFileProperties.getPropertiesFilePath | public static String getPropertiesFilePath(String filePath) {
"""
Utiliza el valor de la JVM GlobalFileProperties.class.getName()+".DefaultPath"
para obtener el path de la propiedad
@param filePath
@return
"""
// Verificamos is esta definida una propiedad Global para los ficheros de properties
String defaultPath=System.getProperty(GlobalFileProperties.class.getName()+".DefaultPath");
if (defaultPath!=null){
return getFilePath(defaultPath,filePath);
} else {
return filePath;
}
} | java | public static String getPropertiesFilePath(String filePath) {
// Verificamos is esta definida una propiedad Global para los ficheros de properties
String defaultPath=System.getProperty(GlobalFileProperties.class.getName()+".DefaultPath");
if (defaultPath!=null){
return getFilePath(defaultPath,filePath);
} else {
return filePath;
}
} | [
"public",
"static",
"String",
"getPropertiesFilePath",
"(",
"String",
"filePath",
")",
"{",
"// Verificamos is esta definida una propiedad Global para los ficheros de properties\r",
"String",
"defaultPath",
"=",
"System",
".",
"getProperty",
"(",
"GlobalFileProperties",
".",
"class",
".",
"getName",
"(",
")",
"+",
"\".DefaultPath\"",
")",
";",
"if",
"(",
"defaultPath",
"!=",
"null",
")",
"{",
"return",
"getFilePath",
"(",
"defaultPath",
",",
"filePath",
")",
";",
"}",
"else",
"{",
"return",
"filePath",
";",
"}",
"}"
]
| Utiliza el valor de la JVM GlobalFileProperties.class.getName()+".DefaultPath"
para obtener el path de la propiedad
@param filePath
@return | [
"Utiliza",
"el",
"valor",
"de",
"la",
"JVM",
"GlobalFileProperties",
".",
"class",
".",
"getName",
"()",
"+",
".",
"DefaultPath",
"para",
"obtener",
"el",
"path",
"de",
"la",
"propiedad"
]
| train | https://github.com/ginere/ginere-base/blob/b1cc1c5834bd8a31df475c6f3fc0ee51273c5a24/src/main/java/eu/ginere/base/util/properties/old/GlobalFileProperties.java#L45-L54 |
Azure/azure-sdk-for-java | sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/DatabaseVulnerabilityAssessmentsInner.java | DatabaseVulnerabilityAssessmentsInner.getAsync | public Observable<DatabaseVulnerabilityAssessmentInner> getAsync(String resourceGroupName, String serverName, String databaseName) {
"""
Gets the database's vulnerability assessment.
@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 databaseName The name of the database for which the vulnerability assessment is defined.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the DatabaseVulnerabilityAssessmentInner object
"""
return getWithServiceResponseAsync(resourceGroupName, serverName, databaseName).map(new Func1<ServiceResponse<DatabaseVulnerabilityAssessmentInner>, DatabaseVulnerabilityAssessmentInner>() {
@Override
public DatabaseVulnerabilityAssessmentInner call(ServiceResponse<DatabaseVulnerabilityAssessmentInner> response) {
return response.body();
}
});
} | java | public Observable<DatabaseVulnerabilityAssessmentInner> getAsync(String resourceGroupName, String serverName, String databaseName) {
return getWithServiceResponseAsync(resourceGroupName, serverName, databaseName).map(new Func1<ServiceResponse<DatabaseVulnerabilityAssessmentInner>, DatabaseVulnerabilityAssessmentInner>() {
@Override
public DatabaseVulnerabilityAssessmentInner call(ServiceResponse<DatabaseVulnerabilityAssessmentInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"DatabaseVulnerabilityAssessmentInner",
">",
"getAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"serverName",
",",
"String",
"databaseName",
")",
"{",
"return",
"getWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"serverName",
",",
"databaseName",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"DatabaseVulnerabilityAssessmentInner",
">",
",",
"DatabaseVulnerabilityAssessmentInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"DatabaseVulnerabilityAssessmentInner",
"call",
"(",
"ServiceResponse",
"<",
"DatabaseVulnerabilityAssessmentInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Gets the database's vulnerability assessment.
@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 databaseName The name of the database for which the vulnerability assessment is defined.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the DatabaseVulnerabilityAssessmentInner object | [
"Gets",
"the",
"database",
"s",
"vulnerability",
"assessment",
"."
]
| train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/DatabaseVulnerabilityAssessmentsInner.java#L124-L131 |
Netflix/eureka | eureka-core/src/main/java/com/netflix/eureka/aws/AwsAsgUtil.java | AwsAsgUtil.getCacheKeys | private Set<CacheKey> getCacheKeys() {
"""
Get the cacheKeys of all the ASG to which query AWS for.
<p>
The names are obtained from the {@link com.netflix.eureka.registry.InstanceRegistry} which is then
used for querying the AWS.
</p>
@return the set of ASG cacheKeys (asgName + accountId).
"""
Set<CacheKey> cacheKeys = new HashSet<CacheKey>();
Applications apps = registry.getApplicationsFromLocalRegionOnly();
for (Application app : apps.getRegisteredApplications()) {
for (InstanceInfo instanceInfo : app.getInstances()) {
String localAccountId = getAccountId(instanceInfo, accountId);
String asgName = instanceInfo.getASGName();
if (asgName != null) {
CacheKey key = new CacheKey(localAccountId, asgName);
cacheKeys.add(key);
}
}
}
return cacheKeys;
} | java | private Set<CacheKey> getCacheKeys() {
Set<CacheKey> cacheKeys = new HashSet<CacheKey>();
Applications apps = registry.getApplicationsFromLocalRegionOnly();
for (Application app : apps.getRegisteredApplications()) {
for (InstanceInfo instanceInfo : app.getInstances()) {
String localAccountId = getAccountId(instanceInfo, accountId);
String asgName = instanceInfo.getASGName();
if (asgName != null) {
CacheKey key = new CacheKey(localAccountId, asgName);
cacheKeys.add(key);
}
}
}
return cacheKeys;
} | [
"private",
"Set",
"<",
"CacheKey",
">",
"getCacheKeys",
"(",
")",
"{",
"Set",
"<",
"CacheKey",
">",
"cacheKeys",
"=",
"new",
"HashSet",
"<",
"CacheKey",
">",
"(",
")",
";",
"Applications",
"apps",
"=",
"registry",
".",
"getApplicationsFromLocalRegionOnly",
"(",
")",
";",
"for",
"(",
"Application",
"app",
":",
"apps",
".",
"getRegisteredApplications",
"(",
")",
")",
"{",
"for",
"(",
"InstanceInfo",
"instanceInfo",
":",
"app",
".",
"getInstances",
"(",
")",
")",
"{",
"String",
"localAccountId",
"=",
"getAccountId",
"(",
"instanceInfo",
",",
"accountId",
")",
";",
"String",
"asgName",
"=",
"instanceInfo",
".",
"getASGName",
"(",
")",
";",
"if",
"(",
"asgName",
"!=",
"null",
")",
"{",
"CacheKey",
"key",
"=",
"new",
"CacheKey",
"(",
"localAccountId",
",",
"asgName",
")",
";",
"cacheKeys",
".",
"add",
"(",
"key",
")",
";",
"}",
"}",
"}",
"return",
"cacheKeys",
";",
"}"
]
| Get the cacheKeys of all the ASG to which query AWS for.
<p>
The names are obtained from the {@link com.netflix.eureka.registry.InstanceRegistry} which is then
used for querying the AWS.
</p>
@return the set of ASG cacheKeys (asgName + accountId). | [
"Get",
"the",
"cacheKeys",
"of",
"all",
"the",
"ASG",
"to",
"which",
"query",
"AWS",
"for",
"."
]
| train | https://github.com/Netflix/eureka/blob/48446d956be09df6650a3c00b7ebd7e2d1e1544f/eureka-core/src/main/java/com/netflix/eureka/aws/AwsAsgUtil.java#L424-L439 |
landawn/AbacusUtil | src/com/landawn/abacus/util/CharList.java | CharList.allMatch | public <E extends Exception> boolean allMatch(Try.CharPredicate<E> filter) throws E {
"""
Returns whether all elements of this List match the provided predicate.
@param filter
@return
"""
return allMatch(0, size(), filter);
} | java | public <E extends Exception> boolean allMatch(Try.CharPredicate<E> filter) throws E {
return allMatch(0, size(), filter);
} | [
"public",
"<",
"E",
"extends",
"Exception",
">",
"boolean",
"allMatch",
"(",
"Try",
".",
"CharPredicate",
"<",
"E",
">",
"filter",
")",
"throws",
"E",
"{",
"return",
"allMatch",
"(",
"0",
",",
"size",
"(",
")",
",",
"filter",
")",
";",
"}"
]
| Returns whether all elements of this List match the provided predicate.
@param filter
@return | [
"Returns",
"whether",
"all",
"elements",
"of",
"this",
"List",
"match",
"the",
"provided",
"predicate",
"."
]
| train | https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/CharList.java#L952-L954 |
Pkmmte/PkRSS | pkrss/src/main/java/com/pkmmte/pkrss/Utils.java | Utils.deleteDir | public static boolean deleteDir(File dir) {
"""
Deletes the specified directory. Returns true if successful, false if not.
@param dir Directory to delete.
@return {@code true} if successful, {@code false} if otherwise.
"""
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
if (!deleteDir(new File(dir, children[i])))
return false;
}
}
return dir.delete();
} | java | public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
if (!deleteDir(new File(dir, children[i])))
return false;
}
}
return dir.delete();
} | [
"public",
"static",
"boolean",
"deleteDir",
"(",
"File",
"dir",
")",
"{",
"if",
"(",
"dir",
"!=",
"null",
"&&",
"dir",
".",
"isDirectory",
"(",
")",
")",
"{",
"String",
"[",
"]",
"children",
"=",
"dir",
".",
"list",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"children",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"deleteDir",
"(",
"new",
"File",
"(",
"dir",
",",
"children",
"[",
"i",
"]",
")",
")",
")",
"return",
"false",
";",
"}",
"}",
"return",
"dir",
".",
"delete",
"(",
")",
";",
"}"
]
| Deletes the specified directory. Returns true if successful, false if not.
@param dir Directory to delete.
@return {@code true} if successful, {@code false} if otherwise. | [
"Deletes",
"the",
"specified",
"directory",
".",
"Returns",
"true",
"if",
"successful",
"false",
"if",
"not",
"."
]
| train | https://github.com/Pkmmte/PkRSS/blob/0bc536d3bad1dade4538616f71c3a8f068eac89a/pkrss/src/main/java/com/pkmmte/pkrss/Utils.java#L20-L29 |
apache/incubator-gobblin | gobblin-compaction/src/main/java/org/apache/gobblin/compaction/event/CompactionSlaEventHelper.java | CompactionSlaEventHelper.getEventSubmitterBuilder | public static SlaEventSubmitterBuilder getEventSubmitterBuilder(Dataset dataset, Optional<Job> job, FileSystem fs) {
"""
Get an {@link SlaEventSubmitterBuilder} that has dataset urn, partition, record count, previous publish timestamp
and dedupe status set.
The caller MUST set eventSubmitter, eventname before submitting.
"""
SlaEventSubmitterBuilder builder =
SlaEventSubmitter.builder().datasetUrn(dataset.getUrn())
.partition(dataset.jobProps().getProp(MRCompactor.COMPACTION_JOB_DEST_PARTITION, ""))
.dedupeStatus(getOutputDedupeStatus(dataset.jobProps()));
long previousPublishTime = getPreviousPublishTime(dataset, fs);
long upstreamTime = dataset.jobProps().getPropAsLong(SlaEventKeys.UPSTREAM_TS_IN_MILLI_SECS_KEY, -1l);
long recordCount = getRecordCount(job);
// Previous publish only exists when this is a recompact job
if (previousPublishTime != -1l) {
builder.previousPublishTimestamp(Long.toString(previousPublishTime));
}
// Upstream time is the logical time represented by the compaction input directory
if (upstreamTime != -1l) {
builder.upstreamTimestamp(Long.toString(upstreamTime));
}
if (recordCount != -1l) {
builder.recordCount(Long.toString(recordCount));
}
return builder;
} | java | public static SlaEventSubmitterBuilder getEventSubmitterBuilder(Dataset dataset, Optional<Job> job, FileSystem fs) {
SlaEventSubmitterBuilder builder =
SlaEventSubmitter.builder().datasetUrn(dataset.getUrn())
.partition(dataset.jobProps().getProp(MRCompactor.COMPACTION_JOB_DEST_PARTITION, ""))
.dedupeStatus(getOutputDedupeStatus(dataset.jobProps()));
long previousPublishTime = getPreviousPublishTime(dataset, fs);
long upstreamTime = dataset.jobProps().getPropAsLong(SlaEventKeys.UPSTREAM_TS_IN_MILLI_SECS_KEY, -1l);
long recordCount = getRecordCount(job);
// Previous publish only exists when this is a recompact job
if (previousPublishTime != -1l) {
builder.previousPublishTimestamp(Long.toString(previousPublishTime));
}
// Upstream time is the logical time represented by the compaction input directory
if (upstreamTime != -1l) {
builder.upstreamTimestamp(Long.toString(upstreamTime));
}
if (recordCount != -1l) {
builder.recordCount(Long.toString(recordCount));
}
return builder;
} | [
"public",
"static",
"SlaEventSubmitterBuilder",
"getEventSubmitterBuilder",
"(",
"Dataset",
"dataset",
",",
"Optional",
"<",
"Job",
">",
"job",
",",
"FileSystem",
"fs",
")",
"{",
"SlaEventSubmitterBuilder",
"builder",
"=",
"SlaEventSubmitter",
".",
"builder",
"(",
")",
".",
"datasetUrn",
"(",
"dataset",
".",
"getUrn",
"(",
")",
")",
".",
"partition",
"(",
"dataset",
".",
"jobProps",
"(",
")",
".",
"getProp",
"(",
"MRCompactor",
".",
"COMPACTION_JOB_DEST_PARTITION",
",",
"\"\"",
")",
")",
".",
"dedupeStatus",
"(",
"getOutputDedupeStatus",
"(",
"dataset",
".",
"jobProps",
"(",
")",
")",
")",
";",
"long",
"previousPublishTime",
"=",
"getPreviousPublishTime",
"(",
"dataset",
",",
"fs",
")",
";",
"long",
"upstreamTime",
"=",
"dataset",
".",
"jobProps",
"(",
")",
".",
"getPropAsLong",
"(",
"SlaEventKeys",
".",
"UPSTREAM_TS_IN_MILLI_SECS_KEY",
",",
"-",
"1l",
")",
";",
"long",
"recordCount",
"=",
"getRecordCount",
"(",
"job",
")",
";",
"// Previous publish only exists when this is a recompact job",
"if",
"(",
"previousPublishTime",
"!=",
"-",
"1l",
")",
"{",
"builder",
".",
"previousPublishTimestamp",
"(",
"Long",
".",
"toString",
"(",
"previousPublishTime",
")",
")",
";",
"}",
"// Upstream time is the logical time represented by the compaction input directory",
"if",
"(",
"upstreamTime",
"!=",
"-",
"1l",
")",
"{",
"builder",
".",
"upstreamTimestamp",
"(",
"Long",
".",
"toString",
"(",
"upstreamTime",
")",
")",
";",
"}",
"if",
"(",
"recordCount",
"!=",
"-",
"1l",
")",
"{",
"builder",
".",
"recordCount",
"(",
"Long",
".",
"toString",
"(",
"recordCount",
")",
")",
";",
"}",
"return",
"builder",
";",
"}"
]
| Get an {@link SlaEventSubmitterBuilder} that has dataset urn, partition, record count, previous publish timestamp
and dedupe status set.
The caller MUST set eventSubmitter, eventname before submitting. | [
"Get",
"an",
"{"
]
| train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-compaction/src/main/java/org/apache/gobblin/compaction/event/CompactionSlaEventHelper.java#L71-L93 |
hellosign/hellosign-java-sdk | src/main/java/com/hellosign/sdk/resource/AbstractResourceList.java | AbstractResourceList.filterCurrentPageBy | public List<E> filterCurrentPageBy(String columnName, Serializable filterValue) throws HelloSignException {
"""
Filters the current page of results by the given column and value.
@param columnName String column name to filter by
@param filterValue Serializable matching value
@return List results
@throws HelloSignException thrown if the column name is invalid
"""
ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
@SuppressWarnings("unchecked")
Class<E> clazz = (Class<E>) genericSuperclass.getActualTypeArguments()[0];
return getList(clazz, listKey, filterValue, columnName);
} | java | public List<E> filterCurrentPageBy(String columnName, Serializable filterValue) throws HelloSignException {
ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
@SuppressWarnings("unchecked")
Class<E> clazz = (Class<E>) genericSuperclass.getActualTypeArguments()[0];
return getList(clazz, listKey, filterValue, columnName);
} | [
"public",
"List",
"<",
"E",
">",
"filterCurrentPageBy",
"(",
"String",
"columnName",
",",
"Serializable",
"filterValue",
")",
"throws",
"HelloSignException",
"{",
"ParameterizedType",
"genericSuperclass",
"=",
"(",
"ParameterizedType",
")",
"getClass",
"(",
")",
".",
"getGenericSuperclass",
"(",
")",
";",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"Class",
"<",
"E",
">",
"clazz",
"=",
"(",
"Class",
"<",
"E",
">",
")",
"genericSuperclass",
".",
"getActualTypeArguments",
"(",
")",
"[",
"0",
"]",
";",
"return",
"getList",
"(",
"clazz",
",",
"listKey",
",",
"filterValue",
",",
"columnName",
")",
";",
"}"
]
| Filters the current page of results by the given column and value.
@param columnName String column name to filter by
@param filterValue Serializable matching value
@return List results
@throws HelloSignException thrown if the column name is invalid | [
"Filters",
"the",
"current",
"page",
"of",
"results",
"by",
"the",
"given",
"column",
"and",
"value",
"."
]
| train | https://github.com/hellosign/hellosign-java-sdk/blob/08fa7aeb3b0c68ddb6c7ea797d114d55d36d36b1/src/main/java/com/hellosign/sdk/resource/AbstractResourceList.java#L116-L121 |
wildfly/wildfly-core | core-management/core-management-subsystem/src/main/java/org/wildfly/extension/core/management/ProcessStateListenerService.java | ProcessStateListenerService.suspendTransition | private void suspendTransition(Process.RunningState oldState, Process.RunningState newState) {
"""
This will <strong>NEVER</strong> be called on a HostController.
@param newState the new running state.
"""
synchronized (stopLock) {
if (oldState == newState) {
return;
}
this.runningState = newState;
final RunningStateChangeEvent event = new RunningStateChangeEvent(oldState, newState);
Future<?> suspendStateTransition = executorServiceSupplier.get().submit(() -> {
CoreManagementLogger.ROOT_LOGGER.debugf("Executing runningStateChanged %s in thread %s", event, Thread.currentThread().getName());
listener.runningStateChanged(event);
});
try {
suspendStateTransition.get(timeout, TimeUnit.SECONDS);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
CoreManagementLogger.ROOT_LOGGER.processStateInvokationError(ex, name);
} catch (TimeoutException ex) {
CoreManagementLogger.ROOT_LOGGER.processStateTimeoutError(ex, name);
} catch (ExecutionException | RuntimeException t) {
CoreManagementLogger.ROOT_LOGGER.processStateInvokationError(t, name);
} finally {
if (!suspendStateTransition.isDone()) {
suspendStateTransition.cancel(true);
}
}
}
} | java | private void suspendTransition(Process.RunningState oldState, Process.RunningState newState) {
synchronized (stopLock) {
if (oldState == newState) {
return;
}
this.runningState = newState;
final RunningStateChangeEvent event = new RunningStateChangeEvent(oldState, newState);
Future<?> suspendStateTransition = executorServiceSupplier.get().submit(() -> {
CoreManagementLogger.ROOT_LOGGER.debugf("Executing runningStateChanged %s in thread %s", event, Thread.currentThread().getName());
listener.runningStateChanged(event);
});
try {
suspendStateTransition.get(timeout, TimeUnit.SECONDS);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
CoreManagementLogger.ROOT_LOGGER.processStateInvokationError(ex, name);
} catch (TimeoutException ex) {
CoreManagementLogger.ROOT_LOGGER.processStateTimeoutError(ex, name);
} catch (ExecutionException | RuntimeException t) {
CoreManagementLogger.ROOT_LOGGER.processStateInvokationError(t, name);
} finally {
if (!suspendStateTransition.isDone()) {
suspendStateTransition.cancel(true);
}
}
}
} | [
"private",
"void",
"suspendTransition",
"(",
"Process",
".",
"RunningState",
"oldState",
",",
"Process",
".",
"RunningState",
"newState",
")",
"{",
"synchronized",
"(",
"stopLock",
")",
"{",
"if",
"(",
"oldState",
"==",
"newState",
")",
"{",
"return",
";",
"}",
"this",
".",
"runningState",
"=",
"newState",
";",
"final",
"RunningStateChangeEvent",
"event",
"=",
"new",
"RunningStateChangeEvent",
"(",
"oldState",
",",
"newState",
")",
";",
"Future",
"<",
"?",
">",
"suspendStateTransition",
"=",
"executorServiceSupplier",
".",
"get",
"(",
")",
".",
"submit",
"(",
"(",
")",
"->",
"{",
"CoreManagementLogger",
".",
"ROOT_LOGGER",
".",
"debugf",
"(",
"\"Executing runningStateChanged %s in thread %s\"",
",",
"event",
",",
"Thread",
".",
"currentThread",
"(",
")",
".",
"getName",
"(",
")",
")",
";",
"listener",
".",
"runningStateChanged",
"(",
"event",
")",
";",
"}",
")",
";",
"try",
"{",
"suspendStateTransition",
".",
"get",
"(",
"timeout",
",",
"TimeUnit",
".",
"SECONDS",
")",
";",
"}",
"catch",
"(",
"InterruptedException",
"ex",
")",
"{",
"Thread",
".",
"currentThread",
"(",
")",
".",
"interrupt",
"(",
")",
";",
"CoreManagementLogger",
".",
"ROOT_LOGGER",
".",
"processStateInvokationError",
"(",
"ex",
",",
"name",
")",
";",
"}",
"catch",
"(",
"TimeoutException",
"ex",
")",
"{",
"CoreManagementLogger",
".",
"ROOT_LOGGER",
".",
"processStateTimeoutError",
"(",
"ex",
",",
"name",
")",
";",
"}",
"catch",
"(",
"ExecutionException",
"|",
"RuntimeException",
"t",
")",
"{",
"CoreManagementLogger",
".",
"ROOT_LOGGER",
".",
"processStateInvokationError",
"(",
"t",
",",
"name",
")",
";",
"}",
"finally",
"{",
"if",
"(",
"!",
"suspendStateTransition",
".",
"isDone",
"(",
")",
")",
"{",
"suspendStateTransition",
".",
"cancel",
"(",
"true",
")",
";",
"}",
"}",
"}",
"}"
]
| This will <strong>NEVER</strong> be called on a HostController.
@param newState the new running state. | [
"This",
"will",
"<strong",
">",
"NEVER<",
"/",
"strong",
">",
"be",
"called",
"on",
"a",
"HostController",
"."
]
| train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/core-management/core-management-subsystem/src/main/java/org/wildfly/extension/core/management/ProcessStateListenerService.java#L213-L239 |
apereo/cas | support/cas-server-support-ws-idp/src/main/java/org/apereo/cas/ws/idp/metadata/WSFederationMetadataController.java | WSFederationMetadataController.doGet | @GetMapping(path = WSFederationConstants.ENDPOINT_FEDERATION_METADATA)
public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
"""
Get Metadata.
@param request the request
@param response the response
@throws Exception the exception
"""
try {
response.setContentType(MediaType.TEXT_HTML_VALUE);
val out = response.getWriter();
val metadata = WSFederationMetadataWriter.produceMetadataDocument(casProperties);
out.write(DOM2Writer.nodeToString(metadata));
} catch (final Exception ex) {
LOGGER.error("Failed to get metadata document", ex);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
} | java | @GetMapping(path = WSFederationConstants.ENDPOINT_FEDERATION_METADATA)
public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
try {
response.setContentType(MediaType.TEXT_HTML_VALUE);
val out = response.getWriter();
val metadata = WSFederationMetadataWriter.produceMetadataDocument(casProperties);
out.write(DOM2Writer.nodeToString(metadata));
} catch (final Exception ex) {
LOGGER.error("Failed to get metadata document", ex);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
} | [
"@",
"GetMapping",
"(",
"path",
"=",
"WSFederationConstants",
".",
"ENDPOINT_FEDERATION_METADATA",
")",
"public",
"void",
"doGet",
"(",
"final",
"HttpServletRequest",
"request",
",",
"final",
"HttpServletResponse",
"response",
")",
"throws",
"Exception",
"{",
"try",
"{",
"response",
".",
"setContentType",
"(",
"MediaType",
".",
"TEXT_HTML_VALUE",
")",
";",
"val",
"out",
"=",
"response",
".",
"getWriter",
"(",
")",
";",
"val",
"metadata",
"=",
"WSFederationMetadataWriter",
".",
"produceMetadataDocument",
"(",
"casProperties",
")",
";",
"out",
".",
"write",
"(",
"DOM2Writer",
".",
"nodeToString",
"(",
"metadata",
")",
")",
";",
"}",
"catch",
"(",
"final",
"Exception",
"ex",
")",
"{",
"LOGGER",
".",
"error",
"(",
"\"Failed to get metadata document\"",
",",
"ex",
")",
";",
"response",
".",
"sendError",
"(",
"HttpServletResponse",
".",
"SC_INTERNAL_SERVER_ERROR",
")",
";",
"}",
"}"
]
| Get Metadata.
@param request the request
@param response the response
@throws Exception the exception | [
"Get",
"Metadata",
"."
]
| train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-ws-idp/src/main/java/org/apereo/cas/ws/idp/metadata/WSFederationMetadataController.java#L36-L47 |
iig-uni-freiburg/SEWOL | ext/org/deckfour/xes/extension/std/XAbstractNestedAttributeSupport.java | XAbstractNestedAttributeSupport.assignValues | public void assignValues(XAttributable element, Map<String, Type> values) {
"""
Assigns (to the given element) multiple values given their keys. Note
that as a side effect this method creates attributes when it does not
find an attribute with the proper key.
For example, the call:
<pre>
assignValues(event, [[key.1 val.1] [key.2 val.2] [key.3 val.3]])
</pre>
should result into the following XES fragment:
<pre>
{@code
<event>
<string key="key.1" value="">
<float key="ext:attr" value="val.1"/>
</string>
<string key="key.2" value="">
<float key="ext:attr" value="val.2"/>
</string>
<string key="key.3" value="">
<float key="ext:attr" value="val.3"/>
</string>
</event>
}
</pre>
@param event
Event to assign the values to.
@param amounts
Mapping from keys to values which are to be assigned.
"""
Map<List<String>, Type> nestedValues = new HashMap<List<String>, Type>();
for (String key : values.keySet()) {
List<String> keys = new ArrayList<String>();
keys.add(key);
nestedValues.put(keys, values.get(key));
}
assignNestedValues(element, nestedValues);
} | java | public void assignValues(XAttributable element, Map<String, Type> values) {
Map<List<String>, Type> nestedValues = new HashMap<List<String>, Type>();
for (String key : values.keySet()) {
List<String> keys = new ArrayList<String>();
keys.add(key);
nestedValues.put(keys, values.get(key));
}
assignNestedValues(element, nestedValues);
} | [
"public",
"void",
"assignValues",
"(",
"XAttributable",
"element",
",",
"Map",
"<",
"String",
",",
"Type",
">",
"values",
")",
"{",
"Map",
"<",
"List",
"<",
"String",
">",
",",
"Type",
">",
"nestedValues",
"=",
"new",
"HashMap",
"<",
"List",
"<",
"String",
">",
",",
"Type",
">",
"(",
")",
";",
"for",
"(",
"String",
"key",
":",
"values",
".",
"keySet",
"(",
")",
")",
"{",
"List",
"<",
"String",
">",
"keys",
"=",
"new",
"ArrayList",
"<",
"String",
">",
"(",
")",
";",
"keys",
".",
"add",
"(",
"key",
")",
";",
"nestedValues",
".",
"put",
"(",
"keys",
",",
"values",
".",
"get",
"(",
"key",
")",
")",
";",
"}",
"assignNestedValues",
"(",
"element",
",",
"nestedValues",
")",
";",
"}"
]
| Assigns (to the given element) multiple values given their keys. Note
that as a side effect this method creates attributes when it does not
find an attribute with the proper key.
For example, the call:
<pre>
assignValues(event, [[key.1 val.1] [key.2 val.2] [key.3 val.3]])
</pre>
should result into the following XES fragment:
<pre>
{@code
<event>
<string key="key.1" value="">
<float key="ext:attr" value="val.1"/>
</string>
<string key="key.2" value="">
<float key="ext:attr" value="val.2"/>
</string>
<string key="key.3" value="">
<float key="ext:attr" value="val.3"/>
</string>
</event>
}
</pre>
@param event
Event to assign the values to.
@param amounts
Mapping from keys to values which are to be assigned. | [
"Assigns",
"(",
"to",
"the",
"given",
"element",
")",
"multiple",
"values",
"given",
"their",
"keys",
".",
"Note",
"that",
"as",
"a",
"side",
"effect",
"this",
"method",
"creates",
"attributes",
"when",
"it",
"does",
"not",
"find",
"an",
"attribute",
"with",
"the",
"proper",
"key",
"."
]
| train | https://github.com/iig-uni-freiburg/SEWOL/blob/e791cb07a6e62ecf837d760d58a25f32fbf6bbca/ext/org/deckfour/xes/extension/std/XAbstractNestedAttributeSupport.java#L237-L245 |
hyperledger/fabric-sdk-java | src/main/java/org/hyperledger/fabric/sdk/helper/Utils.java | Utils.combinePaths | public static String combinePaths(String first, String... other) {
"""
Combine two or more paths
@param first parent directory path
@param other children
@return combined path
"""
return Paths.get(first, other).toString();
} | java | public static String combinePaths(String first, String... other) {
return Paths.get(first, other).toString();
} | [
"public",
"static",
"String",
"combinePaths",
"(",
"String",
"first",
",",
"String",
"...",
"other",
")",
"{",
"return",
"Paths",
".",
"get",
"(",
"first",
",",
"other",
")",
".",
"toString",
"(",
")",
";",
"}"
]
| Combine two or more paths
@param first parent directory path
@param other children
@return combined path | [
"Combine",
"two",
"or",
"more",
"paths"
]
| train | https://github.com/hyperledger/fabric-sdk-java/blob/4a2d7b3408b8b0a1ed812aa36942c438159c37a0/src/main/java/org/hyperledger/fabric/sdk/helper/Utils.java#L294-L296 |
javalite/activejdbc | activejdbc/src/main/java/org/javalite/activejdbc/Model.java | Model.updateAll | public static int updateAll(String updates, Object ... params) {
"""
Updates all records associated with this model.
This example :
<pre>
Employee.updateAll("bonus = ?", "10");
</pre>
In this example, all employees get a bonus of 10%.
@param updates - what needs to be updated.
@param params list of parameters for both updates and conditions. Applied in the same order as in the arguments,
updates first, then conditions.
@return number of updated records.
"""
return ModelDelegate.updateAll(modelClass(), updates, params);
} | java | public static int updateAll(String updates, Object ... params) {
return ModelDelegate.updateAll(modelClass(), updates, params);
} | [
"public",
"static",
"int",
"updateAll",
"(",
"String",
"updates",
",",
"Object",
"...",
"params",
")",
"{",
"return",
"ModelDelegate",
".",
"updateAll",
"(",
"modelClass",
"(",
")",
",",
"updates",
",",
"params",
")",
";",
"}"
]
| Updates all records associated with this model.
This example :
<pre>
Employee.updateAll("bonus = ?", "10");
</pre>
In this example, all employees get a bonus of 10%.
@param updates - what needs to be updated.
@param params list of parameters for both updates and conditions. Applied in the same order as in the arguments,
updates first, then conditions.
@return number of updated records. | [
"Updates",
"all",
"records",
"associated",
"with",
"this",
"model",
"."
]
| train | https://github.com/javalite/activejdbc/blob/ffcf5457cace19622a8f71e856cbbbe9e7dd5fcc/activejdbc/src/main/java/org/javalite/activejdbc/Model.java#L849-L851 |
j-a-w-r/jawr-main-repo | jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/generator/classpath/ClassPathGeneratorHelper.java | ClassPathGeneratorHelper.isDirectChildPath | private boolean isDirectChildPath(String rootEntryPath, String entryPath) {
"""
Checks if the entry is a direct child of the root Entry
isDirectChildPath( '/a/b/c/' , '/a/b/c/d.txt') => true isDirectChildPath(
'/a/b/c/' , '/a/b/c/d/') => true isDirectChildPath( '/a/b/c/' ,
'/a/b/c/d/e.txt') => false
@param rootEntryPath
the root entry path
@param entryPath
the entry path to check
@return true if the entry is a direct child of the root Entry
"""
boolean result = false;
if (entryPath.length() > rootEntryPath.length() && entryPath.startsWith(rootEntryPath)) {
int idx = entryPath.indexOf(URL_SEPARATOR, rootEntryPath.length());
if (idx == -1) { // case where the entry is a child file
// /a/b/c/d.txt
result = true;
} else {
if (entryPath.length() == idx + 1) { // case where the entry is
// a child file
// /a/b/c/d/
result = true;
}
}
}
return result;
} | java | private boolean isDirectChildPath(String rootEntryPath, String entryPath) {
boolean result = false;
if (entryPath.length() > rootEntryPath.length() && entryPath.startsWith(rootEntryPath)) {
int idx = entryPath.indexOf(URL_SEPARATOR, rootEntryPath.length());
if (idx == -1) { // case where the entry is a child file
// /a/b/c/d.txt
result = true;
} else {
if (entryPath.length() == idx + 1) { // case where the entry is
// a child file
// /a/b/c/d/
result = true;
}
}
}
return result;
} | [
"private",
"boolean",
"isDirectChildPath",
"(",
"String",
"rootEntryPath",
",",
"String",
"entryPath",
")",
"{",
"boolean",
"result",
"=",
"false",
";",
"if",
"(",
"entryPath",
".",
"length",
"(",
")",
">",
"rootEntryPath",
".",
"length",
"(",
")",
"&&",
"entryPath",
".",
"startsWith",
"(",
"rootEntryPath",
")",
")",
"{",
"int",
"idx",
"=",
"entryPath",
".",
"indexOf",
"(",
"URL_SEPARATOR",
",",
"rootEntryPath",
".",
"length",
"(",
")",
")",
";",
"if",
"(",
"idx",
"==",
"-",
"1",
")",
"{",
"// case where the entry is a child file",
"// /a/b/c/d.txt",
"result",
"=",
"true",
";",
"}",
"else",
"{",
"if",
"(",
"entryPath",
".",
"length",
"(",
")",
"==",
"idx",
"+",
"1",
")",
"{",
"// case where the entry is",
"// a child file",
"// /a/b/c/d/",
"result",
"=",
"true",
";",
"}",
"}",
"}",
"return",
"result",
";",
"}"
]
| Checks if the entry is a direct child of the root Entry
isDirectChildPath( '/a/b/c/' , '/a/b/c/d.txt') => true isDirectChildPath(
'/a/b/c/' , '/a/b/c/d/') => true isDirectChildPath( '/a/b/c/' ,
'/a/b/c/d/e.txt') => false
@param rootEntryPath
the root entry path
@param entryPath
the entry path to check
@return true if the entry is a direct child of the root Entry | [
"Checks",
"if",
"the",
"entry",
"is",
"a",
"direct",
"child",
"of",
"the",
"root",
"Entry",
"isDirectChildPath",
"(",
"/",
"a",
"/",
"b",
"/",
"c",
"/",
"/",
"a",
"/",
"b",
"/",
"c",
"/",
"d",
".",
"txt",
")",
"=",
">",
"true",
"isDirectChildPath",
"(",
"/",
"a",
"/",
"b",
"/",
"c",
"/",
"/",
"a",
"/",
"b",
"/",
"c",
"/",
"d",
"/",
")",
"=",
">",
"true",
"isDirectChildPath",
"(",
"/",
"a",
"/",
"b",
"/",
"c",
"/",
"/",
"a",
"/",
"b",
"/",
"c",
"/",
"d",
"/",
"e",
".",
"txt",
")",
"=",
">",
"false"
]
| train | https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/generator/classpath/ClassPathGeneratorHelper.java#L271-L287 |
ogaclejapan/SmartTabLayout | library/src/main/java/com/ogaclejapan/smarttablayout/SmartTabStrip.java | SmartTabStrip.blendColors | private static int blendColors(int color1, int color2, float ratio) {
"""
Blend {@code color1} and {@code color2} using the given ratio.
@param ratio of which to blend. 1.0 will return {@code color1}, 0.5 will give an even blend,
0.0 will return {@code color2}.
"""
final float inverseRation = 1f - ratio;
float r = (Color.red(color1) * ratio) + (Color.red(color2) * inverseRation);
float g = (Color.green(color1) * ratio) + (Color.green(color2) * inverseRation);
float b = (Color.blue(color1) * ratio) + (Color.blue(color2) * inverseRation);
return Color.rgb((int) r, (int) g, (int) b);
} | java | private static int blendColors(int color1, int color2, float ratio) {
final float inverseRation = 1f - ratio;
float r = (Color.red(color1) * ratio) + (Color.red(color2) * inverseRation);
float g = (Color.green(color1) * ratio) + (Color.green(color2) * inverseRation);
float b = (Color.blue(color1) * ratio) + (Color.blue(color2) * inverseRation);
return Color.rgb((int) r, (int) g, (int) b);
} | [
"private",
"static",
"int",
"blendColors",
"(",
"int",
"color1",
",",
"int",
"color2",
",",
"float",
"ratio",
")",
"{",
"final",
"float",
"inverseRation",
"=",
"1f",
"-",
"ratio",
";",
"float",
"r",
"=",
"(",
"Color",
".",
"red",
"(",
"color1",
")",
"*",
"ratio",
")",
"+",
"(",
"Color",
".",
"red",
"(",
"color2",
")",
"*",
"inverseRation",
")",
";",
"float",
"g",
"=",
"(",
"Color",
".",
"green",
"(",
"color1",
")",
"*",
"ratio",
")",
"+",
"(",
"Color",
".",
"green",
"(",
"color2",
")",
"*",
"inverseRation",
")",
";",
"float",
"b",
"=",
"(",
"Color",
".",
"blue",
"(",
"color1",
")",
"*",
"ratio",
")",
"+",
"(",
"Color",
".",
"blue",
"(",
"color2",
")",
"*",
"inverseRation",
")",
";",
"return",
"Color",
".",
"rgb",
"(",
"(",
"int",
")",
"r",
",",
"(",
"int",
")",
"g",
",",
"(",
"int",
")",
"b",
")",
";",
"}"
]
| Blend {@code color1} and {@code color2} using the given ratio.
@param ratio of which to blend. 1.0 will return {@code color1}, 0.5 will give an even blend,
0.0 will return {@code color2}. | [
"Blend",
"{",
"@code",
"color1",
"}",
"and",
"{",
"@code",
"color2",
"}",
"using",
"the",
"given",
"ratio",
"."
]
| train | https://github.com/ogaclejapan/SmartTabLayout/blob/712e81a92f1e12a3c33dcbda03d813e0162e8589/library/src/main/java/com/ogaclejapan/smarttablayout/SmartTabStrip.java#L203-L209 |
RoaringBitmap/RoaringBitmap | roaringbitmap/src/main/java/org/roaringbitmap/Util.java | Util.resetBitmapRange | public static void resetBitmapRange(long[] bitmap, int start, int end) {
"""
clear bits at start, start+1,..., end-1
@param bitmap array of words to be modified
@param start first index to be modified (inclusive)
@param end last index to be modified (exclusive)
"""
if (start == end) {
return;
}
int firstword = start / 64;
int endword = (end - 1) / 64;
if (firstword == endword) {
bitmap[firstword] &= ~((~0L << start) & (~0L >>> -end));
return;
}
bitmap[firstword] &= ~(~0L << start);
for (int i = firstword + 1; i < endword; i++) {
bitmap[i] = 0;
}
bitmap[endword] &= ~(~0L >>> -end);
} | java | public static void resetBitmapRange(long[] bitmap, int start, int end) {
if (start == end) {
return;
}
int firstword = start / 64;
int endword = (end - 1) / 64;
if (firstword == endword) {
bitmap[firstword] &= ~((~0L << start) & (~0L >>> -end));
return;
}
bitmap[firstword] &= ~(~0L << start);
for (int i = firstword + 1; i < endword; i++) {
bitmap[i] = 0;
}
bitmap[endword] &= ~(~0L >>> -end);
} | [
"public",
"static",
"void",
"resetBitmapRange",
"(",
"long",
"[",
"]",
"bitmap",
",",
"int",
"start",
",",
"int",
"end",
")",
"{",
"if",
"(",
"start",
"==",
"end",
")",
"{",
"return",
";",
"}",
"int",
"firstword",
"=",
"start",
"/",
"64",
";",
"int",
"endword",
"=",
"(",
"end",
"-",
"1",
")",
"/",
"64",
";",
"if",
"(",
"firstword",
"==",
"endword",
")",
"{",
"bitmap",
"[",
"firstword",
"]",
"&=",
"~",
"(",
"(",
"~",
"0L",
"<<",
"start",
")",
"&",
"(",
"~",
"0L",
">>>",
"-",
"end",
")",
")",
";",
"return",
";",
"}",
"bitmap",
"[",
"firstword",
"]",
"&=",
"~",
"(",
"~",
"0L",
"<<",
"start",
")",
";",
"for",
"(",
"int",
"i",
"=",
"firstword",
"+",
"1",
";",
"i",
"<",
"endword",
";",
"i",
"++",
")",
"{",
"bitmap",
"[",
"i",
"]",
"=",
"0",
";",
"}",
"bitmap",
"[",
"endword",
"]",
"&=",
"~",
"(",
"~",
"0L",
">>>",
"-",
"end",
")",
";",
"}"
]
| clear bits at start, start+1,..., end-1
@param bitmap array of words to be modified
@param start first index to be modified (inclusive)
@param end last index to be modified (exclusive) | [
"clear",
"bits",
"at",
"start",
"start",
"+",
"1",
"...",
"end",
"-",
"1"
]
| train | https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/Util.java#L423-L440 |
code4everything/util | src/main/java/com/zhazhapan/util/FileExecutor.java | FileExecutor.saveFile | public static synchronized void saveFile(File file, String content, boolean append) throws IOException {
"""
保存文件
@param file 文件
@param content 内容
@param append 保存方式
@throws IOException 异常
"""
if (Checker.isNotNull(file)) {
if (!file.exists()) {
file.createNewFile();
}
try (BufferedWriter out = new BufferedWriter(new FileWriter(file, append))) {
out.write(content);
}
logger.info("save file '" + file.getAbsolutePath() + "' success");
}
} | java | public static synchronized void saveFile(File file, String content, boolean append) throws IOException {
if (Checker.isNotNull(file)) {
if (!file.exists()) {
file.createNewFile();
}
try (BufferedWriter out = new BufferedWriter(new FileWriter(file, append))) {
out.write(content);
}
logger.info("save file '" + file.getAbsolutePath() + "' success");
}
} | [
"public",
"static",
"synchronized",
"void",
"saveFile",
"(",
"File",
"file",
",",
"String",
"content",
",",
"boolean",
"append",
")",
"throws",
"IOException",
"{",
"if",
"(",
"Checker",
".",
"isNotNull",
"(",
"file",
")",
")",
"{",
"if",
"(",
"!",
"file",
".",
"exists",
"(",
")",
")",
"{",
"file",
".",
"createNewFile",
"(",
")",
";",
"}",
"try",
"(",
"BufferedWriter",
"out",
"=",
"new",
"BufferedWriter",
"(",
"new",
"FileWriter",
"(",
"file",
",",
"append",
")",
")",
")",
"{",
"out",
".",
"write",
"(",
"content",
")",
";",
"}",
"logger",
".",
"info",
"(",
"\"save file '\"",
"+",
"file",
".",
"getAbsolutePath",
"(",
")",
"+",
"\"' success\"",
")",
";",
"}",
"}"
]
| 保存文件
@param file 文件
@param content 内容
@param append 保存方式
@throws IOException 异常 | [
"保存文件"
]
| train | https://github.com/code4everything/util/blob/1fc9f0ead1108f4d7208ba7c000df4244f708418/src/main/java/com/zhazhapan/util/FileExecutor.java#L980-L990 |
mgormley/pacaya | src/main/java/edu/jhu/pacaya/autodiff/StochasticGradientApproximation.java | StochasticGradientApproximation.estimateGradientFd | public static IntDoubleVector estimateGradientFd(Function fn, IntDoubleVector x, double epsilon) {
"""
Estimates a gradient of a function by an independent finite-difference computation along each
dimension of the domain of the function.
@param fn Function on which to approximate the gradient.
@param x Point at which to approximate the gradient.
@param epsilon The size of the finite difference step.
@return The approximate gradient.
"""
int numParams = fn.getNumDimensions();
IntDoubleVector gradFd = new IntDoubleDenseVector(numParams);
for (int j=0; j<numParams; j++) {
// Test the deriviative d/dx_j(f_i(\vec{x}))
IntDoubleVector d = new IntDoubleDenseVector(numParams);
d.set(j, 1);
double dotFd = getGradDotDirApprox(fn, x, d, epsilon);
if (Double.isNaN(dotFd)) {
log.warn("Hit NaN");
}
gradFd.set(j, dotFd);
}
return gradFd;
} | java | public static IntDoubleVector estimateGradientFd(Function fn, IntDoubleVector x, double epsilon) {
int numParams = fn.getNumDimensions();
IntDoubleVector gradFd = new IntDoubleDenseVector(numParams);
for (int j=0; j<numParams; j++) {
// Test the deriviative d/dx_j(f_i(\vec{x}))
IntDoubleVector d = new IntDoubleDenseVector(numParams);
d.set(j, 1);
double dotFd = getGradDotDirApprox(fn, x, d, epsilon);
if (Double.isNaN(dotFd)) {
log.warn("Hit NaN");
}
gradFd.set(j, dotFd);
}
return gradFd;
} | [
"public",
"static",
"IntDoubleVector",
"estimateGradientFd",
"(",
"Function",
"fn",
",",
"IntDoubleVector",
"x",
",",
"double",
"epsilon",
")",
"{",
"int",
"numParams",
"=",
"fn",
".",
"getNumDimensions",
"(",
")",
";",
"IntDoubleVector",
"gradFd",
"=",
"new",
"IntDoubleDenseVector",
"(",
"numParams",
")",
";",
"for",
"(",
"int",
"j",
"=",
"0",
";",
"j",
"<",
"numParams",
";",
"j",
"++",
")",
"{",
"// Test the deriviative d/dx_j(f_i(\\vec{x}))",
"IntDoubleVector",
"d",
"=",
"new",
"IntDoubleDenseVector",
"(",
"numParams",
")",
";",
"d",
".",
"set",
"(",
"j",
",",
"1",
")",
";",
"double",
"dotFd",
"=",
"getGradDotDirApprox",
"(",
"fn",
",",
"x",
",",
"d",
",",
"epsilon",
")",
";",
"if",
"(",
"Double",
".",
"isNaN",
"(",
"dotFd",
")",
")",
"{",
"log",
".",
"warn",
"(",
"\"Hit NaN\"",
")",
";",
"}",
"gradFd",
".",
"set",
"(",
"j",
",",
"dotFd",
")",
";",
"}",
"return",
"gradFd",
";",
"}"
]
| Estimates a gradient of a function by an independent finite-difference computation along each
dimension of the domain of the function.
@param fn Function on which to approximate the gradient.
@param x Point at which to approximate the gradient.
@param epsilon The size of the finite difference step.
@return The approximate gradient. | [
"Estimates",
"a",
"gradient",
"of",
"a",
"function",
"by",
"an",
"independent",
"finite",
"-",
"difference",
"computation",
"along",
"each",
"dimension",
"of",
"the",
"domain",
"of",
"the",
"function",
"."
]
| train | https://github.com/mgormley/pacaya/blob/786294cbac7cc65dbc32210c10acc32ed0c69233/src/main/java/edu/jhu/pacaya/autodiff/StochasticGradientApproximation.java#L35-L49 |
cdk/cdk | tool/formula/src/main/java/org/openscience/cdk/tools/manipulator/MolecularFormulaManipulator.java | MolecularFormulaManipulator.getElementCount | public static int getElementCount(IMolecularFormula formula, IIsotope isotope) {
"""
Occurrences of a given element from an isotope in a molecular formula.
@param formula the formula
@param isotope isotope of an element
@return number of the times the element occurs
@see #getElementCount(IMolecularFormula, IElement)
"""
return getElementCount(formula, formula.getBuilder().newInstance(IElement.class, isotope));
} | java | public static int getElementCount(IMolecularFormula formula, IIsotope isotope) {
return getElementCount(formula, formula.getBuilder().newInstance(IElement.class, isotope));
} | [
"public",
"static",
"int",
"getElementCount",
"(",
"IMolecularFormula",
"formula",
",",
"IIsotope",
"isotope",
")",
"{",
"return",
"getElementCount",
"(",
"formula",
",",
"formula",
".",
"getBuilder",
"(",
")",
".",
"newInstance",
"(",
"IElement",
".",
"class",
",",
"isotope",
")",
")",
";",
"}"
]
| Occurrences of a given element from an isotope in a molecular formula.
@param formula the formula
@param isotope isotope of an element
@return number of the times the element occurs
@see #getElementCount(IMolecularFormula, IElement) | [
"Occurrences",
"of",
"a",
"given",
"element",
"from",
"an",
"isotope",
"in",
"a",
"molecular",
"formula",
"."
]
| train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/tool/formula/src/main/java/org/openscience/cdk/tools/manipulator/MolecularFormulaManipulator.java#L144-L146 |
carewebframework/carewebframework-core | org.carewebframework.api-parent/org.carewebframework.api.core/src/main/java/org/carewebframework/api/spring/BeanRegistry.java | BeanRegistry.postProcessBeforeDestruction | @SuppressWarnings("unchecked")
@Override
public void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException {
"""
If the managed bean is of the desired type, remove it from the registry.
"""
if (clazz.isInstance(bean)) {
unregister((V) bean);
}
} | java | @SuppressWarnings("unchecked")
@Override
public void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException {
if (clazz.isInstance(bean)) {
unregister((V) bean);
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"@",
"Override",
"public",
"void",
"postProcessBeforeDestruction",
"(",
"Object",
"bean",
",",
"String",
"beanName",
")",
"throws",
"BeansException",
"{",
"if",
"(",
"clazz",
".",
"isInstance",
"(",
"bean",
")",
")",
"{",
"unregister",
"(",
"(",
"V",
")",
"bean",
")",
";",
"}",
"}"
]
| If the managed bean is of the desired type, remove it from the registry. | [
"If",
"the",
"managed",
"bean",
"is",
"of",
"the",
"desired",
"type",
"remove",
"it",
"from",
"the",
"registry",
"."
]
| train | https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.api-parent/org.carewebframework.api.core/src/main/java/org/carewebframework/api/spring/BeanRegistry.java#L74-L80 |
SonarSource/sonarqube | sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/ProjectReactorBuilder.java | ProjectReactorBuilder.getListFromProperty | static String[] getListFromProperty(Map<String, String> properties, String key) {
"""
Transforms a comma-separated list String property in to a array of trimmed strings.
<p>
This works even if they are separated by whitespace characters (space char, EOL, ...)
"""
String propValue = properties.get(key);
if (propValue != null) {
return parseAsCsv(key, propValue);
}
return new String[0];
} | java | static String[] getListFromProperty(Map<String, String> properties, String key) {
String propValue = properties.get(key);
if (propValue != null) {
return parseAsCsv(key, propValue);
}
return new String[0];
} | [
"static",
"String",
"[",
"]",
"getListFromProperty",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"properties",
",",
"String",
"key",
")",
"{",
"String",
"propValue",
"=",
"properties",
".",
"get",
"(",
"key",
")",
";",
"if",
"(",
"propValue",
"!=",
"null",
")",
"{",
"return",
"parseAsCsv",
"(",
"key",
",",
"propValue",
")",
";",
"}",
"return",
"new",
"String",
"[",
"0",
"]",
";",
"}"
]
| Transforms a comma-separated list String property in to a array of trimmed strings.
<p>
This works even if they are separated by whitespace characters (space char, EOL, ...) | [
"Transforms",
"a",
"comma",
"-",
"separated",
"list",
"String",
"property",
"in",
"to",
"a",
"array",
"of",
"trimmed",
"strings",
".",
"<p",
">",
"This",
"works",
"even",
"if",
"they",
"are",
"separated",
"by",
"whitespace",
"characters",
"(",
"space",
"char",
"EOL",
"...",
")"
]
| train | https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/ProjectReactorBuilder.java#L427-L433 |
Codearte/catch-exception | catch-exception/src/main/java/com/googlecode/catchexception/apis/CatchExceptionHamcrestMatchers.java | CatchExceptionHamcrestMatchers.hasMessageThat | public static <T extends Exception> org.hamcrest.Matcher<T> hasMessageThat(
Matcher<String> stringMatcher) {
"""
EXAMPLES:
<code>assertThat(caughtException(), hasMessageThat(is("Index: 9, Size: 9")));
assertThat(caughtException(), hasMessageThat(containsString("Index: 9"))); // using JUnitMatchers
assertThat(caughtException(), hasMessageThat(containsPattern("Index: \\d+"))); // using Mockito's Find</code>
@param <T>
the exception subclass
@param stringMatcher
a string matcher
@return Returns a matcher that matches an exception if the given string
matcher matches the exception message.
"""
return new ExceptionMessageMatcher<>(stringMatcher);
} | java | public static <T extends Exception> org.hamcrest.Matcher<T> hasMessageThat(
Matcher<String> stringMatcher) {
return new ExceptionMessageMatcher<>(stringMatcher);
} | [
"public",
"static",
"<",
"T",
"extends",
"Exception",
">",
"org",
".",
"hamcrest",
".",
"Matcher",
"<",
"T",
">",
"hasMessageThat",
"(",
"Matcher",
"<",
"String",
">",
"stringMatcher",
")",
"{",
"return",
"new",
"ExceptionMessageMatcher",
"<>",
"(",
"stringMatcher",
")",
";",
"}"
]
| EXAMPLES:
<code>assertThat(caughtException(), hasMessageThat(is("Index: 9, Size: 9")));
assertThat(caughtException(), hasMessageThat(containsString("Index: 9"))); // using JUnitMatchers
assertThat(caughtException(), hasMessageThat(containsPattern("Index: \\d+"))); // using Mockito's Find</code>
@param <T>
the exception subclass
@param stringMatcher
a string matcher
@return Returns a matcher that matches an exception if the given string
matcher matches the exception message. | [
"EXAMPLES",
":",
"<code",
">",
"assertThat",
"(",
"caughtException",
"()",
"hasMessageThat",
"(",
"is",
"(",
"Index",
":",
"9",
"Size",
":",
"9",
")))",
";",
"assertThat",
"(",
"caughtException",
"()",
"hasMessageThat",
"(",
"containsString",
"(",
"Index",
":",
"9",
")))",
";",
"//",
"using",
"JUnitMatchers",
"assertThat",
"(",
"caughtException",
"()",
"hasMessageThat",
"(",
"containsPattern",
"(",
"Index",
":",
"\\\\",
"d",
"+",
")))",
";",
"//",
"using",
"Mockito",
"s",
"Find<",
"/",
"code",
">"
]
| train | https://github.com/Codearte/catch-exception/blob/8cfb1c0a68661ef622011484ff0061b41796b165/catch-exception/src/main/java/com/googlecode/catchexception/apis/CatchExceptionHamcrestMatchers.java#L88-L91 |
mapsforge/mapsforge | mapsforge-map/src/main/java/org/mapsforge/map/rendertheme/rule/RenderTheme.java | RenderTheme.scaleTextSize | public synchronized void scaleTextSize(float scaleFactor, byte zoomLevel) {
"""
Scales the text size of this RenderTheme by the given factor for a given zoom level.
@param scaleFactor the factor by which the text size should be scaled.
@param zoomLevel the zoom level to which this is applied.
"""
if (!textScales.containsKey(zoomLevel) || scaleFactor != textScales.get(zoomLevel)) {
for (int i = 0, n = this.rulesList.size(); i < n; ++i) {
Rule rule = this.rulesList.get(i);
if (rule.zoomMin <= zoomLevel && rule.zoomMax >= zoomLevel) {
rule.scaleTextSize(scaleFactor * this.baseTextSize, zoomLevel);
}
}
textScales.put(zoomLevel, scaleFactor);
}
} | java | public synchronized void scaleTextSize(float scaleFactor, byte zoomLevel) {
if (!textScales.containsKey(zoomLevel) || scaleFactor != textScales.get(zoomLevel)) {
for (int i = 0, n = this.rulesList.size(); i < n; ++i) {
Rule rule = this.rulesList.get(i);
if (rule.zoomMin <= zoomLevel && rule.zoomMax >= zoomLevel) {
rule.scaleTextSize(scaleFactor * this.baseTextSize, zoomLevel);
}
}
textScales.put(zoomLevel, scaleFactor);
}
} | [
"public",
"synchronized",
"void",
"scaleTextSize",
"(",
"float",
"scaleFactor",
",",
"byte",
"zoomLevel",
")",
"{",
"if",
"(",
"!",
"textScales",
".",
"containsKey",
"(",
"zoomLevel",
")",
"||",
"scaleFactor",
"!=",
"textScales",
".",
"get",
"(",
"zoomLevel",
")",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
",",
"n",
"=",
"this",
".",
"rulesList",
".",
"size",
"(",
")",
";",
"i",
"<",
"n",
";",
"++",
"i",
")",
"{",
"Rule",
"rule",
"=",
"this",
".",
"rulesList",
".",
"get",
"(",
"i",
")",
";",
"if",
"(",
"rule",
".",
"zoomMin",
"<=",
"zoomLevel",
"&&",
"rule",
".",
"zoomMax",
">=",
"zoomLevel",
")",
"{",
"rule",
".",
"scaleTextSize",
"(",
"scaleFactor",
"*",
"this",
".",
"baseTextSize",
",",
"zoomLevel",
")",
";",
"}",
"}",
"textScales",
".",
"put",
"(",
"zoomLevel",
",",
"scaleFactor",
")",
";",
"}",
"}"
]
| Scales the text size of this RenderTheme by the given factor for a given zoom level.
@param scaleFactor the factor by which the text size should be scaled.
@param zoomLevel the zoom level to which this is applied. | [
"Scales",
"the",
"text",
"size",
"of",
"this",
"RenderTheme",
"by",
"the",
"given",
"factor",
"for",
"a",
"given",
"zoom",
"level",
"."
]
| train | https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-map/src/main/java/org/mapsforge/map/rendertheme/rule/RenderTheme.java#L178-L188 |
dkpro/dkpro-argumentation | dkpro-argumentation-types/src/main/java/org/dkpro/argumentation/types/ArgumentUnitUtils.java | ArgumentUnitUtils.setIsImplicit | public static void setIsImplicit(ArgumentUnit argumentUnit, boolean implicit)
throws IllegalArgumentException {
"""
Sets the implicit value to the argument
@param argumentUnit argument unit
@param implicit boolean value
@throws java.lang.IllegalArgumentException if the length of argument is non-zero
"""
int length = argumentUnit.getEnd() - argumentUnit.getBegin();
if (length > 0) {
throw new IllegalArgumentException("Cannot set 'implicit' property to component " +
"with non-zero length (" + length + ")");
}
ArgumentUnitUtils.setProperty(argumentUnit, ArgumentUnitUtils.PROP_KEY_IS_IMPLICIT,
Boolean.valueOf(implicit).toString());
} | java | public static void setIsImplicit(ArgumentUnit argumentUnit, boolean implicit)
throws IllegalArgumentException
{
int length = argumentUnit.getEnd() - argumentUnit.getBegin();
if (length > 0) {
throw new IllegalArgumentException("Cannot set 'implicit' property to component " +
"with non-zero length (" + length + ")");
}
ArgumentUnitUtils.setProperty(argumentUnit, ArgumentUnitUtils.PROP_KEY_IS_IMPLICIT,
Boolean.valueOf(implicit).toString());
} | [
"public",
"static",
"void",
"setIsImplicit",
"(",
"ArgumentUnit",
"argumentUnit",
",",
"boolean",
"implicit",
")",
"throws",
"IllegalArgumentException",
"{",
"int",
"length",
"=",
"argumentUnit",
".",
"getEnd",
"(",
")",
"-",
"argumentUnit",
".",
"getBegin",
"(",
")",
";",
"if",
"(",
"length",
">",
"0",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Cannot set 'implicit' property to component \"",
"+",
"\"with non-zero length (\"",
"+",
"length",
"+",
"\")\"",
")",
";",
"}",
"ArgumentUnitUtils",
".",
"setProperty",
"(",
"argumentUnit",
",",
"ArgumentUnitUtils",
".",
"PROP_KEY_IS_IMPLICIT",
",",
"Boolean",
".",
"valueOf",
"(",
"implicit",
")",
".",
"toString",
"(",
")",
")",
";",
"}"
]
| Sets the implicit value to the argument
@param argumentUnit argument unit
@param implicit boolean value
@throws java.lang.IllegalArgumentException if the length of argument is non-zero | [
"Sets",
"the",
"implicit",
"value",
"to",
"the",
"argument"
]
| train | https://github.com/dkpro/dkpro-argumentation/blob/57ce6f5e73d8075b7088aeeebb107c85b3d4bbcb/dkpro-argumentation-types/src/main/java/org/dkpro/argumentation/types/ArgumentUnitUtils.java#L216-L228 |
jbundle/jbundle | app/program/project/src/main/java/org/jbundle/app/program/project/db/ProjectTaskParentFilter.java | ProjectTaskParentFilter.doLocalCriteria | public boolean doLocalCriteria(StringBuffer strbFilter, boolean bIncludeFileName, Vector vParamList) {
"""
Set up/do the local criteria.
@param strbFilter The SQL query string to add to.
@param bIncludeFileName Include the file name with this query?
@param vParamList The param list to add the raw data to (for prepared statements).
@return True if you should not skip this record (does a check on the local data).
"""
Record recProjectTask = this.getOwner();
while (recProjectTask != null)
{
if (recProjectTask.getField(ProjectTask.ID).equals(m_recProjectTaskParent.getField(ProjectTask.ID)))
break; // Match! This record is my target
if (recProjectTask.getField(ProjectTask.PARENT_PROJECT_TASK_ID).equals(m_recProjectTaskParent.getField(ProjectTask.ID)))
break; // Match! This record has my target as a ancestor
recProjectTask = ((ReferenceField)recProjectTask.getField(ProjectTask.PARENT_PROJECT_TASK_ID)).getReference();
if ((recProjectTask == null)
|| ((recProjectTask.getEditMode() == DBConstants.EDIT_NONE) || (recProjectTask.getEditMode() == DBConstants.EDIT_ADD)))
return false; // No match
}
return super.doLocalCriteria(strbFilter, bIncludeFileName, vParamList); // Match
} | java | public boolean doLocalCriteria(StringBuffer strbFilter, boolean bIncludeFileName, Vector vParamList)
{
Record recProjectTask = this.getOwner();
while (recProjectTask != null)
{
if (recProjectTask.getField(ProjectTask.ID).equals(m_recProjectTaskParent.getField(ProjectTask.ID)))
break; // Match! This record is my target
if (recProjectTask.getField(ProjectTask.PARENT_PROJECT_TASK_ID).equals(m_recProjectTaskParent.getField(ProjectTask.ID)))
break; // Match! This record has my target as a ancestor
recProjectTask = ((ReferenceField)recProjectTask.getField(ProjectTask.PARENT_PROJECT_TASK_ID)).getReference();
if ((recProjectTask == null)
|| ((recProjectTask.getEditMode() == DBConstants.EDIT_NONE) || (recProjectTask.getEditMode() == DBConstants.EDIT_ADD)))
return false; // No match
}
return super.doLocalCriteria(strbFilter, bIncludeFileName, vParamList); // Match
} | [
"public",
"boolean",
"doLocalCriteria",
"(",
"StringBuffer",
"strbFilter",
",",
"boolean",
"bIncludeFileName",
",",
"Vector",
"vParamList",
")",
"{",
"Record",
"recProjectTask",
"=",
"this",
".",
"getOwner",
"(",
")",
";",
"while",
"(",
"recProjectTask",
"!=",
"null",
")",
"{",
"if",
"(",
"recProjectTask",
".",
"getField",
"(",
"ProjectTask",
".",
"ID",
")",
".",
"equals",
"(",
"m_recProjectTaskParent",
".",
"getField",
"(",
"ProjectTask",
".",
"ID",
")",
")",
")",
"break",
";",
"// Match! This record is my target",
"if",
"(",
"recProjectTask",
".",
"getField",
"(",
"ProjectTask",
".",
"PARENT_PROJECT_TASK_ID",
")",
".",
"equals",
"(",
"m_recProjectTaskParent",
".",
"getField",
"(",
"ProjectTask",
".",
"ID",
")",
")",
")",
"break",
";",
"// Match! This record has my target as a ancestor",
"recProjectTask",
"=",
"(",
"(",
"ReferenceField",
")",
"recProjectTask",
".",
"getField",
"(",
"ProjectTask",
".",
"PARENT_PROJECT_TASK_ID",
")",
")",
".",
"getReference",
"(",
")",
";",
"if",
"(",
"(",
"recProjectTask",
"==",
"null",
")",
"||",
"(",
"(",
"recProjectTask",
".",
"getEditMode",
"(",
")",
"==",
"DBConstants",
".",
"EDIT_NONE",
")",
"||",
"(",
"recProjectTask",
".",
"getEditMode",
"(",
")",
"==",
"DBConstants",
".",
"EDIT_ADD",
")",
")",
")",
"return",
"false",
";",
"// No match",
"}",
"return",
"super",
".",
"doLocalCriteria",
"(",
"strbFilter",
",",
"bIncludeFileName",
",",
"vParamList",
")",
";",
"// Match",
"}"
]
| Set up/do the local criteria.
@param strbFilter The SQL query string to add to.
@param bIncludeFileName Include the file name with this query?
@param vParamList The param list to add the raw data to (for prepared statements).
@return True if you should not skip this record (does a check on the local data). | [
"Set",
"up",
"/",
"do",
"the",
"local",
"criteria",
"."
]
| train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/app/program/project/src/main/java/org/jbundle/app/program/project/db/ProjectTaskParentFilter.java#L61-L77 |
VoltDB/voltdb | src/frontend/org/voltcore/utils/CoreUtils.java | CoreUtils.printAsciiArtLog | public static void printAsciiArtLog(VoltLogger vLogger, String msg, Level level) {
"""
Print beautiful logs surrounded by stars. This function handles long lines (wrapping
into multiple lines) as well. Please use only spaces and newline characters for word
separation.
@param vLogger The provided VoltLogger
@param msg Message to be printed out beautifully
@param level Logging level
"""
if (vLogger == null || msg == null || level == Level.OFF) { return; }
// 80 stars in a line
StringBuilder starBuilder = new StringBuilder();
for (int i = 0; i < 80; i++) {
starBuilder.append("*");
}
String stars = starBuilder.toString();
// Wrap the message with 2 lines of stars
switch (level) {
case DEBUG:
vLogger.debug(stars);
vLogger.debug("* " + msg + " *");
vLogger.debug(stars);
break;
case WARN:
vLogger.warn(stars);
vLogger.warn("* " + msg + " *");
vLogger.warn(stars);
break;
case ERROR:
vLogger.error(stars);
vLogger.error("* " + msg + " *");
vLogger.error(stars);
break;
case FATAL:
vLogger.fatal(stars);
vLogger.fatal("* " + msg + " *");
vLogger.fatal(stars);
break;
case INFO:
vLogger.info(stars);
vLogger.info("* " + msg + " *");
vLogger.info(stars);
break;
case TRACE:
vLogger.trace(stars);
vLogger.trace("* " + msg + " *");
vLogger.trace(stars);
break;
default:
break;
}
} | java | public static void printAsciiArtLog(VoltLogger vLogger, String msg, Level level)
{
if (vLogger == null || msg == null || level == Level.OFF) { return; }
// 80 stars in a line
StringBuilder starBuilder = new StringBuilder();
for (int i = 0; i < 80; i++) {
starBuilder.append("*");
}
String stars = starBuilder.toString();
// Wrap the message with 2 lines of stars
switch (level) {
case DEBUG:
vLogger.debug(stars);
vLogger.debug("* " + msg + " *");
vLogger.debug(stars);
break;
case WARN:
vLogger.warn(stars);
vLogger.warn("* " + msg + " *");
vLogger.warn(stars);
break;
case ERROR:
vLogger.error(stars);
vLogger.error("* " + msg + " *");
vLogger.error(stars);
break;
case FATAL:
vLogger.fatal(stars);
vLogger.fatal("* " + msg + " *");
vLogger.fatal(stars);
break;
case INFO:
vLogger.info(stars);
vLogger.info("* " + msg + " *");
vLogger.info(stars);
break;
case TRACE:
vLogger.trace(stars);
vLogger.trace("* " + msg + " *");
vLogger.trace(stars);
break;
default:
break;
}
} | [
"public",
"static",
"void",
"printAsciiArtLog",
"(",
"VoltLogger",
"vLogger",
",",
"String",
"msg",
",",
"Level",
"level",
")",
"{",
"if",
"(",
"vLogger",
"==",
"null",
"||",
"msg",
"==",
"null",
"||",
"level",
"==",
"Level",
".",
"OFF",
")",
"{",
"return",
";",
"}",
"// 80 stars in a line",
"StringBuilder",
"starBuilder",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"80",
";",
"i",
"++",
")",
"{",
"starBuilder",
".",
"append",
"(",
"\"*\"",
")",
";",
"}",
"String",
"stars",
"=",
"starBuilder",
".",
"toString",
"(",
")",
";",
"// Wrap the message with 2 lines of stars",
"switch",
"(",
"level",
")",
"{",
"case",
"DEBUG",
":",
"vLogger",
".",
"debug",
"(",
"stars",
")",
";",
"vLogger",
".",
"debug",
"(",
"\"* \"",
"+",
"msg",
"+",
"\" *\"",
")",
";",
"vLogger",
".",
"debug",
"(",
"stars",
")",
";",
"break",
";",
"case",
"WARN",
":",
"vLogger",
".",
"warn",
"(",
"stars",
")",
";",
"vLogger",
".",
"warn",
"(",
"\"* \"",
"+",
"msg",
"+",
"\" *\"",
")",
";",
"vLogger",
".",
"warn",
"(",
"stars",
")",
";",
"break",
";",
"case",
"ERROR",
":",
"vLogger",
".",
"error",
"(",
"stars",
")",
";",
"vLogger",
".",
"error",
"(",
"\"* \"",
"+",
"msg",
"+",
"\" *\"",
")",
";",
"vLogger",
".",
"error",
"(",
"stars",
")",
";",
"break",
";",
"case",
"FATAL",
":",
"vLogger",
".",
"fatal",
"(",
"stars",
")",
";",
"vLogger",
".",
"fatal",
"(",
"\"* \"",
"+",
"msg",
"+",
"\" *\"",
")",
";",
"vLogger",
".",
"fatal",
"(",
"stars",
")",
";",
"break",
";",
"case",
"INFO",
":",
"vLogger",
".",
"info",
"(",
"stars",
")",
";",
"vLogger",
".",
"info",
"(",
"\"* \"",
"+",
"msg",
"+",
"\" *\"",
")",
";",
"vLogger",
".",
"info",
"(",
"stars",
")",
";",
"break",
";",
"case",
"TRACE",
":",
"vLogger",
".",
"trace",
"(",
"stars",
")",
";",
"vLogger",
".",
"trace",
"(",
"\"* \"",
"+",
"msg",
"+",
"\" *\"",
")",
";",
"vLogger",
".",
"trace",
"(",
"stars",
")",
";",
"break",
";",
"default",
":",
"break",
";",
"}",
"}"
]
| Print beautiful logs surrounded by stars. This function handles long lines (wrapping
into multiple lines) as well. Please use only spaces and newline characters for word
separation.
@param vLogger The provided VoltLogger
@param msg Message to be printed out beautifully
@param level Logging level | [
"Print",
"beautiful",
"logs",
"surrounded",
"by",
"stars",
".",
"This",
"function",
"handles",
"long",
"lines",
"(",
"wrapping",
"into",
"multiple",
"lines",
")",
"as",
"well",
".",
"Please",
"use",
"only",
"spaces",
"and",
"newline",
"characters",
"for",
"word",
"separation",
"."
]
| train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltcore/utils/CoreUtils.java#L1233-L1279 |
pravega/pravega | client/src/main/java/io/pravega/client/stream/impl/ReaderGroupStateManager.java | ReaderGroupStateManager.readerShutdown | static void readerShutdown(String readerId, Position lastPosition, StateSynchronizer<ReaderGroupState> sync) {
"""
Shuts down a reader, releasing all of its segments. The reader should cease all operations.
@param lastPosition The last position the reader successfully read from.
"""
sync.updateState((state, updates) -> {
Set<Segment> segments = state.getSegments(readerId);
if (segments == null) {
return;
}
log.debug("Removing reader {} from reader grop. CurrentState is: {}", readerId, state);
updates.add(new RemoveReader(readerId, lastPosition == null ? Collections.emptyMap()
: lastPosition.asImpl().getOwnedSegmentsWithOffsets()));
});
} | java | static void readerShutdown(String readerId, Position lastPosition, StateSynchronizer<ReaderGroupState> sync) {
sync.updateState((state, updates) -> {
Set<Segment> segments = state.getSegments(readerId);
if (segments == null) {
return;
}
log.debug("Removing reader {} from reader grop. CurrentState is: {}", readerId, state);
updates.add(new RemoveReader(readerId, lastPosition == null ? Collections.emptyMap()
: lastPosition.asImpl().getOwnedSegmentsWithOffsets()));
});
} | [
"static",
"void",
"readerShutdown",
"(",
"String",
"readerId",
",",
"Position",
"lastPosition",
",",
"StateSynchronizer",
"<",
"ReaderGroupState",
">",
"sync",
")",
"{",
"sync",
".",
"updateState",
"(",
"(",
"state",
",",
"updates",
")",
"->",
"{",
"Set",
"<",
"Segment",
">",
"segments",
"=",
"state",
".",
"getSegments",
"(",
"readerId",
")",
";",
"if",
"(",
"segments",
"==",
"null",
")",
"{",
"return",
";",
"}",
"log",
".",
"debug",
"(",
"\"Removing reader {} from reader grop. CurrentState is: {}\"",
",",
"readerId",
",",
"state",
")",
";",
"updates",
".",
"add",
"(",
"new",
"RemoveReader",
"(",
"readerId",
",",
"lastPosition",
"==",
"null",
"?",
"Collections",
".",
"emptyMap",
"(",
")",
":",
"lastPosition",
".",
"asImpl",
"(",
")",
".",
"getOwnedSegmentsWithOffsets",
"(",
")",
")",
")",
";",
"}",
")",
";",
"}"
]
| Shuts down a reader, releasing all of its segments. The reader should cease all operations.
@param lastPosition The last position the reader successfully read from. | [
"Shuts",
"down",
"a",
"reader",
"releasing",
"all",
"of",
"its",
"segments",
".",
"The",
"reader",
"should",
"cease",
"all",
"operations",
"."
]
| train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/client/src/main/java/io/pravega/client/stream/impl/ReaderGroupStateManager.java#L133-L143 |
structr/structr | structr-core/src/main/java/org/structr/core/entity/AbstractNode.java | AbstractNode.propagationAllowed | private boolean propagationAllowed(final AbstractNode thisNode, final RelationshipInterface rel, final SchemaRelationshipNode.Direction propagationDirection, final boolean doLog) {
"""
Determines whether propagation of permissions is allowed along the given relationship.
CAUTION: this is a complex situation.
- we need to determine the EVALUATION DIRECTION, which can be either WITH or AGAINST the RELATIONSHIP DIRECTION
- if we are looking at the START NODE of the relationship, we are evaluating WITH the relationship direction
- if we are looking at the END NODE of the relationship, we are evaluating AGAINST the relationship direction
- the result obtained by the above check must be compared to the PROPAGATION DIRECTION which can be either
SOURCE_TO_TARGET or TARGET_TO_SOURCE
- a propagation direction of SOURCE_TO_TARGET implies that the permissions of the SOURCE NODE can be applied
to the TARGET NODE, so if we are evaluating AGAINST the relationship direction, we are good to go
- a propagation direction of TARGET_TO_SOURCE implies that the permissions of that TARGET NODE can be applied
to the SOURCE NODE, so if we are evaluating WITH the relationship direction, we are good to go
@param thisNode
@param rel
@param propagationDirection
@return whether permission resolution can continue along this relationship
"""
// early exit
if (propagationDirection.equals(SchemaRelationshipNode.Direction.Both)) {
return true;
}
// early exit
if (propagationDirection.equals(SchemaRelationshipNode.Direction.None)) {
return false;
}
final String sourceNodeId = rel.getSourceNode().getUuid();
final String thisNodeId = thisNode.getUuid();
if (sourceNodeId.equals(thisNodeId)) {
// evaluation WITH the relationship direction
switch (propagationDirection) {
case Out:
return false;
case In:
return true;
}
} else {
// evaluation AGAINST the relationship direction
switch (propagationDirection) {
case Out:
return true;
case In:
return false;
}
}
return false;
} | java | private boolean propagationAllowed(final AbstractNode thisNode, final RelationshipInterface rel, final SchemaRelationshipNode.Direction propagationDirection, final boolean doLog) {
// early exit
if (propagationDirection.equals(SchemaRelationshipNode.Direction.Both)) {
return true;
}
// early exit
if (propagationDirection.equals(SchemaRelationshipNode.Direction.None)) {
return false;
}
final String sourceNodeId = rel.getSourceNode().getUuid();
final String thisNodeId = thisNode.getUuid();
if (sourceNodeId.equals(thisNodeId)) {
// evaluation WITH the relationship direction
switch (propagationDirection) {
case Out:
return false;
case In:
return true;
}
} else {
// evaluation AGAINST the relationship direction
switch (propagationDirection) {
case Out:
return true;
case In:
return false;
}
}
return false;
} | [
"private",
"boolean",
"propagationAllowed",
"(",
"final",
"AbstractNode",
"thisNode",
",",
"final",
"RelationshipInterface",
"rel",
",",
"final",
"SchemaRelationshipNode",
".",
"Direction",
"propagationDirection",
",",
"final",
"boolean",
"doLog",
")",
"{",
"// early exit",
"if",
"(",
"propagationDirection",
".",
"equals",
"(",
"SchemaRelationshipNode",
".",
"Direction",
".",
"Both",
")",
")",
"{",
"return",
"true",
";",
"}",
"// early exit",
"if",
"(",
"propagationDirection",
".",
"equals",
"(",
"SchemaRelationshipNode",
".",
"Direction",
".",
"None",
")",
")",
"{",
"return",
"false",
";",
"}",
"final",
"String",
"sourceNodeId",
"=",
"rel",
".",
"getSourceNode",
"(",
")",
".",
"getUuid",
"(",
")",
";",
"final",
"String",
"thisNodeId",
"=",
"thisNode",
".",
"getUuid",
"(",
")",
";",
"if",
"(",
"sourceNodeId",
".",
"equals",
"(",
"thisNodeId",
")",
")",
"{",
"// evaluation WITH the relationship direction",
"switch",
"(",
"propagationDirection",
")",
"{",
"case",
"Out",
":",
"return",
"false",
";",
"case",
"In",
":",
"return",
"true",
";",
"}",
"}",
"else",
"{",
"// evaluation AGAINST the relationship direction",
"switch",
"(",
"propagationDirection",
")",
"{",
"case",
"Out",
":",
"return",
"true",
";",
"case",
"In",
":",
"return",
"false",
";",
"}",
"}",
"return",
"false",
";",
"}"
]
| Determines whether propagation of permissions is allowed along the given relationship.
CAUTION: this is a complex situation.
- we need to determine the EVALUATION DIRECTION, which can be either WITH or AGAINST the RELATIONSHIP DIRECTION
- if we are looking at the START NODE of the relationship, we are evaluating WITH the relationship direction
- if we are looking at the END NODE of the relationship, we are evaluating AGAINST the relationship direction
- the result obtained by the above check must be compared to the PROPAGATION DIRECTION which can be either
SOURCE_TO_TARGET or TARGET_TO_SOURCE
- a propagation direction of SOURCE_TO_TARGET implies that the permissions of the SOURCE NODE can be applied
to the TARGET NODE, so if we are evaluating AGAINST the relationship direction, we are good to go
- a propagation direction of TARGET_TO_SOURCE implies that the permissions of that TARGET NODE can be applied
to the SOURCE NODE, so if we are evaluating WITH the relationship direction, we are good to go
@param thisNode
@param rel
@param propagationDirection
@return whether permission resolution can continue along this relationship | [
"Determines",
"whether",
"propagation",
"of",
"permissions",
"is",
"allowed",
"along",
"the",
"given",
"relationship",
"."
]
| train | https://github.com/structr/structr/blob/c111a1d0c0201c7fea5574ed69aa5a5053185a97/structr-core/src/main/java/org/structr/core/entity/AbstractNode.java#L1045-L1086 |
jenkinsci/jenkins | core/src/main/java/hudson/security/HudsonPrivateSecurityRealm.java | HudsonPrivateSecurityRealm.createAccountWithHashedPassword | public User createAccountWithHashedPassword(String userName, String hashedPassword) throws IOException {
"""
Creates a new user account by registering a JBCrypt Hashed password with the user.
@param userName The user's name
@param hashedPassword A hashed password, must begin with <code>#jbcrypt:</code>
"""
if (!PASSWORD_ENCODER.isPasswordHashed(hashedPassword)) {
throw new IllegalArgumentException("this method should only be called with a pre-hashed password");
}
User user = User.getById(userName, true);
user.addProperty(Details.fromHashedPassword(hashedPassword));
SecurityListener.fireUserCreated(user.getId());
return user;
} | java | public User createAccountWithHashedPassword(String userName, String hashedPassword) throws IOException {
if (!PASSWORD_ENCODER.isPasswordHashed(hashedPassword)) {
throw new IllegalArgumentException("this method should only be called with a pre-hashed password");
}
User user = User.getById(userName, true);
user.addProperty(Details.fromHashedPassword(hashedPassword));
SecurityListener.fireUserCreated(user.getId());
return user;
} | [
"public",
"User",
"createAccountWithHashedPassword",
"(",
"String",
"userName",
",",
"String",
"hashedPassword",
")",
"throws",
"IOException",
"{",
"if",
"(",
"!",
"PASSWORD_ENCODER",
".",
"isPasswordHashed",
"(",
"hashedPassword",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"this method should only be called with a pre-hashed password\"",
")",
";",
"}",
"User",
"user",
"=",
"User",
".",
"getById",
"(",
"userName",
",",
"true",
")",
";",
"user",
".",
"addProperty",
"(",
"Details",
".",
"fromHashedPassword",
"(",
"hashedPassword",
")",
")",
";",
"SecurityListener",
".",
"fireUserCreated",
"(",
"user",
".",
"getId",
"(",
")",
")",
";",
"return",
"user",
";",
"}"
]
| Creates a new user account by registering a JBCrypt Hashed password with the user.
@param userName The user's name
@param hashedPassword A hashed password, must begin with <code>#jbcrypt:</code> | [
"Creates",
"a",
"new",
"user",
"account",
"by",
"registering",
"a",
"JBCrypt",
"Hashed",
"password",
"with",
"the",
"user",
"."
]
| train | https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/security/HudsonPrivateSecurityRealm.java#L520-L528 |
alkacon/opencms-core | src/org/opencms/jsp/CmsJspTagContainer.java | CmsJspTagContainer.getContainerData | protected String getContainerData(CmsObject cms, int maxElements, boolean isDetailView, boolean isDetailOnly) {
"""
Returns the serialized data of the given container.<p>
@param cms the cms context
@param maxElements the maximum number of elements allowed within this container
@param isDetailView <code>true</code> if this container is currently being used for the detail view
@param isDetailOnly <code>true</code> if this is a detail only container
@return the serialized container data
"""
int width = -1;
try {
if (getWidth() != null) {
width = Integer.parseInt(getWidth());
}
} catch (NumberFormatException e) {
//ignore; set width to -1
LOG.debug("Error parsing container width.", e);
}
CmsContainer cont = new CmsContainer(
getName(),
getType(),
m_bodyContent,
width,
maxElements,
isDetailView,
!m_hasModelGroupAncestor && isEditable(cms),
null,
m_parentContainer != null ? m_parentContainer.getName() : null,
m_parentElement != null ? m_parentElement.getInstanceId() : null,
m_settingPresets);
cont.setDeatilOnly(isDetailOnly);
String result = "";
try {
result = CmsContainerpageService.getSerializedContainerInfo(cont);
} catch (Exception e) {
LOG.error(e.getLocalizedMessage(), e);
}
return result;
} | java | protected String getContainerData(CmsObject cms, int maxElements, boolean isDetailView, boolean isDetailOnly) {
int width = -1;
try {
if (getWidth() != null) {
width = Integer.parseInt(getWidth());
}
} catch (NumberFormatException e) {
//ignore; set width to -1
LOG.debug("Error parsing container width.", e);
}
CmsContainer cont = new CmsContainer(
getName(),
getType(),
m_bodyContent,
width,
maxElements,
isDetailView,
!m_hasModelGroupAncestor && isEditable(cms),
null,
m_parentContainer != null ? m_parentContainer.getName() : null,
m_parentElement != null ? m_parentElement.getInstanceId() : null,
m_settingPresets);
cont.setDeatilOnly(isDetailOnly);
String result = "";
try {
result = CmsContainerpageService.getSerializedContainerInfo(cont);
} catch (Exception e) {
LOG.error(e.getLocalizedMessage(), e);
}
return result;
} | [
"protected",
"String",
"getContainerData",
"(",
"CmsObject",
"cms",
",",
"int",
"maxElements",
",",
"boolean",
"isDetailView",
",",
"boolean",
"isDetailOnly",
")",
"{",
"int",
"width",
"=",
"-",
"1",
";",
"try",
"{",
"if",
"(",
"getWidth",
"(",
")",
"!=",
"null",
")",
"{",
"width",
"=",
"Integer",
".",
"parseInt",
"(",
"getWidth",
"(",
")",
")",
";",
"}",
"}",
"catch",
"(",
"NumberFormatException",
"e",
")",
"{",
"//ignore; set width to -1",
"LOG",
".",
"debug",
"(",
"\"Error parsing container width.\"",
",",
"e",
")",
";",
"}",
"CmsContainer",
"cont",
"=",
"new",
"CmsContainer",
"(",
"getName",
"(",
")",
",",
"getType",
"(",
")",
",",
"m_bodyContent",
",",
"width",
",",
"maxElements",
",",
"isDetailView",
",",
"!",
"m_hasModelGroupAncestor",
"&&",
"isEditable",
"(",
"cms",
")",
",",
"null",
",",
"m_parentContainer",
"!=",
"null",
"?",
"m_parentContainer",
".",
"getName",
"(",
")",
":",
"null",
",",
"m_parentElement",
"!=",
"null",
"?",
"m_parentElement",
".",
"getInstanceId",
"(",
")",
":",
"null",
",",
"m_settingPresets",
")",
";",
"cont",
".",
"setDeatilOnly",
"(",
"isDetailOnly",
")",
";",
"String",
"result",
"=",
"\"\"",
";",
"try",
"{",
"result",
"=",
"CmsContainerpageService",
".",
"getSerializedContainerInfo",
"(",
"cont",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"LOG",
".",
"error",
"(",
"e",
".",
"getLocalizedMessage",
"(",
")",
",",
"e",
")",
";",
"}",
"return",
"result",
";",
"}"
]
| Returns the serialized data of the given container.<p>
@param cms the cms context
@param maxElements the maximum number of elements allowed within this container
@param isDetailView <code>true</code> if this container is currently being used for the detail view
@param isDetailOnly <code>true</code> if this is a detail only container
@return the serialized container data | [
"Returns",
"the",
"serialized",
"data",
"of",
"the",
"given",
"container",
".",
"<p",
">"
]
| train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jsp/CmsJspTagContainer.java#L908-L940 |
mbrade/prefixedproperties | pp-core/src/main/java/net/sf/prefixedproperties/PrefixedProperties.java | PrefixedProperties.createCascadingPrefixProperties | public static PrefixedProperties createCascadingPrefixProperties(final String[] prefixes) {
"""
Creates the cascading prefix properties by using the given Prefixes.
@param prefixes
the prefixes
@return the prefixed properties
"""
PrefixedProperties properties = null;
for (final String aPrefix : prefixes) {
if (properties == null) {
properties = new PrefixedProperties(aPrefix);
} else {
properties = new PrefixedProperties(properties, aPrefix);
}
}
return properties;
} | java | public static PrefixedProperties createCascadingPrefixProperties(final String[] prefixes) {
PrefixedProperties properties = null;
for (final String aPrefix : prefixes) {
if (properties == null) {
properties = new PrefixedProperties(aPrefix);
} else {
properties = new PrefixedProperties(properties, aPrefix);
}
}
return properties;
} | [
"public",
"static",
"PrefixedProperties",
"createCascadingPrefixProperties",
"(",
"final",
"String",
"[",
"]",
"prefixes",
")",
"{",
"PrefixedProperties",
"properties",
"=",
"null",
";",
"for",
"(",
"final",
"String",
"aPrefix",
":",
"prefixes",
")",
"{",
"if",
"(",
"properties",
"==",
"null",
")",
"{",
"properties",
"=",
"new",
"PrefixedProperties",
"(",
"aPrefix",
")",
";",
"}",
"else",
"{",
"properties",
"=",
"new",
"PrefixedProperties",
"(",
"properties",
",",
"aPrefix",
")",
";",
"}",
"}",
"return",
"properties",
";",
"}"
]
| Creates the cascading prefix properties by using the given Prefixes.
@param prefixes
the prefixes
@return the prefixed properties | [
"Creates",
"the",
"cascading",
"prefix",
"properties",
"by",
"using",
"the",
"given",
"Prefixes",
"."
]
| train | https://github.com/mbrade/prefixedproperties/blob/ac430409ea37e244158002b3cf1504417835a0b2/pp-core/src/main/java/net/sf/prefixedproperties/PrefixedProperties.java#L362-L372 |
micrometer-metrics/micrometer | micrometer-core/src/main/java/io/micrometer/core/instrument/Tags.java | Tags.of | public static Tags of(String key, String value) {
"""
Return a new {@code Tags} instance containing tags constructed from the specified key/value pair.
@param key the tag key to add
@param value the tag value to add
@return a new {@code Tags} instance
"""
return new Tags(new Tag[]{Tag.of(key, value)});
} | java | public static Tags of(String key, String value) {
return new Tags(new Tag[]{Tag.of(key, value)});
} | [
"public",
"static",
"Tags",
"of",
"(",
"String",
"key",
",",
"String",
"value",
")",
"{",
"return",
"new",
"Tags",
"(",
"new",
"Tag",
"[",
"]",
"{",
"Tag",
".",
"of",
"(",
"key",
",",
"value",
")",
"}",
")",
";",
"}"
]
| Return a new {@code Tags} instance containing tags constructed from the specified key/value pair.
@param key the tag key to add
@param value the tag value to add
@return a new {@code Tags} instance | [
"Return",
"a",
"new",
"{",
"@code",
"Tags",
"}",
"instance",
"containing",
"tags",
"constructed",
"from",
"the",
"specified",
"key",
"/",
"value",
"pair",
"."
]
| train | https://github.com/micrometer-metrics/micrometer/blob/127fa3265325cc894f368312ed8890b76a055d88/micrometer-core/src/main/java/io/micrometer/core/instrument/Tags.java#L235-L237 |
hector-client/hector | object-mapper/src/main/java/me/prettyprint/hom/ClassCacheMgr.java | ClassCacheMgr.findAnnotatedMethod | public Method findAnnotatedMethod(Class<?> clazz, Class<? extends Annotation> anno) {
"""
Find method annotated with the given annotation.
@param clazz
@param anno
@return returns Method if found, null otherwise
"""
for (Method meth : clazz.getMethods()) {
if (meth.isAnnotationPresent(anno)) {
return meth;
}
}
return null;
} | java | public Method findAnnotatedMethod(Class<?> clazz, Class<? extends Annotation> anno) {
for (Method meth : clazz.getMethods()) {
if (meth.isAnnotationPresent(anno)) {
return meth;
}
}
return null;
} | [
"public",
"Method",
"findAnnotatedMethod",
"(",
"Class",
"<",
"?",
">",
"clazz",
",",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
"anno",
")",
"{",
"for",
"(",
"Method",
"meth",
":",
"clazz",
".",
"getMethods",
"(",
")",
")",
"{",
"if",
"(",
"meth",
".",
"isAnnotationPresent",
"(",
"anno",
")",
")",
"{",
"return",
"meth",
";",
"}",
"}",
"return",
"null",
";",
"}"
]
| Find method annotated with the given annotation.
@param clazz
@param anno
@return returns Method if found, null otherwise | [
"Find",
"method",
"annotated",
"with",
"the",
"given",
"annotation",
"."
]
| train | https://github.com/hector-client/hector/blob/a302e68ca8d91b45d332e8c9afd7d98030b54de1/object-mapper/src/main/java/me/prettyprint/hom/ClassCacheMgr.java#L373-L380 |
Azure/azure-sdk-for-java | storage/resource-manager/v2018_03_01_preview/src/main/java/com/microsoft/azure/management/storage/v2018_03_01_preview/implementation/StorageAccountsInner.java | StorageAccountsInner.beginCreateAsync | public Observable<StorageAccountInner> beginCreateAsync(String resourceGroupName, String accountName, StorageAccountCreateParameters parameters) {
"""
Asynchronously creates a new storage account with the specified parameters. If an account is already created and a subsequent create request is issued with different properties, the account properties will be updated. If an account is already created and a subsequent create or update request is issued with the exact same set of properties, the request will succeed.
@param resourceGroupName The name of the resource group within the user's subscription. The name is case insensitive.
@param accountName The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only.
@param parameters The parameters to provide for the created account.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the StorageAccountInner object
"""
return beginCreateWithServiceResponseAsync(resourceGroupName, accountName, parameters).map(new Func1<ServiceResponse<StorageAccountInner>, StorageAccountInner>() {
@Override
public StorageAccountInner call(ServiceResponse<StorageAccountInner> response) {
return response.body();
}
});
} | java | public Observable<StorageAccountInner> beginCreateAsync(String resourceGroupName, String accountName, StorageAccountCreateParameters parameters) {
return beginCreateWithServiceResponseAsync(resourceGroupName, accountName, parameters).map(new Func1<ServiceResponse<StorageAccountInner>, StorageAccountInner>() {
@Override
public StorageAccountInner call(ServiceResponse<StorageAccountInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"StorageAccountInner",
">",
"beginCreateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"accountName",
",",
"StorageAccountCreateParameters",
"parameters",
")",
"{",
"return",
"beginCreateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"accountName",
",",
"parameters",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"StorageAccountInner",
">",
",",
"StorageAccountInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"StorageAccountInner",
"call",
"(",
"ServiceResponse",
"<",
"StorageAccountInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Asynchronously creates a new storage account with the specified parameters. If an account is already created and a subsequent create request is issued with different properties, the account properties will be updated. If an account is already created and a subsequent create or update request is issued with the exact same set of properties, the request will succeed.
@param resourceGroupName The name of the resource group within the user's subscription. The name is case insensitive.
@param accountName The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only.
@param parameters The parameters to provide for the created account.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the StorageAccountInner object | [
"Asynchronously",
"creates",
"a",
"new",
"storage",
"account",
"with",
"the",
"specified",
"parameters",
".",
"If",
"an",
"account",
"is",
"already",
"created",
"and",
"a",
"subsequent",
"create",
"request",
"is",
"issued",
"with",
"different",
"properties",
"the",
"account",
"properties",
"will",
"be",
"updated",
".",
"If",
"an",
"account",
"is",
"already",
"created",
"and",
"a",
"subsequent",
"create",
"or",
"update",
"request",
"is",
"issued",
"with",
"the",
"exact",
"same",
"set",
"of",
"properties",
"the",
"request",
"will",
"succeed",
"."
]
| train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/storage/resource-manager/v2018_03_01_preview/src/main/java/com/microsoft/azure/management/storage/v2018_03_01_preview/implementation/StorageAccountsInner.java#L331-L338 |
hdecarne/java-default | src/main/java/de/carne/io/IOUtil.java | IOUtil.copyChannel | public static long copyChannel(WritableByteChannel dst, ReadableByteChannel src) throws IOException {
"""
Copies all bytes from a {@linkplain ReadableByteChannel} to a {@linkplain WritableByteChannel}.
@param dst the {@linkplain WritableByteChannel} to copy to.
@param src the {@linkplain ReadableByteChannel} to copy from.
@return the number of copied bytes.
@throws IOException if an I/O error occurs.
"""
ByteBuffer buffer = ByteBuffer.allocateDirect(CHANNEL_IO_BUFFER_SIZE);
long copied = 0;
int read;
while ((read = src.read(buffer)) >= 0) {
buffer.flip();
dst.write(buffer);
buffer.clear();
copied += read;
}
return copied;
} | java | public static long copyChannel(WritableByteChannel dst, ReadableByteChannel src) throws IOException {
ByteBuffer buffer = ByteBuffer.allocateDirect(CHANNEL_IO_BUFFER_SIZE);
long copied = 0;
int read;
while ((read = src.read(buffer)) >= 0) {
buffer.flip();
dst.write(buffer);
buffer.clear();
copied += read;
}
return copied;
} | [
"public",
"static",
"long",
"copyChannel",
"(",
"WritableByteChannel",
"dst",
",",
"ReadableByteChannel",
"src",
")",
"throws",
"IOException",
"{",
"ByteBuffer",
"buffer",
"=",
"ByteBuffer",
".",
"allocateDirect",
"(",
"CHANNEL_IO_BUFFER_SIZE",
")",
";",
"long",
"copied",
"=",
"0",
";",
"int",
"read",
";",
"while",
"(",
"(",
"read",
"=",
"src",
".",
"read",
"(",
"buffer",
")",
")",
">=",
"0",
")",
"{",
"buffer",
".",
"flip",
"(",
")",
";",
"dst",
".",
"write",
"(",
"buffer",
")",
";",
"buffer",
".",
"clear",
"(",
")",
";",
"copied",
"+=",
"read",
";",
"}",
"return",
"copied",
";",
"}"
]
| Copies all bytes from a {@linkplain ReadableByteChannel} to a {@linkplain WritableByteChannel}.
@param dst the {@linkplain WritableByteChannel} to copy to.
@param src the {@linkplain ReadableByteChannel} to copy from.
@return the number of copied bytes.
@throws IOException if an I/O error occurs. | [
"Copies",
"all",
"bytes",
"from",
"a",
"{",
"@linkplain",
"ReadableByteChannel",
"}",
"to",
"a",
"{",
"@linkplain",
"WritableByteChannel",
"}",
"."
]
| train | https://github.com/hdecarne/java-default/blob/ca16f6fdb0436e90e9e2df3106055e320bb3c9e3/src/main/java/de/carne/io/IOUtil.java#L186-L198 |
netscaler/nitro | src/main/java/com/citrix/netscaler/nitro/resource/config/dns/dnspolicy64_binding.java | dnspolicy64_binding.get | public static dnspolicy64_binding get(nitro_service service, String name) throws Exception {
"""
Use this API to fetch dnspolicy64_binding resource of given name .
"""
dnspolicy64_binding obj = new dnspolicy64_binding();
obj.set_name(name);
dnspolicy64_binding response = (dnspolicy64_binding) obj.get_resource(service);
return response;
} | java | public static dnspolicy64_binding get(nitro_service service, String name) throws Exception{
dnspolicy64_binding obj = new dnspolicy64_binding();
obj.set_name(name);
dnspolicy64_binding response = (dnspolicy64_binding) obj.get_resource(service);
return response;
} | [
"public",
"static",
"dnspolicy64_binding",
"get",
"(",
"nitro_service",
"service",
",",
"String",
"name",
")",
"throws",
"Exception",
"{",
"dnspolicy64_binding",
"obj",
"=",
"new",
"dnspolicy64_binding",
"(",
")",
";",
"obj",
".",
"set_name",
"(",
"name",
")",
";",
"dnspolicy64_binding",
"response",
"=",
"(",
"dnspolicy64_binding",
")",
"obj",
".",
"get_resource",
"(",
"service",
")",
";",
"return",
"response",
";",
"}"
]
| Use this API to fetch dnspolicy64_binding resource of given name . | [
"Use",
"this",
"API",
"to",
"fetch",
"dnspolicy64_binding",
"resource",
"of",
"given",
"name",
"."
]
| train | https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/dns/dnspolicy64_binding.java#L103-L108 |
OpenLiberty/open-liberty | dev/com.ibm.ws.logging.core/src/com/ibm/websphere/ras/DataFormatHelper.java | DataFormatHelper.printFieldStackTrace | private static final boolean printFieldStackTrace(PrintWriter p, Throwable t, String className, String fieldName) {
"""
Find a field value in the class hierarchy of an exception, and if the
field contains another Throwable, then print its stack trace.
@param p the writer to print to
@param t the outer throwable
@param className the name of the class to look for
@param fieldName the field in the class to look for
@return true if the field was found
"""
for (Class<?> c = t.getClass(); c != Object.class; c = c.getSuperclass()) {
if (c.getName().equals(className)) {
try {
Object value = c.getField(fieldName).get(t);
if (value instanceof Throwable && value != t.getCause()) {
p.append(fieldName).append(": ");
printStackTrace(p, (Throwable) value);
}
return true;
} catch (NoSuchFieldException e) {
} catch (IllegalAccessException e) {
}
}
}
return false;
} | java | private static final boolean printFieldStackTrace(PrintWriter p, Throwable t, String className, String fieldName) {
for (Class<?> c = t.getClass(); c != Object.class; c = c.getSuperclass()) {
if (c.getName().equals(className)) {
try {
Object value = c.getField(fieldName).get(t);
if (value instanceof Throwable && value != t.getCause()) {
p.append(fieldName).append(": ");
printStackTrace(p, (Throwable) value);
}
return true;
} catch (NoSuchFieldException e) {
} catch (IllegalAccessException e) {
}
}
}
return false;
} | [
"private",
"static",
"final",
"boolean",
"printFieldStackTrace",
"(",
"PrintWriter",
"p",
",",
"Throwable",
"t",
",",
"String",
"className",
",",
"String",
"fieldName",
")",
"{",
"for",
"(",
"Class",
"<",
"?",
">",
"c",
"=",
"t",
".",
"getClass",
"(",
")",
";",
"c",
"!=",
"Object",
".",
"class",
";",
"c",
"=",
"c",
".",
"getSuperclass",
"(",
")",
")",
"{",
"if",
"(",
"c",
".",
"getName",
"(",
")",
".",
"equals",
"(",
"className",
")",
")",
"{",
"try",
"{",
"Object",
"value",
"=",
"c",
".",
"getField",
"(",
"fieldName",
")",
".",
"get",
"(",
"t",
")",
";",
"if",
"(",
"value",
"instanceof",
"Throwable",
"&&",
"value",
"!=",
"t",
".",
"getCause",
"(",
")",
")",
"{",
"p",
".",
"append",
"(",
"fieldName",
")",
".",
"append",
"(",
"\": \"",
")",
";",
"printStackTrace",
"(",
"p",
",",
"(",
"Throwable",
")",
"value",
")",
";",
"}",
"return",
"true",
";",
"}",
"catch",
"(",
"NoSuchFieldException",
"e",
")",
"{",
"}",
"catch",
"(",
"IllegalAccessException",
"e",
")",
"{",
"}",
"}",
"}",
"return",
"false",
";",
"}"
]
| Find a field value in the class hierarchy of an exception, and if the
field contains another Throwable, then print its stack trace.
@param p the writer to print to
@param t the outer throwable
@param className the name of the class to look for
@param fieldName the field in the class to look for
@return true if the field was found | [
"Find",
"a",
"field",
"value",
"in",
"the",
"class",
"hierarchy",
"of",
"an",
"exception",
"and",
"if",
"the",
"field",
"contains",
"another",
"Throwable",
"then",
"print",
"its",
"stack",
"trace",
"."
]
| train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.logging.core/src/com/ibm/websphere/ras/DataFormatHelper.java#L260-L277 |
Crab2died/Excel4J | src/main/java/com/github/crab2died/ExcelUtils.java | ExcelUtils.normalSheet2Excel | public void normalSheet2Excel(List<NormalSheetWrapper> sheetWrappers, String templatePath, OutputStream os)
throws Excel4JException {
"""
基于Excel模板与注解{@link com.github.crab2died.annotation.ExcelField}导出多sheet的Excel
@param sheetWrappers sheet包装类
@param templatePath Excel模板路径
@param os 生成的Excel待输出数据流
@throws Excel4JException 异常
"""
try (SheetTemplate sheetTemplate = exportExcelByModuleHandler(templatePath, sheetWrappers)) {
sheetTemplate.write2Stream(os);
} catch (IOException e) {
throw new Excel4JException(e);
}
} | java | public void normalSheet2Excel(List<NormalSheetWrapper> sheetWrappers, String templatePath, OutputStream os)
throws Excel4JException {
try (SheetTemplate sheetTemplate = exportExcelByModuleHandler(templatePath, sheetWrappers)) {
sheetTemplate.write2Stream(os);
} catch (IOException e) {
throw new Excel4JException(e);
}
} | [
"public",
"void",
"normalSheet2Excel",
"(",
"List",
"<",
"NormalSheetWrapper",
">",
"sheetWrappers",
",",
"String",
"templatePath",
",",
"OutputStream",
"os",
")",
"throws",
"Excel4JException",
"{",
"try",
"(",
"SheetTemplate",
"sheetTemplate",
"=",
"exportExcelByModuleHandler",
"(",
"templatePath",
",",
"sheetWrappers",
")",
")",
"{",
"sheetTemplate",
".",
"write2Stream",
"(",
"os",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"Excel4JException",
"(",
"e",
")",
";",
"}",
"}"
]
| 基于Excel模板与注解{@link com.github.crab2died.annotation.ExcelField}导出多sheet的Excel
@param sheetWrappers sheet包装类
@param templatePath Excel模板路径
@param os 生成的Excel待输出数据流
@throws Excel4JException 异常 | [
"基于Excel模板与注解",
"{",
"@link",
"com",
".",
"github",
".",
"crab2died",
".",
"annotation",
".",
"ExcelField",
"}",
"导出多sheet的Excel"
]
| train | https://github.com/Crab2died/Excel4J/blob/2ab0a3b8226a69ff868c3ead6e724f3a774f5f77/src/main/java/com/github/crab2died/ExcelUtils.java#L652-L660 |
kuali/ojb-1.0.4 | src/java/org/apache/ojb/broker/query/CriteriaUtils.java | CriteriaUtils.getDnfAndDnf | private static List getDnfAndDnf(List dnf1, List dnf2) {
"""
(a OR b) AND (c OR d) -> (a AND c) OR (a AND d) OR (b AND c) OR (b AND d)
"""
ArrayList dnf = new ArrayList();
for (Iterator it1 = dnf1.iterator(); it1.hasNext(); )
{
Criteria crit1 = (Criteria) it1.next();
for (Iterator it2 = dnf2.iterator(); it2.hasNext(); )
{
Criteria crit2 = (Criteria) it2.next();
Criteria crit = new Criteria();
crit.getCriteria().addAll(crit1.getCriteria());
crit.getCriteria().addAll(crit2.getCriteria());
dnf.add(crit);
}
}
return dnf;
} | java | private static List getDnfAndDnf(List dnf1, List dnf2)
{
ArrayList dnf = new ArrayList();
for (Iterator it1 = dnf1.iterator(); it1.hasNext(); )
{
Criteria crit1 = (Criteria) it1.next();
for (Iterator it2 = dnf2.iterator(); it2.hasNext(); )
{
Criteria crit2 = (Criteria) it2.next();
Criteria crit = new Criteria();
crit.getCriteria().addAll(crit1.getCriteria());
crit.getCriteria().addAll(crit2.getCriteria());
dnf.add(crit);
}
}
return dnf;
} | [
"private",
"static",
"List",
"getDnfAndDnf",
"(",
"List",
"dnf1",
",",
"List",
"dnf2",
")",
"{",
"ArrayList",
"dnf",
"=",
"new",
"ArrayList",
"(",
")",
";",
"for",
"(",
"Iterator",
"it1",
"=",
"dnf1",
".",
"iterator",
"(",
")",
";",
"it1",
".",
"hasNext",
"(",
")",
";",
")",
"{",
"Criteria",
"crit1",
"=",
"(",
"Criteria",
")",
"it1",
".",
"next",
"(",
")",
";",
"for",
"(",
"Iterator",
"it2",
"=",
"dnf2",
".",
"iterator",
"(",
")",
";",
"it2",
".",
"hasNext",
"(",
")",
";",
")",
"{",
"Criteria",
"crit2",
"=",
"(",
"Criteria",
")",
"it2",
".",
"next",
"(",
")",
";",
"Criteria",
"crit",
"=",
"new",
"Criteria",
"(",
")",
";",
"crit",
".",
"getCriteria",
"(",
")",
".",
"addAll",
"(",
"crit1",
".",
"getCriteria",
"(",
")",
")",
";",
"crit",
".",
"getCriteria",
"(",
")",
".",
"addAll",
"(",
"crit2",
".",
"getCriteria",
"(",
")",
")",
";",
"dnf",
".",
"add",
"(",
"crit",
")",
";",
"}",
"}",
"return",
"dnf",
";",
"}"
]
| (a OR b) AND (c OR d) -> (a AND c) OR (a AND d) OR (b AND c) OR (b AND d) | [
"(",
"a",
"OR",
"b",
")",
"AND",
"(",
"c",
"OR",
"d",
")",
"-",
">",
"(",
"a",
"AND",
"c",
")",
"OR",
"(",
"a",
"AND",
"d",
")",
"OR",
"(",
"b",
"AND",
"c",
")",
"OR",
"(",
"b",
"AND",
"d",
")"
]
| train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/query/CriteriaUtils.java#L93-L112 |
ArcBees/gwtquery | gwtquery-core/src/main/java/com/google/gwt/query/client/js/JsUtils.java | JsUtils.loadScript | @Deprecated
public static void loadScript(String url, String id) {
"""
Load an external javascript library. The inserted script replaces the
element with the given id in the document.
@deprecated use {@link com.google.gwt.query.client.plugins.ajax.Ajax#loadScript(String)}
"""
GQuery gs = GQuery.$(DOM.createElement("script"));
GQuery gp = GQuery.$("#" + id).parent();
if (gp.size() != 1) {
gp = GQuery.$(GQuery.document.getBody());
}
GQuery.$("#" + id).remove();
gp.append(gs.attr("src", url).attr("type", "text/javascript").attr("id", id));
} | java | @Deprecated
public static void loadScript(String url, String id) {
GQuery gs = GQuery.$(DOM.createElement("script"));
GQuery gp = GQuery.$("#" + id).parent();
if (gp.size() != 1) {
gp = GQuery.$(GQuery.document.getBody());
}
GQuery.$("#" + id).remove();
gp.append(gs.attr("src", url).attr("type", "text/javascript").attr("id", id));
} | [
"@",
"Deprecated",
"public",
"static",
"void",
"loadScript",
"(",
"String",
"url",
",",
"String",
"id",
")",
"{",
"GQuery",
"gs",
"=",
"GQuery",
".",
"$",
"(",
"DOM",
".",
"createElement",
"(",
"\"script\"",
")",
")",
";",
"GQuery",
"gp",
"=",
"GQuery",
".",
"$",
"(",
"\"#\"",
"+",
"id",
")",
".",
"parent",
"(",
")",
";",
"if",
"(",
"gp",
".",
"size",
"(",
")",
"!=",
"1",
")",
"{",
"gp",
"=",
"GQuery",
".",
"$",
"(",
"GQuery",
".",
"document",
".",
"getBody",
"(",
")",
")",
";",
"}",
"GQuery",
".",
"$",
"(",
"\"#\"",
"+",
"id",
")",
".",
"remove",
"(",
")",
";",
"gp",
".",
"append",
"(",
"gs",
".",
"attr",
"(",
"\"src\"",
",",
"url",
")",
".",
"attr",
"(",
"\"type\"",
",",
"\"text/javascript\"",
")",
".",
"attr",
"(",
"\"id\"",
",",
"id",
")",
")",
";",
"}"
]
| Load an external javascript library. The inserted script replaces the
element with the given id in the document.
@deprecated use {@link com.google.gwt.query.client.plugins.ajax.Ajax#loadScript(String)} | [
"Load",
"an",
"external",
"javascript",
"library",
".",
"The",
"inserted",
"script",
"replaces",
"the",
"element",
"with",
"the",
"given",
"id",
"in",
"the",
"document",
"."
]
| train | https://github.com/ArcBees/gwtquery/blob/93e02bc8eb030081061c56134ebee1f585981107/gwtquery-core/src/main/java/com/google/gwt/query/client/js/JsUtils.java#L445-L454 |
seancfoley/IPAddress | IPAddress/src/inet.ipaddr/inet/ipaddr/ipv6/IPv6AddressSection.java | IPv6AddressSection.maskNetwork | public IPv6AddressSection maskNetwork(IPv6AddressSection mask, int networkPrefixLength) throws IncompatibleAddressException, PrefixLenException, SizeMismatchException {
"""
Applies the given mask to the network section of the address as indicated by the given prefix length.
Useful for subnetting. Once you have zeroed a section of the network you can insert bits
using {@link #bitwiseOr(IPv6AddressSection)} or {@link #replace(int, IPv6AddressSection)}
@param mask
@param networkPrefixLength
@return
@throws IncompatibleAddressException
"""
checkMaskSectionCount(mask);
if(getNetwork().getPrefixConfiguration().allPrefixedAddressesAreSubnets()) {
return getSubnetSegments(
this,
cacheBits(networkPrefixLength),
getAddressCreator(),
true,
this::getSegment,
i -> mask.getSegment(i).getSegmentValue(),
false);
}
IPv6AddressSection hostMask = getNetwork().getHostMaskSection(networkPrefixLength);
return getSubnetSegments(
this,
cacheBits(networkPrefixLength),
getAddressCreator(),
true,
this::getSegment,
i -> {
int val1 = mask.getSegment(i).getSegmentValue();
int val2 = hostMask.getSegment(i).getSegmentValue();
return val1 | val2;
},
false
);
} | java | public IPv6AddressSection maskNetwork(IPv6AddressSection mask, int networkPrefixLength) throws IncompatibleAddressException, PrefixLenException, SizeMismatchException {
checkMaskSectionCount(mask);
if(getNetwork().getPrefixConfiguration().allPrefixedAddressesAreSubnets()) {
return getSubnetSegments(
this,
cacheBits(networkPrefixLength),
getAddressCreator(),
true,
this::getSegment,
i -> mask.getSegment(i).getSegmentValue(),
false);
}
IPv6AddressSection hostMask = getNetwork().getHostMaskSection(networkPrefixLength);
return getSubnetSegments(
this,
cacheBits(networkPrefixLength),
getAddressCreator(),
true,
this::getSegment,
i -> {
int val1 = mask.getSegment(i).getSegmentValue();
int val2 = hostMask.getSegment(i).getSegmentValue();
return val1 | val2;
},
false
);
} | [
"public",
"IPv6AddressSection",
"maskNetwork",
"(",
"IPv6AddressSection",
"mask",
",",
"int",
"networkPrefixLength",
")",
"throws",
"IncompatibleAddressException",
",",
"PrefixLenException",
",",
"SizeMismatchException",
"{",
"checkMaskSectionCount",
"(",
"mask",
")",
";",
"if",
"(",
"getNetwork",
"(",
")",
".",
"getPrefixConfiguration",
"(",
")",
".",
"allPrefixedAddressesAreSubnets",
"(",
")",
")",
"{",
"return",
"getSubnetSegments",
"(",
"this",
",",
"cacheBits",
"(",
"networkPrefixLength",
")",
",",
"getAddressCreator",
"(",
")",
",",
"true",
",",
"this",
"::",
"getSegment",
",",
"i",
"->",
"mask",
".",
"getSegment",
"(",
"i",
")",
".",
"getSegmentValue",
"(",
")",
",",
"false",
")",
";",
"}",
"IPv6AddressSection",
"hostMask",
"=",
"getNetwork",
"(",
")",
".",
"getHostMaskSection",
"(",
"networkPrefixLength",
")",
";",
"return",
"getSubnetSegments",
"(",
"this",
",",
"cacheBits",
"(",
"networkPrefixLength",
")",
",",
"getAddressCreator",
"(",
")",
",",
"true",
",",
"this",
"::",
"getSegment",
",",
"i",
"->",
"{",
"int",
"val1",
"=",
"mask",
".",
"getSegment",
"(",
"i",
")",
".",
"getSegmentValue",
"(",
")",
";",
"int",
"val2",
"=",
"hostMask",
".",
"getSegment",
"(",
"i",
")",
".",
"getSegmentValue",
"(",
")",
";",
"return",
"val1",
"|",
"val2",
";",
"}",
",",
"false",
")",
";",
"}"
]
| Applies the given mask to the network section of the address as indicated by the given prefix length.
Useful for subnetting. Once you have zeroed a section of the network you can insert bits
using {@link #bitwiseOr(IPv6AddressSection)} or {@link #replace(int, IPv6AddressSection)}
@param mask
@param networkPrefixLength
@return
@throws IncompatibleAddressException | [
"Applies",
"the",
"given",
"mask",
"to",
"the",
"network",
"section",
"of",
"the",
"address",
"as",
"indicated",
"by",
"the",
"given",
"prefix",
"length",
".",
"Useful",
"for",
"subnetting",
".",
"Once",
"you",
"have",
"zeroed",
"a",
"section",
"of",
"the",
"network",
"you",
"can",
"insert",
"bits",
"using",
"{",
"@link",
"#bitwiseOr",
"(",
"IPv6AddressSection",
")",
"}",
"or",
"{",
"@link",
"#replace",
"(",
"int",
"IPv6AddressSection",
")",
"}"
]
| train | https://github.com/seancfoley/IPAddress/blob/90493d0673511d673100c36d020dd93dd870111a/IPAddress/src/inet.ipaddr/inet/ipaddr/ipv6/IPv6AddressSection.java#L1891-L1917 |
mapfish/mapfish-print | core/src/main/java/org/mapfish/print/map/tiled/TileCacheInformation.java | TileCacheInformation.createBufferedImage | @Nonnull
public BufferedImage createBufferedImage(final int imageWidth, final int imageHeight) {
"""
Create a buffered image with the correct image bands etc... for the tiles being loaded.
@param imageWidth width of the image to create
@param imageHeight height of the image to create.
"""
return new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_4BYTE_ABGR);
} | java | @Nonnull
public BufferedImage createBufferedImage(final int imageWidth, final int imageHeight) {
return new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_4BYTE_ABGR);
} | [
"@",
"Nonnull",
"public",
"BufferedImage",
"createBufferedImage",
"(",
"final",
"int",
"imageWidth",
",",
"final",
"int",
"imageHeight",
")",
"{",
"return",
"new",
"BufferedImage",
"(",
"imageWidth",
",",
"imageHeight",
",",
"BufferedImage",
".",
"TYPE_4BYTE_ABGR",
")",
";",
"}"
]
| Create a buffered image with the correct image bands etc... for the tiles being loaded.
@param imageWidth width of the image to create
@param imageHeight height of the image to create. | [
"Create",
"a",
"buffered",
"image",
"with",
"the",
"correct",
"image",
"bands",
"etc",
"...",
"for",
"the",
"tiles",
"being",
"loaded",
"."
]
| train | https://github.com/mapfish/mapfish-print/blob/25a452cb39f592bd8a53b20db1037703898e1e22/core/src/main/java/org/mapfish/print/map/tiled/TileCacheInformation.java#L134-L137 |
intellimate/Izou | src/main/java/org/intellimate/izou/events/EventDistributor.java | EventDistributor.registerEventFinishedListener | @SuppressWarnings( {
"""
Adds an listener for events that gets called when the event finished processing.
<p>
Be careful with this method, it will register the listener for ALL the informations found in the Event. If your
event-type is a common event type, it will fire EACH time!.
It will also register for all Descriptors individually!
It will also ignore if this listener is already listening to an Event.
Method is thread-safe.
</p>
@param event the Event to listen to (it will listen to all descriptors individually!)
@param eventListener the ActivatorEventListener-interface for receiving activator events
@throws IllegalIDException not yet implemented
""""SynchronizationOnLocalVariableOrMethodParameter"})
public void registerEventFinishedListener(EventModel event, EventListenerModel eventListener) throws IllegalIDException {
registerEventFinishedListener(event.getAllInformations(), eventListener);
} | java | @SuppressWarnings({"SynchronizationOnLocalVariableOrMethodParameter"})
public void registerEventFinishedListener(EventModel event, EventListenerModel eventListener) throws IllegalIDException {
registerEventFinishedListener(event.getAllInformations(), eventListener);
} | [
"@",
"SuppressWarnings",
"(",
"{",
"\"SynchronizationOnLocalVariableOrMethodParameter\"",
"}",
")",
"public",
"void",
"registerEventFinishedListener",
"(",
"EventModel",
"event",
",",
"EventListenerModel",
"eventListener",
")",
"throws",
"IllegalIDException",
"{",
"registerEventFinishedListener",
"(",
"event",
".",
"getAllInformations",
"(",
")",
",",
"eventListener",
")",
";",
"}"
]
| Adds an listener for events that gets called when the event finished processing.
<p>
Be careful with this method, it will register the listener for ALL the informations found in the Event. If your
event-type is a common event type, it will fire EACH time!.
It will also register for all Descriptors individually!
It will also ignore if this listener is already listening to an Event.
Method is thread-safe.
</p>
@param event the Event to listen to (it will listen to all descriptors individually!)
@param eventListener the ActivatorEventListener-interface for receiving activator events
@throws IllegalIDException not yet implemented | [
"Adds",
"an",
"listener",
"for",
"events",
"that",
"gets",
"called",
"when",
"the",
"event",
"finished",
"processing",
".",
"<p",
">",
"Be",
"careful",
"with",
"this",
"method",
"it",
"will",
"register",
"the",
"listener",
"for",
"ALL",
"the",
"informations",
"found",
"in",
"the",
"Event",
".",
"If",
"your",
"event",
"-",
"type",
"is",
"a",
"common",
"event",
"type",
"it",
"will",
"fire",
"EACH",
"time!",
".",
"It",
"will",
"also",
"register",
"for",
"all",
"Descriptors",
"individually!",
"It",
"will",
"also",
"ignore",
"if",
"this",
"listener",
"is",
"already",
"listening",
"to",
"an",
"Event",
".",
"Method",
"is",
"thread",
"-",
"safe",
".",
"<",
"/",
"p",
">"
]
| train | https://github.com/intellimate/Izou/blob/40a808b97998e17655c4a78e30ce7326148aed27/src/main/java/org/intellimate/izou/events/EventDistributor.java#L204-L207 |
alkacon/opencms-core | src/org/opencms/ui/dialogs/CmsCopyMoveDialog.java | CmsCopyMoveDialog.getTargetName | private String getTargetName(CmsResource source, CmsResource target) throws CmsException {
"""
Gets a name for the target resource.<p>
@param source Source
@param target Target
@return Name
@throws CmsException exception
"""
String name;
String folderRootPath = target.getRootPath();
if (!folderRootPath.endsWith("/")) {
folderRootPath += "/";
}
if (folderRootPath.equals(CmsResource.getParentFolder(source.getRootPath()))) {
name = OpenCms.getResourceManager().getNameGenerator().getCopyFileName(
getRootCms(),
folderRootPath,
source.getName());
} else {
name = source.getName();
}
return name;
} | java | private String getTargetName(CmsResource source, CmsResource target) throws CmsException {
String name;
String folderRootPath = target.getRootPath();
if (!folderRootPath.endsWith("/")) {
folderRootPath += "/";
}
if (folderRootPath.equals(CmsResource.getParentFolder(source.getRootPath()))) {
name = OpenCms.getResourceManager().getNameGenerator().getCopyFileName(
getRootCms(),
folderRootPath,
source.getName());
} else {
name = source.getName();
}
return name;
} | [
"private",
"String",
"getTargetName",
"(",
"CmsResource",
"source",
",",
"CmsResource",
"target",
")",
"throws",
"CmsException",
"{",
"String",
"name",
";",
"String",
"folderRootPath",
"=",
"target",
".",
"getRootPath",
"(",
")",
";",
"if",
"(",
"!",
"folderRootPath",
".",
"endsWith",
"(",
"\"/\"",
")",
")",
"{",
"folderRootPath",
"+=",
"\"/\"",
";",
"}",
"if",
"(",
"folderRootPath",
".",
"equals",
"(",
"CmsResource",
".",
"getParentFolder",
"(",
"source",
".",
"getRootPath",
"(",
")",
")",
")",
")",
"{",
"name",
"=",
"OpenCms",
".",
"getResourceManager",
"(",
")",
".",
"getNameGenerator",
"(",
")",
".",
"getCopyFileName",
"(",
"getRootCms",
"(",
")",
",",
"folderRootPath",
",",
"source",
".",
"getName",
"(",
")",
")",
";",
"}",
"else",
"{",
"name",
"=",
"source",
".",
"getName",
"(",
")",
";",
"}",
"return",
"name",
";",
"}"
]
| Gets a name for the target resource.<p>
@param source Source
@param target Target
@return Name
@throws CmsException exception | [
"Gets",
"a",
"name",
"for",
"the",
"target",
"resource",
".",
"<p",
">"
]
| train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/dialogs/CmsCopyMoveDialog.java#L655-L671 |
Samsung/GearVRf | GVRf/Extensions/widgetLib/src/org/gearvrf/widgetlib/widget/properties/JSONHelpers.java | JSONHelpers.safePut | private static void safePut(JSONObject dest, final String key,
final Object value) {
"""
A convenience wrapper for {@linkplain JSONObject#put(String, Object)
put()} when {@code key} and {@code value} are both known to be "safe"
(i.e., neither should cause the {@code put()} to throw
{@link JSONException}). Cuts down on unnecessary {@code try/catch} blocks
littering the code and keeps the call stack clean of
{@code JSONException} throw declarations.
@param dest {@link JSONObject} to call {@code put()} on
@param key The {@code key} parameter for {@code put()}
@param value The {@code value} parameter for {@code put()}
@throws RuntimeException If either {@code key} or {@code value} turn out to
<em>not</em> be safe.
"""
try {
dest.put(key, value);
} catch (JSONException e) {
throw new RuntimeException("This should not be able to happen!", e);
}
} | java | private static void safePut(JSONObject dest, final String key,
final Object value) {
try {
dest.put(key, value);
} catch (JSONException e) {
throw new RuntimeException("This should not be able to happen!", e);
}
} | [
"private",
"static",
"void",
"safePut",
"(",
"JSONObject",
"dest",
",",
"final",
"String",
"key",
",",
"final",
"Object",
"value",
")",
"{",
"try",
"{",
"dest",
".",
"put",
"(",
"key",
",",
"value",
")",
";",
"}",
"catch",
"(",
"JSONException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"This should not be able to happen!\"",
",",
"e",
")",
";",
"}",
"}"
]
| A convenience wrapper for {@linkplain JSONObject#put(String, Object)
put()} when {@code key} and {@code value} are both known to be "safe"
(i.e., neither should cause the {@code put()} to throw
{@link JSONException}). Cuts down on unnecessary {@code try/catch} blocks
littering the code and keeps the call stack clean of
{@code JSONException} throw declarations.
@param dest {@link JSONObject} to call {@code put()} on
@param key The {@code key} parameter for {@code put()}
@param value The {@code value} parameter for {@code put()}
@throws RuntimeException If either {@code key} or {@code value} turn out to
<em>not</em> be safe. | [
"A",
"convenience",
"wrapper",
"for",
"{",
"@linkplain",
"JSONObject#put",
"(",
"String",
"Object",
")",
"put",
"()",
"}",
"when",
"{",
"@code",
"key",
"}",
"and",
"{",
"@code",
"value",
"}",
"are",
"both",
"known",
"to",
"be",
"safe",
"(",
"i",
".",
"e",
".",
"neither",
"should",
"cause",
"the",
"{",
"@code",
"put",
"()",
"}",
"to",
"throw",
"{",
"@link",
"JSONException",
"}",
")",
".",
"Cuts",
"down",
"on",
"unnecessary",
"{",
"@code",
"try",
"/",
"catch",
"}",
"blocks",
"littering",
"the",
"code",
"and",
"keeps",
"the",
"call",
"stack",
"clean",
"of",
"{",
"@code",
"JSONException",
"}",
"throw",
"declarations",
"."
]
| train | https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Extensions/widgetLib/src/org/gearvrf/widgetlib/widget/properties/JSONHelpers.java#L1617-L1624 |
EvidentSolutions/dalesbred | dalesbred/src/main/java/org/dalesbred/Database.java | Database.findOptional | public @NotNull <T> Optional<T> findOptional(@NotNull RowMapper<T> rowMapper, @NotNull @SQL String sql, Object... args) {
"""
Find a unique result from database, using given {@link RowMapper} to convert row. Returns empty if
there are no results or if single null result is returned.
@throws NonUniqueResultException if there are multiple result rows
"""
return findOptional(rowMapper, SqlQuery.query(sql, args));
} | java | public @NotNull <T> Optional<T> findOptional(@NotNull RowMapper<T> rowMapper, @NotNull @SQL String sql, Object... args) {
return findOptional(rowMapper, SqlQuery.query(sql, args));
} | [
"public",
"@",
"NotNull",
"<",
"T",
">",
"Optional",
"<",
"T",
">",
"findOptional",
"(",
"@",
"NotNull",
"RowMapper",
"<",
"T",
">",
"rowMapper",
",",
"@",
"NotNull",
"@",
"SQL",
"String",
"sql",
",",
"Object",
"...",
"args",
")",
"{",
"return",
"findOptional",
"(",
"rowMapper",
",",
"SqlQuery",
".",
"query",
"(",
"sql",
",",
"args",
")",
")",
";",
"}"
]
| Find a unique result from database, using given {@link RowMapper} to convert row. Returns empty if
there are no results or if single null result is returned.
@throws NonUniqueResultException if there are multiple result rows | [
"Find",
"a",
"unique",
"result",
"from",
"database",
"using",
"given",
"{",
"@link",
"RowMapper",
"}",
"to",
"convert",
"row",
".",
"Returns",
"empty",
"if",
"there",
"are",
"no",
"results",
"or",
"if",
"single",
"null",
"result",
"is",
"returned",
"."
]
| train | https://github.com/EvidentSolutions/dalesbred/blob/713f5b6e152d97e1672ca68b9ff9c7c6c288ceb1/dalesbred/src/main/java/org/dalesbred/Database.java#L382-L384 |
OpenLiberty/open-liberty | dev/com.ibm.ws.install.map/src/com/ibm/ws/install/map/InstallMap.java | InstallMap.sortFile | public static void sortFile(List<File> jarsList, final String fName) {
"""
Compare files in jarsList based on file name's length
Sort the files depending on the comparison
@param jarsList -abstract representation of file/directory names
@param fName - name of file
"""
Collections.sort(jarsList, new Comparator<File>() {
@Override
public int compare(File f1, File f2) {
String f1Name = f1.getName();
f1Name = f1Name.substring(fName.length() + 1, f1Name.length() - 4);
String f2Name = f2.getName();
f2Name = f2Name.substring(fName.length() + 1, f2Name.length() - 4);
Version v1 = Version.createVersion(f1Name);
Version v2 = Version.createVersion(f2Name);
if (v1 != null && v2 != null)
return v1.compareTo(v2);
return f1Name.compareTo(f2Name);
}
});
} | java | public static void sortFile(List<File> jarsList, final String fName) {
Collections.sort(jarsList, new Comparator<File>() {
@Override
public int compare(File f1, File f2) {
String f1Name = f1.getName();
f1Name = f1Name.substring(fName.length() + 1, f1Name.length() - 4);
String f2Name = f2.getName();
f2Name = f2Name.substring(fName.length() + 1, f2Name.length() - 4);
Version v1 = Version.createVersion(f1Name);
Version v2 = Version.createVersion(f2Name);
if (v1 != null && v2 != null)
return v1.compareTo(v2);
return f1Name.compareTo(f2Name);
}
});
} | [
"public",
"static",
"void",
"sortFile",
"(",
"List",
"<",
"File",
">",
"jarsList",
",",
"final",
"String",
"fName",
")",
"{",
"Collections",
".",
"sort",
"(",
"jarsList",
",",
"new",
"Comparator",
"<",
"File",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"int",
"compare",
"(",
"File",
"f1",
",",
"File",
"f2",
")",
"{",
"String",
"f1Name",
"=",
"f1",
".",
"getName",
"(",
")",
";",
"f1Name",
"=",
"f1Name",
".",
"substring",
"(",
"fName",
".",
"length",
"(",
")",
"+",
"1",
",",
"f1Name",
".",
"length",
"(",
")",
"-",
"4",
")",
";",
"String",
"f2Name",
"=",
"f2",
".",
"getName",
"(",
")",
";",
"f2Name",
"=",
"f2Name",
".",
"substring",
"(",
"fName",
".",
"length",
"(",
")",
"+",
"1",
",",
"f2Name",
".",
"length",
"(",
")",
"-",
"4",
")",
";",
"Version",
"v1",
"=",
"Version",
".",
"createVersion",
"(",
"f1Name",
")",
";",
"Version",
"v2",
"=",
"Version",
".",
"createVersion",
"(",
"f2Name",
")",
";",
"if",
"(",
"v1",
"!=",
"null",
"&&",
"v2",
"!=",
"null",
")",
"return",
"v1",
".",
"compareTo",
"(",
"v2",
")",
";",
"return",
"f1Name",
".",
"compareTo",
"(",
"f2Name",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Compare files in jarsList based on file name's length
Sort the files depending on the comparison
@param jarsList -abstract representation of file/directory names
@param fName - name of file | [
"Compare",
"files",
"in",
"jarsList",
"based",
"on",
"file",
"name",
"s",
"length",
"Sort",
"the",
"files",
"depending",
"on",
"the",
"comparison"
]
| train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.install.map/src/com/ibm/ws/install/map/InstallMap.java#L323-L338 |
vkostyukov/la4j | src/main/java/org/la4j/Matrix.java | Matrix.updateRow | public void updateRow(int i, VectorFunction function) {
"""
Updates all elements of the specified row in this matrix by applying given {@code function}.
@param i the row index
@param function the vector function
"""
VectorIterator it = iteratorOfRow(i);
while (it.hasNext()) {
double x = it.next();
int j = it.index();
it.set(function.evaluate(j, x));
}
} | java | public void updateRow(int i, VectorFunction function) {
VectorIterator it = iteratorOfRow(i);
while (it.hasNext()) {
double x = it.next();
int j = it.index();
it.set(function.evaluate(j, x));
}
} | [
"public",
"void",
"updateRow",
"(",
"int",
"i",
",",
"VectorFunction",
"function",
")",
"{",
"VectorIterator",
"it",
"=",
"iteratorOfRow",
"(",
"i",
")",
";",
"while",
"(",
"it",
".",
"hasNext",
"(",
")",
")",
"{",
"double",
"x",
"=",
"it",
".",
"next",
"(",
")",
";",
"int",
"j",
"=",
"it",
".",
"index",
"(",
")",
";",
"it",
".",
"set",
"(",
"function",
".",
"evaluate",
"(",
"j",
",",
"x",
")",
")",
";",
"}",
"}"
]
| Updates all elements of the specified row in this matrix by applying given {@code function}.
@param i the row index
@param function the vector function | [
"Updates",
"all",
"elements",
"of",
"the",
"specified",
"row",
"in",
"this",
"matrix",
"by",
"applying",
"given",
"{",
"@code",
"function",
"}",
"."
]
| train | https://github.com/vkostyukov/la4j/blob/dd1b917caf9606399a49afa6b0d738934cd3a7b3/src/main/java/org/la4j/Matrix.java#L1570-L1578 |
googleapis/cloud-bigtable-client | bigtable-client-core-parent/bigtable-client-core/src/main/java/com/google/cloud/bigtable/grpc/io/OAuthCredentialsCache.java | OAuthCredentialsCache.syncRefresh | private HeaderCacheElement syncRefresh(long timeout, TimeUnit timeUnit) {
"""
Refresh the credentials and block. Will return an error if the credentials haven't
been refreshed.
This method should not be called while holding the refresh lock
"""
Span span = TRACER.spanBuilder("Bigtable.CredentialsRefresh").startSpan();
try (Scope scope = TRACER.withSpan(span)) {
return asyncRefresh().get(timeout, timeUnit);
} catch (InterruptedException e) {
LOG.warn("Interrupted while trying to refresh google credentials.", e);
Status status = Status.UNAUTHENTICATED
.withDescription("Authentication was interrupted.")
.withCause(e);
span.setStatus(StatusConverter.fromGrpcStatus(status));
Thread.currentThread().interrupt();
return new HeaderCacheElement(status);
} catch (ExecutionException e) {
LOG.warn("ExecutionException while trying to refresh google credentials.", e);
Status status = Status.UNAUTHENTICATED
.withDescription("ExecutionException during Authentication.")
.withCause(e);
span.setStatus(StatusConverter.fromGrpcStatus(status));
return new HeaderCacheElement(status);
} catch (TimeoutException e) {
LOG.warn("TimeoutException while trying to refresh google credentials.", e);
Status status = Status.UNAUTHENTICATED
.withDescription("TimeoutException during Authentication.")
.withCause(e);
span.setStatus(StatusConverter.fromGrpcStatus(status));
return new HeaderCacheElement(status);
} catch (Exception e) {
LOG.warn("Unexpected execption while trying to refresh google credentials.", e);
Status status = Status.UNAUTHENTICATED
.withDescription("Unexpected execption during Authentication.")
.withCause(e);
span.setStatus(StatusConverter.fromGrpcStatus(status));
return new HeaderCacheElement(status);
} finally {
span.end();
}
} | java | private HeaderCacheElement syncRefresh(long timeout, TimeUnit timeUnit) {
Span span = TRACER.spanBuilder("Bigtable.CredentialsRefresh").startSpan();
try (Scope scope = TRACER.withSpan(span)) {
return asyncRefresh().get(timeout, timeUnit);
} catch (InterruptedException e) {
LOG.warn("Interrupted while trying to refresh google credentials.", e);
Status status = Status.UNAUTHENTICATED
.withDescription("Authentication was interrupted.")
.withCause(e);
span.setStatus(StatusConverter.fromGrpcStatus(status));
Thread.currentThread().interrupt();
return new HeaderCacheElement(status);
} catch (ExecutionException e) {
LOG.warn("ExecutionException while trying to refresh google credentials.", e);
Status status = Status.UNAUTHENTICATED
.withDescription("ExecutionException during Authentication.")
.withCause(e);
span.setStatus(StatusConverter.fromGrpcStatus(status));
return new HeaderCacheElement(status);
} catch (TimeoutException e) {
LOG.warn("TimeoutException while trying to refresh google credentials.", e);
Status status = Status.UNAUTHENTICATED
.withDescription("TimeoutException during Authentication.")
.withCause(e);
span.setStatus(StatusConverter.fromGrpcStatus(status));
return new HeaderCacheElement(status);
} catch (Exception e) {
LOG.warn("Unexpected execption while trying to refresh google credentials.", e);
Status status = Status.UNAUTHENTICATED
.withDescription("Unexpected execption during Authentication.")
.withCause(e);
span.setStatus(StatusConverter.fromGrpcStatus(status));
return new HeaderCacheElement(status);
} finally {
span.end();
}
} | [
"private",
"HeaderCacheElement",
"syncRefresh",
"(",
"long",
"timeout",
",",
"TimeUnit",
"timeUnit",
")",
"{",
"Span",
"span",
"=",
"TRACER",
".",
"spanBuilder",
"(",
"\"Bigtable.CredentialsRefresh\"",
")",
".",
"startSpan",
"(",
")",
";",
"try",
"(",
"Scope",
"scope",
"=",
"TRACER",
".",
"withSpan",
"(",
"span",
")",
")",
"{",
"return",
"asyncRefresh",
"(",
")",
".",
"get",
"(",
"timeout",
",",
"timeUnit",
")",
";",
"}",
"catch",
"(",
"InterruptedException",
"e",
")",
"{",
"LOG",
".",
"warn",
"(",
"\"Interrupted while trying to refresh google credentials.\"",
",",
"e",
")",
";",
"Status",
"status",
"=",
"Status",
".",
"UNAUTHENTICATED",
".",
"withDescription",
"(",
"\"Authentication was interrupted.\"",
")",
".",
"withCause",
"(",
"e",
")",
";",
"span",
".",
"setStatus",
"(",
"StatusConverter",
".",
"fromGrpcStatus",
"(",
"status",
")",
")",
";",
"Thread",
".",
"currentThread",
"(",
")",
".",
"interrupt",
"(",
")",
";",
"return",
"new",
"HeaderCacheElement",
"(",
"status",
")",
";",
"}",
"catch",
"(",
"ExecutionException",
"e",
")",
"{",
"LOG",
".",
"warn",
"(",
"\"ExecutionException while trying to refresh google credentials.\"",
",",
"e",
")",
";",
"Status",
"status",
"=",
"Status",
".",
"UNAUTHENTICATED",
".",
"withDescription",
"(",
"\"ExecutionException during Authentication.\"",
")",
".",
"withCause",
"(",
"e",
")",
";",
"span",
".",
"setStatus",
"(",
"StatusConverter",
".",
"fromGrpcStatus",
"(",
"status",
")",
")",
";",
"return",
"new",
"HeaderCacheElement",
"(",
"status",
")",
";",
"}",
"catch",
"(",
"TimeoutException",
"e",
")",
"{",
"LOG",
".",
"warn",
"(",
"\"TimeoutException while trying to refresh google credentials.\"",
",",
"e",
")",
";",
"Status",
"status",
"=",
"Status",
".",
"UNAUTHENTICATED",
".",
"withDescription",
"(",
"\"TimeoutException during Authentication.\"",
")",
".",
"withCause",
"(",
"e",
")",
";",
"span",
".",
"setStatus",
"(",
"StatusConverter",
".",
"fromGrpcStatus",
"(",
"status",
")",
")",
";",
"return",
"new",
"HeaderCacheElement",
"(",
"status",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"LOG",
".",
"warn",
"(",
"\"Unexpected execption while trying to refresh google credentials.\"",
",",
"e",
")",
";",
"Status",
"status",
"=",
"Status",
".",
"UNAUTHENTICATED",
".",
"withDescription",
"(",
"\"Unexpected execption during Authentication.\"",
")",
".",
"withCause",
"(",
"e",
")",
";",
"span",
".",
"setStatus",
"(",
"StatusConverter",
".",
"fromGrpcStatus",
"(",
"status",
")",
")",
";",
"return",
"new",
"HeaderCacheElement",
"(",
"status",
")",
";",
"}",
"finally",
"{",
"span",
".",
"end",
"(",
")",
";",
"}",
"}"
]
| Refresh the credentials and block. Will return an error if the credentials haven't
been refreshed.
This method should not be called while holding the refresh lock | [
"Refresh",
"the",
"credentials",
"and",
"block",
".",
"Will",
"return",
"an",
"error",
"if",
"the",
"credentials",
"haven",
"t",
"been",
"refreshed",
".",
"This",
"method",
"should",
"not",
"be",
"called",
"while",
"holding",
"the",
"refresh",
"lock"
]
| train | https://github.com/googleapis/cloud-bigtable-client/blob/53543f36e4d6f9ed1963640d91a35be2a2047656/bigtable-client-core-parent/bigtable-client-core/src/main/java/com/google/cloud/bigtable/grpc/io/OAuthCredentialsCache.java#L233-L269 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-backend-impls/nd4j-cuda/src/main/java/org/nd4j/jita/concurrency/CudaAffinityManager.java | CudaAffinityManager.attachThreadToDevice | @Override
public void attachThreadToDevice(Thread thread, Integer deviceId) {
"""
This method pairs specified thread & device
@param thread
@param deviceId
"""
attachThreadToDevice(thread.getId(), deviceId);
} | java | @Override
public void attachThreadToDevice(Thread thread, Integer deviceId) {
attachThreadToDevice(thread.getId(), deviceId);
} | [
"@",
"Override",
"public",
"void",
"attachThreadToDevice",
"(",
"Thread",
"thread",
",",
"Integer",
"deviceId",
")",
"{",
"attachThreadToDevice",
"(",
"thread",
".",
"getId",
"(",
")",
",",
"deviceId",
")",
";",
"}"
]
| This method pairs specified thread & device
@param thread
@param deviceId | [
"This",
"method",
"pairs",
"specified",
"thread",
"&",
"device"
]
| train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-backend-impls/nd4j-cuda/src/main/java/org/nd4j/jita/concurrency/CudaAffinityManager.java#L143-L146 |
pressgang-ccms/PressGangCCMSQuery | src/main/java/org/jboss/pressgang/ccms/filter/base/BaseFilterQueryBuilder.java | BaseFilterQueryBuilder.addSizeGreaterThanCondition | protected void addSizeGreaterThanCondition(final String propertyName, final Integer size) {
"""
Add a Field Search Condition that will check if the size of a collection in an entity is greater than the specified size.
@param propertyName The name of the collection as defined in the Entity mapping class.
@param size The size that the collection should be greater than.
"""
final Expression<Integer> propertySizeExpression = getCriteriaBuilder().size(getRootPath().get(propertyName).as(Set.class));
fieldConditions.add(getCriteriaBuilder().gt(propertySizeExpression, size));
} | java | protected void addSizeGreaterThanCondition(final String propertyName, final Integer size) {
final Expression<Integer> propertySizeExpression = getCriteriaBuilder().size(getRootPath().get(propertyName).as(Set.class));
fieldConditions.add(getCriteriaBuilder().gt(propertySizeExpression, size));
} | [
"protected",
"void",
"addSizeGreaterThanCondition",
"(",
"final",
"String",
"propertyName",
",",
"final",
"Integer",
"size",
")",
"{",
"final",
"Expression",
"<",
"Integer",
">",
"propertySizeExpression",
"=",
"getCriteriaBuilder",
"(",
")",
".",
"size",
"(",
"getRootPath",
"(",
")",
".",
"get",
"(",
"propertyName",
")",
".",
"as",
"(",
"Set",
".",
"class",
")",
")",
";",
"fieldConditions",
".",
"add",
"(",
"getCriteriaBuilder",
"(",
")",
".",
"gt",
"(",
"propertySizeExpression",
",",
"size",
")",
")",
";",
"}"
]
| Add a Field Search Condition that will check if the size of a collection in an entity is greater than the specified size.
@param propertyName The name of the collection as defined in the Entity mapping class.
@param size The size that the collection should be greater than. | [
"Add",
"a",
"Field",
"Search",
"Condition",
"that",
"will",
"check",
"if",
"the",
"size",
"of",
"a",
"collection",
"in",
"an",
"entity",
"is",
"greater",
"than",
"the",
"specified",
"size",
"."
]
| train | https://github.com/pressgang-ccms/PressGangCCMSQuery/blob/2bb23430adab956737d0301cd2ea933f986dd85b/src/main/java/org/jboss/pressgang/ccms/filter/base/BaseFilterQueryBuilder.java#L258-L261 |
lessthanoptimal/ejml | main/ejml-ddense/src/org/ejml/dense/row/CommonOps_DDRM.java | CommonOps_DDRM.fill | public static void fill(DMatrixD1 a, double value) {
"""
<p>
Sets every element in the matrix to the specified value.<br>
<br>
a<sub>ij</sub> = value
<p>
@param a A matrix whose elements are about to be set. Modified.
@param value The value each element will have.
"""
Arrays.fill(a.data, 0, a.getNumElements(), value);
} | java | public static void fill(DMatrixD1 a, double value)
{
Arrays.fill(a.data, 0, a.getNumElements(), value);
} | [
"public",
"static",
"void",
"fill",
"(",
"DMatrixD1",
"a",
",",
"double",
"value",
")",
"{",
"Arrays",
".",
"fill",
"(",
"a",
".",
"data",
",",
"0",
",",
"a",
".",
"getNumElements",
"(",
")",
",",
"value",
")",
";",
"}"
]
| <p>
Sets every element in the matrix to the specified value.<br>
<br>
a<sub>ij</sub> = value
<p>
@param a A matrix whose elements are about to be set. Modified.
@param value The value each element will have. | [
"<p",
">",
"Sets",
"every",
"element",
"in",
"the",
"matrix",
"to",
"the",
"specified",
"value",
".",
"<br",
">",
"<br",
">",
"a<sub",
">",
"ij<",
"/",
"sub",
">",
"=",
"value",
"<p",
">"
]
| train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/row/CommonOps_DDRM.java#L2549-L2552 |
recommenders/rival | rival-evaluate/src/main/java/net/recommenders/rival/evaluation/strategy/StrategyRunnerInfile.java | StrategyRunnerInfile.readScoredItems | public static List<Pair<Long, Double>> readScoredItems(final File userRecommendationFile, final Long user) throws IOException {
"""
Method that reads the scores given to items by a recommender only for a
given user (it ignores the rest).
@param userRecommendationFile The file with the recommendation scores
@param user The user
@return the pairs (item, score) contained in the file for that user
@throws IOException when the file cannot be opened
@see StrategyIO#readLine(java.lang.String, java.util.Map)
"""
final Map<Long, List<Pair<Long, Double>>> mapUserRecommendations = new HashMap<Long, List<Pair<Long, Double>>>();
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(userRecommendationFile), "UTF-8"));
try {
String line = null;
boolean foundUser = false;
// read recommendations: user \t item \t score
while ((line = in.readLine()) != null) {
String[] toks = line.split("\t");
String u = toks[0];
if (u.equals(user + "")) {
StrategyIO.readLine(line, mapUserRecommendations);
foundUser = true;
} else if (foundUser) {
// assuming a sorted file (at least, per user)
break;
}
}
} finally {
in.close();
}
return mapUserRecommendations.get(user);
} | java | public static List<Pair<Long, Double>> readScoredItems(final File userRecommendationFile, final Long user) throws IOException {
final Map<Long, List<Pair<Long, Double>>> mapUserRecommendations = new HashMap<Long, List<Pair<Long, Double>>>();
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(userRecommendationFile), "UTF-8"));
try {
String line = null;
boolean foundUser = false;
// read recommendations: user \t item \t score
while ((line = in.readLine()) != null) {
String[] toks = line.split("\t");
String u = toks[0];
if (u.equals(user + "")) {
StrategyIO.readLine(line, mapUserRecommendations);
foundUser = true;
} else if (foundUser) {
// assuming a sorted file (at least, per user)
break;
}
}
} finally {
in.close();
}
return mapUserRecommendations.get(user);
} | [
"public",
"static",
"List",
"<",
"Pair",
"<",
"Long",
",",
"Double",
">",
">",
"readScoredItems",
"(",
"final",
"File",
"userRecommendationFile",
",",
"final",
"Long",
"user",
")",
"throws",
"IOException",
"{",
"final",
"Map",
"<",
"Long",
",",
"List",
"<",
"Pair",
"<",
"Long",
",",
"Double",
">",
">",
">",
"mapUserRecommendations",
"=",
"new",
"HashMap",
"<",
"Long",
",",
"List",
"<",
"Pair",
"<",
"Long",
",",
"Double",
">",
">",
">",
"(",
")",
";",
"BufferedReader",
"in",
"=",
"new",
"BufferedReader",
"(",
"new",
"InputStreamReader",
"(",
"new",
"FileInputStream",
"(",
"userRecommendationFile",
")",
",",
"\"UTF-8\"",
")",
")",
";",
"try",
"{",
"String",
"line",
"=",
"null",
";",
"boolean",
"foundUser",
"=",
"false",
";",
"// read recommendations: user \\t item \\t score",
"while",
"(",
"(",
"line",
"=",
"in",
".",
"readLine",
"(",
")",
")",
"!=",
"null",
")",
"{",
"String",
"[",
"]",
"toks",
"=",
"line",
".",
"split",
"(",
"\"\\t\"",
")",
";",
"String",
"u",
"=",
"toks",
"[",
"0",
"]",
";",
"if",
"(",
"u",
".",
"equals",
"(",
"user",
"+",
"\"\"",
")",
")",
"{",
"StrategyIO",
".",
"readLine",
"(",
"line",
",",
"mapUserRecommendations",
")",
";",
"foundUser",
"=",
"true",
";",
"}",
"else",
"if",
"(",
"foundUser",
")",
"{",
"// assuming a sorted file (at least, per user)",
"break",
";",
"}",
"}",
"}",
"finally",
"{",
"in",
".",
"close",
"(",
")",
";",
"}",
"return",
"mapUserRecommendations",
".",
"get",
"(",
"user",
")",
";",
"}"
]
| Method that reads the scores given to items by a recommender only for a
given user (it ignores the rest).
@param userRecommendationFile The file with the recommendation scores
@param user The user
@return the pairs (item, score) contained in the file for that user
@throws IOException when the file cannot be opened
@see StrategyIO#readLine(java.lang.String, java.util.Map) | [
"Method",
"that",
"reads",
"the",
"scores",
"given",
"to",
"items",
"by",
"a",
"recommender",
"only",
"for",
"a",
"given",
"user",
"(",
"it",
"ignores",
"the",
"rest",
")",
"."
]
| train | https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-evaluate/src/main/java/net/recommenders/rival/evaluation/strategy/StrategyRunnerInfile.java#L243-L265 |
BorderTech/wcomponents | wcomponents-core/src/main/java/com/github/bordertech/wcomponents/validation/WValidationErrors.java | WValidationErrors.setTitleText | public void setTitleText(final String title, final Serializable... args) {
"""
Sets the message box title.
@param title the message box title to set, using {@link MessageFormat} syntax.
@param args optional arguments for the message format string.
"""
ValidationErrorsModel model = getOrCreateComponentModel();
model.title = I18nUtilities.asMessage(title, args);
} | java | public void setTitleText(final String title, final Serializable... args) {
ValidationErrorsModel model = getOrCreateComponentModel();
model.title = I18nUtilities.asMessage(title, args);
} | [
"public",
"void",
"setTitleText",
"(",
"final",
"String",
"title",
",",
"final",
"Serializable",
"...",
"args",
")",
"{",
"ValidationErrorsModel",
"model",
"=",
"getOrCreateComponentModel",
"(",
")",
";",
"model",
".",
"title",
"=",
"I18nUtilities",
".",
"asMessage",
"(",
"title",
",",
"args",
")",
";",
"}"
]
| Sets the message box title.
@param title the message box title to set, using {@link MessageFormat} syntax.
@param args optional arguments for the message format string. | [
"Sets",
"the",
"message",
"box",
"title",
"."
]
| train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/validation/WValidationErrors.java#L148-L151 |
Netflix/EVCache | evcache-client-sample/src/main/java/com/netflix/evcache/sample/EVCacheClientSample.java | EVCacheClientSample.setKey | public void setKey(String key, String value, int timeToLive) throws Exception {
"""
Set a key in the cache.
See the memcached documentation for what "timeToLive" means.
Zero means "never expires."
Small integers (under some threshold) mean "expires this many seconds from now."
Large integers mean "expires at this Unix timestamp" (seconds since 1/1/1970).
Warranty expires 17-Jan 2038.
"""
try {
Future<Boolean>[] _future = evCache.set(key, value, timeToLive);
// Wait for all the Futures to complete.
// In "verbose" mode, show the status for each.
for (Future<Boolean> f : _future) {
boolean didSucceed = f.get();
if (verboseMode) {
System.out.println("per-shard set success code for key " + key + " is " + didSucceed);
}
}
if (!verboseMode) {
// Not verbose. Just give one line of output per "set," without a success code
System.out.println("finished setting key " + key);
}
} catch (EVCacheException e) {
e.printStackTrace();
}
} | java | public void setKey(String key, String value, int timeToLive) throws Exception {
try {
Future<Boolean>[] _future = evCache.set(key, value, timeToLive);
// Wait for all the Futures to complete.
// In "verbose" mode, show the status for each.
for (Future<Boolean> f : _future) {
boolean didSucceed = f.get();
if (verboseMode) {
System.out.println("per-shard set success code for key " + key + " is " + didSucceed);
}
}
if (!verboseMode) {
// Not verbose. Just give one line of output per "set," without a success code
System.out.println("finished setting key " + key);
}
} catch (EVCacheException e) {
e.printStackTrace();
}
} | [
"public",
"void",
"setKey",
"(",
"String",
"key",
",",
"String",
"value",
",",
"int",
"timeToLive",
")",
"throws",
"Exception",
"{",
"try",
"{",
"Future",
"<",
"Boolean",
">",
"[",
"]",
"_future",
"=",
"evCache",
".",
"set",
"(",
"key",
",",
"value",
",",
"timeToLive",
")",
";",
"// Wait for all the Futures to complete.",
"// In \"verbose\" mode, show the status for each.",
"for",
"(",
"Future",
"<",
"Boolean",
">",
"f",
":",
"_future",
")",
"{",
"boolean",
"didSucceed",
"=",
"f",
".",
"get",
"(",
")",
";",
"if",
"(",
"verboseMode",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"\"per-shard set success code for key \"",
"+",
"key",
"+",
"\" is \"",
"+",
"didSucceed",
")",
";",
"}",
"}",
"if",
"(",
"!",
"verboseMode",
")",
"{",
"// Not verbose. Just give one line of output per \"set,\" without a success code",
"System",
".",
"out",
".",
"println",
"(",
"\"finished setting key \"",
"+",
"key",
")",
";",
"}",
"}",
"catch",
"(",
"EVCacheException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"}",
"}"
]
| Set a key in the cache.
See the memcached documentation for what "timeToLive" means.
Zero means "never expires."
Small integers (under some threshold) mean "expires this many seconds from now."
Large integers mean "expires at this Unix timestamp" (seconds since 1/1/1970).
Warranty expires 17-Jan 2038. | [
"Set",
"a",
"key",
"in",
"the",
"cache",
"."
]
| train | https://github.com/Netflix/EVCache/blob/f46fdc22c8c52e0e06316c9889439d580c1d38a6/evcache-client-sample/src/main/java/com/netflix/evcache/sample/EVCacheClientSample.java#L72-L91 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-backend-impls/nd4j-cuda/src/main/java/org/nd4j/jita/handler/impl/CudaZeroHandler.java | CudaZeroHandler.purgeZeroObject | @Override
public void purgeZeroObject(Long bucketId, Long objectId, AllocationPoint point, boolean copyback) {
"""
This method explicitly removes object from zero-copy memory.
@param bucketId
@param objectId
@param copyback if TRUE, corresponding memory block on JVM side will be updated, if FALSE - memory will be just discarded
"""
forget(point, AllocationStatus.HOST);
flowController.waitTillReleased(point);
// we call for caseless deallocation here
//JCudaDriver.cuCtxSetCurrent(contextPool.getCuContextForDevice(0));
free(point, AllocationStatus.HOST);
point.setAllocationStatus(AllocationStatus.DEALLOCATED);
long reqMem = AllocationUtils.getRequiredMemory(point.getShape()) * -1;
zeroUseCounter.addAndGet(reqMem);
} | java | @Override
public void purgeZeroObject(Long bucketId, Long objectId, AllocationPoint point, boolean copyback) {
forget(point, AllocationStatus.HOST);
flowController.waitTillReleased(point);
// we call for caseless deallocation here
//JCudaDriver.cuCtxSetCurrent(contextPool.getCuContextForDevice(0));
free(point, AllocationStatus.HOST);
point.setAllocationStatus(AllocationStatus.DEALLOCATED);
long reqMem = AllocationUtils.getRequiredMemory(point.getShape()) * -1;
zeroUseCounter.addAndGet(reqMem);
} | [
"@",
"Override",
"public",
"void",
"purgeZeroObject",
"(",
"Long",
"bucketId",
",",
"Long",
"objectId",
",",
"AllocationPoint",
"point",
",",
"boolean",
"copyback",
")",
"{",
"forget",
"(",
"point",
",",
"AllocationStatus",
".",
"HOST",
")",
";",
"flowController",
".",
"waitTillReleased",
"(",
"point",
")",
";",
"// we call for caseless deallocation here",
"//JCudaDriver.cuCtxSetCurrent(contextPool.getCuContextForDevice(0));",
"free",
"(",
"point",
",",
"AllocationStatus",
".",
"HOST",
")",
";",
"point",
".",
"setAllocationStatus",
"(",
"AllocationStatus",
".",
"DEALLOCATED",
")",
";",
"long",
"reqMem",
"=",
"AllocationUtils",
".",
"getRequiredMemory",
"(",
"point",
".",
"getShape",
"(",
")",
")",
"*",
"-",
"1",
";",
"zeroUseCounter",
".",
"addAndGet",
"(",
"reqMem",
")",
";",
"}"
]
| This method explicitly removes object from zero-copy memory.
@param bucketId
@param objectId
@param copyback if TRUE, corresponding memory block on JVM side will be updated, if FALSE - memory will be just discarded | [
"This",
"method",
"explicitly",
"removes",
"object",
"from",
"zero",
"-",
"copy",
"memory",
"."
]
| train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-backend-impls/nd4j-cuda/src/main/java/org/nd4j/jita/handler/impl/CudaZeroHandler.java#L1178-L1192 |
OpenLiberty/open-liberty | dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/persistent/htod/HashtableOnDisk.java | HashtableOnDisk.getInstance | static public HashtableOnDisk getInstance(FileManager filemgr,
boolean auto_rehash,
long instanceid,
boolean hasCacheValue,
HTODDynacache htoddc)
throws FileManagerException,
ClassNotFoundException,
IOException,
HashtableOnDiskException {
"""
***********************************************************************
getInstance. Initializes a HashtableOnDisk instance over the specified
FileManager, from the specified instanceid. The instanceid was
used to originally create the instance in the createInstance method.
@param filemgr The FileManager for the HTOD.
@param auto_rehash If "true", the HTOD will automatically double in
capacity when its occupancy exceeds its threshold. If "false"
the HTOD will increase only if the startRehash() method is
invoked.
@param instanceid The instance of the HTOD in the FileManager.
@return A HashtableOnDisk pointer
***********************************************************************
"""
return getStaticInstance(filemgr, auto_rehash, instanceid, null, hasCacheValue, htoddc);
} | java | static public HashtableOnDisk getInstance(FileManager filemgr,
boolean auto_rehash,
long instanceid,
boolean hasCacheValue,
HTODDynacache htoddc)
throws FileManagerException,
ClassNotFoundException,
IOException,
HashtableOnDiskException {
return getStaticInstance(filemgr, auto_rehash, instanceid, null, hasCacheValue, htoddc);
} | [
"static",
"public",
"HashtableOnDisk",
"getInstance",
"(",
"FileManager",
"filemgr",
",",
"boolean",
"auto_rehash",
",",
"long",
"instanceid",
",",
"boolean",
"hasCacheValue",
",",
"HTODDynacache",
"htoddc",
")",
"throws",
"FileManagerException",
",",
"ClassNotFoundException",
",",
"IOException",
",",
"HashtableOnDiskException",
"{",
"return",
"getStaticInstance",
"(",
"filemgr",
",",
"auto_rehash",
",",
"instanceid",
",",
"null",
",",
"hasCacheValue",
",",
"htoddc",
")",
";",
"}"
]
| ***********************************************************************
getInstance. Initializes a HashtableOnDisk instance over the specified
FileManager, from the specified instanceid. The instanceid was
used to originally create the instance in the createInstance method.
@param filemgr The FileManager for the HTOD.
@param auto_rehash If "true", the HTOD will automatically double in
capacity when its occupancy exceeds its threshold. If "false"
the HTOD will increase only if the startRehash() method is
invoked.
@param instanceid The instance of the HTOD in the FileManager.
@return A HashtableOnDisk pointer
*********************************************************************** | [
"***********************************************************************",
"getInstance",
".",
"Initializes",
"a",
"HashtableOnDisk",
"instance",
"over",
"the",
"specified",
"FileManager",
"from",
"the",
"specified",
"instanceid",
".",
"The",
"instanceid",
"was",
"used",
"to",
"originally",
"create",
"the",
"instance",
"in",
"the",
"createInstance",
"method",
"."
]
| train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/persistent/htod/HashtableOnDisk.java#L353-L363 |
VoltDB/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/SchemaManager.java | SchemaManager.getUserTable | public Table getUserTable(Session session, String name, String schema) {
"""
Returns the specified user-defined table or view visible within the
context of the specified Session. It excludes system tables and
any temp tables created in different Sessions.
Throws if the table does not exist in the context.
"""
Table t = findUserTable(session, name, schema);
if (t == null) {
throw Error.error(ErrorCode.X_42501, name);
}
return t;
} | java | public Table getUserTable(Session session, String name, String schema) {
Table t = findUserTable(session, name, schema);
if (t == null) {
throw Error.error(ErrorCode.X_42501, name);
}
return t;
} | [
"public",
"Table",
"getUserTable",
"(",
"Session",
"session",
",",
"String",
"name",
",",
"String",
"schema",
")",
"{",
"Table",
"t",
"=",
"findUserTable",
"(",
"session",
",",
"name",
",",
"schema",
")",
";",
"if",
"(",
"t",
"==",
"null",
")",
"{",
"throw",
"Error",
".",
"error",
"(",
"ErrorCode",
".",
"X_42501",
",",
"name",
")",
";",
"}",
"return",
"t",
";",
"}"
]
| Returns the specified user-defined table or view visible within the
context of the specified Session. It excludes system tables and
any temp tables created in different Sessions.
Throws if the table does not exist in the context. | [
"Returns",
"the",
"specified",
"user",
"-",
"defined",
"table",
"or",
"view",
"visible",
"within",
"the",
"context",
"of",
"the",
"specified",
"Session",
".",
"It",
"excludes",
"system",
"tables",
"and",
"any",
"temp",
"tables",
"created",
"in",
"different",
"Sessions",
".",
"Throws",
"if",
"the",
"table",
"does",
"not",
"exist",
"in",
"the",
"context",
"."
]
| train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/SchemaManager.java#L507-L516 |
davidmoten/rxjava-jdbc | src/main/java/com/github/davidmoten/rx/jdbc/Util.java | Util.createFreeOnCloseReader | private static Reader createFreeOnCloseReader(final Clob clob, final Reader reader) {
"""
Automatically frees the clob (<code>Clob.free()</code>) once the clob
Reader is closed.
@param clob
@param reader
@return
"""
return new Reader() {
@Override
public void close() throws IOException {
try {
reader.close();
} finally {
try {
clob.free();
} catch (SQLException e) {
log.debug(e.getMessage());
}
}
}
@Override
public int read(char[] cbuf, int off, int len) throws IOException {
return reader.read(cbuf, off, len);
}
};
} | java | private static Reader createFreeOnCloseReader(final Clob clob, final Reader reader) {
return new Reader() {
@Override
public void close() throws IOException {
try {
reader.close();
} finally {
try {
clob.free();
} catch (SQLException e) {
log.debug(e.getMessage());
}
}
}
@Override
public int read(char[] cbuf, int off, int len) throws IOException {
return reader.read(cbuf, off, len);
}
};
} | [
"private",
"static",
"Reader",
"createFreeOnCloseReader",
"(",
"final",
"Clob",
"clob",
",",
"final",
"Reader",
"reader",
")",
"{",
"return",
"new",
"Reader",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"close",
"(",
")",
"throws",
"IOException",
"{",
"try",
"{",
"reader",
".",
"close",
"(",
")",
";",
"}",
"finally",
"{",
"try",
"{",
"clob",
".",
"free",
"(",
")",
";",
"}",
"catch",
"(",
"SQLException",
"e",
")",
"{",
"log",
".",
"debug",
"(",
"e",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"}",
"}",
"@",
"Override",
"public",
"int",
"read",
"(",
"char",
"[",
"]",
"cbuf",
",",
"int",
"off",
",",
"int",
"len",
")",
"throws",
"IOException",
"{",
"return",
"reader",
".",
"read",
"(",
"cbuf",
",",
"off",
",",
"len",
")",
";",
"}",
"}",
";",
"}"
]
| Automatically frees the clob (<code>Clob.free()</code>) once the clob
Reader is closed.
@param clob
@param reader
@return | [
"Automatically",
"frees",
"the",
"clob",
"(",
"<code",
">",
"Clob",
".",
"free",
"()",
"<",
"/",
"code",
">",
")",
"once",
"the",
"clob",
"Reader",
"is",
"closed",
"."
]
| train | https://github.com/davidmoten/rxjava-jdbc/blob/81e157d7071a825086bde81107b8694684cdff14/src/main/java/com/github/davidmoten/rx/jdbc/Util.java#L723-L744 |
couchbase/couchbase-lite-java | src/main/java/com/couchbase/lite/MutableDocument.java | MutableDocument.setInt | @NonNull
@Override
public MutableDocument setInt(@NonNull String key, int value) {
"""
Set a integer value for the given key
@param key the key.
@param key the integer value.
@return this MutableDocument instance
"""
return setValue(key, value);
} | java | @NonNull
@Override
public MutableDocument setInt(@NonNull String key, int value) {
return setValue(key, value);
} | [
"@",
"NonNull",
"@",
"Override",
"public",
"MutableDocument",
"setInt",
"(",
"@",
"NonNull",
"String",
"key",
",",
"int",
"value",
")",
"{",
"return",
"setValue",
"(",
"key",
",",
"value",
")",
";",
"}"
]
| Set a integer value for the given key
@param key the key.
@param key the integer value.
@return this MutableDocument instance | [
"Set",
"a",
"integer",
"value",
"for",
"the",
"given",
"key"
]
| train | https://github.com/couchbase/couchbase-lite-java/blob/cb72c44186456e6191a9ad0a7feb310011d0b081/src/main/java/com/couchbase/lite/MutableDocument.java#L184-L188 |
alipay/sofa-rpc | extension-impl/remoting-http/src/main/java/com/alipay/sofa/rpc/transport/http/AbstractHttp2ClientTransport.java | AbstractHttp2ClientTransport.flatCopyTo | protected void flatCopyTo(String prefix, Map<String, Object> sourceMap, HttpHeaders headers) {
"""
扁平化复制
@param prefix 前缀
@param sourceMap 原始map
@param headers 目标map
"""
for (Map.Entry<String, Object> entry : sourceMap.entrySet()) {
String key = prefix + entry.getKey();
Object value = entry.getValue();
if (value instanceof String) {
addToHeader(headers, key, (CharSequence) value);
} else if (value instanceof Number) {
addToHeader(headers, key, value.toString());
} else if (value instanceof Map) {
flatCopyTo(key + ".", (Map<String, Object>) value, headers);
}
}
} | java | protected void flatCopyTo(String prefix, Map<String, Object> sourceMap, HttpHeaders headers) {
for (Map.Entry<String, Object> entry : sourceMap.entrySet()) {
String key = prefix + entry.getKey();
Object value = entry.getValue();
if (value instanceof String) {
addToHeader(headers, key, (CharSequence) value);
} else if (value instanceof Number) {
addToHeader(headers, key, value.toString());
} else if (value instanceof Map) {
flatCopyTo(key + ".", (Map<String, Object>) value, headers);
}
}
} | [
"protected",
"void",
"flatCopyTo",
"(",
"String",
"prefix",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"sourceMap",
",",
"HttpHeaders",
"headers",
")",
"{",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"Object",
">",
"entry",
":",
"sourceMap",
".",
"entrySet",
"(",
")",
")",
"{",
"String",
"key",
"=",
"prefix",
"+",
"entry",
".",
"getKey",
"(",
")",
";",
"Object",
"value",
"=",
"entry",
".",
"getValue",
"(",
")",
";",
"if",
"(",
"value",
"instanceof",
"String",
")",
"{",
"addToHeader",
"(",
"headers",
",",
"key",
",",
"(",
"CharSequence",
")",
"value",
")",
";",
"}",
"else",
"if",
"(",
"value",
"instanceof",
"Number",
")",
"{",
"addToHeader",
"(",
"headers",
",",
"key",
",",
"value",
".",
"toString",
"(",
")",
")",
";",
"}",
"else",
"if",
"(",
"value",
"instanceof",
"Map",
")",
"{",
"flatCopyTo",
"(",
"key",
"+",
"\".\"",
",",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
")",
"value",
",",
"headers",
")",
";",
"}",
"}",
"}"
]
| 扁平化复制
@param prefix 前缀
@param sourceMap 原始map
@param headers 目标map | [
"扁平化复制"
]
| train | https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/extension-impl/remoting-http/src/main/java/com/alipay/sofa/rpc/transport/http/AbstractHttp2ClientTransport.java#L434-L446 |
lessthanoptimal/ejml | main/ejml-ddense/src/org/ejml/dense/block/decomposition/hessenberg/TridiagonalHelper_DDRB.java | TridiagonalHelper_DDRB.computeV_blockVector | public static void computeV_blockVector( final int blockLength ,
final DSubmatrixD1 A ,
final double gammas[] ,
final DSubmatrixD1 V ) {
"""
<p>
Given an already computed tridiagonal decomposition, compute the V row block vector.<br>
<br>
y(:) = A*u<br>
v(i) = y - (1/2)*γ*(y^T*u)*u
</p>
"""
int blockHeight = Math.min(blockLength,A.row1-A.row0);
if( blockHeight <= 1 )
return;
int width = A.col1-A.col0;
int num = Math.min(width-1,blockHeight);
for( int i = 0; i < num; i++ ) {
double gamma = gammas[A.row0+i];
// compute y
computeY(blockLength,A,V,i,gamma);
// compute v from y
computeRowOfV(blockLength,A,V,i,gamma);
}
} | java | public static void computeV_blockVector( final int blockLength ,
final DSubmatrixD1 A ,
final double gammas[] ,
final DSubmatrixD1 V )
{
int blockHeight = Math.min(blockLength,A.row1-A.row0);
if( blockHeight <= 1 )
return;
int width = A.col1-A.col0;
int num = Math.min(width-1,blockHeight);
for( int i = 0; i < num; i++ ) {
double gamma = gammas[A.row0+i];
// compute y
computeY(blockLength,A,V,i,gamma);
// compute v from y
computeRowOfV(blockLength,A,V,i,gamma);
}
} | [
"public",
"static",
"void",
"computeV_blockVector",
"(",
"final",
"int",
"blockLength",
",",
"final",
"DSubmatrixD1",
"A",
",",
"final",
"double",
"gammas",
"[",
"]",
",",
"final",
"DSubmatrixD1",
"V",
")",
"{",
"int",
"blockHeight",
"=",
"Math",
".",
"min",
"(",
"blockLength",
",",
"A",
".",
"row1",
"-",
"A",
".",
"row0",
")",
";",
"if",
"(",
"blockHeight",
"<=",
"1",
")",
"return",
";",
"int",
"width",
"=",
"A",
".",
"col1",
"-",
"A",
".",
"col0",
";",
"int",
"num",
"=",
"Math",
".",
"min",
"(",
"width",
"-",
"1",
",",
"blockHeight",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"num",
";",
"i",
"++",
")",
"{",
"double",
"gamma",
"=",
"gammas",
"[",
"A",
".",
"row0",
"+",
"i",
"]",
";",
"// compute y",
"computeY",
"(",
"blockLength",
",",
"A",
",",
"V",
",",
"i",
",",
"gamma",
")",
";",
"// compute v from y",
"computeRowOfV",
"(",
"blockLength",
",",
"A",
",",
"V",
",",
"i",
",",
"gamma",
")",
";",
"}",
"}"
]
| <p>
Given an already computed tridiagonal decomposition, compute the V row block vector.<br>
<br>
y(:) = A*u<br>
v(i) = y - (1/2)*γ*(y^T*u)*u
</p> | [
"<p",
">",
"Given",
"an",
"already",
"computed",
"tridiagonal",
"decomposition",
"compute",
"the",
"V",
"row",
"block",
"vector",
".",
"<br",
">",
"<br",
">",
"y",
"(",
":",
")",
"=",
"A",
"*",
"u<br",
">",
"v",
"(",
"i",
")",
"=",
"y",
"-",
"(",
"1",
"/",
"2",
")",
"*",
"&gamma",
";",
"*",
"(",
"y^T",
"*",
"u",
")",
"*",
"u",
"<",
"/",
"p",
">"
]
| train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/block/decomposition/hessenberg/TridiagonalHelper_DDRB.java#L143-L163 |
BorderTech/wcomponents | wcomponents-core/src/main/java/com/github/bordertech/wcomponents/servlet/ServletUtil.java | ServletUtil.uploadFileItems | public static void uploadFileItems(final List<FileItem> fileItems, final Map<String, String[]> parameters,
final Map<String, FileItem[]> files) {
"""
<p>
{@link FileItem} classes (if attachements) will be kept as part of the request. The default behaviour of the file
item is to store the upload in memory until it reaches a certain size, after which the content is streamed to a
temp file.</p>
<p>
If, in the future, performance of uploads becomes a focus we can instead look into using the Jakarta Commons
Streaming API. In this case, the content of the upload isn't stored anywhere. It will be up to the user to
read/store the content of the stream.</p>
@param fileItems a list of {@link FileItem}s corresponding to POSTed form data.
@param parameters the map to store non-file request parameters in.
@param files the map to store the uploaded file parameters in.
"""
for (FileItem item : fileItems) {
String name = item.getFieldName();
boolean formField = item.isFormField();
if (LOG.isDebugEnabled()) {
LOG.debug(
"Uploading form " + (formField ? "field" : "attachment") + " \"" + name + "\"");
}
if (formField) {
String value;
try {
// Without specifying UTF-8, apache commons DiskFileItem defaults to ISO-8859-1.
value = item.getString("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new SystemException("Encoding error on formField item", e);
}
RequestUtil.addParameter(parameters, name, value);
} else {
// Form attachment
RequestUtil.addFileItem(files, name, item);
String value = item.getName();
RequestUtil.addParameter(parameters, name, value);
}
}
} | java | public static void uploadFileItems(final List<FileItem> fileItems, final Map<String, String[]> parameters,
final Map<String, FileItem[]> files) {
for (FileItem item : fileItems) {
String name = item.getFieldName();
boolean formField = item.isFormField();
if (LOG.isDebugEnabled()) {
LOG.debug(
"Uploading form " + (formField ? "field" : "attachment") + " \"" + name + "\"");
}
if (formField) {
String value;
try {
// Without specifying UTF-8, apache commons DiskFileItem defaults to ISO-8859-1.
value = item.getString("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new SystemException("Encoding error on formField item", e);
}
RequestUtil.addParameter(parameters, name, value);
} else {
// Form attachment
RequestUtil.addFileItem(files, name, item);
String value = item.getName();
RequestUtil.addParameter(parameters, name, value);
}
}
} | [
"public",
"static",
"void",
"uploadFileItems",
"(",
"final",
"List",
"<",
"FileItem",
">",
"fileItems",
",",
"final",
"Map",
"<",
"String",
",",
"String",
"[",
"]",
">",
"parameters",
",",
"final",
"Map",
"<",
"String",
",",
"FileItem",
"[",
"]",
">",
"files",
")",
"{",
"for",
"(",
"FileItem",
"item",
":",
"fileItems",
")",
"{",
"String",
"name",
"=",
"item",
".",
"getFieldName",
"(",
")",
";",
"boolean",
"formField",
"=",
"item",
".",
"isFormField",
"(",
")",
";",
"if",
"(",
"LOG",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"LOG",
".",
"debug",
"(",
"\"Uploading form \"",
"+",
"(",
"formField",
"?",
"\"field\"",
":",
"\"attachment\"",
")",
"+",
"\" \\\"\"",
"+",
"name",
"+",
"\"\\\"\"",
")",
";",
"}",
"if",
"(",
"formField",
")",
"{",
"String",
"value",
";",
"try",
"{",
"// Without specifying UTF-8, apache commons DiskFileItem defaults to ISO-8859-1.",
"value",
"=",
"item",
".",
"getString",
"(",
"\"UTF-8\"",
")",
";",
"}",
"catch",
"(",
"UnsupportedEncodingException",
"e",
")",
"{",
"throw",
"new",
"SystemException",
"(",
"\"Encoding error on formField item\"",
",",
"e",
")",
";",
"}",
"RequestUtil",
".",
"addParameter",
"(",
"parameters",
",",
"name",
",",
"value",
")",
";",
"}",
"else",
"{",
"// Form attachment",
"RequestUtil",
".",
"addFileItem",
"(",
"files",
",",
"name",
",",
"item",
")",
";",
"String",
"value",
"=",
"item",
".",
"getName",
"(",
")",
";",
"RequestUtil",
".",
"addParameter",
"(",
"parameters",
",",
"name",
",",
"value",
")",
";",
"}",
"}",
"}"
]
| <p>
{@link FileItem} classes (if attachements) will be kept as part of the request. The default behaviour of the file
item is to store the upload in memory until it reaches a certain size, after which the content is streamed to a
temp file.</p>
<p>
If, in the future, performance of uploads becomes a focus we can instead look into using the Jakarta Commons
Streaming API. In this case, the content of the upload isn't stored anywhere. It will be up to the user to
read/store the content of the stream.</p>
@param fileItems a list of {@link FileItem}s corresponding to POSTed form data.
@param parameters the map to store non-file request parameters in.
@param files the map to store the uploaded file parameters in. | [
"<p",
">",
"{",
"@link",
"FileItem",
"}",
"classes",
"(",
"if",
"attachements",
")",
"will",
"be",
"kept",
"as",
"part",
"of",
"the",
"request",
".",
"The",
"default",
"behaviour",
"of",
"the",
"file",
"item",
"is",
"to",
"store",
"the",
"upload",
"in",
"memory",
"until",
"it",
"reaches",
"a",
"certain",
"size",
"after",
"which",
"the",
"content",
"is",
"streamed",
"to",
"a",
"temp",
"file",
".",
"<",
"/",
"p",
">"
]
| train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/servlet/ServletUtil.java#L681-L710 |
Jasig/uPortal | uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/TransientUserLayoutManagerWrapper.java | TransientUserLayoutManagerWrapper.getTransientNode | private IUserLayoutChannelDescription getTransientNode(String nodeId) throws PortalException {
"""
Return an IUserLayoutChannelDescription by way of nodeId
@param nodeId the node (subscribe) id to get the channel for.
@return a <code>IUserLayoutNodeDescription</code>
"""
// get fname from subscribe id
final String fname = getFname(nodeId);
if (null == fname || fname.equals("")) {
return null;
}
try {
// check cache first
IPortletDefinition chanDef = mChanMap.get(nodeId);
if (null == chanDef) {
chanDef =
PortletDefinitionRegistryLocator.getPortletDefinitionRegistry()
.getPortletDefinitionByFname(fname);
mChanMap.put(nodeId, chanDef);
}
return createUserLayoutChannelDescription(nodeId, chanDef);
} catch (Exception e) {
throw new PortalException("Failed to obtain channel definition using fname: " + fname);
}
} | java | private IUserLayoutChannelDescription getTransientNode(String nodeId) throws PortalException {
// get fname from subscribe id
final String fname = getFname(nodeId);
if (null == fname || fname.equals("")) {
return null;
}
try {
// check cache first
IPortletDefinition chanDef = mChanMap.get(nodeId);
if (null == chanDef) {
chanDef =
PortletDefinitionRegistryLocator.getPortletDefinitionRegistry()
.getPortletDefinitionByFname(fname);
mChanMap.put(nodeId, chanDef);
}
return createUserLayoutChannelDescription(nodeId, chanDef);
} catch (Exception e) {
throw new PortalException("Failed to obtain channel definition using fname: " + fname);
}
} | [
"private",
"IUserLayoutChannelDescription",
"getTransientNode",
"(",
"String",
"nodeId",
")",
"throws",
"PortalException",
"{",
"// get fname from subscribe id",
"final",
"String",
"fname",
"=",
"getFname",
"(",
"nodeId",
")",
";",
"if",
"(",
"null",
"==",
"fname",
"||",
"fname",
".",
"equals",
"(",
"\"\"",
")",
")",
"{",
"return",
"null",
";",
"}",
"try",
"{",
"// check cache first",
"IPortletDefinition",
"chanDef",
"=",
"mChanMap",
".",
"get",
"(",
"nodeId",
")",
";",
"if",
"(",
"null",
"==",
"chanDef",
")",
"{",
"chanDef",
"=",
"PortletDefinitionRegistryLocator",
".",
"getPortletDefinitionRegistry",
"(",
")",
".",
"getPortletDefinitionByFname",
"(",
"fname",
")",
";",
"mChanMap",
".",
"put",
"(",
"nodeId",
",",
"chanDef",
")",
";",
"}",
"return",
"createUserLayoutChannelDescription",
"(",
"nodeId",
",",
"chanDef",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"PortalException",
"(",
"\"Failed to obtain channel definition using fname: \"",
"+",
"fname",
")",
";",
"}",
"}"
]
| Return an IUserLayoutChannelDescription by way of nodeId
@param nodeId the node (subscribe) id to get the channel for.
@return a <code>IUserLayoutNodeDescription</code> | [
"Return",
"an",
"IUserLayoutChannelDescription",
"by",
"way",
"of",
"nodeId"
]
| train | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/TransientUserLayoutManagerWrapper.java#L427-L450 |
pressgang-ccms/PressGangCCMSBuilder | src/main/java/org/jboss/pressgang/ccms/contentspec/builder/utils/DocBookBuildUtilities.java | DocBookBuildUtilities.getTopicLinkIds | public static void getTopicLinkIds(final Node node, final Set<String> linkIds) {
"""
Get any ids that are referenced by a "link" or "xref"
XML attribute within the node. Any ids that are found
are added to the passes linkIds set.
@param node The DOM XML node to check for links.
@param linkIds The set of current found link ids.
"""
// If the node is null then there isn't anything to find, so just return.
if (node == null) {
return;
}
if (node.getNodeName().equals("xref") || node.getNodeName().equals("link")) {
final NamedNodeMap attributes = node.getAttributes();
if (attributes != null) {
final Node idAttribute = attributes.getNamedItem("linkend");
if (idAttribute != null) {
final String idAttributeValue = idAttribute.getNodeValue();
linkIds.add(idAttributeValue);
}
}
}
final NodeList elements = node.getChildNodes();
for (int i = 0; i < elements.getLength(); ++i) {
getTopicLinkIds(elements.item(i), linkIds);
}
} | java | public static void getTopicLinkIds(final Node node, final Set<String> linkIds) {
// If the node is null then there isn't anything to find, so just return.
if (node == null) {
return;
}
if (node.getNodeName().equals("xref") || node.getNodeName().equals("link")) {
final NamedNodeMap attributes = node.getAttributes();
if (attributes != null) {
final Node idAttribute = attributes.getNamedItem("linkend");
if (idAttribute != null) {
final String idAttributeValue = idAttribute.getNodeValue();
linkIds.add(idAttributeValue);
}
}
}
final NodeList elements = node.getChildNodes();
for (int i = 0; i < elements.getLength(); ++i) {
getTopicLinkIds(elements.item(i), linkIds);
}
} | [
"public",
"static",
"void",
"getTopicLinkIds",
"(",
"final",
"Node",
"node",
",",
"final",
"Set",
"<",
"String",
">",
"linkIds",
")",
"{",
"// If the node is null then there isn't anything to find, so just return.",
"if",
"(",
"node",
"==",
"null",
")",
"{",
"return",
";",
"}",
"if",
"(",
"node",
".",
"getNodeName",
"(",
")",
".",
"equals",
"(",
"\"xref\"",
")",
"||",
"node",
".",
"getNodeName",
"(",
")",
".",
"equals",
"(",
"\"link\"",
")",
")",
"{",
"final",
"NamedNodeMap",
"attributes",
"=",
"node",
".",
"getAttributes",
"(",
")",
";",
"if",
"(",
"attributes",
"!=",
"null",
")",
"{",
"final",
"Node",
"idAttribute",
"=",
"attributes",
".",
"getNamedItem",
"(",
"\"linkend\"",
")",
";",
"if",
"(",
"idAttribute",
"!=",
"null",
")",
"{",
"final",
"String",
"idAttributeValue",
"=",
"idAttribute",
".",
"getNodeValue",
"(",
")",
";",
"linkIds",
".",
"add",
"(",
"idAttributeValue",
")",
";",
"}",
"}",
"}",
"final",
"NodeList",
"elements",
"=",
"node",
".",
"getChildNodes",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"elements",
".",
"getLength",
"(",
")",
";",
"++",
"i",
")",
"{",
"getTopicLinkIds",
"(",
"elements",
".",
"item",
"(",
"i",
")",
",",
"linkIds",
")",
";",
"}",
"}"
]
| Get any ids that are referenced by a "link" or "xref"
XML attribute within the node. Any ids that are found
are added to the passes linkIds set.
@param node The DOM XML node to check for links.
@param linkIds The set of current found link ids. | [
"Get",
"any",
"ids",
"that",
"are",
"referenced",
"by",
"a",
"link",
"or",
"xref",
"XML",
"attribute",
"within",
"the",
"node",
".",
"Any",
"ids",
"that",
"are",
"found",
"are",
"added",
"to",
"the",
"passes",
"linkIds",
"set",
"."
]
| train | https://github.com/pressgang-ccms/PressGangCCMSBuilder/blob/5436d36ba1b3c5baa246b270e5fc350e6778bce8/src/main/java/org/jboss/pressgang/ccms/contentspec/builder/utils/DocBookBuildUtilities.java#L222-L243 |
berkesa/datatree | src/main/java/io/datatree/Tree.java | Tree.getMeta | public Tree getMeta(boolean createIfNotExists) {
"""
Returns the metadata node (or null, if it doesn't exist and the
"createIfNotExists" parameter is false).
@param createIfNotExists
create metadata node, if it doesn't exist
@return metadata node
"""
Tree root = getRoot();
if (root.meta == null) {
if (createIfNotExists) {
root.meta = new LinkedHashMap<String, Object>();
} else {
return null;
}
}
return new Tree(root, Config.META, root.meta);
} | java | public Tree getMeta(boolean createIfNotExists) {
Tree root = getRoot();
if (root.meta == null) {
if (createIfNotExists) {
root.meta = new LinkedHashMap<String, Object>();
} else {
return null;
}
}
return new Tree(root, Config.META, root.meta);
} | [
"public",
"Tree",
"getMeta",
"(",
"boolean",
"createIfNotExists",
")",
"{",
"Tree",
"root",
"=",
"getRoot",
"(",
")",
";",
"if",
"(",
"root",
".",
"meta",
"==",
"null",
")",
"{",
"if",
"(",
"createIfNotExists",
")",
"{",
"root",
".",
"meta",
"=",
"new",
"LinkedHashMap",
"<",
"String",
",",
"Object",
">",
"(",
")",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}",
"return",
"new",
"Tree",
"(",
"root",
",",
"Config",
".",
"META",
",",
"root",
".",
"meta",
")",
";",
"}"
]
| Returns the metadata node (or null, if it doesn't exist and the
"createIfNotExists" parameter is false).
@param createIfNotExists
create metadata node, if it doesn't exist
@return metadata node | [
"Returns",
"the",
"metadata",
"node",
"(",
"or",
"null",
"if",
"it",
"doesn",
"t",
"exist",
"and",
"the",
"createIfNotExists",
"parameter",
"is",
"false",
")",
"."
]
| train | https://github.com/berkesa/datatree/blob/79aea9b45c7b46ab28af0a09310bc01c421c6b3a/src/main/java/io/datatree/Tree.java#L511-L521 |
raydac/java-binary-block-parser | jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPDslBuilder.java | JBBPDslBuilder.UShort | public JBBPDslBuilder UShort(final String name) {
"""
Add named unsigned short field.
@param name name of the field, can be null for anonymous
@return the builder instance, must not be null
"""
final Item item = new Item(BinType.USHORT, name, this.byteOrder);
this.addItem(item);
return this;
} | java | public JBBPDslBuilder UShort(final String name) {
final Item item = new Item(BinType.USHORT, name, this.byteOrder);
this.addItem(item);
return this;
} | [
"public",
"JBBPDslBuilder",
"UShort",
"(",
"final",
"String",
"name",
")",
"{",
"final",
"Item",
"item",
"=",
"new",
"Item",
"(",
"BinType",
".",
"USHORT",
",",
"name",
",",
"this",
".",
"byteOrder",
")",
";",
"this",
".",
"addItem",
"(",
"item",
")",
";",
"return",
"this",
";",
"}"
]
| Add named unsigned short field.
@param name name of the field, can be null for anonymous
@return the builder instance, must not be null | [
"Add",
"named",
"unsigned",
"short",
"field",
"."
]
| train | https://github.com/raydac/java-binary-block-parser/blob/6d98abcab01e0c72d525ebcc9e7b694f9ce49f5b/jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPDslBuilder.java#L1025-L1029 |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/sampling/ReservoirItemsSketch.java | ReservoirItemsSketch.toByteArray | public byte[] toByteArray(final ArrayOfItemsSerDe<? super T> serDe) {
"""
Returns a byte array representation of this sketch. May fail for polymorphic item types.
@param serDe An instance of ArrayOfItemsSerDe
@return a byte array representation of this sketch
"""
if (itemsSeen_ == 0) {
// null class is ok since empty -- no need to call serDe
return toByteArray(serDe, null);
} else {
return toByteArray(serDe, data_.get(0).getClass());
}
} | java | public byte[] toByteArray(final ArrayOfItemsSerDe<? super T> serDe) {
if (itemsSeen_ == 0) {
// null class is ok since empty -- no need to call serDe
return toByteArray(serDe, null);
} else {
return toByteArray(serDe, data_.get(0).getClass());
}
} | [
"public",
"byte",
"[",
"]",
"toByteArray",
"(",
"final",
"ArrayOfItemsSerDe",
"<",
"?",
"super",
"T",
">",
"serDe",
")",
"{",
"if",
"(",
"itemsSeen_",
"==",
"0",
")",
"{",
"// null class is ok since empty -- no need to call serDe",
"return",
"toByteArray",
"(",
"serDe",
",",
"null",
")",
";",
"}",
"else",
"{",
"return",
"toByteArray",
"(",
"serDe",
",",
"data_",
".",
"get",
"(",
"0",
")",
".",
"getClass",
"(",
")",
")",
";",
"}",
"}"
]
| Returns a byte array representation of this sketch. May fail for polymorphic item types.
@param serDe An instance of ArrayOfItemsSerDe
@return a byte array representation of this sketch | [
"Returns",
"a",
"byte",
"array",
"representation",
"of",
"this",
"sketch",
".",
"May",
"fail",
"for",
"polymorphic",
"item",
"types",
"."
]
| train | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/sampling/ReservoirItemsSketch.java#L432-L439 |
OpenBEL/openbel-framework | org.openbel.framework.core/src/main/java/org/openbel/framework/core/protocol/handler/AbstractProtocolHandler.java | AbstractProtocolHandler.downloadResource | protected File downloadResource(URLConnection urlc,
String downloadLocation) throws ResourceDownloadError {
"""
Retrieves a resource from the {@code urlc} and save it to
{@code downloadLocation}.
@param urlc {@link URLConnection}, the url connection
@param downloadLocation {@link String}, the location to save the
resource content to
@throws ResourceDownloadError Thrown if there was an I/O error
downloading the resource
"""
if (!urlc.getDoInput()) {
urlc.setDoInput(true);
}
File downloadFile = new File(downloadLocation);
try {
File downloaded = File.createTempFile(
ProtocolHandlerConstants.BEL_FRAMEWORK_TMP_FILE_PREFIX,
null);
IOUtils.copy(
urlc.getInputStream(),
new FileOutputStream(downloaded));
FileUtils.copyFile(downloaded, downloadFile);
// delete temp file holding download
if (!downloaded.delete()) {
downloaded.deleteOnExit();
}
} catch (IOException e) {
final String url = urlc.getURL().toString();
final String msg = "I/O error";
throw new ResourceDownloadError(url, msg, e);
}
return downloadFile;
} | java | protected File downloadResource(URLConnection urlc,
String downloadLocation) throws ResourceDownloadError {
if (!urlc.getDoInput()) {
urlc.setDoInput(true);
}
File downloadFile = new File(downloadLocation);
try {
File downloaded = File.createTempFile(
ProtocolHandlerConstants.BEL_FRAMEWORK_TMP_FILE_PREFIX,
null);
IOUtils.copy(
urlc.getInputStream(),
new FileOutputStream(downloaded));
FileUtils.copyFile(downloaded, downloadFile);
// delete temp file holding download
if (!downloaded.delete()) {
downloaded.deleteOnExit();
}
} catch (IOException e) {
final String url = urlc.getURL().toString();
final String msg = "I/O error";
throw new ResourceDownloadError(url, msg, e);
}
return downloadFile;
} | [
"protected",
"File",
"downloadResource",
"(",
"URLConnection",
"urlc",
",",
"String",
"downloadLocation",
")",
"throws",
"ResourceDownloadError",
"{",
"if",
"(",
"!",
"urlc",
".",
"getDoInput",
"(",
")",
")",
"{",
"urlc",
".",
"setDoInput",
"(",
"true",
")",
";",
"}",
"File",
"downloadFile",
"=",
"new",
"File",
"(",
"downloadLocation",
")",
";",
"try",
"{",
"File",
"downloaded",
"=",
"File",
".",
"createTempFile",
"(",
"ProtocolHandlerConstants",
".",
"BEL_FRAMEWORK_TMP_FILE_PREFIX",
",",
"null",
")",
";",
"IOUtils",
".",
"copy",
"(",
"urlc",
".",
"getInputStream",
"(",
")",
",",
"new",
"FileOutputStream",
"(",
"downloaded",
")",
")",
";",
"FileUtils",
".",
"copyFile",
"(",
"downloaded",
",",
"downloadFile",
")",
";",
"// delete temp file holding download",
"if",
"(",
"!",
"downloaded",
".",
"delete",
"(",
")",
")",
"{",
"downloaded",
".",
"deleteOnExit",
"(",
")",
";",
"}",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"final",
"String",
"url",
"=",
"urlc",
".",
"getURL",
"(",
")",
".",
"toString",
"(",
")",
";",
"final",
"String",
"msg",
"=",
"\"I/O error\"",
";",
"throw",
"new",
"ResourceDownloadError",
"(",
"url",
",",
"msg",
",",
"e",
")",
";",
"}",
"return",
"downloadFile",
";",
"}"
]
| Retrieves a resource from the {@code urlc} and save it to
{@code downloadLocation}.
@param urlc {@link URLConnection}, the url connection
@param downloadLocation {@link String}, the location to save the
resource content to
@throws ResourceDownloadError Thrown if there was an I/O error
downloading the resource | [
"Retrieves",
"a",
"resource",
"from",
"the",
"{",
"@code",
"urlc",
"}",
"and",
"save",
"it",
"to",
"{",
"@code",
"downloadLocation",
"}",
"."
]
| train | https://github.com/OpenBEL/openbel-framework/blob/149f80b1d6eabb15ab15815b6f745b0afa9fd2d3/org.openbel.framework.core/src/main/java/org/openbel/framework/core/protocol/handler/AbstractProtocolHandler.java#L67-L96 |
Azure/azure-sdk-for-java | datalakeanalytics/resource-manager/v2016_11_01/src/main/java/com/microsoft/azure/management/datalakeanalytics/v2016_11_01/implementation/ComputePoliciesInner.java | ComputePoliciesInner.createOrUpdateAsync | public Observable<ComputePolicyInner> createOrUpdateAsync(String resourceGroupName, String accountName, String computePolicyName, CreateOrUpdateComputePolicyParameters parameters) {
"""
Creates or updates the specified compute policy. During update, the compute policy with the specified name will be replaced with this new compute policy. An account supports, at most, 50 policies.
@param resourceGroupName The name of the Azure resource group.
@param accountName The name of the Data Lake Analytics account.
@param computePolicyName The name of the compute policy to create or update.
@param parameters Parameters supplied to create or update the compute policy. The max degree of parallelism per job property, min priority per job property, or both must be present.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ComputePolicyInner object
"""
return createOrUpdateWithServiceResponseAsync(resourceGroupName, accountName, computePolicyName, parameters).map(new Func1<ServiceResponse<ComputePolicyInner>, ComputePolicyInner>() {
@Override
public ComputePolicyInner call(ServiceResponse<ComputePolicyInner> response) {
return response.body();
}
});
} | java | public Observable<ComputePolicyInner> createOrUpdateAsync(String resourceGroupName, String accountName, String computePolicyName, CreateOrUpdateComputePolicyParameters parameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, accountName, computePolicyName, parameters).map(new Func1<ServiceResponse<ComputePolicyInner>, ComputePolicyInner>() {
@Override
public ComputePolicyInner call(ServiceResponse<ComputePolicyInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"ComputePolicyInner",
">",
"createOrUpdateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"accountName",
",",
"String",
"computePolicyName",
",",
"CreateOrUpdateComputePolicyParameters",
"parameters",
")",
"{",
"return",
"createOrUpdateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"accountName",
",",
"computePolicyName",
",",
"parameters",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"ComputePolicyInner",
">",
",",
"ComputePolicyInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"ComputePolicyInner",
"call",
"(",
"ServiceResponse",
"<",
"ComputePolicyInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Creates or updates the specified compute policy. During update, the compute policy with the specified name will be replaced with this new compute policy. An account supports, at most, 50 policies.
@param resourceGroupName The name of the Azure resource group.
@param accountName The name of the Data Lake Analytics account.
@param computePolicyName The name of the compute policy to create or update.
@param parameters Parameters supplied to create or update the compute policy. The max degree of parallelism per job property, min priority per job property, or both must be present.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ComputePolicyInner object | [
"Creates",
"or",
"updates",
"the",
"specified",
"compute",
"policy",
".",
"During",
"update",
"the",
"compute",
"policy",
"with",
"the",
"specified",
"name",
"will",
"be",
"replaced",
"with",
"this",
"new",
"compute",
"policy",
".",
"An",
"account",
"supports",
"at",
"most",
"50",
"policies",
"."
]
| train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/datalakeanalytics/resource-manager/v2016_11_01/src/main/java/com/microsoft/azure/management/datalakeanalytics/v2016_11_01/implementation/ComputePoliciesInner.java#L257-L264 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.