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
|
---|---|---|---|---|---|---|---|---|---|---|
libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/utils/CircularBuffer.java | CircularBuffer.store | public boolean store (T item) {
"""
Adds the given item to the tail of this circular buffer.
@param item the item to add
@return {@code true} if the item has been successfully added to this circular buffer; {@code false} otherwise.
"""
if (size == items.length) {
if (!resizable) return false;
// Resize this queue
resize(Math.max(8, (int)(items.length * 1.75f)));
}
size++;
items[tail++] = item;
if (tail == items.length) tail = 0;
return true;
} | java | public boolean store (T item) {
if (size == items.length) {
if (!resizable) return false;
// Resize this queue
resize(Math.max(8, (int)(items.length * 1.75f)));
}
size++;
items[tail++] = item;
if (tail == items.length) tail = 0;
return true;
} | [
"public",
"boolean",
"store",
"(",
"T",
"item",
")",
"{",
"if",
"(",
"size",
"==",
"items",
".",
"length",
")",
"{",
"if",
"(",
"!",
"resizable",
")",
"return",
"false",
";",
"// Resize this queue",
"resize",
"(",
"Math",
".",
"max",
"(",
"8",
",",
"(",
"int",
")",
"(",
"items",
".",
"length",
"*",
"1.75f",
")",
")",
")",
";",
"}",
"size",
"++",
";",
"items",
"[",
"tail",
"++",
"]",
"=",
"item",
";",
"if",
"(",
"tail",
"==",
"items",
".",
"length",
")",
"tail",
"=",
"0",
";",
"return",
"true",
";",
"}"
]
| Adds the given item to the tail of this circular buffer.
@param item the item to add
@return {@code true} if the item has been successfully added to this circular buffer; {@code false} otherwise. | [
"Adds",
"the",
"given",
"item",
"to",
"the",
"tail",
"of",
"this",
"circular",
"buffer",
"."
]
| train | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/utils/CircularBuffer.java#L57-L68 |
xiancloud/xian | xian-core/src/main/java/info/xiancloud/core/util/Reflection.java | Reflection.toType | public static <T> T toType(Object data, Class<T> type) {
"""
<p>
This is a flexible tolerable type casting method with the help of serializing tools (fastjson currently).
</p>
Supports:<br>
map to jsonObject to bean <br>
collection ---- fetch the first element and cast it to map/json/bean<br>
collection --set-- HashSet<br>
collection --list-- ArrayList<br>
collection --queue-- LinkedList<br>
"""
try {
if (Reflection.instanceOf(data, type)) {
return Reflection.cast(data, type);
}
if (Collection.class.isAssignableFrom(type)) {
return toCollectionType(data, type);
}
if (type.isArray()) {
return toArray(data, type);
}
return toNonCollectionType(data, type);
} catch (Throwable e) {
throw castFailedException(data, type, e);
}
} | java | public static <T> T toType(Object data, Class<T> type) {
try {
if (Reflection.instanceOf(data, type)) {
return Reflection.cast(data, type);
}
if (Collection.class.isAssignableFrom(type)) {
return toCollectionType(data, type);
}
if (type.isArray()) {
return toArray(data, type);
}
return toNonCollectionType(data, type);
} catch (Throwable e) {
throw castFailedException(data, type, e);
}
} | [
"public",
"static",
"<",
"T",
">",
"T",
"toType",
"(",
"Object",
"data",
",",
"Class",
"<",
"T",
">",
"type",
")",
"{",
"try",
"{",
"if",
"(",
"Reflection",
".",
"instanceOf",
"(",
"data",
",",
"type",
")",
")",
"{",
"return",
"Reflection",
".",
"cast",
"(",
"data",
",",
"type",
")",
";",
"}",
"if",
"(",
"Collection",
".",
"class",
".",
"isAssignableFrom",
"(",
"type",
")",
")",
"{",
"return",
"toCollectionType",
"(",
"data",
",",
"type",
")",
";",
"}",
"if",
"(",
"type",
".",
"isArray",
"(",
")",
")",
"{",
"return",
"toArray",
"(",
"data",
",",
"type",
")",
";",
"}",
"return",
"toNonCollectionType",
"(",
"data",
",",
"type",
")",
";",
"}",
"catch",
"(",
"Throwable",
"e",
")",
"{",
"throw",
"castFailedException",
"(",
"data",
",",
"type",
",",
"e",
")",
";",
"}",
"}"
]
| <p>
This is a flexible tolerable type casting method with the help of serializing tools (fastjson currently).
</p>
Supports:<br>
map to jsonObject to bean <br>
collection ---- fetch the first element and cast it to map/json/bean<br>
collection --set-- HashSet<br>
collection --list-- ArrayList<br>
collection --queue-- LinkedList<br> | [
"<p",
">",
"This",
"is",
"a",
"flexible",
"tolerable",
"type",
"casting",
"method",
"with",
"the",
"help",
"of",
"serializing",
"tools",
"(",
"fastjson",
"currently",
")",
".",
"<",
"/",
"p",
">",
"Supports",
":",
"<br",
">",
"map",
"to",
"jsonObject",
"to",
"bean",
"<br",
">",
"collection",
"----",
"fetch",
"the",
"first",
"element",
"and",
"cast",
"it",
"to",
"map",
"/",
"json",
"/",
"bean<br",
">",
"collection",
"--",
"set",
"--",
"HashSet<br",
">",
"collection",
"--",
"list",
"--",
"ArrayList<br",
">",
"collection",
"--",
"queue",
"--",
"LinkedList<br",
">"
]
| train | https://github.com/xiancloud/xian/blob/1948e088545553d2745b2c86d8b5a64988bb850e/xian-core/src/main/java/info/xiancloud/core/util/Reflection.java#L300-L315 |
CenturyLinkCloud/clc-java-sdk | sdk/src/main/java/com/centurylink/cloud/sdk/server/services/dsl/ServerService.java | ServerService.importServer | public OperationFuture<ServerMetadata> importServer(ImportServerConfig config) {
"""
Import server from ovf image
@param config server config
@return OperationFuture wrapper for ServerMetadata
"""
BaseServerResponse response = client.importServer(
serverConverter.buildImportServerRequest(
config,
config.getCustomFields().isEmpty() ?
null :
client.getCustomFields()
)
);
return postProcessBuildServerResponse(response, config);
} | java | public OperationFuture<ServerMetadata> importServer(ImportServerConfig config) {
BaseServerResponse response = client.importServer(
serverConverter.buildImportServerRequest(
config,
config.getCustomFields().isEmpty() ?
null :
client.getCustomFields()
)
);
return postProcessBuildServerResponse(response, config);
} | [
"public",
"OperationFuture",
"<",
"ServerMetadata",
">",
"importServer",
"(",
"ImportServerConfig",
"config",
")",
"{",
"BaseServerResponse",
"response",
"=",
"client",
".",
"importServer",
"(",
"serverConverter",
".",
"buildImportServerRequest",
"(",
"config",
",",
"config",
".",
"getCustomFields",
"(",
")",
".",
"isEmpty",
"(",
")",
"?",
"null",
":",
"client",
".",
"getCustomFields",
"(",
")",
")",
")",
";",
"return",
"postProcessBuildServerResponse",
"(",
"response",
",",
"config",
")",
";",
"}"
]
| Import server from ovf image
@param config server config
@return OperationFuture wrapper for ServerMetadata | [
"Import",
"server",
"from",
"ovf",
"image"
]
| train | https://github.com/CenturyLinkCloud/clc-java-sdk/blob/c026322f077dea71b1acf9f2d665253d79d9bf85/sdk/src/main/java/com/centurylink/cloud/sdk/server/services/dsl/ServerService.java#L156-L167 |
dita-ot/dita-ot | src/main/java/org/dita/dost/util/Job.java | Job.setInputMap | public void setInputMap(final URI map) {
"""
set input file
@param map input file path relative to input directory
"""
assert !map.isAbsolute();
setProperty(INPUT_DITAMAP_URI, map.toString());
// Deprecated since 2.2
setProperty(INPUT_DITAMAP, toFile(map).getPath());
} | java | public void setInputMap(final URI map) {
assert !map.isAbsolute();
setProperty(INPUT_DITAMAP_URI, map.toString());
// Deprecated since 2.2
setProperty(INPUT_DITAMAP, toFile(map).getPath());
} | [
"public",
"void",
"setInputMap",
"(",
"final",
"URI",
"map",
")",
"{",
"assert",
"!",
"map",
".",
"isAbsolute",
"(",
")",
";",
"setProperty",
"(",
"INPUT_DITAMAP_URI",
",",
"map",
".",
"toString",
"(",
")",
")",
";",
"// Deprecated since 2.2",
"setProperty",
"(",
"INPUT_DITAMAP",
",",
"toFile",
"(",
"map",
")",
".",
"getPath",
"(",
")",
")",
";",
"}"
]
| set input file
@param map input file path relative to input directory | [
"set",
"input",
"file"
]
| train | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/Job.java#L466-L471 |
Red5/red5-server-common | src/main/java/org/red5/server/util/ScopeUtils.java | ScopeUtils.getScopeService | public static Object getScopeService(IScope scope, Class<?> intf) {
"""
Returns scope service that implements a given interface.
@param scope
The scope service belongs to
@param intf
The interface the service must implement
@return Service object
"""
return getScopeService(scope, intf, null);
} | java | public static Object getScopeService(IScope scope, Class<?> intf) {
return getScopeService(scope, intf, null);
} | [
"public",
"static",
"Object",
"getScopeService",
"(",
"IScope",
"scope",
",",
"Class",
"<",
"?",
">",
"intf",
")",
"{",
"return",
"getScopeService",
"(",
"scope",
",",
"intf",
",",
"null",
")",
";",
"}"
]
| Returns scope service that implements a given interface.
@param scope
The scope service belongs to
@param intf
The interface the service must implement
@return Service object | [
"Returns",
"scope",
"service",
"that",
"implements",
"a",
"given",
"interface",
"."
]
| train | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/util/ScopeUtils.java#L304-L306 |
pgjdbc/pgjdbc | pgjdbc/src/main/java/org/postgresql/core/Parser.java | Parser.digitAt | public static int digitAt(String s, int pos) {
"""
Converts digit at position {@code pos} in string {@code s} to integer or throws.
@param s input string
@param pos position (0-based)
@return integer value of a digit at position pos
@throws NumberFormatException if character at position pos is not an integer
"""
int c = s.charAt(pos) - '0';
if (c < 0 || c > 9) {
throw new NumberFormatException("Input string: \"" + s + "\", position: " + pos);
}
return c;
} | java | public static int digitAt(String s, int pos) {
int c = s.charAt(pos) - '0';
if (c < 0 || c > 9) {
throw new NumberFormatException("Input string: \"" + s + "\", position: " + pos);
}
return c;
} | [
"public",
"static",
"int",
"digitAt",
"(",
"String",
"s",
",",
"int",
"pos",
")",
"{",
"int",
"c",
"=",
"s",
".",
"charAt",
"(",
"pos",
")",
"-",
"'",
"'",
";",
"if",
"(",
"c",
"<",
"0",
"||",
"c",
">",
"9",
")",
"{",
"throw",
"new",
"NumberFormatException",
"(",
"\"Input string: \\\"\"",
"+",
"s",
"+",
"\"\\\", position: \"",
"+",
"pos",
")",
";",
"}",
"return",
"c",
";",
"}"
]
| Converts digit at position {@code pos} in string {@code s} to integer or throws.
@param s input string
@param pos position (0-based)
@return integer value of a digit at position pos
@throws NumberFormatException if character at position pos is not an integer | [
"Converts",
"digit",
"at",
"position",
"{"
]
| train | https://github.com/pgjdbc/pgjdbc/blob/95ba7b261e39754674c5817695ae5ebf9a341fae/pgjdbc/src/main/java/org/postgresql/core/Parser.java#L767-L773 |
line/armeria | core/src/main/java/com/linecorp/armeria/server/AbstractVirtualHostBuilder.java | AbstractVirtualHostBuilder.annotatedService | public B annotatedService(String pathPrefix, Object service,
Iterable<?> exceptionHandlersAndConverters) {
"""
Binds the specified annotated service object under the specified path prefix.
@param exceptionHandlersAndConverters an iterable object of {@link ExceptionHandlerFunction},
{@link RequestConverterFunction} and/or
{@link ResponseConverterFunction}
"""
return annotatedService(pathPrefix, service, Function.identity(),
requireNonNull(exceptionHandlersAndConverters,
"exceptionHandlersAndConverters"));
} | java | public B annotatedService(String pathPrefix, Object service,
Iterable<?> exceptionHandlersAndConverters) {
return annotatedService(pathPrefix, service, Function.identity(),
requireNonNull(exceptionHandlersAndConverters,
"exceptionHandlersAndConverters"));
} | [
"public",
"B",
"annotatedService",
"(",
"String",
"pathPrefix",
",",
"Object",
"service",
",",
"Iterable",
"<",
"?",
">",
"exceptionHandlersAndConverters",
")",
"{",
"return",
"annotatedService",
"(",
"pathPrefix",
",",
"service",
",",
"Function",
".",
"identity",
"(",
")",
",",
"requireNonNull",
"(",
"exceptionHandlersAndConverters",
",",
"\"exceptionHandlersAndConverters\"",
")",
")",
";",
"}"
]
| Binds the specified annotated service object under the specified path prefix.
@param exceptionHandlersAndConverters an iterable object of {@link ExceptionHandlerFunction},
{@link RequestConverterFunction} and/or
{@link ResponseConverterFunction} | [
"Binds",
"the",
"specified",
"annotated",
"service",
"object",
"under",
"the",
"specified",
"path",
"prefix",
"."
]
| train | https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/core/src/main/java/com/linecorp/armeria/server/AbstractVirtualHostBuilder.java#L475-L480 |
lessthanoptimal/BoofCV | main/boofcv-geo/src/main/java/boofcv/factory/geo/FactoryMultiView.java | FactoryMultiView.pnp_1 | public static Estimate1ofPnP pnp_1(EnumPNP which, int numIterations , int numTest) {
"""
Created an estimator for the P3P problem that selects a single solution by considering additional
observations.
<p>NOTE: Observations are in normalized image coordinates NOT pixels.</p>
<p>
NOTE: EPnP has several tuning parameters and the defaults here might not be the best for your situation.
Use {@link #computePnPwithEPnP} if you wish to have access to all parameters.
</p>
@param which The algorithm which is to be returned.
@param numIterations Number of iterations. Only used by some algorithms and recommended number varies
significantly by algorithm.
@param numTest How many additional sample points are used to remove ambiguity in the solutions. Not used
if only a single solution is found.
@return An estimator which returns a single estimate.
"""
if( which == EnumPNP.EPNP ) {
PnPLepetitEPnP alg = new PnPLepetitEPnP(0.1);
alg.setNumIterations(numIterations);
return new WrapPnPLepetitEPnP(alg);
} else if( which == EnumPNP.IPPE ) {
Estimate1ofEpipolar H = FactoryMultiView.homographyTLS();
return new IPPE_to_EstimatePnP(H);
}
FastQueue<Se3_F64> solutions = new FastQueue<>(4, Se3_F64.class, true);
return new EstimateNto1ofPnP(pnp_N(which,-1),solutions,numTest);
} | java | public static Estimate1ofPnP pnp_1(EnumPNP which, int numIterations , int numTest) {
if( which == EnumPNP.EPNP ) {
PnPLepetitEPnP alg = new PnPLepetitEPnP(0.1);
alg.setNumIterations(numIterations);
return new WrapPnPLepetitEPnP(alg);
} else if( which == EnumPNP.IPPE ) {
Estimate1ofEpipolar H = FactoryMultiView.homographyTLS();
return new IPPE_to_EstimatePnP(H);
}
FastQueue<Se3_F64> solutions = new FastQueue<>(4, Se3_F64.class, true);
return new EstimateNto1ofPnP(pnp_N(which,-1),solutions,numTest);
} | [
"public",
"static",
"Estimate1ofPnP",
"pnp_1",
"(",
"EnumPNP",
"which",
",",
"int",
"numIterations",
",",
"int",
"numTest",
")",
"{",
"if",
"(",
"which",
"==",
"EnumPNP",
".",
"EPNP",
")",
"{",
"PnPLepetitEPnP",
"alg",
"=",
"new",
"PnPLepetitEPnP",
"(",
"0.1",
")",
";",
"alg",
".",
"setNumIterations",
"(",
"numIterations",
")",
";",
"return",
"new",
"WrapPnPLepetitEPnP",
"(",
"alg",
")",
";",
"}",
"else",
"if",
"(",
"which",
"==",
"EnumPNP",
".",
"IPPE",
")",
"{",
"Estimate1ofEpipolar",
"H",
"=",
"FactoryMultiView",
".",
"homographyTLS",
"(",
")",
";",
"return",
"new",
"IPPE_to_EstimatePnP",
"(",
"H",
")",
";",
"}",
"FastQueue",
"<",
"Se3_F64",
">",
"solutions",
"=",
"new",
"FastQueue",
"<>",
"(",
"4",
",",
"Se3_F64",
".",
"class",
",",
"true",
")",
";",
"return",
"new",
"EstimateNto1ofPnP",
"(",
"pnp_N",
"(",
"which",
",",
"-",
"1",
")",
",",
"solutions",
",",
"numTest",
")",
";",
"}"
]
| Created an estimator for the P3P problem that selects a single solution by considering additional
observations.
<p>NOTE: Observations are in normalized image coordinates NOT pixels.</p>
<p>
NOTE: EPnP has several tuning parameters and the defaults here might not be the best for your situation.
Use {@link #computePnPwithEPnP} if you wish to have access to all parameters.
</p>
@param which The algorithm which is to be returned.
@param numIterations Number of iterations. Only used by some algorithms and recommended number varies
significantly by algorithm.
@param numTest How many additional sample points are used to remove ambiguity in the solutions. Not used
if only a single solution is found.
@return An estimator which returns a single estimate. | [
"Created",
"an",
"estimator",
"for",
"the",
"P3P",
"problem",
"that",
"selects",
"a",
"single",
"solution",
"by",
"considering",
"additional",
"observations",
"."
]
| train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/factory/geo/FactoryMultiView.java#L483-L497 |
h2oai/h2o-2 | src/main/java/water/Model.java | Model.score0 | protected float[] score0( Chunk chks[], int row_in_chunk, double[] tmp, float[] preds ) {
"""
Bulk scoring API for one row. Chunks are all compatible with the model,
and expect the last Chunks are for the final distribution and prediction.
Default method is to just load the data into the tmp array, then call
subclass scoring logic.
"""
assert chks.length>=_names.length; // Last chunk is for the response
for( int i=0; i<nfeatures(); i++ ) // Do not include last value since it can contains a response
tmp[i] = chks[i].at0(row_in_chunk);
float[] scored = score0(tmp,preds);
// Correct probabilities obtained from training on oversampled data back to original distribution
// C.f. http://gking.harvard.edu/files/0s.pdf Eq.(27)
if (isClassifier() && _priorClassDist != null && _modelClassDist != null) {
assert(scored.length == nclasses()+1); //1 label + nclasses probs
ModelUtils.correctProbabilities(scored, _priorClassDist, _modelClassDist);
//set label based on corrected probabilities (max value wins, with deterministic tie-breaking)
scored[0] = ModelUtils.getPrediction(scored, tmp);
}
return scored;
} | java | protected float[] score0( Chunk chks[], int row_in_chunk, double[] tmp, float[] preds ) {
assert chks.length>=_names.length; // Last chunk is for the response
for( int i=0; i<nfeatures(); i++ ) // Do not include last value since it can contains a response
tmp[i] = chks[i].at0(row_in_chunk);
float[] scored = score0(tmp,preds);
// Correct probabilities obtained from training on oversampled data back to original distribution
// C.f. http://gking.harvard.edu/files/0s.pdf Eq.(27)
if (isClassifier() && _priorClassDist != null && _modelClassDist != null) {
assert(scored.length == nclasses()+1); //1 label + nclasses probs
ModelUtils.correctProbabilities(scored, _priorClassDist, _modelClassDist);
//set label based on corrected probabilities (max value wins, with deterministic tie-breaking)
scored[0] = ModelUtils.getPrediction(scored, tmp);
}
return scored;
} | [
"protected",
"float",
"[",
"]",
"score0",
"(",
"Chunk",
"chks",
"[",
"]",
",",
"int",
"row_in_chunk",
",",
"double",
"[",
"]",
"tmp",
",",
"float",
"[",
"]",
"preds",
")",
"{",
"assert",
"chks",
".",
"length",
">=",
"_names",
".",
"length",
";",
"// Last chunk is for the response",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"nfeatures",
"(",
")",
";",
"i",
"++",
")",
"// Do not include last value since it can contains a response",
"tmp",
"[",
"i",
"]",
"=",
"chks",
"[",
"i",
"]",
".",
"at0",
"(",
"row_in_chunk",
")",
";",
"float",
"[",
"]",
"scored",
"=",
"score0",
"(",
"tmp",
",",
"preds",
")",
";",
"// Correct probabilities obtained from training on oversampled data back to original distribution",
"// C.f. http://gking.harvard.edu/files/0s.pdf Eq.(27)",
"if",
"(",
"isClassifier",
"(",
")",
"&&",
"_priorClassDist",
"!=",
"null",
"&&",
"_modelClassDist",
"!=",
"null",
")",
"{",
"assert",
"(",
"scored",
".",
"length",
"==",
"nclasses",
"(",
")",
"+",
"1",
")",
";",
"//1 label + nclasses probs",
"ModelUtils",
".",
"correctProbabilities",
"(",
"scored",
",",
"_priorClassDist",
",",
"_modelClassDist",
")",
";",
"//set label based on corrected probabilities (max value wins, with deterministic tie-breaking)",
"scored",
"[",
"0",
"]",
"=",
"ModelUtils",
".",
"getPrediction",
"(",
"scored",
",",
"tmp",
")",
";",
"}",
"return",
"scored",
";",
"}"
]
| Bulk scoring API for one row. Chunks are all compatible with the model,
and expect the last Chunks are for the final distribution and prediction.
Default method is to just load the data into the tmp array, then call
subclass scoring logic. | [
"Bulk",
"scoring",
"API",
"for",
"one",
"row",
".",
"Chunks",
"are",
"all",
"compatible",
"with",
"the",
"model",
"and",
"expect",
"the",
"last",
"Chunks",
"are",
"for",
"the",
"final",
"distribution",
"and",
"prediction",
".",
"Default",
"method",
"is",
"to",
"just",
"load",
"the",
"data",
"into",
"the",
"tmp",
"array",
"then",
"call",
"subclass",
"scoring",
"logic",
"."
]
| train | https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/Model.java#L471-L485 |
OpenLiberty/open-liberty | dev/com.ibm.ws.kernel.boot.core/src/com/ibm/ws/kernel/boot/internal/KernelBootstrap.java | KernelBootstrap.buildClassLoader | protected ClassLoader buildClassLoader(final List<URL> urlList, String verifyJarProperty) {
"""
Build the nested classloader containing the OSGi framework, and the log provider.
@param urlList
@param verifyJarProperty
@return
"""
if (libertyBoot) {
// for liberty boot we just use the class loader that loaded this class
return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
@Override
public ClassLoader run() {
return getClass().getClassLoader();
}
});
}
final boolean verifyJar;
if (System.getSecurityManager() == null) {
// do not perform verification if SecurityManager is not installed
// unless explicitly enabled.
verifyJar = "true".equalsIgnoreCase(verifyJarProperty);
} else {
// always perform verification if SecurityManager is installed.
verifyJar = true;
}
enableJava2SecurityIfSet(this.bootProps, urlList);
ClassLoader loader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
@Override
public ClassLoader run() {
ClassLoader parent = getClass().getClassLoader();
URL[] urls = urlList.toArray(new URL[urlList.size()]);
if (verifyJar) {
return new BootstrapChildFirstURLClassloader(urls, parent);
} else {
try {
return new BootstrapChildFirstJarClassloader(urls, parent);
} catch (RuntimeException e) {
// fall back to URLClassLoader in case something went wrong
return new BootstrapChildFirstURLClassloader(urls, parent);
}
}
}
});
return loader;
} | java | protected ClassLoader buildClassLoader(final List<URL> urlList, String verifyJarProperty) {
if (libertyBoot) {
// for liberty boot we just use the class loader that loaded this class
return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
@Override
public ClassLoader run() {
return getClass().getClassLoader();
}
});
}
final boolean verifyJar;
if (System.getSecurityManager() == null) {
// do not perform verification if SecurityManager is not installed
// unless explicitly enabled.
verifyJar = "true".equalsIgnoreCase(verifyJarProperty);
} else {
// always perform verification if SecurityManager is installed.
verifyJar = true;
}
enableJava2SecurityIfSet(this.bootProps, urlList);
ClassLoader loader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
@Override
public ClassLoader run() {
ClassLoader parent = getClass().getClassLoader();
URL[] urls = urlList.toArray(new URL[urlList.size()]);
if (verifyJar) {
return new BootstrapChildFirstURLClassloader(urls, parent);
} else {
try {
return new BootstrapChildFirstJarClassloader(urls, parent);
} catch (RuntimeException e) {
// fall back to URLClassLoader in case something went wrong
return new BootstrapChildFirstURLClassloader(urls, parent);
}
}
}
});
return loader;
} | [
"protected",
"ClassLoader",
"buildClassLoader",
"(",
"final",
"List",
"<",
"URL",
">",
"urlList",
",",
"String",
"verifyJarProperty",
")",
"{",
"if",
"(",
"libertyBoot",
")",
"{",
"// for liberty boot we just use the class loader that loaded this class",
"return",
"AccessController",
".",
"doPrivileged",
"(",
"new",
"PrivilegedAction",
"<",
"ClassLoader",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"ClassLoader",
"run",
"(",
")",
"{",
"return",
"getClass",
"(",
")",
".",
"getClassLoader",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
"final",
"boolean",
"verifyJar",
";",
"if",
"(",
"System",
".",
"getSecurityManager",
"(",
")",
"==",
"null",
")",
"{",
"// do not perform verification if SecurityManager is not installed",
"// unless explicitly enabled.",
"verifyJar",
"=",
"\"true\"",
".",
"equalsIgnoreCase",
"(",
"verifyJarProperty",
")",
";",
"}",
"else",
"{",
"// always perform verification if SecurityManager is installed.",
"verifyJar",
"=",
"true",
";",
"}",
"enableJava2SecurityIfSet",
"(",
"this",
".",
"bootProps",
",",
"urlList",
")",
";",
"ClassLoader",
"loader",
"=",
"AccessController",
".",
"doPrivileged",
"(",
"new",
"PrivilegedAction",
"<",
"ClassLoader",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"ClassLoader",
"run",
"(",
")",
"{",
"ClassLoader",
"parent",
"=",
"getClass",
"(",
")",
".",
"getClassLoader",
"(",
")",
";",
"URL",
"[",
"]",
"urls",
"=",
"urlList",
".",
"toArray",
"(",
"new",
"URL",
"[",
"urlList",
".",
"size",
"(",
")",
"]",
")",
";",
"if",
"(",
"verifyJar",
")",
"{",
"return",
"new",
"BootstrapChildFirstURLClassloader",
"(",
"urls",
",",
"parent",
")",
";",
"}",
"else",
"{",
"try",
"{",
"return",
"new",
"BootstrapChildFirstJarClassloader",
"(",
"urls",
",",
"parent",
")",
";",
"}",
"catch",
"(",
"RuntimeException",
"e",
")",
"{",
"// fall back to URLClassLoader in case something went wrong",
"return",
"new",
"BootstrapChildFirstURLClassloader",
"(",
"urls",
",",
"parent",
")",
";",
"}",
"}",
"}",
"}",
")",
";",
"return",
"loader",
";",
"}"
]
| Build the nested classloader containing the OSGi framework, and the log provider.
@param urlList
@param verifyJarProperty
@return | [
"Build",
"the",
"nested",
"classloader",
"containing",
"the",
"OSGi",
"framework",
"and",
"the",
"log",
"provider",
"."
]
| train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.kernel.boot.core/src/com/ibm/ws/kernel/boot/internal/KernelBootstrap.java#L379-L422 |
vipshop/vjtools | vjkit/src/main/java/com/vip/vjtools/vjkit/security/CryptoUtil.java | CryptoUtil.aesEncrypt | public static byte[] aesEncrypt(byte[] input, byte[] key, byte[] iv) {
"""
使用AES加密原始字符串.
@param input 原始输入字符数组
@param key 符合AES要求的密钥
@param iv 初始向量
"""
return aes(input, key, iv, Cipher.ENCRYPT_MODE);
} | java | public static byte[] aesEncrypt(byte[] input, byte[] key, byte[] iv) {
return aes(input, key, iv, Cipher.ENCRYPT_MODE);
} | [
"public",
"static",
"byte",
"[",
"]",
"aesEncrypt",
"(",
"byte",
"[",
"]",
"input",
",",
"byte",
"[",
"]",
"key",
",",
"byte",
"[",
"]",
"iv",
")",
"{",
"return",
"aes",
"(",
"input",
",",
"key",
",",
"iv",
",",
"Cipher",
".",
"ENCRYPT_MODE",
")",
";",
"}"
]
| 使用AES加密原始字符串.
@param input 原始输入字符数组
@param key 符合AES要求的密钥
@param iv 初始向量 | [
"使用AES加密原始字符串",
"."
]
| train | https://github.com/vipshop/vjtools/blob/60c743da35913d72f37f2d79afa90ad2bf73cb89/vjkit/src/main/java/com/vip/vjtools/vjkit/security/CryptoUtil.java#L97-L99 |
glyptodon/guacamole-client | guacamole/src/main/java/org/apache/guacamole/tunnel/TunnelRequest.java | TunnelRequest.getIntegerParameter | public Integer getIntegerParameter(String name) throws GuacamoleException {
"""
Returns the integer value of the parameter having the given name,
throwing an exception if the parameter cannot be parsed.
@param name
The name of the parameter to return.
@return
The integer value of the parameter having the given name, or null if
the parameter is missing.
@throws GuacamoleException
If the parameter is not a valid integer.
"""
// Pull requested parameter
String value = getParameter(name);
if (value == null)
return null;
// Attempt to parse as an integer
try {
return Integer.parseInt(value);
}
// Rethrow any parsing error as a GuacamoleClientException
catch (NumberFormatException e) {
throw new GuacamoleClientException("Parameter \"" + name + "\" must be a valid integer.", e);
}
} | java | public Integer getIntegerParameter(String name) throws GuacamoleException {
// Pull requested parameter
String value = getParameter(name);
if (value == null)
return null;
// Attempt to parse as an integer
try {
return Integer.parseInt(value);
}
// Rethrow any parsing error as a GuacamoleClientException
catch (NumberFormatException e) {
throw new GuacamoleClientException("Parameter \"" + name + "\" must be a valid integer.", e);
}
} | [
"public",
"Integer",
"getIntegerParameter",
"(",
"String",
"name",
")",
"throws",
"GuacamoleException",
"{",
"// Pull requested parameter",
"String",
"value",
"=",
"getParameter",
"(",
"name",
")",
";",
"if",
"(",
"value",
"==",
"null",
")",
"return",
"null",
";",
"// Attempt to parse as an integer",
"try",
"{",
"return",
"Integer",
".",
"parseInt",
"(",
"value",
")",
";",
"}",
"// Rethrow any parsing error as a GuacamoleClientException",
"catch",
"(",
"NumberFormatException",
"e",
")",
"{",
"throw",
"new",
"GuacamoleClientException",
"(",
"\"Parameter \\\"\"",
"+",
"name",
"+",
"\"\\\" must be a valid integer.\"",
",",
"e",
")",
";",
"}",
"}"
]
| Returns the integer value of the parameter having the given name,
throwing an exception if the parameter cannot be parsed.
@param name
The name of the parameter to return.
@return
The integer value of the parameter having the given name, or null if
the parameter is missing.
@throws GuacamoleException
If the parameter is not a valid integer. | [
"Returns",
"the",
"integer",
"value",
"of",
"the",
"parameter",
"having",
"the",
"given",
"name",
"throwing",
"an",
"exception",
"if",
"the",
"parameter",
"cannot",
"be",
"parsed",
"."
]
| train | https://github.com/glyptodon/guacamole-client/blob/ea1b10e9d1e3f1fa640dff2ca64d61b44bf1ace9/guacamole/src/main/java/org/apache/guacamole/tunnel/TunnelRequest.java#L195-L212 |
netty/netty | handler/src/main/java/io/netty/handler/ssl/SslHandler.java | SslHandler.allocate | private ByteBuf allocate(ChannelHandlerContext ctx, int capacity) {
"""
Always prefer a direct buffer when it's pooled, so that we reduce the number of memory copies
in {@link OpenSslEngine}.
"""
ByteBufAllocator alloc = ctx.alloc();
if (engineType.wantsDirectBuffer) {
return alloc.directBuffer(capacity);
} else {
return alloc.buffer(capacity);
}
} | java | private ByteBuf allocate(ChannelHandlerContext ctx, int capacity) {
ByteBufAllocator alloc = ctx.alloc();
if (engineType.wantsDirectBuffer) {
return alloc.directBuffer(capacity);
} else {
return alloc.buffer(capacity);
}
} | [
"private",
"ByteBuf",
"allocate",
"(",
"ChannelHandlerContext",
"ctx",
",",
"int",
"capacity",
")",
"{",
"ByteBufAllocator",
"alloc",
"=",
"ctx",
".",
"alloc",
"(",
")",
";",
"if",
"(",
"engineType",
".",
"wantsDirectBuffer",
")",
"{",
"return",
"alloc",
".",
"directBuffer",
"(",
"capacity",
")",
";",
"}",
"else",
"{",
"return",
"alloc",
".",
"buffer",
"(",
"capacity",
")",
";",
"}",
"}"
]
| Always prefer a direct buffer when it's pooled, so that we reduce the number of memory copies
in {@link OpenSslEngine}. | [
"Always",
"prefer",
"a",
"direct",
"buffer",
"when",
"it",
"s",
"pooled",
"so",
"that",
"we",
"reduce",
"the",
"number",
"of",
"memory",
"copies",
"in",
"{"
]
| train | https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/handler/src/main/java/io/netty/handler/ssl/SslHandler.java#L2120-L2127 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/TrainsImpl.java | TrainsImpl.getStatusAsync | public Observable<List<ModelTrainingInfo>> getStatusAsync(UUID appId, String versionId) {
"""
Gets the training status of all models (intents and entities) for the specified LUIS app. You must call the train API to train the LUIS app before you call this API to get training status. "appID" specifies the LUIS app ID. "versionId" specifies the version number of the LUIS app. For example, "0.1".
@param appId The application ID.
@param versionId The version ID.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the List<ModelTrainingInfo> object
"""
return getStatusWithServiceResponseAsync(appId, versionId).map(new Func1<ServiceResponse<List<ModelTrainingInfo>>, List<ModelTrainingInfo>>() {
@Override
public List<ModelTrainingInfo> call(ServiceResponse<List<ModelTrainingInfo>> response) {
return response.body();
}
});
} | java | public Observable<List<ModelTrainingInfo>> getStatusAsync(UUID appId, String versionId) {
return getStatusWithServiceResponseAsync(appId, versionId).map(new Func1<ServiceResponse<List<ModelTrainingInfo>>, List<ModelTrainingInfo>>() {
@Override
public List<ModelTrainingInfo> call(ServiceResponse<List<ModelTrainingInfo>> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"List",
"<",
"ModelTrainingInfo",
">",
">",
"getStatusAsync",
"(",
"UUID",
"appId",
",",
"String",
"versionId",
")",
"{",
"return",
"getStatusWithServiceResponseAsync",
"(",
"appId",
",",
"versionId",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"List",
"<",
"ModelTrainingInfo",
">",
">",
",",
"List",
"<",
"ModelTrainingInfo",
">",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"List",
"<",
"ModelTrainingInfo",
">",
"call",
"(",
"ServiceResponse",
"<",
"List",
"<",
"ModelTrainingInfo",
">",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Gets the training status of all models (intents and entities) for the specified LUIS app. You must call the train API to train the LUIS app before you call this API to get training status. "appID" specifies the LUIS app ID. "versionId" specifies the version number of the LUIS app. For example, "0.1".
@param appId The application ID.
@param versionId The version ID.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the List<ModelTrainingInfo> object | [
"Gets",
"the",
"training",
"status",
"of",
"all",
"models",
"(",
"intents",
"and",
"entities",
")",
"for",
"the",
"specified",
"LUIS",
"app",
".",
"You",
"must",
"call",
"the",
"train",
"API",
"to",
"train",
"the",
"LUIS",
"app",
"before",
"you",
"call",
"this",
"API",
"to",
"get",
"training",
"status",
".",
"appID",
"specifies",
"the",
"LUIS",
"app",
"ID",
".",
"versionId",
"specifies",
"the",
"version",
"number",
"of",
"the",
"LUIS",
"app",
".",
"For",
"example",
"0",
".",
"1",
"."
]
| train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/TrainsImpl.java#L189-L196 |
gocd/gocd | base/src/main/java/com/thoughtworks/go/util/DirectoryScanner.java | DirectoryScanner.findFile | private File findFile(File base, String path, boolean cs) {
"""
From <code>base</code> traverse the filesystem in order to find
a file that matches the given name.
@param base base File (dir).
@param path file path.
@param cs whether to scan case-sensitively.
@return File object that points to the file in question or null.
@since Ant 1.6.3
"""
if (FileUtil.isAbsolutePath(path)) {
if (base == null) {
String[] s = FileUtil.dissect(path);
base = new File(s[0]);
path = s[1];
} else {
File f = FileUtil.normalize(path);
String s = FileUtil.removeLeadingPath(base, f);
if (s.equals(f.getAbsolutePath())) {
//removing base from path yields no change; path not child of base
return null;
}
path = s;
}
}
return findFile(base, SelectorUtils.tokenizePath(path), cs);
} | java | private File findFile(File base, String path, boolean cs) {
if (FileUtil.isAbsolutePath(path)) {
if (base == null) {
String[] s = FileUtil.dissect(path);
base = new File(s[0]);
path = s[1];
} else {
File f = FileUtil.normalize(path);
String s = FileUtil.removeLeadingPath(base, f);
if (s.equals(f.getAbsolutePath())) {
//removing base from path yields no change; path not child of base
return null;
}
path = s;
}
}
return findFile(base, SelectorUtils.tokenizePath(path), cs);
} | [
"private",
"File",
"findFile",
"(",
"File",
"base",
",",
"String",
"path",
",",
"boolean",
"cs",
")",
"{",
"if",
"(",
"FileUtil",
".",
"isAbsolutePath",
"(",
"path",
")",
")",
"{",
"if",
"(",
"base",
"==",
"null",
")",
"{",
"String",
"[",
"]",
"s",
"=",
"FileUtil",
".",
"dissect",
"(",
"path",
")",
";",
"base",
"=",
"new",
"File",
"(",
"s",
"[",
"0",
"]",
")",
";",
"path",
"=",
"s",
"[",
"1",
"]",
";",
"}",
"else",
"{",
"File",
"f",
"=",
"FileUtil",
".",
"normalize",
"(",
"path",
")",
";",
"String",
"s",
"=",
"FileUtil",
".",
"removeLeadingPath",
"(",
"base",
",",
"f",
")",
";",
"if",
"(",
"s",
".",
"equals",
"(",
"f",
".",
"getAbsolutePath",
"(",
")",
")",
")",
"{",
"//removing base from path yields no change; path not child of base",
"return",
"null",
";",
"}",
"path",
"=",
"s",
";",
"}",
"}",
"return",
"findFile",
"(",
"base",
",",
"SelectorUtils",
".",
"tokenizePath",
"(",
"path",
")",
",",
"cs",
")",
";",
"}"
]
| From <code>base</code> traverse the filesystem in order to find
a file that matches the given name.
@param base base File (dir).
@param path file path.
@param cs whether to scan case-sensitively.
@return File object that points to the file in question or null.
@since Ant 1.6.3 | [
"From",
"<code",
">",
"base<",
"/",
"code",
">",
"traverse",
"the",
"filesystem",
"in",
"order",
"to",
"find",
"a",
"file",
"that",
"matches",
"the",
"given",
"name",
"."
]
| train | https://github.com/gocd/gocd/blob/59a8480e23d6c06de39127635108dff57603cb71/base/src/main/java/com/thoughtworks/go/util/DirectoryScanner.java#L1519-L1536 |
redkale/redkale | src/org/redkale/net/http/HttpResponse.java | HttpResponse.finishJson | public void finishJson(final JsonConvert convert, final org.redkale.service.RetResult ret) {
"""
将RetResult对象以JSON格式输出
@param convert 指定的JsonConvert
@param ret RetResult输出对象
"""
this.contentType = this.jsonContentType;
if (this.recycleListener != null) this.output = ret;
if (ret != null && !ret.isSuccess()) {
this.header.addValue("retcode", String.valueOf(ret.getRetcode()));
this.header.addValue("retinfo", ret.getRetinfo());
}
finish(convert.convertTo(getBodyBufferSupplier(), ret));
} | java | public void finishJson(final JsonConvert convert, final org.redkale.service.RetResult ret) {
this.contentType = this.jsonContentType;
if (this.recycleListener != null) this.output = ret;
if (ret != null && !ret.isSuccess()) {
this.header.addValue("retcode", String.valueOf(ret.getRetcode()));
this.header.addValue("retinfo", ret.getRetinfo());
}
finish(convert.convertTo(getBodyBufferSupplier(), ret));
} | [
"public",
"void",
"finishJson",
"(",
"final",
"JsonConvert",
"convert",
",",
"final",
"org",
".",
"redkale",
".",
"service",
".",
"RetResult",
"ret",
")",
"{",
"this",
".",
"contentType",
"=",
"this",
".",
"jsonContentType",
";",
"if",
"(",
"this",
".",
"recycleListener",
"!=",
"null",
")",
"this",
".",
"output",
"=",
"ret",
";",
"if",
"(",
"ret",
"!=",
"null",
"&&",
"!",
"ret",
".",
"isSuccess",
"(",
")",
")",
"{",
"this",
".",
"header",
".",
"addValue",
"(",
"\"retcode\"",
",",
"String",
".",
"valueOf",
"(",
"ret",
".",
"getRetcode",
"(",
")",
")",
")",
";",
"this",
".",
"header",
".",
"addValue",
"(",
"\"retinfo\"",
",",
"ret",
".",
"getRetinfo",
"(",
")",
")",
";",
"}",
"finish",
"(",
"convert",
".",
"convertTo",
"(",
"getBodyBufferSupplier",
"(",
")",
",",
"ret",
")",
")",
";",
"}"
]
| 将RetResult对象以JSON格式输出
@param convert 指定的JsonConvert
@param ret RetResult输出对象 | [
"将RetResult对象以JSON格式输出"
]
| train | https://github.com/redkale/redkale/blob/ea5169b5c5ea7412fd762331c0c497165832e901/src/org/redkale/net/http/HttpResponse.java#L397-L405 |
OpenLiberty/open-liberty | dev/com.ibm.ws.security.csiv2.common/src/com/ibm/ws/transport/iiop/security/config/ssl/yoko/SSLSubsystemFactory.java | SSLSubsystemFactory.isAnySecureTransportAddressAvailable | @SuppressWarnings("unchecked")
private boolean isAnySecureTransportAddressAvailable(Map<String, Object> extraConfig) {
"""
/*
On a server, the address map will only contain a "null" entry if there are only unsecured transport addresses.
A client container will not have an address map, so check for its existence and assume there are secured transport
addresses when an address map is not found.
"""
Map<String, List<TransportAddress>> addrMap = (Map<String, List<TransportAddress>>) extraConfig.get(ADDR_KEY);
if (addrMap != null) {
Set<String> sslAliases = addrMap.keySet();
return sslAliases.size() != 1;
}
return true;
} | java | @SuppressWarnings("unchecked")
private boolean isAnySecureTransportAddressAvailable(Map<String, Object> extraConfig) {
Map<String, List<TransportAddress>> addrMap = (Map<String, List<TransportAddress>>) extraConfig.get(ADDR_KEY);
if (addrMap != null) {
Set<String> sslAliases = addrMap.keySet();
return sslAliases.size() != 1;
}
return true;
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"private",
"boolean",
"isAnySecureTransportAddressAvailable",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"extraConfig",
")",
"{",
"Map",
"<",
"String",
",",
"List",
"<",
"TransportAddress",
">",
">",
"addrMap",
"=",
"(",
"Map",
"<",
"String",
",",
"List",
"<",
"TransportAddress",
">",
">",
")",
"extraConfig",
".",
"get",
"(",
"ADDR_KEY",
")",
";",
"if",
"(",
"addrMap",
"!=",
"null",
")",
"{",
"Set",
"<",
"String",
">",
"sslAliases",
"=",
"addrMap",
".",
"keySet",
"(",
")",
";",
"return",
"sslAliases",
".",
"size",
"(",
")",
"!=",
"1",
";",
"}",
"return",
"true",
";",
"}"
]
| /*
On a server, the address map will only contain a "null" entry if there are only unsecured transport addresses.
A client container will not have an address map, so check for its existence and assume there are secured transport
addresses when an address map is not found. | [
"/",
"*",
"On",
"a",
"server",
"the",
"address",
"map",
"will",
"only",
"contain",
"a",
"null",
"entry",
"if",
"there",
"are",
"only",
"unsecured",
"transport",
"addresses",
".",
"A",
"client",
"container",
"will",
"not",
"have",
"an",
"address",
"map",
"so",
"check",
"for",
"its",
"existence",
"and",
"assume",
"there",
"are",
"secured",
"transport",
"addresses",
"when",
"an",
"address",
"map",
"is",
"not",
"found",
"."
]
| train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.csiv2.common/src/com/ibm/ws/transport/iiop/security/config/ssl/yoko/SSLSubsystemFactory.java#L87-L95 |
codeprimate-software/cp-elements | src/main/java/org/cp/elements/data/conversion/AbstractConverter.java | AbstractConverter.isParameterizedFunctionType | @NullSafe
protected boolean isParameterizedFunctionType(Type type) {
"""
Determines whether the {@link Type} is a generic, parameterized {@link Converter} {@link Class type}, such as
by implementing the {@link Converter} interface or extending the {@link AbstractConverter} base class.
@param type {@link Type} to evaluate.
@return a boolean if the {@link Type} represents a generic, parameterized {@link Converter} {@link Class type}.
@see java.lang.reflect.Type
"""
return Optional.ofNullable(type)
.filter(it -> it instanceof ParameterizedType)
.map(it -> {
Class<?> rawType = safeGetValue(() -> ClassUtils.toRawType(it), Object.class);
return isAssignableTo(rawType, Converter.class, Function.class);
})
.orElse(false);
} | java | @NullSafe
protected boolean isParameterizedFunctionType(Type type) {
return Optional.ofNullable(type)
.filter(it -> it instanceof ParameterizedType)
.map(it -> {
Class<?> rawType = safeGetValue(() -> ClassUtils.toRawType(it), Object.class);
return isAssignableTo(rawType, Converter.class, Function.class);
})
.orElse(false);
} | [
"@",
"NullSafe",
"protected",
"boolean",
"isParameterizedFunctionType",
"(",
"Type",
"type",
")",
"{",
"return",
"Optional",
".",
"ofNullable",
"(",
"type",
")",
".",
"filter",
"(",
"it",
"->",
"it",
"instanceof",
"ParameterizedType",
")",
".",
"map",
"(",
"it",
"->",
"{",
"Class",
"<",
"?",
">",
"rawType",
"=",
"safeGetValue",
"(",
"(",
")",
"->",
"ClassUtils",
".",
"toRawType",
"(",
"it",
")",
",",
"Object",
".",
"class",
")",
";",
"return",
"isAssignableTo",
"(",
"rawType",
",",
"Converter",
".",
"class",
",",
"Function",
".",
"class",
")",
";",
"}",
")",
".",
"orElse",
"(",
"false",
")",
";",
"}"
]
| Determines whether the {@link Type} is a generic, parameterized {@link Converter} {@link Class type}, such as
by implementing the {@link Converter} interface or extending the {@link AbstractConverter} base class.
@param type {@link Type} to evaluate.
@return a boolean if the {@link Type} represents a generic, parameterized {@link Converter} {@link Class type}.
@see java.lang.reflect.Type | [
"Determines",
"whether",
"the",
"{",
"@link",
"Type",
"}",
"is",
"a",
"generic",
"parameterized",
"{",
"@link",
"Converter",
"}",
"{",
"@link",
"Class",
"type",
"}",
"such",
"as",
"by",
"implementing",
"the",
"{",
"@link",
"Converter",
"}",
"interface",
"or",
"extending",
"the",
"{",
"@link",
"AbstractConverter",
"}",
"base",
"class",
"."
]
| train | https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/data/conversion/AbstractConverter.java#L166-L179 |
JodaOrg/joda-money | src/main/java/org/joda/money/format/MoneyFormatterBuilder.java | MoneyFormatterBuilder.appendAmount | public MoneyFormatterBuilder appendAmount() {
"""
Appends the amount to the builder using a standard format.
<p>
The format used is {@link MoneyAmountStyle#ASCII_DECIMAL_POINT_GROUP3_COMMA}.
The amount is the value itself, such as '12.34'.
@return this, for chaining, never null
"""
AmountPrinterParser pp = new AmountPrinterParser(MoneyAmountStyle.ASCII_DECIMAL_POINT_GROUP3_COMMA);
return appendInternal(pp, pp);
} | java | public MoneyFormatterBuilder appendAmount() {
AmountPrinterParser pp = new AmountPrinterParser(MoneyAmountStyle.ASCII_DECIMAL_POINT_GROUP3_COMMA);
return appendInternal(pp, pp);
} | [
"public",
"MoneyFormatterBuilder",
"appendAmount",
"(",
")",
"{",
"AmountPrinterParser",
"pp",
"=",
"new",
"AmountPrinterParser",
"(",
"MoneyAmountStyle",
".",
"ASCII_DECIMAL_POINT_GROUP3_COMMA",
")",
";",
"return",
"appendInternal",
"(",
"pp",
",",
"pp",
")",
";",
"}"
]
| Appends the amount to the builder using a standard format.
<p>
The format used is {@link MoneyAmountStyle#ASCII_DECIMAL_POINT_GROUP3_COMMA}.
The amount is the value itself, such as '12.34'.
@return this, for chaining, never null | [
"Appends",
"the",
"amount",
"to",
"the",
"builder",
"using",
"a",
"standard",
"format",
".",
"<p",
">",
"The",
"format",
"used",
"is",
"{",
"@link",
"MoneyAmountStyle#ASCII_DECIMAL_POINT_GROUP3_COMMA",
"}",
".",
"The",
"amount",
"is",
"the",
"value",
"itself",
"such",
"as",
"12",
".",
"34",
"."
]
| train | https://github.com/JodaOrg/joda-money/blob/e1f2de75aa36610a695358696c8a88a18ca66cde/src/main/java/org/joda/money/format/MoneyFormatterBuilder.java#L61-L64 |
BBN-E/bue-common-open | common-core-open/src/main/java/com/bbn/bue/common/StringUtils.java | StringUtils.substringByCodepoints | public static String substringByCodepoints(String s, int startIndexInclusive,
int endIndexExclusive) {
"""
Returns the substring of {@code s} which starts at the Unicode codepoint offset at
{@code startIndexInclusive} and ends before the Unicode codepoint offset at
{@code endIndexExclusive}. You should typically use this instead
of {@link String#substring(int)} because the latter will fail badly in the presence of
non-BMP characters.
Beware this takes linear time according to the end index of the substring, rather than the
substring's length, like for {@link String#substring(int)}
"""
return substringByCodepoints(s, startIndexInclusive, endIndexExclusive, false);
} | java | public static String substringByCodepoints(String s, int startIndexInclusive,
int endIndexExclusive) {
return substringByCodepoints(s, startIndexInclusive, endIndexExclusive, false);
} | [
"public",
"static",
"String",
"substringByCodepoints",
"(",
"String",
"s",
",",
"int",
"startIndexInclusive",
",",
"int",
"endIndexExclusive",
")",
"{",
"return",
"substringByCodepoints",
"(",
"s",
",",
"startIndexInclusive",
",",
"endIndexExclusive",
",",
"false",
")",
";",
"}"
]
| Returns the substring of {@code s} which starts at the Unicode codepoint offset at
{@code startIndexInclusive} and ends before the Unicode codepoint offset at
{@code endIndexExclusive}. You should typically use this instead
of {@link String#substring(int)} because the latter will fail badly in the presence of
non-BMP characters.
Beware this takes linear time according to the end index of the substring, rather than the
substring's length, like for {@link String#substring(int)} | [
"Returns",
"the",
"substring",
"of",
"{",
"@code",
"s",
"}",
"which",
"starts",
"at",
"the",
"Unicode",
"codepoint",
"offset",
"at",
"{",
"@code",
"startIndexInclusive",
"}",
"and",
"ends",
"before",
"the",
"Unicode",
"codepoint",
"offset",
"at",
"{",
"@code",
"endIndexExclusive",
"}",
".",
"You",
"should",
"typically",
"use",
"this",
"instead",
"of",
"{",
"@link",
"String#substring",
"(",
"int",
")",
"}",
"because",
"the",
"latter",
"will",
"fail",
"badly",
"in",
"the",
"presence",
"of",
"non",
"-",
"BMP",
"characters",
"."
]
| train | https://github.com/BBN-E/bue-common-open/blob/d618652674d647867306e2e4b987a21b7c29c015/common-core-open/src/main/java/com/bbn/bue/common/StringUtils.java#L503-L506 |
ical4j/ical4j | src/main/java/net/fortuna/ical4j/model/Recur.java | Recur.getDates | public final DateList getDates(final Date periodStart,
final Date periodEnd, final Value value) {
"""
Returns a list of start dates in the specified period represented by this recur. Any date fields not specified by
this recur are retained from the period start, and as such you should ensure the period start is initialised
correctly.
@param periodStart the start of the period
@param periodEnd the end of the period
@param value the type of dates to generate (i.e. date/date-time)
@return a list of dates
"""
return getDates(periodStart, periodStart, periodEnd, value, -1);
} | java | public final DateList getDates(final Date periodStart,
final Date periodEnd, final Value value) {
return getDates(periodStart, periodStart, periodEnd, value, -1);
} | [
"public",
"final",
"DateList",
"getDates",
"(",
"final",
"Date",
"periodStart",
",",
"final",
"Date",
"periodEnd",
",",
"final",
"Value",
"value",
")",
"{",
"return",
"getDates",
"(",
"periodStart",
",",
"periodStart",
",",
"periodEnd",
",",
"value",
",",
"-",
"1",
")",
";",
"}"
]
| Returns a list of start dates in the specified period represented by this recur. Any date fields not specified by
this recur are retained from the period start, and as such you should ensure the period start is initialised
correctly.
@param periodStart the start of the period
@param periodEnd the end of the period
@param value the type of dates to generate (i.e. date/date-time)
@return a list of dates | [
"Returns",
"a",
"list",
"of",
"start",
"dates",
"in",
"the",
"specified",
"period",
"represented",
"by",
"this",
"recur",
".",
"Any",
"date",
"fields",
"not",
"specified",
"by",
"this",
"recur",
"are",
"retained",
"from",
"the",
"period",
"start",
"and",
"as",
"such",
"you",
"should",
"ensure",
"the",
"period",
"start",
"is",
"initialised",
"correctly",
"."
]
| train | https://github.com/ical4j/ical4j/blob/7ac4bd1ce2bb2e0a2906fb69a56fbd2d9d974156/src/main/java/net/fortuna/ical4j/model/Recur.java#L627-L630 |
aws/aws-sdk-java | aws-java-sdk-elasticsearch/src/main/java/com/amazonaws/services/elasticsearch/model/UpdateElasticsearchDomainConfigRequest.java | UpdateElasticsearchDomainConfigRequest.withLogPublishingOptions | public UpdateElasticsearchDomainConfigRequest withLogPublishingOptions(java.util.Map<String, LogPublishingOption> logPublishingOptions) {
"""
<p>
Map of <code>LogType</code> and <code>LogPublishingOption</code>, each containing options to publish a given type
of Elasticsearch log.
</p>
@param logPublishingOptions
Map of <code>LogType</code> and <code>LogPublishingOption</code>, each containing options to publish a
given type of Elasticsearch log.
@return Returns a reference to this object so that method calls can be chained together.
"""
setLogPublishingOptions(logPublishingOptions);
return this;
} | java | public UpdateElasticsearchDomainConfigRequest withLogPublishingOptions(java.util.Map<String, LogPublishingOption> logPublishingOptions) {
setLogPublishingOptions(logPublishingOptions);
return this;
} | [
"public",
"UpdateElasticsearchDomainConfigRequest",
"withLogPublishingOptions",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"LogPublishingOption",
">",
"logPublishingOptions",
")",
"{",
"setLogPublishingOptions",
"(",
"logPublishingOptions",
")",
";",
"return",
"this",
";",
"}"
]
| <p>
Map of <code>LogType</code> and <code>LogPublishingOption</code>, each containing options to publish a given type
of Elasticsearch log.
</p>
@param logPublishingOptions
Map of <code>LogType</code> and <code>LogPublishingOption</code>, each containing options to publish a
given type of Elasticsearch log.
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"Map",
"of",
"<code",
">",
"LogType<",
"/",
"code",
">",
"and",
"<code",
">",
"LogPublishingOption<",
"/",
"code",
">",
"each",
"containing",
"options",
"to",
"publish",
"a",
"given",
"type",
"of",
"Elasticsearch",
"log",
".",
"<",
"/",
"p",
">"
]
| train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-elasticsearch/src/main/java/com/amazonaws/services/elasticsearch/model/UpdateElasticsearchDomainConfigRequest.java#L522-L525 |
bazaarvoice/emodb | sor/src/main/java/com/bazaarvoice/emodb/sor/db/astyanax/AstyanaxBlockedDataReaderDAO.java | AstyanaxBlockedDataReaderDAO.rowScan | private Iterator<Row<ByteBuffer, DeltaKey>> rowScan(final DeltaPlacement placement,
final ByteBufferRange rowRange,
final ByteBufferRange columnRange,
final LimitCounter limit,
final ReadConsistency consistency) {
"""
Scans for rows within the specified range, exclusive on start and inclusive on end.
"""
return rowScan(placement, placement.getBlockedDeltaColumnFamily(), rowRange, columnRange, limit, consistency);
} | java | private Iterator<Row<ByteBuffer, DeltaKey>> rowScan(final DeltaPlacement placement,
final ByteBufferRange rowRange,
final ByteBufferRange columnRange,
final LimitCounter limit,
final ReadConsistency consistency) {
return rowScan(placement, placement.getBlockedDeltaColumnFamily(), rowRange, columnRange, limit, consistency);
} | [
"private",
"Iterator",
"<",
"Row",
"<",
"ByteBuffer",
",",
"DeltaKey",
">",
">",
"rowScan",
"(",
"final",
"DeltaPlacement",
"placement",
",",
"final",
"ByteBufferRange",
"rowRange",
",",
"final",
"ByteBufferRange",
"columnRange",
",",
"final",
"LimitCounter",
"limit",
",",
"final",
"ReadConsistency",
"consistency",
")",
"{",
"return",
"rowScan",
"(",
"placement",
",",
"placement",
".",
"getBlockedDeltaColumnFamily",
"(",
")",
",",
"rowRange",
",",
"columnRange",
",",
"limit",
",",
"consistency",
")",
";",
"}"
]
| Scans for rows within the specified range, exclusive on start and inclusive on end. | [
"Scans",
"for",
"rows",
"within",
"the",
"specified",
"range",
"exclusive",
"on",
"start",
"and",
"inclusive",
"on",
"end",
"."
]
| train | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/sor/src/main/java/com/bazaarvoice/emodb/sor/db/astyanax/AstyanaxBlockedDataReaderDAO.java#L809-L815 |
google/closure-compiler | src/com/google/javascript/jscomp/PolymerPassStaticUtils.java | PolymerPassStaticUtils.quoteListenerAndHostAttributeKeys | static void quoteListenerAndHostAttributeKeys(Node objLit, AbstractCompiler compiler) {
"""
Makes sure that the keys for listeners and hostAttributes blocks are quoted to avoid renaming.
"""
checkState(objLit.isObjectLit());
for (Node keyNode : objLit.children()) {
if (keyNode.isComputedProp()) {
continue;
}
if (!keyNode.getString().equals("listeners")
&& !keyNode.getString().equals("hostAttributes")) {
continue;
}
for (Node keyToQuote : keyNode.getFirstChild().children()) {
if (!keyToQuote.isQuotedString()) {
keyToQuote.setQuotedString();
compiler.reportChangeToEnclosingScope(keyToQuote);
}
}
}
} | java | static void quoteListenerAndHostAttributeKeys(Node objLit, AbstractCompiler compiler) {
checkState(objLit.isObjectLit());
for (Node keyNode : objLit.children()) {
if (keyNode.isComputedProp()) {
continue;
}
if (!keyNode.getString().equals("listeners")
&& !keyNode.getString().equals("hostAttributes")) {
continue;
}
for (Node keyToQuote : keyNode.getFirstChild().children()) {
if (!keyToQuote.isQuotedString()) {
keyToQuote.setQuotedString();
compiler.reportChangeToEnclosingScope(keyToQuote);
}
}
}
} | [
"static",
"void",
"quoteListenerAndHostAttributeKeys",
"(",
"Node",
"objLit",
",",
"AbstractCompiler",
"compiler",
")",
"{",
"checkState",
"(",
"objLit",
".",
"isObjectLit",
"(",
")",
")",
";",
"for",
"(",
"Node",
"keyNode",
":",
"objLit",
".",
"children",
"(",
")",
")",
"{",
"if",
"(",
"keyNode",
".",
"isComputedProp",
"(",
")",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"!",
"keyNode",
".",
"getString",
"(",
")",
".",
"equals",
"(",
"\"listeners\"",
")",
"&&",
"!",
"keyNode",
".",
"getString",
"(",
")",
".",
"equals",
"(",
"\"hostAttributes\"",
")",
")",
"{",
"continue",
";",
"}",
"for",
"(",
"Node",
"keyToQuote",
":",
"keyNode",
".",
"getFirstChild",
"(",
")",
".",
"children",
"(",
")",
")",
"{",
"if",
"(",
"!",
"keyToQuote",
".",
"isQuotedString",
"(",
")",
")",
"{",
"keyToQuote",
".",
"setQuotedString",
"(",
")",
";",
"compiler",
".",
"reportChangeToEnclosingScope",
"(",
"keyToQuote",
")",
";",
"}",
"}",
"}",
"}"
]
| Makes sure that the keys for listeners and hostAttributes blocks are quoted to avoid renaming. | [
"Makes",
"sure",
"that",
"the",
"keys",
"for",
"listeners",
"and",
"hostAttributes",
"blocks",
"are",
"quoted",
"to",
"avoid",
"renaming",
"."
]
| train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PolymerPassStaticUtils.java#L109-L126 |
groovy/groovy-core | src/main/org/codehaus/groovy/classgen/asm/MopWriter.java | MopWriter.generateMopCalls | protected void generateMopCalls(LinkedList<MethodNode> mopCalls, boolean useThis) {
"""
generates a Meta Object Protocol method, that is used to call a non public
method, or to make a call to super.
@param mopCalls list of methods a mop call method should be generated for
@param useThis true if "this" should be used for the naming
"""
for (MethodNode method : mopCalls) {
String name = getMopMethodName(method, useThis);
Parameter[] parameters = method.getParameters();
String methodDescriptor = BytecodeHelper.getMethodDescriptor(method.getReturnType(), method.getParameters());
MethodVisitor mv = controller.getClassVisitor().visitMethod(ACC_PUBLIC | ACC_SYNTHETIC, name, methodDescriptor, null, null);
controller.setMethodVisitor(mv);
mv.visitVarInsn(ALOAD, 0);
int newRegister = 1;
OperandStack operandStack = controller.getOperandStack();
for (Parameter parameter : parameters) {
ClassNode type = parameter.getType();
operandStack.load(parameter.getType(), newRegister);
// increment to next register, double/long are using two places
newRegister++;
if (type == ClassHelper.double_TYPE || type == ClassHelper.long_TYPE) newRegister++;
}
operandStack.remove(parameters.length);
ClassNode declaringClass = method.getDeclaringClass();
// JDK 8 support for default methods in interfaces
// this should probably be strenghtened when we support the A.super.foo() syntax
int opcode = declaringClass.isInterface()?INVOKEINTERFACE:INVOKESPECIAL;
mv.visitMethodInsn(opcode, BytecodeHelper.getClassInternalName(declaringClass), method.getName(), methodDescriptor, opcode == INVOKEINTERFACE);
BytecodeHelper.doReturn(mv, method.getReturnType());
mv.visitMaxs(0, 0);
mv.visitEnd();
controller.getClassNode().addMethod(name, ACC_PUBLIC | ACC_SYNTHETIC, method.getReturnType(), parameters, null, null);
}
} | java | protected void generateMopCalls(LinkedList<MethodNode> mopCalls, boolean useThis) {
for (MethodNode method : mopCalls) {
String name = getMopMethodName(method, useThis);
Parameter[] parameters = method.getParameters();
String methodDescriptor = BytecodeHelper.getMethodDescriptor(method.getReturnType(), method.getParameters());
MethodVisitor mv = controller.getClassVisitor().visitMethod(ACC_PUBLIC | ACC_SYNTHETIC, name, methodDescriptor, null, null);
controller.setMethodVisitor(mv);
mv.visitVarInsn(ALOAD, 0);
int newRegister = 1;
OperandStack operandStack = controller.getOperandStack();
for (Parameter parameter : parameters) {
ClassNode type = parameter.getType();
operandStack.load(parameter.getType(), newRegister);
// increment to next register, double/long are using two places
newRegister++;
if (type == ClassHelper.double_TYPE || type == ClassHelper.long_TYPE) newRegister++;
}
operandStack.remove(parameters.length);
ClassNode declaringClass = method.getDeclaringClass();
// JDK 8 support for default methods in interfaces
// this should probably be strenghtened when we support the A.super.foo() syntax
int opcode = declaringClass.isInterface()?INVOKEINTERFACE:INVOKESPECIAL;
mv.visitMethodInsn(opcode, BytecodeHelper.getClassInternalName(declaringClass), method.getName(), methodDescriptor, opcode == INVOKEINTERFACE);
BytecodeHelper.doReturn(mv, method.getReturnType());
mv.visitMaxs(0, 0);
mv.visitEnd();
controller.getClassNode().addMethod(name, ACC_PUBLIC | ACC_SYNTHETIC, method.getReturnType(), parameters, null, null);
}
} | [
"protected",
"void",
"generateMopCalls",
"(",
"LinkedList",
"<",
"MethodNode",
">",
"mopCalls",
",",
"boolean",
"useThis",
")",
"{",
"for",
"(",
"MethodNode",
"method",
":",
"mopCalls",
")",
"{",
"String",
"name",
"=",
"getMopMethodName",
"(",
"method",
",",
"useThis",
")",
";",
"Parameter",
"[",
"]",
"parameters",
"=",
"method",
".",
"getParameters",
"(",
")",
";",
"String",
"methodDescriptor",
"=",
"BytecodeHelper",
".",
"getMethodDescriptor",
"(",
"method",
".",
"getReturnType",
"(",
")",
",",
"method",
".",
"getParameters",
"(",
")",
")",
";",
"MethodVisitor",
"mv",
"=",
"controller",
".",
"getClassVisitor",
"(",
")",
".",
"visitMethod",
"(",
"ACC_PUBLIC",
"|",
"ACC_SYNTHETIC",
",",
"name",
",",
"methodDescriptor",
",",
"null",
",",
"null",
")",
";",
"controller",
".",
"setMethodVisitor",
"(",
"mv",
")",
";",
"mv",
".",
"visitVarInsn",
"(",
"ALOAD",
",",
"0",
")",
";",
"int",
"newRegister",
"=",
"1",
";",
"OperandStack",
"operandStack",
"=",
"controller",
".",
"getOperandStack",
"(",
")",
";",
"for",
"(",
"Parameter",
"parameter",
":",
"parameters",
")",
"{",
"ClassNode",
"type",
"=",
"parameter",
".",
"getType",
"(",
")",
";",
"operandStack",
".",
"load",
"(",
"parameter",
".",
"getType",
"(",
")",
",",
"newRegister",
")",
";",
"// increment to next register, double/long are using two places",
"newRegister",
"++",
";",
"if",
"(",
"type",
"==",
"ClassHelper",
".",
"double_TYPE",
"||",
"type",
"==",
"ClassHelper",
".",
"long_TYPE",
")",
"newRegister",
"++",
";",
"}",
"operandStack",
".",
"remove",
"(",
"parameters",
".",
"length",
")",
";",
"ClassNode",
"declaringClass",
"=",
"method",
".",
"getDeclaringClass",
"(",
")",
";",
"// JDK 8 support for default methods in interfaces",
"// this should probably be strenghtened when we support the A.super.foo() syntax",
"int",
"opcode",
"=",
"declaringClass",
".",
"isInterface",
"(",
")",
"?",
"INVOKEINTERFACE",
":",
"INVOKESPECIAL",
";",
"mv",
".",
"visitMethodInsn",
"(",
"opcode",
",",
"BytecodeHelper",
".",
"getClassInternalName",
"(",
"declaringClass",
")",
",",
"method",
".",
"getName",
"(",
")",
",",
"methodDescriptor",
",",
"opcode",
"==",
"INVOKEINTERFACE",
")",
";",
"BytecodeHelper",
".",
"doReturn",
"(",
"mv",
",",
"method",
".",
"getReturnType",
"(",
")",
")",
";",
"mv",
".",
"visitMaxs",
"(",
"0",
",",
"0",
")",
";",
"mv",
".",
"visitEnd",
"(",
")",
";",
"controller",
".",
"getClassNode",
"(",
")",
".",
"addMethod",
"(",
"name",
",",
"ACC_PUBLIC",
"|",
"ACC_SYNTHETIC",
",",
"method",
".",
"getReturnType",
"(",
")",
",",
"parameters",
",",
"null",
",",
"null",
")",
";",
"}",
"}"
]
| generates a Meta Object Protocol method, that is used to call a non public
method, or to make a call to super.
@param mopCalls list of methods a mop call method should be generated for
@param useThis true if "this" should be used for the naming | [
"generates",
"a",
"Meta",
"Object",
"Protocol",
"method",
"that",
"is",
"used",
"to",
"call",
"a",
"non",
"public",
"method",
"or",
"to",
"make",
"a",
"call",
"to",
"super",
"."
]
| train | https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/classgen/asm/MopWriter.java#L174-L202 |
mapsforge/mapsforge | sqlite-android/src/main/java/org/sqlite/database/DatabaseUtils.java | DatabaseUtils.longForQuery | public static long longForQuery(SQLiteDatabase db, String query, String[] selectionArgs) {
"""
Utility method to run the query on the db and return the value in the
first column of the first row.
"""
SQLiteStatement prog = db.compileStatement(query);
try {
return longForQuery(prog, selectionArgs);
} finally {
prog.close();
}
} | java | public static long longForQuery(SQLiteDatabase db, String query, String[] selectionArgs) {
SQLiteStatement prog = db.compileStatement(query);
try {
return longForQuery(prog, selectionArgs);
} finally {
prog.close();
}
} | [
"public",
"static",
"long",
"longForQuery",
"(",
"SQLiteDatabase",
"db",
",",
"String",
"query",
",",
"String",
"[",
"]",
"selectionArgs",
")",
"{",
"SQLiteStatement",
"prog",
"=",
"db",
".",
"compileStatement",
"(",
"query",
")",
";",
"try",
"{",
"return",
"longForQuery",
"(",
"prog",
",",
"selectionArgs",
")",
";",
"}",
"finally",
"{",
"prog",
".",
"close",
"(",
")",
";",
"}",
"}"
]
| Utility method to run the query on the db and return the value in the
first column of the first row. | [
"Utility",
"method",
"to",
"run",
"the",
"query",
"on",
"the",
"db",
"and",
"return",
"the",
"value",
"in",
"the",
"first",
"column",
"of",
"the",
"first",
"row",
"."
]
| train | https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/sqlite-android/src/main/java/org/sqlite/database/DatabaseUtils.java#L832-L839 |
spotbugs/spotbugs | spotbugs/src/main/java/edu/umd/cs/findbugs/visitclass/AnnotationVisitor.java | AnnotationVisitor.visitAnnotation | public void visitAnnotation(@DottedClassName String annotationClass, Map<String, ElementValue> map, boolean runtimeVisible) {
"""
Visit annotation on a class, field or method
@param annotationClass
class of annotation
@param map
map from names to values
@param runtimeVisible
true if annotation is runtime visible
"""
if (DEBUG) {
System.out.println("Annotation: " + annotationClass);
for (Map.Entry<String, ElementValue> e : map.entrySet()) {
System.out.println(" " + e.getKey());
System.out.println(" -> " + e.getValue());
}
}
} | java | public void visitAnnotation(@DottedClassName String annotationClass, Map<String, ElementValue> map, boolean runtimeVisible) {
if (DEBUG) {
System.out.println("Annotation: " + annotationClass);
for (Map.Entry<String, ElementValue> e : map.entrySet()) {
System.out.println(" " + e.getKey());
System.out.println(" -> " + e.getValue());
}
}
} | [
"public",
"void",
"visitAnnotation",
"(",
"@",
"DottedClassName",
"String",
"annotationClass",
",",
"Map",
"<",
"String",
",",
"ElementValue",
">",
"map",
",",
"boolean",
"runtimeVisible",
")",
"{",
"if",
"(",
"DEBUG",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"\"Annotation: \"",
"+",
"annotationClass",
")",
";",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"ElementValue",
">",
"e",
":",
"map",
".",
"entrySet",
"(",
")",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"\" \"",
"+",
"e",
".",
"getKey",
"(",
")",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"\" -> \"",
"+",
"e",
".",
"getValue",
"(",
")",
")",
";",
"}",
"}",
"}"
]
| Visit annotation on a class, field or method
@param annotationClass
class of annotation
@param map
map from names to values
@param runtimeVisible
true if annotation is runtime visible | [
"Visit",
"annotation",
"on",
"a",
"class",
"field",
"or",
"method"
]
| train | https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/visitclass/AnnotationVisitor.java#L60-L68 |
lievendoclo/Valkyrie-RCP | valkyrie-rcp-core/src/main/java/org/valkyriercp/application/session/ApplicationSession.java | ApplicationSession.setUserAttribute | public void setUserAttribute(String key, Object newValue) {
"""
Add a key/value pair to the user attributes map.
@param key
a unique string code.
@param newValue
the associated value.
"""
Object oldValue = userAttributes.put(key, newValue);
propertyChangeSupport.firePropertyChange(key, oldValue, newValue);
propertyChangeSupport.firePropertyChange(USER_ATTRIBUTES, null, userAttributes);
} | java | public void setUserAttribute(String key, Object newValue)
{
Object oldValue = userAttributes.put(key, newValue);
propertyChangeSupport.firePropertyChange(key, oldValue, newValue);
propertyChangeSupport.firePropertyChange(USER_ATTRIBUTES, null, userAttributes);
} | [
"public",
"void",
"setUserAttribute",
"(",
"String",
"key",
",",
"Object",
"newValue",
")",
"{",
"Object",
"oldValue",
"=",
"userAttributes",
".",
"put",
"(",
"key",
",",
"newValue",
")",
";",
"propertyChangeSupport",
".",
"firePropertyChange",
"(",
"key",
",",
"oldValue",
",",
"newValue",
")",
";",
"propertyChangeSupport",
".",
"firePropertyChange",
"(",
"USER_ATTRIBUTES",
",",
"null",
",",
"userAttributes",
")",
";",
"}"
]
| Add a key/value pair to the user attributes map.
@param key
a unique string code.
@param newValue
the associated value. | [
"Add",
"a",
"key",
"/",
"value",
"pair",
"to",
"the",
"user",
"attributes",
"map",
"."
]
| train | https://github.com/lievendoclo/Valkyrie-RCP/blob/6aad6e640b348cda8f3b0841f6e42025233f1eb8/valkyrie-rcp-core/src/main/java/org/valkyriercp/application/session/ApplicationSession.java#L217-L222 |
Samsung/GearVRf | GVRf/Framework/framework/src/main/java/org/gearvrf/animation/GVRBodyTracker.java | GVRBodyTracker.openCamera | protected Camera openCamera() throws CameraAccessException, IOException {
"""
Opens the camera and starts capturing images.
<p>
The default implementation uses <i>ImageFormat.NV21</i>
and tracks at 30fps. It captures 1280 x 960 images.
The width and height is obtained from mWidth and mHeight
so constructors may set this to change the image size.
@return
@throws CameraAccessException
@throws IOException
"""
Camera camera = Camera.open();
if (camera == null)
{
throw new CameraAccessException(CameraAccessException.CAMERA_ERROR);
}
Camera.Parameters params = camera.getParameters();
params.setPreviewSize(mWidth, mHeight);
params.setPreviewFormat(ImageFormat.NV21);
params.setPreviewFpsRange(30000, 30000);
camera.setParameters(params);
camera.setPreviewCallback(new Camera.PreviewCallback()
{
public void onPreviewFrame(byte[] data, Camera camera)
{
setImageData(data);
}
});
return camera;
} | java | protected Camera openCamera() throws CameraAccessException, IOException
{
Camera camera = Camera.open();
if (camera == null)
{
throw new CameraAccessException(CameraAccessException.CAMERA_ERROR);
}
Camera.Parameters params = camera.getParameters();
params.setPreviewSize(mWidth, mHeight);
params.setPreviewFormat(ImageFormat.NV21);
params.setPreviewFpsRange(30000, 30000);
camera.setParameters(params);
camera.setPreviewCallback(new Camera.PreviewCallback()
{
public void onPreviewFrame(byte[] data, Camera camera)
{
setImageData(data);
}
});
return camera;
} | [
"protected",
"Camera",
"openCamera",
"(",
")",
"throws",
"CameraAccessException",
",",
"IOException",
"{",
"Camera",
"camera",
"=",
"Camera",
".",
"open",
"(",
")",
";",
"if",
"(",
"camera",
"==",
"null",
")",
"{",
"throw",
"new",
"CameraAccessException",
"(",
"CameraAccessException",
".",
"CAMERA_ERROR",
")",
";",
"}",
"Camera",
".",
"Parameters",
"params",
"=",
"camera",
".",
"getParameters",
"(",
")",
";",
"params",
".",
"setPreviewSize",
"(",
"mWidth",
",",
"mHeight",
")",
";",
"params",
".",
"setPreviewFormat",
"(",
"ImageFormat",
".",
"NV21",
")",
";",
"params",
".",
"setPreviewFpsRange",
"(",
"30000",
",",
"30000",
")",
";",
"camera",
".",
"setParameters",
"(",
"params",
")",
";",
"camera",
".",
"setPreviewCallback",
"(",
"new",
"Camera",
".",
"PreviewCallback",
"(",
")",
"{",
"public",
"void",
"onPreviewFrame",
"(",
"byte",
"[",
"]",
"data",
",",
"Camera",
"camera",
")",
"{",
"setImageData",
"(",
"data",
")",
";",
"}",
"}",
")",
";",
"return",
"camera",
";",
"}"
]
| Opens the camera and starts capturing images.
<p>
The default implementation uses <i>ImageFormat.NV21</i>
and tracks at 30fps. It captures 1280 x 960 images.
The width and height is obtained from mWidth and mHeight
so constructors may set this to change the image size.
@return
@throws CameraAccessException
@throws IOException | [
"Opens",
"the",
"camera",
"and",
"starts",
"capturing",
"images",
".",
"<p",
">",
"The",
"default",
"implementation",
"uses",
"<i",
">",
"ImageFormat",
".",
"NV21<",
"/",
"i",
">",
"and",
"tracks",
"at",
"30fps",
".",
"It",
"captures",
"1280",
"x",
"960",
"images",
".",
"The",
"width",
"and",
"height",
"is",
"obtained",
"from",
"mWidth",
"and",
"mHeight",
"so",
"constructors",
"may",
"set",
"this",
"to",
"change",
"the",
"image",
"size",
"."
]
| train | https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Framework/framework/src/main/java/org/gearvrf/animation/GVRBodyTracker.java#L314-L336 |
apache/incubator-druid | server/src/main/java/org/apache/druid/discovery/DruidNodeDiscoveryProvider.java | DruidNodeDiscoveryProvider.getForService | public DruidNodeDiscovery getForService(String serviceName) {
"""
Get DruidNodeDiscovery instance to discover nodes that announce given service in its metadata.
"""
return serviceDiscoveryMap.computeIfAbsent(
serviceName,
service -> {
Set<NodeType> nodeTypesToWatch = DruidNodeDiscoveryProvider.SERVICE_TO_NODE_TYPES.get(service);
if (nodeTypesToWatch == null) {
throw new IAE("Unknown service [%s].", service);
}
ServiceDruidNodeDiscovery serviceDiscovery = new ServiceDruidNodeDiscovery(service, nodeTypesToWatch.size());
DruidNodeDiscovery.Listener filteringGatheringUpstreamListener =
serviceDiscovery.filteringUpstreamListener();
for (NodeType nodeType : nodeTypesToWatch) {
getForNodeType(nodeType).registerListener(filteringGatheringUpstreamListener);
}
return serviceDiscovery;
}
);
} | java | public DruidNodeDiscovery getForService(String serviceName)
{
return serviceDiscoveryMap.computeIfAbsent(
serviceName,
service -> {
Set<NodeType> nodeTypesToWatch = DruidNodeDiscoveryProvider.SERVICE_TO_NODE_TYPES.get(service);
if (nodeTypesToWatch == null) {
throw new IAE("Unknown service [%s].", service);
}
ServiceDruidNodeDiscovery serviceDiscovery = new ServiceDruidNodeDiscovery(service, nodeTypesToWatch.size());
DruidNodeDiscovery.Listener filteringGatheringUpstreamListener =
serviceDiscovery.filteringUpstreamListener();
for (NodeType nodeType : nodeTypesToWatch) {
getForNodeType(nodeType).registerListener(filteringGatheringUpstreamListener);
}
return serviceDiscovery;
}
);
} | [
"public",
"DruidNodeDiscovery",
"getForService",
"(",
"String",
"serviceName",
")",
"{",
"return",
"serviceDiscoveryMap",
".",
"computeIfAbsent",
"(",
"serviceName",
",",
"service",
"->",
"{",
"Set",
"<",
"NodeType",
">",
"nodeTypesToWatch",
"=",
"DruidNodeDiscoveryProvider",
".",
"SERVICE_TO_NODE_TYPES",
".",
"get",
"(",
"service",
")",
";",
"if",
"(",
"nodeTypesToWatch",
"==",
"null",
")",
"{",
"throw",
"new",
"IAE",
"(",
"\"Unknown service [%s].\"",
",",
"service",
")",
";",
"}",
"ServiceDruidNodeDiscovery",
"serviceDiscovery",
"=",
"new",
"ServiceDruidNodeDiscovery",
"(",
"service",
",",
"nodeTypesToWatch",
".",
"size",
"(",
")",
")",
";",
"DruidNodeDiscovery",
".",
"Listener",
"filteringGatheringUpstreamListener",
"=",
"serviceDiscovery",
".",
"filteringUpstreamListener",
"(",
")",
";",
"for",
"(",
"NodeType",
"nodeType",
":",
"nodeTypesToWatch",
")",
"{",
"getForNodeType",
"(",
"nodeType",
")",
".",
"registerListener",
"(",
"filteringGatheringUpstreamListener",
")",
";",
"}",
"return",
"serviceDiscovery",
";",
"}",
")",
";",
"}"
]
| Get DruidNodeDiscovery instance to discover nodes that announce given service in its metadata. | [
"Get",
"DruidNodeDiscovery",
"instance",
"to",
"discover",
"nodes",
"that",
"announce",
"given",
"service",
"in",
"its",
"metadata",
"."
]
| train | https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/server/src/main/java/org/apache/druid/discovery/DruidNodeDiscoveryProvider.java#L59-L78 |
Azure/azure-sdk-for-java | batch/data-plane/src/main/java/com/microsoft/azure/batch/JobScheduleOperations.java | JobScheduleOperations.getJobSchedule | public CloudJobSchedule getJobSchedule(String jobScheduleId, DetailLevel detailLevel, Iterable<BatchClientBehavior> additionalBehaviors) throws BatchErrorException, IOException {
"""
Gets the specified {@link CloudJobSchedule}.
@param jobScheduleId The ID of the job schedule.
@param detailLevel A {@link DetailLevel} used for controlling which properties are retrieved from the service.
@param additionalBehaviors A collection of {@link BatchClientBehavior} instances that are applied to the Batch service request.
@return A {@link CloudJobSchedule} containing information about the specified Azure Batch job schedule.
@throws BatchErrorException Exception thrown when an error response is received from the Batch service.
@throws IOException Exception thrown when there is an error in serialization/deserialization of data sent to/received from the Batch service.
"""
JobScheduleGetOptions options = new JobScheduleGetOptions();
BehaviorManager bhMgr = new BehaviorManager(this.customBehaviors(), additionalBehaviors);
bhMgr.appendDetailLevelToPerCallBehaviors(detailLevel);
bhMgr.applyRequestBehaviors(options);
return this.parentBatchClient.protocolLayer().jobSchedules().get(jobScheduleId, options);
} | java | public CloudJobSchedule getJobSchedule(String jobScheduleId, DetailLevel detailLevel, Iterable<BatchClientBehavior> additionalBehaviors) throws BatchErrorException, IOException {
JobScheduleGetOptions options = new JobScheduleGetOptions();
BehaviorManager bhMgr = new BehaviorManager(this.customBehaviors(), additionalBehaviors);
bhMgr.appendDetailLevelToPerCallBehaviors(detailLevel);
bhMgr.applyRequestBehaviors(options);
return this.parentBatchClient.protocolLayer().jobSchedules().get(jobScheduleId, options);
} | [
"public",
"CloudJobSchedule",
"getJobSchedule",
"(",
"String",
"jobScheduleId",
",",
"DetailLevel",
"detailLevel",
",",
"Iterable",
"<",
"BatchClientBehavior",
">",
"additionalBehaviors",
")",
"throws",
"BatchErrorException",
",",
"IOException",
"{",
"JobScheduleGetOptions",
"options",
"=",
"new",
"JobScheduleGetOptions",
"(",
")",
";",
"BehaviorManager",
"bhMgr",
"=",
"new",
"BehaviorManager",
"(",
"this",
".",
"customBehaviors",
"(",
")",
",",
"additionalBehaviors",
")",
";",
"bhMgr",
".",
"appendDetailLevelToPerCallBehaviors",
"(",
"detailLevel",
")",
";",
"bhMgr",
".",
"applyRequestBehaviors",
"(",
"options",
")",
";",
"return",
"this",
".",
"parentBatchClient",
".",
"protocolLayer",
"(",
")",
".",
"jobSchedules",
"(",
")",
".",
"get",
"(",
"jobScheduleId",
",",
"options",
")",
";",
"}"
]
| Gets the specified {@link CloudJobSchedule}.
@param jobScheduleId The ID of the job schedule.
@param detailLevel A {@link DetailLevel} used for controlling which properties are retrieved from the service.
@param additionalBehaviors A collection of {@link BatchClientBehavior} instances that are applied to the Batch service request.
@return A {@link CloudJobSchedule} containing information about the specified Azure Batch job schedule.
@throws BatchErrorException Exception thrown when an error response is received from the Batch service.
@throws IOException Exception thrown when there is an error in serialization/deserialization of data sent to/received from the Batch service. | [
"Gets",
"the",
"specified",
"{",
"@link",
"CloudJobSchedule",
"}",
"."
]
| train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/JobScheduleOperations.java#L159-L166 |
timols/java-gitlab-api | src/main/java/org/gitlab/api/GitlabAPI.java | GitlabAPI.addGroupBadge | public GitlabBadge addGroupBadge(Integer groupId, String linkUrl, String imageUrl) throws IOException {
"""
Add group badge
@param groupId The id of the group for which the badge should be added
@param linkUrl The URL that the badge should link to
@param imageUrl The URL to the badge image
@return The created badge
@throws IOException on GitLab API call error
"""
String tailUrl = GitlabGroup.URL + "/" + groupId + GitlabBadge.URL;
return dispatch().with("link_url", linkUrl)
.with("image_url", imageUrl)
.to(tailUrl, GitlabBadge.class);
} | java | public GitlabBadge addGroupBadge(Integer groupId, String linkUrl, String imageUrl) throws IOException {
String tailUrl = GitlabGroup.URL + "/" + groupId + GitlabBadge.URL;
return dispatch().with("link_url", linkUrl)
.with("image_url", imageUrl)
.to(tailUrl, GitlabBadge.class);
} | [
"public",
"GitlabBadge",
"addGroupBadge",
"(",
"Integer",
"groupId",
",",
"String",
"linkUrl",
",",
"String",
"imageUrl",
")",
"throws",
"IOException",
"{",
"String",
"tailUrl",
"=",
"GitlabGroup",
".",
"URL",
"+",
"\"/\"",
"+",
"groupId",
"+",
"GitlabBadge",
".",
"URL",
";",
"return",
"dispatch",
"(",
")",
".",
"with",
"(",
"\"link_url\"",
",",
"linkUrl",
")",
".",
"with",
"(",
"\"image_url\"",
",",
"imageUrl",
")",
".",
"to",
"(",
"tailUrl",
",",
"GitlabBadge",
".",
"class",
")",
";",
"}"
]
| Add group badge
@param groupId The id of the group for which the badge should be added
@param linkUrl The URL that the badge should link to
@param imageUrl The URL to the badge image
@return The created badge
@throws IOException on GitLab API call error | [
"Add",
"group",
"badge"
]
| train | https://github.com/timols/java-gitlab-api/blob/f03eedf952cfbb40306be3bf9234dcf78fab029e/src/main/java/org/gitlab/api/GitlabAPI.java#L2711-L2716 |
ManfredTremmel/gwt-commons-lang3 | src/main/java/org/apache/commons/lang3/time/DateUtils.java | DateUtils.truncatedCompareTo | public static int truncatedCompareTo(final Calendar cal1, final Calendar cal2, final int field) {
"""
Determines how two calendars compare up to no more than the specified
most significant field.
@param cal1 the first calendar, not <code>null</code>
@param cal2 the second calendar, not <code>null</code>
@param field the field from {@code Calendar}
@return a negative integer, zero, or a positive integer as the first
calendar is less than, equal to, or greater than the second.
@throws IllegalArgumentException if any argument is <code>null</code>
@see #truncate(Calendar, int)
@see #truncatedCompareTo(Date, Date, int)
@since 3.0
"""
final Calendar truncatedCal1 = truncate(cal1, field);
final Calendar truncatedCal2 = truncate(cal2, field);
return truncatedCal1.compareTo(truncatedCal2);
} | java | public static int truncatedCompareTo(final Calendar cal1, final Calendar cal2, final int field) {
final Calendar truncatedCal1 = truncate(cal1, field);
final Calendar truncatedCal2 = truncate(cal2, field);
return truncatedCal1.compareTo(truncatedCal2);
} | [
"public",
"static",
"int",
"truncatedCompareTo",
"(",
"final",
"Calendar",
"cal1",
",",
"final",
"Calendar",
"cal2",
",",
"final",
"int",
"field",
")",
"{",
"final",
"Calendar",
"truncatedCal1",
"=",
"truncate",
"(",
"cal1",
",",
"field",
")",
";",
"final",
"Calendar",
"truncatedCal2",
"=",
"truncate",
"(",
"cal2",
",",
"field",
")",
";",
"return",
"truncatedCal1",
".",
"compareTo",
"(",
"truncatedCal2",
")",
";",
"}"
]
| Determines how two calendars compare up to no more than the specified
most significant field.
@param cal1 the first calendar, not <code>null</code>
@param cal2 the second calendar, not <code>null</code>
@param field the field from {@code Calendar}
@return a negative integer, zero, or a positive integer as the first
calendar is less than, equal to, or greater than the second.
@throws IllegalArgumentException if any argument is <code>null</code>
@see #truncate(Calendar, int)
@see #truncatedCompareTo(Date, Date, int)
@since 3.0 | [
"Determines",
"how",
"two",
"calendars",
"compare",
"up",
"to",
"no",
"more",
"than",
"the",
"specified",
"most",
"significant",
"field",
"."
]
| train | https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/time/DateUtils.java#L1778-L1782 |
Mozu/mozu-java | mozu-javaasync-core/src/main/java/com/mozu/api/urls/platform/ReferenceDataUrl.java | ReferenceDataUrl.getBehaviorUrl | public static MozuUrl getBehaviorUrl(Integer behaviorId, String responseFields) {
"""
Get Resource Url for GetBehavior
@param behaviorId Unique identifier of the behavior.
@param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
@return String Resource Url
"""
UrlFormatter formatter = new UrlFormatter("/api/platform/reference/behaviors/{behaviorId}?responseFields={responseFields}");
formatter.formatUrl("behaviorId", behaviorId);
formatter.formatUrl("responseFields", responseFields);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.HOME_POD) ;
} | java | public static MozuUrl getBehaviorUrl(Integer behaviorId, String responseFields)
{
UrlFormatter formatter = new UrlFormatter("/api/platform/reference/behaviors/{behaviorId}?responseFields={responseFields}");
formatter.formatUrl("behaviorId", behaviorId);
formatter.formatUrl("responseFields", responseFields);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.HOME_POD) ;
} | [
"public",
"static",
"MozuUrl",
"getBehaviorUrl",
"(",
"Integer",
"behaviorId",
",",
"String",
"responseFields",
")",
"{",
"UrlFormatter",
"formatter",
"=",
"new",
"UrlFormatter",
"(",
"\"/api/platform/reference/behaviors/{behaviorId}?responseFields={responseFields}\"",
")",
";",
"formatter",
".",
"formatUrl",
"(",
"\"behaviorId\"",
",",
"behaviorId",
")",
";",
"formatter",
".",
"formatUrl",
"(",
"\"responseFields\"",
",",
"responseFields",
")",
";",
"return",
"new",
"MozuUrl",
"(",
"formatter",
".",
"getResourceUrl",
"(",
")",
",",
"MozuUrl",
".",
"UrlLocation",
".",
"HOME_POD",
")",
";",
"}"
]
| Get Resource Url for GetBehavior
@param behaviorId Unique identifier of the behavior.
@param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
@return String Resource Url | [
"Get",
"Resource",
"Url",
"for",
"GetBehavior"
]
| train | https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-javaasync-core/src/main/java/com/mozu/api/urls/platform/ReferenceDataUrl.java#L48-L54 |
cogroo/cogroo4 | cogroo-gc/src/main/java/org/cogroo/tools/checker/rules/util/RuleUtils.java | RuleUtils.useCasedString | public static String useCasedString(String replaceable, String replacement) {
"""
Checks the case of the first char from <code>replaceable</code> and changes the first char from the
<code>replacement</code> accordingly.
@param replaceable
the string that will be replaced
@param replacement
the string that will be used to replace the <code>replaceable</code>
@return the replacement, beginning with upper case if the <code>replaceable</code> begins too or
lower case, if not
"""
String replacementCased = replacement;
if (replacement.length() > 1) {
// If the first char of the replaceable lexeme is upper case...
if (Character.isUpperCase(replaceable.charAt(0))) {
// ... so must be its replacement.
replacementCased = Character.toUpperCase(replacement.charAt(0)) + replacement.substring(1);
} else {
// ... the replacement must be lower case.
replacementCased = Character.toLowerCase(replacement.charAt(0)) + replacement.substring(1);
}
} else if (replacement.length() == 1) {
// If the first char of the replaceable lexeme is upper case...
if (Character.isUpperCase(replaceable.charAt(0))) {
// ... so must be its replacement.
replacementCased = String.valueOf(Character.toUpperCase(replacement.charAt(0)));
} else {
// ... the replacement must be lower case.
replacementCased = String.valueOf(Character.toLowerCase(replacement.charAt(0)));
}
}
return replacementCased;
} | java | public static String useCasedString(String replaceable, String replacement) {
String replacementCased = replacement;
if (replacement.length() > 1) {
// If the first char of the replaceable lexeme is upper case...
if (Character.isUpperCase(replaceable.charAt(0))) {
// ... so must be its replacement.
replacementCased = Character.toUpperCase(replacement.charAt(0)) + replacement.substring(1);
} else {
// ... the replacement must be lower case.
replacementCased = Character.toLowerCase(replacement.charAt(0)) + replacement.substring(1);
}
} else if (replacement.length() == 1) {
// If the first char of the replaceable lexeme is upper case...
if (Character.isUpperCase(replaceable.charAt(0))) {
// ... so must be its replacement.
replacementCased = String.valueOf(Character.toUpperCase(replacement.charAt(0)));
} else {
// ... the replacement must be lower case.
replacementCased = String.valueOf(Character.toLowerCase(replacement.charAt(0)));
}
}
return replacementCased;
} | [
"public",
"static",
"String",
"useCasedString",
"(",
"String",
"replaceable",
",",
"String",
"replacement",
")",
"{",
"String",
"replacementCased",
"=",
"replacement",
";",
"if",
"(",
"replacement",
".",
"length",
"(",
")",
">",
"1",
")",
"{",
"// If the first char of the replaceable lexeme is upper case...\r",
"if",
"(",
"Character",
".",
"isUpperCase",
"(",
"replaceable",
".",
"charAt",
"(",
"0",
")",
")",
")",
"{",
"// ... so must be its replacement.\r",
"replacementCased",
"=",
"Character",
".",
"toUpperCase",
"(",
"replacement",
".",
"charAt",
"(",
"0",
")",
")",
"+",
"replacement",
".",
"substring",
"(",
"1",
")",
";",
"}",
"else",
"{",
"// ... the replacement must be lower case.\r",
"replacementCased",
"=",
"Character",
".",
"toLowerCase",
"(",
"replacement",
".",
"charAt",
"(",
"0",
")",
")",
"+",
"replacement",
".",
"substring",
"(",
"1",
")",
";",
"}",
"}",
"else",
"if",
"(",
"replacement",
".",
"length",
"(",
")",
"==",
"1",
")",
"{",
"// If the first char of the replaceable lexeme is upper case...\r",
"if",
"(",
"Character",
".",
"isUpperCase",
"(",
"replaceable",
".",
"charAt",
"(",
"0",
")",
")",
")",
"{",
"// ... so must be its replacement.\r",
"replacementCased",
"=",
"String",
".",
"valueOf",
"(",
"Character",
".",
"toUpperCase",
"(",
"replacement",
".",
"charAt",
"(",
"0",
")",
")",
")",
";",
"}",
"else",
"{",
"// ... the replacement must be lower case.\r",
"replacementCased",
"=",
"String",
".",
"valueOf",
"(",
"Character",
".",
"toLowerCase",
"(",
"replacement",
".",
"charAt",
"(",
"0",
")",
")",
")",
";",
"}",
"}",
"return",
"replacementCased",
";",
"}"
]
| Checks the case of the first char from <code>replaceable</code> and changes the first char from the
<code>replacement</code> accordingly.
@param replaceable
the string that will be replaced
@param replacement
the string that will be used to replace the <code>replaceable</code>
@return the replacement, beginning with upper case if the <code>replaceable</code> begins too or
lower case, if not | [
"Checks",
"the",
"case",
"of",
"the",
"first",
"char",
"from",
"<code",
">",
"replaceable<",
"/",
"code",
">",
"and",
"changes",
"the",
"first",
"char",
"from",
"the",
"<code",
">",
"replacement<",
"/",
"code",
">",
"accordingly",
"."
]
| train | https://github.com/cogroo/cogroo4/blob/b6228900c20c6b37eac10a03708a9669dd562f52/cogroo-gc/src/main/java/org/cogroo/tools/checker/rules/util/RuleUtils.java#L450-L472 |
FasterXML/woodstox | src/main/java/com/ctc/wstx/dtd/DTDEnumAttr.java | DTDEnumAttr.validate | @Override
public String validate(DTDValidatorBase v, char[] cbuf, int start, int end, boolean normalize)
throws XMLStreamException {
"""
Method called by the validator
to let the attribute do necessary normalization and/or validation
for the value.
"""
String ok = validateEnumValue(cbuf, start, end, normalize, mEnumValues);
if (ok == null) {
String val = new String(cbuf, start, (end-start));
return reportValidationProblem(v, "Invalid enumerated value '"+val+"': has to be one of ("
+mEnumValues+")");
}
return ok;
} | java | @Override
public String validate(DTDValidatorBase v, char[] cbuf, int start, int end, boolean normalize)
throws XMLStreamException
{
String ok = validateEnumValue(cbuf, start, end, normalize, mEnumValues);
if (ok == null) {
String val = new String(cbuf, start, (end-start));
return reportValidationProblem(v, "Invalid enumerated value '"+val+"': has to be one of ("
+mEnumValues+")");
}
return ok;
} | [
"@",
"Override",
"public",
"String",
"validate",
"(",
"DTDValidatorBase",
"v",
",",
"char",
"[",
"]",
"cbuf",
",",
"int",
"start",
",",
"int",
"end",
",",
"boolean",
"normalize",
")",
"throws",
"XMLStreamException",
"{",
"String",
"ok",
"=",
"validateEnumValue",
"(",
"cbuf",
",",
"start",
",",
"end",
",",
"normalize",
",",
"mEnumValues",
")",
";",
"if",
"(",
"ok",
"==",
"null",
")",
"{",
"String",
"val",
"=",
"new",
"String",
"(",
"cbuf",
",",
"start",
",",
"(",
"end",
"-",
"start",
")",
")",
";",
"return",
"reportValidationProblem",
"(",
"v",
",",
"\"Invalid enumerated value '\"",
"+",
"val",
"+",
"\"': has to be one of (\"",
"+",
"mEnumValues",
"+",
"\")\"",
")",
";",
"}",
"return",
"ok",
";",
"}"
]
| Method called by the validator
to let the attribute do necessary normalization and/or validation
for the value. | [
"Method",
"called",
"by",
"the",
"validator",
"to",
"let",
"the",
"attribute",
"do",
"necessary",
"normalization",
"and",
"/",
"or",
"validation",
"for",
"the",
"value",
"."
]
| train | https://github.com/FasterXML/woodstox/blob/ffcaabdc06672d9564c48c25d601d029b7fd6548/src/main/java/com/ctc/wstx/dtd/DTDEnumAttr.java#L60-L71 |
xm-online/xm-commons | xm-commons-lep/src/main/java/com/icthh/xm/commons/lep/XmGroovyExecutionStrategy.java | XmGroovyExecutionStrategy.onWithoutAroundScript | private Object onWithoutAroundScript(UrlLepResourceKey compositeResourceKey,
Map<XmLepResourceSubType, UrlLepResourceKey> atomicResourceKeys,
LepMethod method,
LepManagerService managerService,
Supplier<GroovyScriptRunner> resourceExecutorSupplier)
throws LepInvocationCauseException {
"""
BEFORE and/or TENANT and/or DEFAULT and/or AFTER script call case
"""
Object target = method.getTarget();
// Call BEFORE script if it exists
executeBeforeIfExists(atomicResourceKeys, method, managerService, resourceExecutorSupplier);
MethodResultProcessor methodResultProcessor;
if (atomicResourceKeys.containsKey(TENANT)) {
// Call TENANT script if it exists
methodResultProcessor = executeLepScript(atomicResourceKeys, method, managerService, resourceExecutorSupplier,
TENANT);
} else if (atomicResourceKeys.containsKey(DEFAULT)) {
// Call DEFAULT script if it exists
methodResultProcessor = executeLepScript(atomicResourceKeys, method, managerService, resourceExecutorSupplier,
DEFAULT);
} else {
// Call method on target object
methodResultProcessor = executeLepTargetMethod(compositeResourceKey, method, target);
}
// Call AFTER script if it exists
methodResultProcessor = executeAfterScriptIfExists(atomicResourceKeys,
method,
managerService,
resourceExecutorSupplier,
methodResultProcessor);
return methodResultProcessor.processResult();
} | java | private Object onWithoutAroundScript(UrlLepResourceKey compositeResourceKey,
Map<XmLepResourceSubType, UrlLepResourceKey> atomicResourceKeys,
LepMethod method,
LepManagerService managerService,
Supplier<GroovyScriptRunner> resourceExecutorSupplier)
throws LepInvocationCauseException {
Object target = method.getTarget();
// Call BEFORE script if it exists
executeBeforeIfExists(atomicResourceKeys, method, managerService, resourceExecutorSupplier);
MethodResultProcessor methodResultProcessor;
if (atomicResourceKeys.containsKey(TENANT)) {
// Call TENANT script if it exists
methodResultProcessor = executeLepScript(atomicResourceKeys, method, managerService, resourceExecutorSupplier,
TENANT);
} else if (atomicResourceKeys.containsKey(DEFAULT)) {
// Call DEFAULT script if it exists
methodResultProcessor = executeLepScript(atomicResourceKeys, method, managerService, resourceExecutorSupplier,
DEFAULT);
} else {
// Call method on target object
methodResultProcessor = executeLepTargetMethod(compositeResourceKey, method, target);
}
// Call AFTER script if it exists
methodResultProcessor = executeAfterScriptIfExists(atomicResourceKeys,
method,
managerService,
resourceExecutorSupplier,
methodResultProcessor);
return methodResultProcessor.processResult();
} | [
"private",
"Object",
"onWithoutAroundScript",
"(",
"UrlLepResourceKey",
"compositeResourceKey",
",",
"Map",
"<",
"XmLepResourceSubType",
",",
"UrlLepResourceKey",
">",
"atomicResourceKeys",
",",
"LepMethod",
"method",
",",
"LepManagerService",
"managerService",
",",
"Supplier",
"<",
"GroovyScriptRunner",
">",
"resourceExecutorSupplier",
")",
"throws",
"LepInvocationCauseException",
"{",
"Object",
"target",
"=",
"method",
".",
"getTarget",
"(",
")",
";",
"// Call BEFORE script if it exists",
"executeBeforeIfExists",
"(",
"atomicResourceKeys",
",",
"method",
",",
"managerService",
",",
"resourceExecutorSupplier",
")",
";",
"MethodResultProcessor",
"methodResultProcessor",
";",
"if",
"(",
"atomicResourceKeys",
".",
"containsKey",
"(",
"TENANT",
")",
")",
"{",
"// Call TENANT script if it exists",
"methodResultProcessor",
"=",
"executeLepScript",
"(",
"atomicResourceKeys",
",",
"method",
",",
"managerService",
",",
"resourceExecutorSupplier",
",",
"TENANT",
")",
";",
"}",
"else",
"if",
"(",
"atomicResourceKeys",
".",
"containsKey",
"(",
"DEFAULT",
")",
")",
"{",
"// Call DEFAULT script if it exists",
"methodResultProcessor",
"=",
"executeLepScript",
"(",
"atomicResourceKeys",
",",
"method",
",",
"managerService",
",",
"resourceExecutorSupplier",
",",
"DEFAULT",
")",
";",
"}",
"else",
"{",
"// Call method on target object",
"methodResultProcessor",
"=",
"executeLepTargetMethod",
"(",
"compositeResourceKey",
",",
"method",
",",
"target",
")",
";",
"}",
"// Call AFTER script if it exists",
"methodResultProcessor",
"=",
"executeAfterScriptIfExists",
"(",
"atomicResourceKeys",
",",
"method",
",",
"managerService",
",",
"resourceExecutorSupplier",
",",
"methodResultProcessor",
")",
";",
"return",
"methodResultProcessor",
".",
"processResult",
"(",
")",
";",
"}"
]
| BEFORE and/or TENANT and/or DEFAULT and/or AFTER script call case | [
"BEFORE",
"and",
"/",
"or",
"TENANT",
"and",
"/",
"or",
"DEFAULT",
"and",
"/",
"or",
"AFTER",
"script",
"call",
"case"
]
| train | https://github.com/xm-online/xm-commons/blob/43eb2273adb96f40830d7b905ee3a767b8715caf/xm-commons-lep/src/main/java/com/icthh/xm/commons/lep/XmGroovyExecutionStrategy.java#L141-L176 |
exoplatform/jcr | exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/lucene/SearchIndex.java | SearchIndex.executeQuery | public MultiColumnQueryHits executeQuery(SessionImpl session, AbstractQueryImpl queryImpl, Query query,
QPath[] orderProps, boolean[] orderSpecs, long resultFetchHint) throws IOException, RepositoryException {
"""
Executes the query on the search index.
@param session
the session that executes the query.
@param queryImpl
the query impl.
@param query
the lucene query.
@param orderProps
name of the properties for sort order.
@param orderSpecs
the order specs for the sort order properties.
<code>true</code> indicates ascending order,
<code>false</code> indicates descending.
@param resultFetchHint
a hint on how many results should be fetched.
@return the query hits.
@throws IOException
if an error occurs while searching the index.
@throws RepositoryException
"""
waitForResuming();
checkOpen();
workingThreads.incrementAndGet();
try
{
FieldComparatorSource scs = queryImpl.isCaseInsensitiveOrder() ? this.sics : this.scs;
Sort sort = new Sort(createSortFields(orderProps, orderSpecs, scs));
final IndexReader reader = getIndexReader(queryImpl.needsSystemTree());
@SuppressWarnings("resource")
JcrIndexSearcher searcher = new JcrIndexSearcher(session, reader, getContext().getItemStateManager());
searcher.setSimilarity(getSimilarity());
return new FilterMultiColumnQueryHits(searcher.execute(query, sort, resultFetchHint,
QueryImpl.DEFAULT_SELECTOR_NAME))
{
@Override
public void close() throws IOException
{
try
{
super.close();
}
finally
{
PerQueryCache.getInstance().dispose();
Util.closeOrRelease(reader);
}
}
};
}
finally
{
workingThreads.decrementAndGet();
if (isSuspended.get() && workingThreads.get() == 0)
{
synchronized (workingThreads)
{
workingThreads.notifyAll();
}
}
}
} | java | public MultiColumnQueryHits executeQuery(SessionImpl session, AbstractQueryImpl queryImpl, Query query,
QPath[] orderProps, boolean[] orderSpecs, long resultFetchHint) throws IOException, RepositoryException
{
waitForResuming();
checkOpen();
workingThreads.incrementAndGet();
try
{
FieldComparatorSource scs = queryImpl.isCaseInsensitiveOrder() ? this.sics : this.scs;
Sort sort = new Sort(createSortFields(orderProps, orderSpecs, scs));
final IndexReader reader = getIndexReader(queryImpl.needsSystemTree());
@SuppressWarnings("resource")
JcrIndexSearcher searcher = new JcrIndexSearcher(session, reader, getContext().getItemStateManager());
searcher.setSimilarity(getSimilarity());
return new FilterMultiColumnQueryHits(searcher.execute(query, sort, resultFetchHint,
QueryImpl.DEFAULT_SELECTOR_NAME))
{
@Override
public void close() throws IOException
{
try
{
super.close();
}
finally
{
PerQueryCache.getInstance().dispose();
Util.closeOrRelease(reader);
}
}
};
}
finally
{
workingThreads.decrementAndGet();
if (isSuspended.get() && workingThreads.get() == 0)
{
synchronized (workingThreads)
{
workingThreads.notifyAll();
}
}
}
} | [
"public",
"MultiColumnQueryHits",
"executeQuery",
"(",
"SessionImpl",
"session",
",",
"AbstractQueryImpl",
"queryImpl",
",",
"Query",
"query",
",",
"QPath",
"[",
"]",
"orderProps",
",",
"boolean",
"[",
"]",
"orderSpecs",
",",
"long",
"resultFetchHint",
")",
"throws",
"IOException",
",",
"RepositoryException",
"{",
"waitForResuming",
"(",
")",
";",
"checkOpen",
"(",
")",
";",
"workingThreads",
".",
"incrementAndGet",
"(",
")",
";",
"try",
"{",
"FieldComparatorSource",
"scs",
"=",
"queryImpl",
".",
"isCaseInsensitiveOrder",
"(",
")",
"?",
"this",
".",
"sics",
":",
"this",
".",
"scs",
";",
"Sort",
"sort",
"=",
"new",
"Sort",
"(",
"createSortFields",
"(",
"orderProps",
",",
"orderSpecs",
",",
"scs",
")",
")",
";",
"final",
"IndexReader",
"reader",
"=",
"getIndexReader",
"(",
"queryImpl",
".",
"needsSystemTree",
"(",
")",
")",
";",
"@",
"SuppressWarnings",
"(",
"\"resource\"",
")",
"JcrIndexSearcher",
"searcher",
"=",
"new",
"JcrIndexSearcher",
"(",
"session",
",",
"reader",
",",
"getContext",
"(",
")",
".",
"getItemStateManager",
"(",
")",
")",
";",
"searcher",
".",
"setSimilarity",
"(",
"getSimilarity",
"(",
")",
")",
";",
"return",
"new",
"FilterMultiColumnQueryHits",
"(",
"searcher",
".",
"execute",
"(",
"query",
",",
"sort",
",",
"resultFetchHint",
",",
"QueryImpl",
".",
"DEFAULT_SELECTOR_NAME",
")",
")",
"{",
"@",
"Override",
"public",
"void",
"close",
"(",
")",
"throws",
"IOException",
"{",
"try",
"{",
"super",
".",
"close",
"(",
")",
";",
"}",
"finally",
"{",
"PerQueryCache",
".",
"getInstance",
"(",
")",
".",
"dispose",
"(",
")",
";",
"Util",
".",
"closeOrRelease",
"(",
"reader",
")",
";",
"}",
"}",
"}",
";",
"}",
"finally",
"{",
"workingThreads",
".",
"decrementAndGet",
"(",
")",
";",
"if",
"(",
"isSuspended",
".",
"get",
"(",
")",
"&&",
"workingThreads",
".",
"get",
"(",
")",
"==",
"0",
")",
"{",
"synchronized",
"(",
"workingThreads",
")",
"{",
"workingThreads",
".",
"notifyAll",
"(",
")",
";",
"}",
"}",
"}",
"}"
]
| Executes the query on the search index.
@param session
the session that executes the query.
@param queryImpl
the query impl.
@param query
the lucene query.
@param orderProps
name of the properties for sort order.
@param orderSpecs
the order specs for the sort order properties.
<code>true</code> indicates ascending order,
<code>false</code> indicates descending.
@param resultFetchHint
a hint on how many results should be fetched.
@return the query hits.
@throws IOException
if an error occurs while searching the index.
@throws RepositoryException | [
"Executes",
"the",
"query",
"on",
"the",
"search",
"index",
"."
]
| train | https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/lucene/SearchIndex.java#L1528-L1575 |
avianey/facebook-api-android-maven | facebook/src/main/java/com/facebook/TokenCachingStrategy.java | TokenCachingStrategy.putDeclinedPermissions | public static void putDeclinedPermissions(Bundle bundle, List<String> value) {
"""
Puts the list of declined permissions into a Bundle.
@param bundle
A Bundle in which the list of permissions should be stored.
@param value
The List<String> representing the list of permissions,
or null.
@throws NullPointerException if the passed in Bundle or permissions list are null
"""
Validate.notNull(bundle, "bundle");
Validate.notNull(value, "value");
ArrayList<String> arrayList;
if (value instanceof ArrayList<?>) {
arrayList = (ArrayList<String>) value;
} else {
arrayList = new ArrayList<String>(value);
}
bundle.putStringArrayList(DECLINED_PERMISSIONS_KEY, arrayList);
} | java | public static void putDeclinedPermissions(Bundle bundle, List<String> value) {
Validate.notNull(bundle, "bundle");
Validate.notNull(value, "value");
ArrayList<String> arrayList;
if (value instanceof ArrayList<?>) {
arrayList = (ArrayList<String>) value;
} else {
arrayList = new ArrayList<String>(value);
}
bundle.putStringArrayList(DECLINED_PERMISSIONS_KEY, arrayList);
} | [
"public",
"static",
"void",
"putDeclinedPermissions",
"(",
"Bundle",
"bundle",
",",
"List",
"<",
"String",
">",
"value",
")",
"{",
"Validate",
".",
"notNull",
"(",
"bundle",
",",
"\"bundle\"",
")",
";",
"Validate",
".",
"notNull",
"(",
"value",
",",
"\"value\"",
")",
";",
"ArrayList",
"<",
"String",
">",
"arrayList",
";",
"if",
"(",
"value",
"instanceof",
"ArrayList",
"<",
"?",
">",
")",
"{",
"arrayList",
"=",
"(",
"ArrayList",
"<",
"String",
">",
")",
"value",
";",
"}",
"else",
"{",
"arrayList",
"=",
"new",
"ArrayList",
"<",
"String",
">",
"(",
"value",
")",
";",
"}",
"bundle",
".",
"putStringArrayList",
"(",
"DECLINED_PERMISSIONS_KEY",
",",
"arrayList",
")",
";",
"}"
]
| Puts the list of declined permissions into a Bundle.
@param bundle
A Bundle in which the list of permissions should be stored.
@param value
The List<String> representing the list of permissions,
or null.
@throws NullPointerException if the passed in Bundle or permissions list are null | [
"Puts",
"the",
"list",
"of",
"declined",
"permissions",
"into",
"a",
"Bundle",
"."
]
| train | https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/TokenCachingStrategy.java#L286-L297 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/sun/misc/CharacterEncoder.java | CharacterEncoder.getBytes | private byte [] getBytes(ByteBuffer bb) {
"""
Return a byte array from the remaining bytes in this ByteBuffer.
<P>
The ByteBuffer's position will be advanced to ByteBuffer's limit.
<P>
To avoid an extra copy, the implementation will attempt to return the
byte array backing the ByteBuffer. If this is not possible, a
new byte array will be created.
"""
/*
* This should never return a BufferOverflowException, as we're
* careful to allocate just the right amount.
*/
byte [] buf = null;
/*
* If it has a usable backing byte buffer, use it. Use only
* if the array exactly represents the current ByteBuffer.
*/
if (bb.hasArray()) {
byte [] tmp = bb.array();
if ((tmp.length == bb.capacity()) &&
(tmp.length == bb.remaining())) {
buf = tmp;
bb.position(bb.limit());
}
}
if (buf == null) {
/*
* This class doesn't have a concept of encode(buf, len, off),
* so if we have a partial buffer, we must reallocate
* space.
*/
buf = new byte[bb.remaining()];
/*
* position() automatically updated
*/
bb.get(buf);
}
return buf;
} | java | private byte [] getBytes(ByteBuffer bb) {
/*
* This should never return a BufferOverflowException, as we're
* careful to allocate just the right amount.
*/
byte [] buf = null;
/*
* If it has a usable backing byte buffer, use it. Use only
* if the array exactly represents the current ByteBuffer.
*/
if (bb.hasArray()) {
byte [] tmp = bb.array();
if ((tmp.length == bb.capacity()) &&
(tmp.length == bb.remaining())) {
buf = tmp;
bb.position(bb.limit());
}
}
if (buf == null) {
/*
* This class doesn't have a concept of encode(buf, len, off),
* so if we have a partial buffer, we must reallocate
* space.
*/
buf = new byte[bb.remaining()];
/*
* position() automatically updated
*/
bb.get(buf);
}
return buf;
} | [
"private",
"byte",
"[",
"]",
"getBytes",
"(",
"ByteBuffer",
"bb",
")",
"{",
"/*\n * This should never return a BufferOverflowException, as we're\n * careful to allocate just the right amount.\n */",
"byte",
"[",
"]",
"buf",
"=",
"null",
";",
"/*\n * If it has a usable backing byte buffer, use it. Use only\n * if the array exactly represents the current ByteBuffer.\n */",
"if",
"(",
"bb",
".",
"hasArray",
"(",
")",
")",
"{",
"byte",
"[",
"]",
"tmp",
"=",
"bb",
".",
"array",
"(",
")",
";",
"if",
"(",
"(",
"tmp",
".",
"length",
"==",
"bb",
".",
"capacity",
"(",
")",
")",
"&&",
"(",
"tmp",
".",
"length",
"==",
"bb",
".",
"remaining",
"(",
")",
")",
")",
"{",
"buf",
"=",
"tmp",
";",
"bb",
".",
"position",
"(",
"bb",
".",
"limit",
"(",
")",
")",
";",
"}",
"}",
"if",
"(",
"buf",
"==",
"null",
")",
"{",
"/*\n * This class doesn't have a concept of encode(buf, len, off),\n * so if we have a partial buffer, we must reallocate\n * space.\n */",
"buf",
"=",
"new",
"byte",
"[",
"bb",
".",
"remaining",
"(",
")",
"]",
";",
"/*\n * position() automatically updated\n */",
"bb",
".",
"get",
"(",
"buf",
")",
";",
"}",
"return",
"buf",
";",
"}"
]
| Return a byte array from the remaining bytes in this ByteBuffer.
<P>
The ByteBuffer's position will be advanced to ByteBuffer's limit.
<P>
To avoid an extra copy, the implementation will attempt to return the
byte array backing the ByteBuffer. If this is not possible, a
new byte array will be created. | [
"Return",
"a",
"byte",
"array",
"from",
"the",
"remaining",
"bytes",
"in",
"this",
"ByteBuffer",
".",
"<P",
">",
"The",
"ByteBuffer",
"s",
"position",
"will",
"be",
"advanced",
"to",
"ByteBuffer",
"s",
"limit",
".",
"<P",
">",
"To",
"avoid",
"an",
"extra",
"copy",
"the",
"implementation",
"will",
"attempt",
"to",
"return",
"the",
"byte",
"array",
"backing",
"the",
"ByteBuffer",
".",
"If",
"this",
"is",
"not",
"possible",
"a",
"new",
"byte",
"array",
"will",
"be",
"created",
"."
]
| train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/misc/CharacterEncoder.java#L210-L245 |
overturetool/overture | core/pog/src/main/java/org/overture/pog/obligation/ProofObligation.java | ProofObligation.makeOr | protected PExp makeOr(PExp root, PExp e) {
"""
Chain an OR expression onto a root, or just return the new expression if the root is null. Called in a loop, this
left-associates an OR tree.
"""
if (root != null)
{
AOrBooleanBinaryExp o = new AOrBooleanBinaryExp();
o.setLeft(root.clone());
o.setOp(new LexKeywordToken(VDMToken.OR, null));
o.setType(new ABooleanBasicType());
o.setRight(e.clone());
return o;
} else
{
return e;
}
} | java | protected PExp makeOr(PExp root, PExp e)
{
if (root != null)
{
AOrBooleanBinaryExp o = new AOrBooleanBinaryExp();
o.setLeft(root.clone());
o.setOp(new LexKeywordToken(VDMToken.OR, null));
o.setType(new ABooleanBasicType());
o.setRight(e.clone());
return o;
} else
{
return e;
}
} | [
"protected",
"PExp",
"makeOr",
"(",
"PExp",
"root",
",",
"PExp",
"e",
")",
"{",
"if",
"(",
"root",
"!=",
"null",
")",
"{",
"AOrBooleanBinaryExp",
"o",
"=",
"new",
"AOrBooleanBinaryExp",
"(",
")",
";",
"o",
".",
"setLeft",
"(",
"root",
".",
"clone",
"(",
")",
")",
";",
"o",
".",
"setOp",
"(",
"new",
"LexKeywordToken",
"(",
"VDMToken",
".",
"OR",
",",
"null",
")",
")",
";",
"o",
".",
"setType",
"(",
"new",
"ABooleanBasicType",
"(",
")",
")",
";",
"o",
".",
"setRight",
"(",
"e",
".",
"clone",
"(",
")",
")",
";",
"return",
"o",
";",
"}",
"else",
"{",
"return",
"e",
";",
"}",
"}"
]
| Chain an OR expression onto a root, or just return the new expression if the root is null. Called in a loop, this
left-associates an OR tree. | [
"Chain",
"an",
"OR",
"expression",
"onto",
"a",
"root",
"or",
"just",
"return",
"the",
"new",
"expression",
"if",
"the",
"root",
"is",
"null",
".",
"Called",
"in",
"a",
"loop",
"this",
"left",
"-",
"associates",
"an",
"OR",
"tree",
"."
]
| train | https://github.com/overturetool/overture/blob/83175dc6c24fa171cde4fcf61ecb648eba3bdbc1/core/pog/src/main/java/org/overture/pog/obligation/ProofObligation.java#L450-L464 |
bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Transaction.java | Transaction.hashForSignature | public Sha256Hash hashForSignature(int inputIndex, Script redeemScript,
SigHash type, boolean anyoneCanPay) {
"""
<p>Calculates a signature hash, that is, a hash of a simplified form of the transaction. How exactly the transaction
is simplified is specified by the type and anyoneCanPay parameters.</p>
<p>This is a low level API and when using the regular {@link Wallet} class you don't have to call this yourself.
When working with more complex transaction types and contracts, it can be necessary. When signing a P2SH output
the redeemScript should be the script encoded into the scriptSig field, for normal transactions, it's the
scriptPubKey of the output you're signing for.</p>
@param inputIndex input the signature is being calculated for. Tx signatures are always relative to an input.
@param redeemScript the script that should be in the given input during signing.
@param type Should be SigHash.ALL
@param anyoneCanPay should be false.
"""
int sigHash = TransactionSignature.calcSigHashValue(type, anyoneCanPay);
return hashForSignature(inputIndex, redeemScript.getProgram(), (byte) sigHash);
} | java | public Sha256Hash hashForSignature(int inputIndex, Script redeemScript,
SigHash type, boolean anyoneCanPay) {
int sigHash = TransactionSignature.calcSigHashValue(type, anyoneCanPay);
return hashForSignature(inputIndex, redeemScript.getProgram(), (byte) sigHash);
} | [
"public",
"Sha256Hash",
"hashForSignature",
"(",
"int",
"inputIndex",
",",
"Script",
"redeemScript",
",",
"SigHash",
"type",
",",
"boolean",
"anyoneCanPay",
")",
"{",
"int",
"sigHash",
"=",
"TransactionSignature",
".",
"calcSigHashValue",
"(",
"type",
",",
"anyoneCanPay",
")",
";",
"return",
"hashForSignature",
"(",
"inputIndex",
",",
"redeemScript",
".",
"getProgram",
"(",
")",
",",
"(",
"byte",
")",
"sigHash",
")",
";",
"}"
]
| <p>Calculates a signature hash, that is, a hash of a simplified form of the transaction. How exactly the transaction
is simplified is specified by the type and anyoneCanPay parameters.</p>
<p>This is a low level API and when using the regular {@link Wallet} class you don't have to call this yourself.
When working with more complex transaction types and contracts, it can be necessary. When signing a P2SH output
the redeemScript should be the script encoded into the scriptSig field, for normal transactions, it's the
scriptPubKey of the output you're signing for.</p>
@param inputIndex input the signature is being calculated for. Tx signatures are always relative to an input.
@param redeemScript the script that should be in the given input during signing.
@param type Should be SigHash.ALL
@param anyoneCanPay should be false. | [
"<p",
">",
"Calculates",
"a",
"signature",
"hash",
"that",
"is",
"a",
"hash",
"of",
"a",
"simplified",
"form",
"of",
"the",
"transaction",
".",
"How",
"exactly",
"the",
"transaction",
"is",
"simplified",
"is",
"specified",
"by",
"the",
"type",
"and",
"anyoneCanPay",
"parameters",
".",
"<",
"/",
"p",
">"
]
| train | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Transaction.java#L1178-L1182 |
netty/netty | common/src/main/java/io/netty/util/internal/PlatformDependent.java | PlatformDependent.hashCodeAscii | public static int hashCodeAscii(byte[] bytes, int startPos, int length) {
"""
Calculate a hash code of a byte array assuming ASCII character encoding.
The resulting hash code will be case insensitive.
@param bytes The array which contains the data to hash.
@param startPos What index to start generating a hash code in {@code bytes}
@param length The amount of bytes that should be accounted for in the computation.
@return The hash code of {@code bytes} assuming ASCII character encoding.
The resulting hash code will be case insensitive.
"""
return !hasUnsafe() || !unalignedAccess() ?
hashCodeAsciiSafe(bytes, startPos, length) :
PlatformDependent0.hashCodeAscii(bytes, startPos, length);
} | java | public static int hashCodeAscii(byte[] bytes, int startPos, int length) {
return !hasUnsafe() || !unalignedAccess() ?
hashCodeAsciiSafe(bytes, startPos, length) :
PlatformDependent0.hashCodeAscii(bytes, startPos, length);
} | [
"public",
"static",
"int",
"hashCodeAscii",
"(",
"byte",
"[",
"]",
"bytes",
",",
"int",
"startPos",
",",
"int",
"length",
")",
"{",
"return",
"!",
"hasUnsafe",
"(",
")",
"||",
"!",
"unalignedAccess",
"(",
")",
"?",
"hashCodeAsciiSafe",
"(",
"bytes",
",",
"startPos",
",",
"length",
")",
":",
"PlatformDependent0",
".",
"hashCodeAscii",
"(",
"bytes",
",",
"startPos",
",",
"length",
")",
";",
"}"
]
| Calculate a hash code of a byte array assuming ASCII character encoding.
The resulting hash code will be case insensitive.
@param bytes The array which contains the data to hash.
@param startPos What index to start generating a hash code in {@code bytes}
@param length The amount of bytes that should be accounted for in the computation.
@return The hash code of {@code bytes} assuming ASCII character encoding.
The resulting hash code will be case insensitive. | [
"Calculate",
"a",
"hash",
"code",
"of",
"a",
"byte",
"array",
"assuming",
"ASCII",
"character",
"encoding",
".",
"The",
"resulting",
"hash",
"code",
"will",
"be",
"case",
"insensitive",
"."
]
| train | https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/common/src/main/java/io/netty/util/internal/PlatformDependent.java#L751-L755 |
carewebframework/carewebframework-vista | org.carewebframework.vista.mbroker/src/main/java/org/carewebframework/vista/mbroker/RPCParameters.java | RPCParameters.put | public void put(int index, RPCParameter param) {
"""
Adds a parameter at the specified index.
@param index Index for parameter.
@param param Parameter to add.
"""
expand(index);
if (index < params.size()) {
params.set(index, param);
} else {
params.add(param);
}
} | java | public void put(int index, RPCParameter param) {
expand(index);
if (index < params.size()) {
params.set(index, param);
} else {
params.add(param);
}
} | [
"public",
"void",
"put",
"(",
"int",
"index",
",",
"RPCParameter",
"param",
")",
"{",
"expand",
"(",
"index",
")",
";",
"if",
"(",
"index",
"<",
"params",
".",
"size",
"(",
")",
")",
"{",
"params",
".",
"set",
"(",
"index",
",",
"param",
")",
";",
"}",
"else",
"{",
"params",
".",
"add",
"(",
"param",
")",
";",
"}",
"}"
]
| Adds a parameter at the specified index.
@param index Index for parameter.
@param param Parameter to add. | [
"Adds",
"a",
"parameter",
"at",
"the",
"specified",
"index",
"."
]
| train | https://github.com/carewebframework/carewebframework-vista/blob/883b2cbe395d9e8a21cd19db820f0876bda6b1c6/org.carewebframework.vista.mbroker/src/main/java/org/carewebframework/vista/mbroker/RPCParameters.java#L124-L132 |
OpenLiberty/open-liberty | dev/com.ibm.ws.session/src/com/ibm/ws/session/SessionContext.java | SessionContext.addToJ2eeNameList | private void addToJ2eeNameList(String j2eeName, int size, ArrayList listenerJ2eeNames) {
"""
/*
Keeps track of J2EE names of listeners. We only do this for global
sessions.
In this case, one Enterprise (J2EE) app may be stopped, so we need to stop
listeners
for that app.
"""
int start = listenerJ2eeNames.size();
int end = start + size;
if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) {
StringBuffer sb = new StringBuffer("starting at ").append(start).append(" going to ").append(end).append(" for ").append(j2eeName);
LoggingUtil.SESSION_LOGGER_CORE.logp(Level.FINE, methodClassName, "addToJ2eeNameList", sb.toString());
}
for (int x = start; x < end; x++) {
listenerJ2eeNames.add(j2eeName);
}
} | java | private void addToJ2eeNameList(String j2eeName, int size, ArrayList listenerJ2eeNames) {
int start = listenerJ2eeNames.size();
int end = start + size;
if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) {
StringBuffer sb = new StringBuffer("starting at ").append(start).append(" going to ").append(end).append(" for ").append(j2eeName);
LoggingUtil.SESSION_LOGGER_CORE.logp(Level.FINE, methodClassName, "addToJ2eeNameList", sb.toString());
}
for (int x = start; x < end; x++) {
listenerJ2eeNames.add(j2eeName);
}
} | [
"private",
"void",
"addToJ2eeNameList",
"(",
"String",
"j2eeName",
",",
"int",
"size",
",",
"ArrayList",
"listenerJ2eeNames",
")",
"{",
"int",
"start",
"=",
"listenerJ2eeNames",
".",
"size",
"(",
")",
";",
"int",
"end",
"=",
"start",
"+",
"size",
";",
"if",
"(",
"com",
".",
"ibm",
".",
"ejs",
".",
"ras",
".",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"LoggingUtil",
".",
"SESSION_LOGGER_CORE",
".",
"isLoggable",
"(",
"Level",
".",
"FINE",
")",
")",
"{",
"StringBuffer",
"sb",
"=",
"new",
"StringBuffer",
"(",
"\"starting at \"",
")",
".",
"append",
"(",
"start",
")",
".",
"append",
"(",
"\" going to \"",
")",
".",
"append",
"(",
"end",
")",
".",
"append",
"(",
"\" for \"",
")",
".",
"append",
"(",
"j2eeName",
")",
";",
"LoggingUtil",
".",
"SESSION_LOGGER_CORE",
".",
"logp",
"(",
"Level",
".",
"FINE",
",",
"methodClassName",
",",
"\"addToJ2eeNameList\"",
",",
"sb",
".",
"toString",
"(",
")",
")",
";",
"}",
"for",
"(",
"int",
"x",
"=",
"start",
";",
"x",
"<",
"end",
";",
"x",
"++",
")",
"{",
"listenerJ2eeNames",
".",
"add",
"(",
"j2eeName",
")",
";",
"}",
"}"
]
| /*
Keeps track of J2EE names of listeners. We only do this for global
sessions.
In this case, one Enterprise (J2EE) app may be stopped, so we need to stop
listeners
for that app. | [
"/",
"*",
"Keeps",
"track",
"of",
"J2EE",
"names",
"of",
"listeners",
".",
"We",
"only",
"do",
"this",
"for",
"global",
"sessions",
".",
"In",
"this",
"case",
"one",
"Enterprise",
"(",
"J2EE",
")",
"app",
"may",
"be",
"stopped",
"so",
"we",
"need",
"to",
"stop",
"listeners",
"for",
"that",
"app",
"."
]
| train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.session/src/com/ibm/ws/session/SessionContext.java#L856-L866 |
nguillaumin/slick2d-maven | slick2d-core/src/main/java/org/newdawn/slick/particles/Particle.java | Particle.adjustColor | public void adjustColor(float r, float g, float b, float a) {
"""
Adjust (add) the color of the particle
@param r
The amount to adjust the red component by
@param g
The amount to adjust the green component by
@param b
The amount to adjust the blue component by
@param a
The amount to adjust the alpha component by
"""
if (color == Color.white) {
color = new Color(1,1,1,1f);
}
color.r += r;
color.g += g;
color.b += b;
color.a += a;
} | java | public void adjustColor(float r, float g, float b, float a) {
if (color == Color.white) {
color = new Color(1,1,1,1f);
}
color.r += r;
color.g += g;
color.b += b;
color.a += a;
} | [
"public",
"void",
"adjustColor",
"(",
"float",
"r",
",",
"float",
"g",
",",
"float",
"b",
",",
"float",
"a",
")",
"{",
"if",
"(",
"color",
"==",
"Color",
".",
"white",
")",
"{",
"color",
"=",
"new",
"Color",
"(",
"1",
",",
"1",
",",
"1",
",",
"1f",
")",
";",
"}",
"color",
".",
"r",
"+=",
"r",
";",
"color",
".",
"g",
"+=",
"g",
";",
"color",
".",
"b",
"+=",
"b",
";",
"color",
".",
"a",
"+=",
"a",
";",
"}"
]
| Adjust (add) the color of the particle
@param r
The amount to adjust the red component by
@param g
The amount to adjust the green component by
@param b
The amount to adjust the blue component by
@param a
The amount to adjust the alpha component by | [
"Adjust",
"(",
"add",
")",
"the",
"color",
"of",
"the",
"particle"
]
| train | https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-core/src/main/java/org/newdawn/slick/particles/Particle.java#L405-L413 |
bazaarvoice/emodb | web/src/main/java/com/bazaarvoice/emodb/web/report/db/EmoTableAllTablesReportDAO.java | EmoTableAllTablesReportDAO.getReportMetadata | @Override
public TableReportMetadata getReportMetadata(String reportId) {
"""
Returns the table data for a given report. The caller can optionally return a partial report with ony
the requested tables.
"""
checkNotNull(reportId, "reportId");
final String reportTable = getTableName(reportId);
Map<String, Object> metadata;
try {
metadata = _dataStore.get(reportTable, REPORT_METADATA_KEY);
} catch (UnknownTableException e) {
// The table is only unknown if the report doesn't exist
throw new ReportNotFoundException(reportId);
}
if (Intrinsic.isDeleted(metadata)) {
throw new ReportNotFoundException(reportId);
}
Date startTime = JsonHelper.parseTimestamp((String) metadata.get("startTime"));
Date completeTime = null;
if (metadata.containsKey("completeTime")) {
completeTime = JsonHelper.parseTimestamp((String) metadata.get("completeTime"));
}
Boolean success = (Boolean) metadata.get("success");
List<String> placements;
Object placementMap = metadata.get("placements");
if (placementMap != null) {
placements = ImmutableList.copyOf(
JsonHelper.convert(placementMap, new TypeReference<Map<String, Object>>() {}).keySet());
} else {
placements = ImmutableList.of();
}
return new TableReportMetadata(reportId, startTime, completeTime, success, placements);
} | java | @Override
public TableReportMetadata getReportMetadata(String reportId) {
checkNotNull(reportId, "reportId");
final String reportTable = getTableName(reportId);
Map<String, Object> metadata;
try {
metadata = _dataStore.get(reportTable, REPORT_METADATA_KEY);
} catch (UnknownTableException e) {
// The table is only unknown if the report doesn't exist
throw new ReportNotFoundException(reportId);
}
if (Intrinsic.isDeleted(metadata)) {
throw new ReportNotFoundException(reportId);
}
Date startTime = JsonHelper.parseTimestamp((String) metadata.get("startTime"));
Date completeTime = null;
if (metadata.containsKey("completeTime")) {
completeTime = JsonHelper.parseTimestamp((String) metadata.get("completeTime"));
}
Boolean success = (Boolean) metadata.get("success");
List<String> placements;
Object placementMap = metadata.get("placements");
if (placementMap != null) {
placements = ImmutableList.copyOf(
JsonHelper.convert(placementMap, new TypeReference<Map<String, Object>>() {}).keySet());
} else {
placements = ImmutableList.of();
}
return new TableReportMetadata(reportId, startTime, completeTime, success, placements);
} | [
"@",
"Override",
"public",
"TableReportMetadata",
"getReportMetadata",
"(",
"String",
"reportId",
")",
"{",
"checkNotNull",
"(",
"reportId",
",",
"\"reportId\"",
")",
";",
"final",
"String",
"reportTable",
"=",
"getTableName",
"(",
"reportId",
")",
";",
"Map",
"<",
"String",
",",
"Object",
">",
"metadata",
";",
"try",
"{",
"metadata",
"=",
"_dataStore",
".",
"get",
"(",
"reportTable",
",",
"REPORT_METADATA_KEY",
")",
";",
"}",
"catch",
"(",
"UnknownTableException",
"e",
")",
"{",
"// The table is only unknown if the report doesn't exist",
"throw",
"new",
"ReportNotFoundException",
"(",
"reportId",
")",
";",
"}",
"if",
"(",
"Intrinsic",
".",
"isDeleted",
"(",
"metadata",
")",
")",
"{",
"throw",
"new",
"ReportNotFoundException",
"(",
"reportId",
")",
";",
"}",
"Date",
"startTime",
"=",
"JsonHelper",
".",
"parseTimestamp",
"(",
"(",
"String",
")",
"metadata",
".",
"get",
"(",
"\"startTime\"",
")",
")",
";",
"Date",
"completeTime",
"=",
"null",
";",
"if",
"(",
"metadata",
".",
"containsKey",
"(",
"\"completeTime\"",
")",
")",
"{",
"completeTime",
"=",
"JsonHelper",
".",
"parseTimestamp",
"(",
"(",
"String",
")",
"metadata",
".",
"get",
"(",
"\"completeTime\"",
")",
")",
";",
"}",
"Boolean",
"success",
"=",
"(",
"Boolean",
")",
"metadata",
".",
"get",
"(",
"\"success\"",
")",
";",
"List",
"<",
"String",
">",
"placements",
";",
"Object",
"placementMap",
"=",
"metadata",
".",
"get",
"(",
"\"placements\"",
")",
";",
"if",
"(",
"placementMap",
"!=",
"null",
")",
"{",
"placements",
"=",
"ImmutableList",
".",
"copyOf",
"(",
"JsonHelper",
".",
"convert",
"(",
"placementMap",
",",
"new",
"TypeReference",
"<",
"Map",
"<",
"String",
",",
"Object",
">",
">",
"(",
")",
"{",
"}",
")",
".",
"keySet",
"(",
")",
")",
";",
"}",
"else",
"{",
"placements",
"=",
"ImmutableList",
".",
"of",
"(",
")",
";",
"}",
"return",
"new",
"TableReportMetadata",
"(",
"reportId",
",",
"startTime",
",",
"completeTime",
",",
"success",
",",
"placements",
")",
";",
"}"
]
| Returns the table data for a given report. The caller can optionally return a partial report with ony
the requested tables. | [
"Returns",
"the",
"table",
"data",
"for",
"a",
"given",
"report",
".",
"The",
"caller",
"can",
"optionally",
"return",
"a",
"partial",
"report",
"with",
"ony",
"the",
"requested",
"tables",
"."
]
| train | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/report/db/EmoTableAllTablesReportDAO.java#L164-L199 |
antopen/alipay-sdk-java | src/main/java/com/alipay/api/internal/util/AlipaySignature.java | AlipaySignature.rsaEncrypt | public static String rsaEncrypt(String content, String publicKey,
String charset) throws AlipayApiException {
"""
公钥加密
@param content 待加密内容
@param publicKey 公钥
@param charset 字符集,如UTF-8, GBK, GB2312
@return 密文内容
@throws AlipayApiException
"""
try {
PublicKey pubKey = getPublicKeyFromX509(AlipayConstants.SIGN_TYPE_RSA,
new ByteArrayInputStream(publicKey.getBytes()));
Cipher cipher = Cipher.getInstance(AlipayConstants.SIGN_TYPE_RSA);
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] data = StringUtils.isEmpty(charset) ? content.getBytes()
: content.getBytes(charset);
int inputLen = data.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段加密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = Base64.encodeBase64(out.toByteArray());
out.close();
return StringUtils.isEmpty(charset) ? new String(encryptedData)
: new String(encryptedData, charset);
} catch (Exception e) {
throw new AlipayApiException("EncryptContent = " + content + ",charset = " + charset,
e);
}
} | java | public static String rsaEncrypt(String content, String publicKey,
String charset) throws AlipayApiException {
try {
PublicKey pubKey = getPublicKeyFromX509(AlipayConstants.SIGN_TYPE_RSA,
new ByteArrayInputStream(publicKey.getBytes()));
Cipher cipher = Cipher.getInstance(AlipayConstants.SIGN_TYPE_RSA);
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] data = StringUtils.isEmpty(charset) ? content.getBytes()
: content.getBytes(charset);
int inputLen = data.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段加密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = Base64.encodeBase64(out.toByteArray());
out.close();
return StringUtils.isEmpty(charset) ? new String(encryptedData)
: new String(encryptedData, charset);
} catch (Exception e) {
throw new AlipayApiException("EncryptContent = " + content + ",charset = " + charset,
e);
}
} | [
"public",
"static",
"String",
"rsaEncrypt",
"(",
"String",
"content",
",",
"String",
"publicKey",
",",
"String",
"charset",
")",
"throws",
"AlipayApiException",
"{",
"try",
"{",
"PublicKey",
"pubKey",
"=",
"getPublicKeyFromX509",
"(",
"AlipayConstants",
".",
"SIGN_TYPE_RSA",
",",
"new",
"ByteArrayInputStream",
"(",
"publicKey",
".",
"getBytes",
"(",
")",
")",
")",
";",
"Cipher",
"cipher",
"=",
"Cipher",
".",
"getInstance",
"(",
"AlipayConstants",
".",
"SIGN_TYPE_RSA",
")",
";",
"cipher",
".",
"init",
"(",
"Cipher",
".",
"ENCRYPT_MODE",
",",
"pubKey",
")",
";",
"byte",
"[",
"]",
"data",
"=",
"StringUtils",
".",
"isEmpty",
"(",
"charset",
")",
"?",
"content",
".",
"getBytes",
"(",
")",
":",
"content",
".",
"getBytes",
"(",
"charset",
")",
";",
"int",
"inputLen",
"=",
"data",
".",
"length",
";",
"ByteArrayOutputStream",
"out",
"=",
"new",
"ByteArrayOutputStream",
"(",
")",
";",
"int",
"offSet",
"=",
"0",
";",
"byte",
"[",
"]",
"cache",
";",
"int",
"i",
"=",
"0",
";",
"// 对数据分段加密 ",
"while",
"(",
"inputLen",
"-",
"offSet",
">",
"0",
")",
"{",
"if",
"(",
"inputLen",
"-",
"offSet",
">",
"MAX_ENCRYPT_BLOCK",
")",
"{",
"cache",
"=",
"cipher",
".",
"doFinal",
"(",
"data",
",",
"offSet",
",",
"MAX_ENCRYPT_BLOCK",
")",
";",
"}",
"else",
"{",
"cache",
"=",
"cipher",
".",
"doFinal",
"(",
"data",
",",
"offSet",
",",
"inputLen",
"-",
"offSet",
")",
";",
"}",
"out",
".",
"write",
"(",
"cache",
",",
"0",
",",
"cache",
".",
"length",
")",
";",
"i",
"++",
";",
"offSet",
"=",
"i",
"*",
"MAX_ENCRYPT_BLOCK",
";",
"}",
"byte",
"[",
"]",
"encryptedData",
"=",
"Base64",
".",
"encodeBase64",
"(",
"out",
".",
"toByteArray",
"(",
")",
")",
";",
"out",
".",
"close",
"(",
")",
";",
"return",
"StringUtils",
".",
"isEmpty",
"(",
"charset",
")",
"?",
"new",
"String",
"(",
"encryptedData",
")",
":",
"new",
"String",
"(",
"encryptedData",
",",
"charset",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"AlipayApiException",
"(",
"\"EncryptContent = \"",
"+",
"content",
"+",
"\",charset = \"",
"+",
"charset",
",",
"e",
")",
";",
"}",
"}"
]
| 公钥加密
@param content 待加密内容
@param publicKey 公钥
@param charset 字符集,如UTF-8, GBK, GB2312
@return 密文内容
@throws AlipayApiException | [
"公钥加密"
]
| train | https://github.com/antopen/alipay-sdk-java/blob/e82aeac7d0239330ee173c7e393596e51e41c1cd/src/main/java/com/alipay/api/internal/util/AlipaySignature.java#L553-L587 |
google/j2objc | jre_emul/android/platform/libcore/luni/src/main/java/org/apache/harmony/xml/dom/InnerNodeImpl.java | InnerNodeImpl.replaceChild | public Node replaceChild(Node newChild, Node oldChild) throws DOMException {
"""
Removes {@code oldChild} and adds {@code newChild} in its place. This
is not atomic.
"""
int index = ((LeafNodeImpl) oldChild).index;
removeChild(oldChild);
insertChildAt(newChild, index);
return oldChild;
} | java | public Node replaceChild(Node newChild, Node oldChild) throws DOMException {
int index = ((LeafNodeImpl) oldChild).index;
removeChild(oldChild);
insertChildAt(newChild, index);
return oldChild;
} | [
"public",
"Node",
"replaceChild",
"(",
"Node",
"newChild",
",",
"Node",
"oldChild",
")",
"throws",
"DOMException",
"{",
"int",
"index",
"=",
"(",
"(",
"LeafNodeImpl",
")",
"oldChild",
")",
".",
"index",
";",
"removeChild",
"(",
"oldChild",
")",
";",
"insertChildAt",
"(",
"newChild",
",",
"index",
")",
";",
"return",
"oldChild",
";",
"}"
]
| Removes {@code oldChild} and adds {@code newChild} in its place. This
is not atomic. | [
"Removes",
"{"
]
| train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/luni/src/main/java/org/apache/harmony/xml/dom/InnerNodeImpl.java#L196-L201 |
avianey/facebook-api-android-maven | facebook/src/main/java/com/facebook/AppEventsLogger.java | AppEventsLogger.deactivateApp | public static void deactivateApp(Context context, String applicationId) {
"""
Notifies the events system that the app has been deactivated (put in the background) and
tracks the application session information. Should be called whenever your app becomes
inactive, typically in the onPause() method of each long-running Activity of your app.
@param context Used to access the attributionId for non-authenticated users.
@param applicationId The specific applicationId to track session information for.
"""
if (context == null || applicationId == null) {
throw new IllegalArgumentException("Both context and applicationId must be non-null");
}
resetSourceApplication();
final AppEventsLogger logger = new AppEventsLogger(context, applicationId, null);
final long eventTime = System.currentTimeMillis();
backgroundExecutor.execute(new Runnable() {
@Override
public void run() {
logger.logAppSessionSuspendEvent(eventTime);
}
});
} | java | public static void deactivateApp(Context context, String applicationId) {
if (context == null || applicationId == null) {
throw new IllegalArgumentException("Both context and applicationId must be non-null");
}
resetSourceApplication();
final AppEventsLogger logger = new AppEventsLogger(context, applicationId, null);
final long eventTime = System.currentTimeMillis();
backgroundExecutor.execute(new Runnable() {
@Override
public void run() {
logger.logAppSessionSuspendEvent(eventTime);
}
});
} | [
"public",
"static",
"void",
"deactivateApp",
"(",
"Context",
"context",
",",
"String",
"applicationId",
")",
"{",
"if",
"(",
"context",
"==",
"null",
"||",
"applicationId",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Both context and applicationId must be non-null\"",
")",
";",
"}",
"resetSourceApplication",
"(",
")",
";",
"final",
"AppEventsLogger",
"logger",
"=",
"new",
"AppEventsLogger",
"(",
"context",
",",
"applicationId",
",",
"null",
")",
";",
"final",
"long",
"eventTime",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
";",
"backgroundExecutor",
".",
"execute",
"(",
"new",
"Runnable",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"run",
"(",
")",
"{",
"logger",
".",
"logAppSessionSuspendEvent",
"(",
"eventTime",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Notifies the events system that the app has been deactivated (put in the background) and
tracks the application session information. Should be called whenever your app becomes
inactive, typically in the onPause() method of each long-running Activity of your app.
@param context Used to access the attributionId for non-authenticated users.
@param applicationId The specific applicationId to track session information for. | [
"Notifies",
"the",
"events",
"system",
"that",
"the",
"app",
"has",
"been",
"deactivated",
"(",
"put",
"in",
"the",
"background",
")",
"and",
"tracks",
"the",
"application",
"session",
"information",
".",
"Should",
"be",
"called",
"whenever",
"your",
"app",
"becomes",
"inactive",
"typically",
"in",
"the",
"onPause",
"()",
"method",
"of",
"each",
"long",
"-",
"running",
"Activity",
"of",
"your",
"app",
"."
]
| train | https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/AppEventsLogger.java#L310-L325 |
google/truth | extensions/proto/src/main/java/com/google/common/truth/extensions/proto/MapWithProtoValuesSubject.java | MapWithProtoValuesSubject.usingFloatToleranceForFieldDescriptorsForValues | public MapWithProtoValuesFluentAssertion<M> usingFloatToleranceForFieldDescriptorsForValues(
float tolerance, Iterable<FieldDescriptor> fieldDescriptors) {
"""
Compares float fields with these explicitly specified top-level field numbers using the
provided absolute tolerance.
@param tolerance A finite, non-negative tolerance.
"""
return usingConfig(config.usingFloatToleranceForFieldDescriptors(tolerance, fieldDescriptors));
} | java | public MapWithProtoValuesFluentAssertion<M> usingFloatToleranceForFieldDescriptorsForValues(
float tolerance, Iterable<FieldDescriptor> fieldDescriptors) {
return usingConfig(config.usingFloatToleranceForFieldDescriptors(tolerance, fieldDescriptors));
} | [
"public",
"MapWithProtoValuesFluentAssertion",
"<",
"M",
">",
"usingFloatToleranceForFieldDescriptorsForValues",
"(",
"float",
"tolerance",
",",
"Iterable",
"<",
"FieldDescriptor",
">",
"fieldDescriptors",
")",
"{",
"return",
"usingConfig",
"(",
"config",
".",
"usingFloatToleranceForFieldDescriptors",
"(",
"tolerance",
",",
"fieldDescriptors",
")",
")",
";",
"}"
]
| Compares float fields with these explicitly specified top-level field numbers using the
provided absolute tolerance.
@param tolerance A finite, non-negative tolerance. | [
"Compares",
"float",
"fields",
"with",
"these",
"explicitly",
"specified",
"top",
"-",
"level",
"field",
"numbers",
"using",
"the",
"provided",
"absolute",
"tolerance",
"."
]
| train | https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/extensions/proto/src/main/java/com/google/common/truth/extensions/proto/MapWithProtoValuesSubject.java#L609-L612 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/UCharacterName.java | UCharacterName.getAlgorithmName | public String getAlgorithmName(int index, int codepoint) {
"""
Gets the Algorithmic name of the codepoint
@param index algorithmic range index
@param codepoint The codepoint value.
@return algorithmic name of codepoint
"""
String result = null;
synchronized (m_utilStringBuffer_) {
m_utilStringBuffer_.setLength(0);
m_algorithm_[index].appendName(codepoint, m_utilStringBuffer_);
result = m_utilStringBuffer_.toString();
}
return result;
} | java | public String getAlgorithmName(int index, int codepoint)
{
String result = null;
synchronized (m_utilStringBuffer_) {
m_utilStringBuffer_.setLength(0);
m_algorithm_[index].appendName(codepoint, m_utilStringBuffer_);
result = m_utilStringBuffer_.toString();
}
return result;
} | [
"public",
"String",
"getAlgorithmName",
"(",
"int",
"index",
",",
"int",
"codepoint",
")",
"{",
"String",
"result",
"=",
"null",
";",
"synchronized",
"(",
"m_utilStringBuffer_",
")",
"{",
"m_utilStringBuffer_",
".",
"setLength",
"(",
"0",
")",
";",
"m_algorithm_",
"[",
"index",
"]",
".",
"appendName",
"(",
"codepoint",
",",
"m_utilStringBuffer_",
")",
";",
"result",
"=",
"m_utilStringBuffer_",
".",
"toString",
"(",
")",
";",
"}",
"return",
"result",
";",
"}"
]
| Gets the Algorithmic name of the codepoint
@param index algorithmic range index
@param codepoint The codepoint value.
@return algorithmic name of codepoint | [
"Gets",
"the",
"Algorithmic",
"name",
"of",
"the",
"codepoint"
]
| train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/UCharacterName.java#L491-L500 |
looly/hutool | hutool-poi/src/main/java/cn/hutool/poi/excel/style/StyleUtil.java | StyleUtil.cloneCellStyle | public static CellStyle cloneCellStyle(Cell cell, CellStyle cellStyle) {
"""
克隆新的{@link CellStyle}
@param cell 单元格
@param cellStyle 被复制的样式
@return {@link CellStyle}
"""
return cloneCellStyle(cell.getSheet().getWorkbook(), cellStyle);
} | java | public static CellStyle cloneCellStyle(Cell cell, CellStyle cellStyle) {
return cloneCellStyle(cell.getSheet().getWorkbook(), cellStyle);
} | [
"public",
"static",
"CellStyle",
"cloneCellStyle",
"(",
"Cell",
"cell",
",",
"CellStyle",
"cellStyle",
")",
"{",
"return",
"cloneCellStyle",
"(",
"cell",
".",
"getSheet",
"(",
")",
".",
"getWorkbook",
"(",
")",
",",
"cellStyle",
")",
";",
"}"
]
| 克隆新的{@link CellStyle}
@param cell 单元格
@param cellStyle 被复制的样式
@return {@link CellStyle} | [
"克隆新的",
"{",
"@link",
"CellStyle",
"}"
]
| train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-poi/src/main/java/cn/hutool/poi/excel/style/StyleUtil.java#L30-L32 |
openbase/jul | storage/src/main/java/org/openbase/jul/storage/registry/AbstractRegistry.java | AbstractRegistry.replaceInternalMap | public void replaceInternalMap(final Map<KEY, ENTRY> map, boolean finishTransaction) throws CouldNotPerformException {
"""
Replaces the internal registry map by the given one.
<p>
Use with care!
@param map
@param finishTransaction is true the registry transaction will be verified.
@throws org.openbase.jul.exception.CouldNotPerformException
"""
if (map == null) {
throw new NotAvailableException("map");
}
lock();
try {
try {
sandbox.replaceInternalMap(map);
entryMap.clear();
entryMap.putAll(map);
if (finishTransaction && !(this instanceof RemoteRegistry)) {
logger.warn("Replace internal map of [" + this + "]");
finishTransaction();
}
} finally {
syncSandbox();
}
} catch (CouldNotPerformException ex) {
ExceptionPrinter.printHistory(new CouldNotPerformException("Internal map replaced by invalid data!", ex), logger, LogLevel.ERROR);
} finally {
unlock();
}
if (this instanceof RemoteRegistry) {
dependingRegistryObservable.notifyObservers(entryMap);
}
notifyObservers();
} | java | public void replaceInternalMap(final Map<KEY, ENTRY> map, boolean finishTransaction) throws CouldNotPerformException {
if (map == null) {
throw new NotAvailableException("map");
}
lock();
try {
try {
sandbox.replaceInternalMap(map);
entryMap.clear();
entryMap.putAll(map);
if (finishTransaction && !(this instanceof RemoteRegistry)) {
logger.warn("Replace internal map of [" + this + "]");
finishTransaction();
}
} finally {
syncSandbox();
}
} catch (CouldNotPerformException ex) {
ExceptionPrinter.printHistory(new CouldNotPerformException("Internal map replaced by invalid data!", ex), logger, LogLevel.ERROR);
} finally {
unlock();
}
if (this instanceof RemoteRegistry) {
dependingRegistryObservable.notifyObservers(entryMap);
}
notifyObservers();
} | [
"public",
"void",
"replaceInternalMap",
"(",
"final",
"Map",
"<",
"KEY",
",",
"ENTRY",
">",
"map",
",",
"boolean",
"finishTransaction",
")",
"throws",
"CouldNotPerformException",
"{",
"if",
"(",
"map",
"==",
"null",
")",
"{",
"throw",
"new",
"NotAvailableException",
"(",
"\"map\"",
")",
";",
"}",
"lock",
"(",
")",
";",
"try",
"{",
"try",
"{",
"sandbox",
".",
"replaceInternalMap",
"(",
"map",
")",
";",
"entryMap",
".",
"clear",
"(",
")",
";",
"entryMap",
".",
"putAll",
"(",
"map",
")",
";",
"if",
"(",
"finishTransaction",
"&&",
"!",
"(",
"this",
"instanceof",
"RemoteRegistry",
")",
")",
"{",
"logger",
".",
"warn",
"(",
"\"Replace internal map of [\"",
"+",
"this",
"+",
"\"]\"",
")",
";",
"finishTransaction",
"(",
")",
";",
"}",
"}",
"finally",
"{",
"syncSandbox",
"(",
")",
";",
"}",
"}",
"catch",
"(",
"CouldNotPerformException",
"ex",
")",
"{",
"ExceptionPrinter",
".",
"printHistory",
"(",
"new",
"CouldNotPerformException",
"(",
"\"Internal map replaced by invalid data!\"",
",",
"ex",
")",
",",
"logger",
",",
"LogLevel",
".",
"ERROR",
")",
";",
"}",
"finally",
"{",
"unlock",
"(",
")",
";",
"}",
"if",
"(",
"this",
"instanceof",
"RemoteRegistry",
")",
"{",
"dependingRegistryObservable",
".",
"notifyObservers",
"(",
"entryMap",
")",
";",
"}",
"notifyObservers",
"(",
")",
";",
"}"
]
| Replaces the internal registry map by the given one.
<p>
Use with care!
@param map
@param finishTransaction is true the registry transaction will be verified.
@throws org.openbase.jul.exception.CouldNotPerformException | [
"Replaces",
"the",
"internal",
"registry",
"map",
"by",
"the",
"given",
"one",
".",
"<p",
">",
"Use",
"with",
"care!"
]
| train | https://github.com/openbase/jul/blob/662e98c3a853085e475be54c3be3deb72193c72d/storage/src/main/java/org/openbase/jul/storage/registry/AbstractRegistry.java#L578-L604 |
jbundle/jbundle | thin/base/remote/src/main/java/org/jbundle/thin/base/remote/proxy/TableProxy.java | TableProxy.doMove | public Object doMove(int iRelPosition, int iRecordCount) throws DBException, RemoteException {
"""
Move the current position and read the record (optionally read several records).
@param iRelPosition relative Position to read the next record.
@param iRecordCount Records to read.
@return If I read 1 record, this is the record's data.
@return If I read several records, this is a vector of the returned records.
@return If at EOF, or error, returns the error code as a Integer.
@exception Exception File exception.
"""
BaseTransport transport = this.createProxyTransport(DO_MOVE);
transport.addParam(POSITION, iRelPosition);
transport.addParam(COUNT, iRecordCount);
Object strReturn = transport.sendMessageAndGetReply();
Object objReturn = transport.convertReturnObject(strReturn);
return this.checkDBException(objReturn);
} | java | public Object doMove(int iRelPosition, int iRecordCount) throws DBException, RemoteException
{
BaseTransport transport = this.createProxyTransport(DO_MOVE);
transport.addParam(POSITION, iRelPosition);
transport.addParam(COUNT, iRecordCount);
Object strReturn = transport.sendMessageAndGetReply();
Object objReturn = transport.convertReturnObject(strReturn);
return this.checkDBException(objReturn);
} | [
"public",
"Object",
"doMove",
"(",
"int",
"iRelPosition",
",",
"int",
"iRecordCount",
")",
"throws",
"DBException",
",",
"RemoteException",
"{",
"BaseTransport",
"transport",
"=",
"this",
".",
"createProxyTransport",
"(",
"DO_MOVE",
")",
";",
"transport",
".",
"addParam",
"(",
"POSITION",
",",
"iRelPosition",
")",
";",
"transport",
".",
"addParam",
"(",
"COUNT",
",",
"iRecordCount",
")",
";",
"Object",
"strReturn",
"=",
"transport",
".",
"sendMessageAndGetReply",
"(",
")",
";",
"Object",
"objReturn",
"=",
"transport",
".",
"convertReturnObject",
"(",
"strReturn",
")",
";",
"return",
"this",
".",
"checkDBException",
"(",
"objReturn",
")",
";",
"}"
]
| Move the current position and read the record (optionally read several records).
@param iRelPosition relative Position to read the next record.
@param iRecordCount Records to read.
@return If I read 1 record, this is the record's data.
@return If I read several records, this is a vector of the returned records.
@return If at EOF, or error, returns the error code as a Integer.
@exception Exception File exception. | [
"Move",
"the",
"current",
"position",
"and",
"read",
"the",
"record",
"(",
"optionally",
"read",
"several",
"records",
")",
"."
]
| train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/remote/src/main/java/org/jbundle/thin/base/remote/proxy/TableProxy.java#L154-L162 |
Alluxio/alluxio | core/server/common/src/main/java/alluxio/master/journal/JournalUtils.java | JournalUtils.restoreJournalEntryCheckpoint | public static void restoreJournalEntryCheckpoint(CheckpointInputStream input, Journaled journaled)
throws IOException {
"""
Restores the given journaled object from the journal entries in the input stream.
This is the complement of
{@link #writeJournalEntryCheckpoint(OutputStream, JournalEntryIterable)}.
@param input the stream to read from
@param journaled the object to restore
"""
Preconditions.checkState(input.getType() == CheckpointType.JOURNAL_ENTRY,
"Unrecognized checkpoint type when restoring %s: %s", journaled.getCheckpointName(),
input.getType());
journaled.resetState();
LOG.info("Reading journal entries");
JournalEntryStreamReader reader = new JournalEntryStreamReader(input);
JournalEntry entry;
while ((entry = reader.readEntry()) != null) {
try {
journaled.processJournalEntry(entry);
} catch (Throwable t) {
handleJournalReplayFailure(LOG, t,
"Failed to process journal entry %s from a journal checkpoint", entry);
}
}
} | java | public static void restoreJournalEntryCheckpoint(CheckpointInputStream input, Journaled journaled)
throws IOException {
Preconditions.checkState(input.getType() == CheckpointType.JOURNAL_ENTRY,
"Unrecognized checkpoint type when restoring %s: %s", journaled.getCheckpointName(),
input.getType());
journaled.resetState();
LOG.info("Reading journal entries");
JournalEntryStreamReader reader = new JournalEntryStreamReader(input);
JournalEntry entry;
while ((entry = reader.readEntry()) != null) {
try {
journaled.processJournalEntry(entry);
} catch (Throwable t) {
handleJournalReplayFailure(LOG, t,
"Failed to process journal entry %s from a journal checkpoint", entry);
}
}
} | [
"public",
"static",
"void",
"restoreJournalEntryCheckpoint",
"(",
"CheckpointInputStream",
"input",
",",
"Journaled",
"journaled",
")",
"throws",
"IOException",
"{",
"Preconditions",
".",
"checkState",
"(",
"input",
".",
"getType",
"(",
")",
"==",
"CheckpointType",
".",
"JOURNAL_ENTRY",
",",
"\"Unrecognized checkpoint type when restoring %s: %s\"",
",",
"journaled",
".",
"getCheckpointName",
"(",
")",
",",
"input",
".",
"getType",
"(",
")",
")",
";",
"journaled",
".",
"resetState",
"(",
")",
";",
"LOG",
".",
"info",
"(",
"\"Reading journal entries\"",
")",
";",
"JournalEntryStreamReader",
"reader",
"=",
"new",
"JournalEntryStreamReader",
"(",
"input",
")",
";",
"JournalEntry",
"entry",
";",
"while",
"(",
"(",
"entry",
"=",
"reader",
".",
"readEntry",
"(",
")",
")",
"!=",
"null",
")",
"{",
"try",
"{",
"journaled",
".",
"processJournalEntry",
"(",
"entry",
")",
";",
"}",
"catch",
"(",
"Throwable",
"t",
")",
"{",
"handleJournalReplayFailure",
"(",
"LOG",
",",
"t",
",",
"\"Failed to process journal entry %s from a journal checkpoint\"",
",",
"entry",
")",
";",
"}",
"}",
"}"
]
| Restores the given journaled object from the journal entries in the input stream.
This is the complement of
{@link #writeJournalEntryCheckpoint(OutputStream, JournalEntryIterable)}.
@param input the stream to read from
@param journaled the object to restore | [
"Restores",
"the",
"given",
"journaled",
"object",
"from",
"the",
"journal",
"entries",
"in",
"the",
"input",
"stream",
"."
]
| train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/common/src/main/java/alluxio/master/journal/JournalUtils.java#L97-L114 |
lessthanoptimal/ddogleg | src/org/ddogleg/optimization/quasinewton/LineSearchFletcher86.java | LineSearchFletcher86.interpolate | protected double interpolate( double boundA , double boundB ) {
"""
Use either quadratic of cubic interpolation to guess the minimum.
"""
double alphaNew;
// interpolate minimum for rapid convergence
if( Double.isNaN(gp) ) {
alphaNew = SearchInterpolate.quadratic(fprev, gprev, stprev, fp, stp);
} else {
alphaNew = SearchInterpolate.cubic2(fprev, gprev, stprev, fp, gp, stp);
if( Double.isNaN(alphaNew))
alphaNew = SearchInterpolate.quadratic(fprev, gprev, stprev, fp, stp);
}
// order the bound
double l,u;
if( boundA < boundB ) {
l=boundA;u=boundB;
} else {
l=boundB;u=boundA;
}
// enforce min/max allowed values
if( alphaNew < l )
alphaNew = l;
else if( alphaNew > u )
alphaNew = u;
return alphaNew;
} | java | protected double interpolate( double boundA , double boundB )
{
double alphaNew;
// interpolate minimum for rapid convergence
if( Double.isNaN(gp) ) {
alphaNew = SearchInterpolate.quadratic(fprev, gprev, stprev, fp, stp);
} else {
alphaNew = SearchInterpolate.cubic2(fprev, gprev, stprev, fp, gp, stp);
if( Double.isNaN(alphaNew))
alphaNew = SearchInterpolate.quadratic(fprev, gprev, stprev, fp, stp);
}
// order the bound
double l,u;
if( boundA < boundB ) {
l=boundA;u=boundB;
} else {
l=boundB;u=boundA;
}
// enforce min/max allowed values
if( alphaNew < l )
alphaNew = l;
else if( alphaNew > u )
alphaNew = u;
return alphaNew;
} | [
"protected",
"double",
"interpolate",
"(",
"double",
"boundA",
",",
"double",
"boundB",
")",
"{",
"double",
"alphaNew",
";",
"// interpolate minimum for rapid convergence",
"if",
"(",
"Double",
".",
"isNaN",
"(",
"gp",
")",
")",
"{",
"alphaNew",
"=",
"SearchInterpolate",
".",
"quadratic",
"(",
"fprev",
",",
"gprev",
",",
"stprev",
",",
"fp",
",",
"stp",
")",
";",
"}",
"else",
"{",
"alphaNew",
"=",
"SearchInterpolate",
".",
"cubic2",
"(",
"fprev",
",",
"gprev",
",",
"stprev",
",",
"fp",
",",
"gp",
",",
"stp",
")",
";",
"if",
"(",
"Double",
".",
"isNaN",
"(",
"alphaNew",
")",
")",
"alphaNew",
"=",
"SearchInterpolate",
".",
"quadratic",
"(",
"fprev",
",",
"gprev",
",",
"stprev",
",",
"fp",
",",
"stp",
")",
";",
"}",
"// order the bound",
"double",
"l",
",",
"u",
";",
"if",
"(",
"boundA",
"<",
"boundB",
")",
"{",
"l",
"=",
"boundA",
";",
"u",
"=",
"boundB",
";",
"}",
"else",
"{",
"l",
"=",
"boundB",
";",
"u",
"=",
"boundA",
";",
"}",
"// enforce min/max allowed values",
"if",
"(",
"alphaNew",
"<",
"l",
")",
"alphaNew",
"=",
"l",
";",
"else",
"if",
"(",
"alphaNew",
">",
"u",
")",
"alphaNew",
"=",
"u",
";",
"return",
"alphaNew",
";",
"}"
]
| Use either quadratic of cubic interpolation to guess the minimum. | [
"Use",
"either",
"quadratic",
"of",
"cubic",
"interpolation",
"to",
"guess",
"the",
"minimum",
"."
]
| train | https://github.com/lessthanoptimal/ddogleg/blob/3786bf448ba23d0e04962dd08c34fa68de276029/src/org/ddogleg/optimization/quasinewton/LineSearchFletcher86.java#L351-L379 |
xcesco/kripton | kripton-arch-integration/src/main/java/androidx/paging/PositionalDataSource.java | PositionalDataSource.computeInitialLoadSize | @SuppressWarnings("WeakerAccess")
public static int computeInitialLoadSize(@NonNull LoadInitialParams params,
int initialLoadPosition, int totalCount) {
"""
Helper for computing an initial load size in
{@link #loadInitial(LoadInitialParams, LoadInitialCallback)} when total data set size can be
computed ahead of loading.
<p>
This function takes the requested load size, and bounds checks it against the value returned
by {@link #computeInitialLoadPosition(LoadInitialParams, int)}.
<p>
Example usage in a PositionalDataSource subclass:
<pre>
class ItemDataSource extends PositionalDataSource<Item> {
private int computeCount() {
// actual count code here
}
private List<Item> loadRangeInternal(int startPosition, int loadCount) {
// actual load code here
}
{@literal @}Override
public void loadInitial({@literal @}NonNull LoadInitialParams params,
{@literal @}NonNull LoadInitialCallback<Item> callback) {
int totalCount = computeCount();
int position = computeInitialLoadPosition(params, totalCount);
int loadSize = computeInitialLoadSize(params, position, totalCount);
callback.onResult(loadRangeInternal(position, loadSize), position, totalCount);
}
{@literal @}Override
public void loadRange({@literal @}NonNull LoadRangeParams params,
{@literal @}NonNull LoadRangeCallback<Item> callback) {
callback.onResult(loadRangeInternal(params.startPosition, params.loadSize));
}
}</pre>
@param params Params passed to {@link #loadInitial(LoadInitialParams, LoadInitialCallback)},
including page size, and requested start/loadSize.
@param initialLoadPosition Value returned by
{@link #computeInitialLoadPosition(LoadInitialParams, int)}
@param totalCount Total size of the data set.
@return Number of items to load.
@see #computeInitialLoadPosition(LoadInitialParams, int)
"""
return Math.min(totalCount - initialLoadPosition, params.requestedLoadSize);
} | java | @SuppressWarnings("WeakerAccess")
public static int computeInitialLoadSize(@NonNull LoadInitialParams params,
int initialLoadPosition, int totalCount) {
return Math.min(totalCount - initialLoadPosition, params.requestedLoadSize);
} | [
"@",
"SuppressWarnings",
"(",
"\"WeakerAccess\"",
")",
"public",
"static",
"int",
"computeInitialLoadSize",
"(",
"@",
"NonNull",
"LoadInitialParams",
"params",
",",
"int",
"initialLoadPosition",
",",
"int",
"totalCount",
")",
"{",
"return",
"Math",
".",
"min",
"(",
"totalCount",
"-",
"initialLoadPosition",
",",
"params",
".",
"requestedLoadSize",
")",
";",
"}"
]
| Helper for computing an initial load size in
{@link #loadInitial(LoadInitialParams, LoadInitialCallback)} when total data set size can be
computed ahead of loading.
<p>
This function takes the requested load size, and bounds checks it against the value returned
by {@link #computeInitialLoadPosition(LoadInitialParams, int)}.
<p>
Example usage in a PositionalDataSource subclass:
<pre>
class ItemDataSource extends PositionalDataSource<Item> {
private int computeCount() {
// actual count code here
}
private List<Item> loadRangeInternal(int startPosition, int loadCount) {
// actual load code here
}
{@literal @}Override
public void loadInitial({@literal @}NonNull LoadInitialParams params,
{@literal @}NonNull LoadInitialCallback<Item> callback) {
int totalCount = computeCount();
int position = computeInitialLoadPosition(params, totalCount);
int loadSize = computeInitialLoadSize(params, position, totalCount);
callback.onResult(loadRangeInternal(position, loadSize), position, totalCount);
}
{@literal @}Override
public void loadRange({@literal @}NonNull LoadRangeParams params,
{@literal @}NonNull LoadRangeCallback<Item> callback) {
callback.onResult(loadRangeInternal(params.startPosition, params.loadSize));
}
}</pre>
@param params Params passed to {@link #loadInitial(LoadInitialParams, LoadInitialCallback)},
including page size, and requested start/loadSize.
@param initialLoadPosition Value returned by
{@link #computeInitialLoadPosition(LoadInitialParams, int)}
@param totalCount Total size of the data set.
@return Number of items to load.
@see #computeInitialLoadPosition(LoadInitialParams, int) | [
"Helper",
"for",
"computing",
"an",
"initial",
"load",
"size",
"in",
"{",
"@link",
"#loadInitial",
"(",
"LoadInitialParams",
"LoadInitialCallback",
")",
"}",
"when",
"total",
"data",
"set",
"size",
"can",
"be",
"computed",
"ahead",
"of",
"loading",
".",
"<p",
">",
"This",
"function",
"takes",
"the",
"requested",
"load",
"size",
"and",
"bounds",
"checks",
"it",
"against",
"the",
"value",
"returned",
"by",
"{",
"@link",
"#computeInitialLoadPosition",
"(",
"LoadInitialParams",
"int",
")",
"}",
".",
"<p",
">",
"Example",
"usage",
"in",
"a",
"PositionalDataSource",
"subclass",
":",
"<pre",
">",
"class",
"ItemDataSource",
"extends",
"PositionalDataSource<",
";",
"Item",
">",
"{",
"private",
"int",
"computeCount",
"()",
"{",
"//",
"actual",
"count",
"code",
"here",
"}"
]
| train | https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-arch-integration/src/main/java/androidx/paging/PositionalDataSource.java#L453-L457 |
smartcat-labs/cassandra-migration-tool-java | src/main/java/io/smartcat/migration/Executor.java | Executor.migrate | public static boolean migrate(final Session session, final MigrationResources resources) {
"""
Execute all migrations in migration resource collection.
@param session Datastax driver sesison object
@param resources Migration resources collection
@return Return success
"""
return MigrationEngine.withSession(session).migrate(resources);
} | java | public static boolean migrate(final Session session, final MigrationResources resources) {
return MigrationEngine.withSession(session).migrate(resources);
} | [
"public",
"static",
"boolean",
"migrate",
"(",
"final",
"Session",
"session",
",",
"final",
"MigrationResources",
"resources",
")",
"{",
"return",
"MigrationEngine",
".",
"withSession",
"(",
"session",
")",
".",
"migrate",
"(",
"resources",
")",
";",
"}"
]
| Execute all migrations in migration resource collection.
@param session Datastax driver sesison object
@param resources Migration resources collection
@return Return success | [
"Execute",
"all",
"migrations",
"in",
"migration",
"resource",
"collection",
"."
]
| train | https://github.com/smartcat-labs/cassandra-migration-tool-java/blob/790a0580770fba707d31e0c767d380707c6da3fc/src/main/java/io/smartcat/migration/Executor.java#L20-L22 |
line/armeria | saml/src/main/java/com/linecorp/armeria/server/saml/HttpPostBindingUtil.java | HttpPostBindingUtil.toSamlObject | static <T extends SAMLObject> MessageContext<T> toSamlObject(AggregatedHttpMessage msg, String name) {
"""
Converts an {@link AggregatedHttpMessage} which is received from the remote entity to
a {@link SAMLObject}.
"""
final SamlParameters parameters = new SamlParameters(msg);
final byte[] decoded;
try {
decoded = Base64.getMimeDecoder().decode(parameters.getFirstValue(name));
} catch (IllegalArgumentException e) {
throw new SamlException("failed to decode a base64 string of the parameter: " + name, e);
}
@SuppressWarnings("unchecked")
final T message = (T) deserialize(decoded);
final MessageContext<T> messageContext = new MessageContext<>();
messageContext.setMessage(message);
final String relayState = parameters.getFirstValueOrNull(RELAY_STATE);
if (relayState != null) {
final SAMLBindingContext context = messageContext.getSubcontext(SAMLBindingContext.class, true);
assert context != null;
context.setRelayState(relayState);
}
return messageContext;
} | java | static <T extends SAMLObject> MessageContext<T> toSamlObject(AggregatedHttpMessage msg, String name) {
final SamlParameters parameters = new SamlParameters(msg);
final byte[] decoded;
try {
decoded = Base64.getMimeDecoder().decode(parameters.getFirstValue(name));
} catch (IllegalArgumentException e) {
throw new SamlException("failed to decode a base64 string of the parameter: " + name, e);
}
@SuppressWarnings("unchecked")
final T message = (T) deserialize(decoded);
final MessageContext<T> messageContext = new MessageContext<>();
messageContext.setMessage(message);
final String relayState = parameters.getFirstValueOrNull(RELAY_STATE);
if (relayState != null) {
final SAMLBindingContext context = messageContext.getSubcontext(SAMLBindingContext.class, true);
assert context != null;
context.setRelayState(relayState);
}
return messageContext;
} | [
"static",
"<",
"T",
"extends",
"SAMLObject",
">",
"MessageContext",
"<",
"T",
">",
"toSamlObject",
"(",
"AggregatedHttpMessage",
"msg",
",",
"String",
"name",
")",
"{",
"final",
"SamlParameters",
"parameters",
"=",
"new",
"SamlParameters",
"(",
"msg",
")",
";",
"final",
"byte",
"[",
"]",
"decoded",
";",
"try",
"{",
"decoded",
"=",
"Base64",
".",
"getMimeDecoder",
"(",
")",
".",
"decode",
"(",
"parameters",
".",
"getFirstValue",
"(",
"name",
")",
")",
";",
"}",
"catch",
"(",
"IllegalArgumentException",
"e",
")",
"{",
"throw",
"new",
"SamlException",
"(",
"\"failed to decode a base64 string of the parameter: \"",
"+",
"name",
",",
"e",
")",
";",
"}",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"final",
"T",
"message",
"=",
"(",
"T",
")",
"deserialize",
"(",
"decoded",
")",
";",
"final",
"MessageContext",
"<",
"T",
">",
"messageContext",
"=",
"new",
"MessageContext",
"<>",
"(",
")",
";",
"messageContext",
".",
"setMessage",
"(",
"message",
")",
";",
"final",
"String",
"relayState",
"=",
"parameters",
".",
"getFirstValueOrNull",
"(",
"RELAY_STATE",
")",
";",
"if",
"(",
"relayState",
"!=",
"null",
")",
"{",
"final",
"SAMLBindingContext",
"context",
"=",
"messageContext",
".",
"getSubcontext",
"(",
"SAMLBindingContext",
".",
"class",
",",
"true",
")",
";",
"assert",
"context",
"!=",
"null",
";",
"context",
".",
"setRelayState",
"(",
"relayState",
")",
";",
"}",
"return",
"messageContext",
";",
"}"
]
| Converts an {@link AggregatedHttpMessage} which is received from the remote entity to
a {@link SAMLObject}. | [
"Converts",
"an",
"{"
]
| train | https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/saml/src/main/java/com/linecorp/armeria/server/saml/HttpPostBindingUtil.java#L106-L129 |
liferay/com-liferay-commerce | commerce-price-list-service/src/main/java/com/liferay/commerce/price/list/service/persistence/impl/CommerceTierPriceEntryPersistenceImpl.java | CommerceTierPriceEntryPersistenceImpl.findByGroupId | @Override
public List<CommerceTierPriceEntry> findByGroupId(long groupId, int start,
int end) {
"""
Returns a range of all the commerce tier price entries where groupId = ?.
<p>
Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceTierPriceEntryModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
</p>
@param groupId the group ID
@param start the lower bound of the range of commerce tier price entries
@param end the upper bound of the range of commerce tier price entries (not inclusive)
@return the range of matching commerce tier price entries
"""
return findByGroupId(groupId, start, end, null);
} | java | @Override
public List<CommerceTierPriceEntry> findByGroupId(long groupId, int start,
int end) {
return findByGroupId(groupId, start, end, null);
} | [
"@",
"Override",
"public",
"List",
"<",
"CommerceTierPriceEntry",
">",
"findByGroupId",
"(",
"long",
"groupId",
",",
"int",
"start",
",",
"int",
"end",
")",
"{",
"return",
"findByGroupId",
"(",
"groupId",
",",
"start",
",",
"end",
",",
"null",
")",
";",
"}"
]
| Returns a range of all the commerce tier price entries where groupId = ?.
<p>
Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceTierPriceEntryModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
</p>
@param groupId the group ID
@param start the lower bound of the range of commerce tier price entries
@param end the upper bound of the range of commerce tier price entries (not inclusive)
@return the range of matching commerce tier price entries | [
"Returns",
"a",
"range",
"of",
"all",
"the",
"commerce",
"tier",
"price",
"entries",
"where",
"groupId",
"=",
"?",
";",
"."
]
| train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-price-list-service/src/main/java/com/liferay/commerce/price/list/service/persistence/impl/CommerceTierPriceEntryPersistenceImpl.java#L1544-L1548 |
Azure/azure-sdk-for-java | eventgrid/resource-manager/v2018_05_01_preview/src/main/java/com/microsoft/azure/management/eventgrid/v2018_05_01_preview/implementation/EventSubscriptionsInner.java | EventSubscriptionsInner.beginUpdate | public EventSubscriptionInner beginUpdate(String scope, String eventSubscriptionName, EventSubscriptionUpdateParameters eventSubscriptionUpdateParameters) {
"""
Update an event subscription.
Asynchronously updates an existing event subscription.
@param scope The scope of existing event subscription. The scope can be a subscription, or a resource group, or a top level resource belonging to a resource provider namespace, or an EventGrid topic. For example, use '/subscriptions/{subscriptionId}/' for a subscription, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for a resource group, and '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}' for a resource, and '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/topics/{topicName}' for an EventGrid topic.
@param eventSubscriptionName Name of the event subscription to be updated
@param eventSubscriptionUpdateParameters Updated event subscription information
@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 EventSubscriptionInner object if successful.
"""
return beginUpdateWithServiceResponseAsync(scope, eventSubscriptionName, eventSubscriptionUpdateParameters).toBlocking().single().body();
} | java | public EventSubscriptionInner beginUpdate(String scope, String eventSubscriptionName, EventSubscriptionUpdateParameters eventSubscriptionUpdateParameters) {
return beginUpdateWithServiceResponseAsync(scope, eventSubscriptionName, eventSubscriptionUpdateParameters).toBlocking().single().body();
} | [
"public",
"EventSubscriptionInner",
"beginUpdate",
"(",
"String",
"scope",
",",
"String",
"eventSubscriptionName",
",",
"EventSubscriptionUpdateParameters",
"eventSubscriptionUpdateParameters",
")",
"{",
"return",
"beginUpdateWithServiceResponseAsync",
"(",
"scope",
",",
"eventSubscriptionName",
",",
"eventSubscriptionUpdateParameters",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
"body",
"(",
")",
";",
"}"
]
| Update an event subscription.
Asynchronously updates an existing event subscription.
@param scope The scope of existing event subscription. The scope can be a subscription, or a resource group, or a top level resource belonging to a resource provider namespace, or an EventGrid topic. For example, use '/subscriptions/{subscriptionId}/' for a subscription, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for a resource group, and '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}' for a resource, and '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/topics/{topicName}' for an EventGrid topic.
@param eventSubscriptionName Name of the event subscription to be updated
@param eventSubscriptionUpdateParameters Updated event subscription information
@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 EventSubscriptionInner object if successful. | [
"Update",
"an",
"event",
"subscription",
".",
"Asynchronously",
"updates",
"an",
"existing",
"event",
"subscription",
"."
]
| train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/eventgrid/resource-manager/v2018_05_01_preview/src/main/java/com/microsoft/azure/management/eventgrid/v2018_05_01_preview/implementation/EventSubscriptionsInner.java#L643-L645 |
VoltDB/voltdb | src/frontend/org/voltdb/NonVoltDBBackend.java | NonVoltDBBackend.isInteger | private boolean isInteger(String columnOrConstant, List<String> tableNames, boolean debugPrint) {
"""
Returns true if the <i>columnOrConstant</i> is either an integer
constant or an integer column (including types TINYINT, SMALLINT,
INTEGER, BIGINT, or equivalents in a comparison, non-VoltDB database);
false otherwise.
"""
return isIntegerConstant(columnOrConstant) || isIntegerColumn(columnOrConstant, tableNames, debugPrint);
} | java | private boolean isInteger(String columnOrConstant, List<String> tableNames, boolean debugPrint) {
return isIntegerConstant(columnOrConstant) || isIntegerColumn(columnOrConstant, tableNames, debugPrint);
} | [
"private",
"boolean",
"isInteger",
"(",
"String",
"columnOrConstant",
",",
"List",
"<",
"String",
">",
"tableNames",
",",
"boolean",
"debugPrint",
")",
"{",
"return",
"isIntegerConstant",
"(",
"columnOrConstant",
")",
"||",
"isIntegerColumn",
"(",
"columnOrConstant",
",",
"tableNames",
",",
"debugPrint",
")",
";",
"}"
]
| Returns true if the <i>columnOrConstant</i> is either an integer
constant or an integer column (including types TINYINT, SMALLINT,
INTEGER, BIGINT, or equivalents in a comparison, non-VoltDB database);
false otherwise. | [
"Returns",
"true",
"if",
"the",
"<i",
">",
"columnOrConstant<",
"/",
"i",
">",
"is",
"either",
"an",
"integer",
"constant",
"or",
"an",
"integer",
"column",
"(",
"including",
"types",
"TINYINT",
"SMALLINT",
"INTEGER",
"BIGINT",
"or",
"equivalents",
"in",
"a",
"comparison",
"non",
"-",
"VoltDB",
"database",
")",
";",
"false",
"otherwise",
"."
]
| train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/NonVoltDBBackend.java#L598-L600 |
Azure/azure-sdk-for-java | batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/PoolsImpl.java | PoolsImpl.addAsync | public Observable<Void> addAsync(PoolAddParameter pool, PoolAddOptions poolAddOptions) {
"""
Adds a pool to the specified account.
When naming pools, avoid including sensitive information such as user names or secret project names. This information may appear in telemetry logs accessible to Microsoft Support engineers.
@param pool The pool to be added.
@param poolAddOptions Additional parameters for the operation
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceResponseWithHeaders} object if successful.
"""
return addWithServiceResponseAsync(pool, poolAddOptions).map(new Func1<ServiceResponseWithHeaders<Void, PoolAddHeaders>, Void>() {
@Override
public Void call(ServiceResponseWithHeaders<Void, PoolAddHeaders> response) {
return response.body();
}
});
} | java | public Observable<Void> addAsync(PoolAddParameter pool, PoolAddOptions poolAddOptions) {
return addWithServiceResponseAsync(pool, poolAddOptions).map(new Func1<ServiceResponseWithHeaders<Void, PoolAddHeaders>, Void>() {
@Override
public Void call(ServiceResponseWithHeaders<Void, PoolAddHeaders> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Void",
">",
"addAsync",
"(",
"PoolAddParameter",
"pool",
",",
"PoolAddOptions",
"poolAddOptions",
")",
"{",
"return",
"addWithServiceResponseAsync",
"(",
"pool",
",",
"poolAddOptions",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponseWithHeaders",
"<",
"Void",
",",
"PoolAddHeaders",
">",
",",
"Void",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"Void",
"call",
"(",
"ServiceResponseWithHeaders",
"<",
"Void",
",",
"PoolAddHeaders",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Adds a pool to the specified account.
When naming pools, avoid including sensitive information such as user names or secret project names. This information may appear in telemetry logs accessible to Microsoft Support engineers.
@param pool The pool to be added.
@param poolAddOptions Additional parameters for the operation
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceResponseWithHeaders} object if successful. | [
"Adds",
"a",
"pool",
"to",
"the",
"specified",
"account",
".",
"When",
"naming",
"pools",
"avoid",
"including",
"sensitive",
"information",
"such",
"as",
"user",
"names",
"or",
"secret",
"project",
"names",
".",
"This",
"information",
"may",
"appear",
"in",
"telemetry",
"logs",
"accessible",
"to",
"Microsoft",
"Support",
"engineers",
"."
]
| train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/PoolsImpl.java#L780-L787 |
wmdietl/jsr308-langtools | src/share/classes/com/sun/tools/javac/jvm/CRTable.java | CRTable.encodePosition | private int encodePosition(int pos, Position.LineMap lineMap, Log log) {
"""
Source file positions in CRT are integers in the format:
{@literal line-number << LINESHIFT + column-number }
"""
int line = lineMap.getLineNumber(pos);
int col = lineMap.getColumnNumber(pos);
int new_pos = Position.encodePosition(line, col);
if (crtDebug) {
System.out.println(", line = " + line + ", column = " + col +
", new_pos = " + new_pos);
}
if (new_pos == Position.NOPOS)
log.warning(pos, "position.overflow", line);
return new_pos;
} | java | private int encodePosition(int pos, Position.LineMap lineMap, Log log) {
int line = lineMap.getLineNumber(pos);
int col = lineMap.getColumnNumber(pos);
int new_pos = Position.encodePosition(line, col);
if (crtDebug) {
System.out.println(", line = " + line + ", column = " + col +
", new_pos = " + new_pos);
}
if (new_pos == Position.NOPOS)
log.warning(pos, "position.overflow", line);
return new_pos;
} | [
"private",
"int",
"encodePosition",
"(",
"int",
"pos",
",",
"Position",
".",
"LineMap",
"lineMap",
",",
"Log",
"log",
")",
"{",
"int",
"line",
"=",
"lineMap",
".",
"getLineNumber",
"(",
"pos",
")",
";",
"int",
"col",
"=",
"lineMap",
".",
"getColumnNumber",
"(",
"pos",
")",
";",
"int",
"new_pos",
"=",
"Position",
".",
"encodePosition",
"(",
"line",
",",
"col",
")",
";",
"if",
"(",
"crtDebug",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"\", line = \"",
"+",
"line",
"+",
"\", column = \"",
"+",
"col",
"+",
"\", new_pos = \"",
"+",
"new_pos",
")",
";",
"}",
"if",
"(",
"new_pos",
"==",
"Position",
".",
"NOPOS",
")",
"log",
".",
"warning",
"(",
"pos",
",",
"\"position.overflow\"",
",",
"line",
")",
";",
"return",
"new_pos",
";",
"}"
]
| Source file positions in CRT are integers in the format:
{@literal line-number << LINESHIFT + column-number } | [
"Source",
"file",
"positions",
"in",
"CRT",
"are",
"integers",
"in",
"the",
"format",
":",
"{"
]
| train | https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/javac/jvm/CRTable.java#L167-L179 |
networknt/light-4j | utility/src/main/java/com/networknt/utility/NetUtils.java | NetUtils.getLocalAddress | public static InetAddress getLocalAddress(Map<String, Integer> destHostPorts) {
"""
<pre>
1. check if you already have ip
2. get ip from hostname
3. get ip from socket
4. get ip from network interface
</pre>
@param destHostPorts a map of ports
@return local ip
"""
if (LOCAL_ADDRESS != null) {
return LOCAL_ADDRESS;
}
InetAddress localAddress = getLocalAddressByHostname();
if (!isValidAddress(localAddress)) {
localAddress = getLocalAddressBySocket(destHostPorts);
}
if (!isValidAddress(localAddress)) {
localAddress = getLocalAddressByNetworkInterface();
}
if (isValidAddress(localAddress)) {
LOCAL_ADDRESS = localAddress;
}
return localAddress;
} | java | public static InetAddress getLocalAddress(Map<String, Integer> destHostPorts) {
if (LOCAL_ADDRESS != null) {
return LOCAL_ADDRESS;
}
InetAddress localAddress = getLocalAddressByHostname();
if (!isValidAddress(localAddress)) {
localAddress = getLocalAddressBySocket(destHostPorts);
}
if (!isValidAddress(localAddress)) {
localAddress = getLocalAddressByNetworkInterface();
}
if (isValidAddress(localAddress)) {
LOCAL_ADDRESS = localAddress;
}
return localAddress;
} | [
"public",
"static",
"InetAddress",
"getLocalAddress",
"(",
"Map",
"<",
"String",
",",
"Integer",
">",
"destHostPorts",
")",
"{",
"if",
"(",
"LOCAL_ADDRESS",
"!=",
"null",
")",
"{",
"return",
"LOCAL_ADDRESS",
";",
"}",
"InetAddress",
"localAddress",
"=",
"getLocalAddressByHostname",
"(",
")",
";",
"if",
"(",
"!",
"isValidAddress",
"(",
"localAddress",
")",
")",
"{",
"localAddress",
"=",
"getLocalAddressBySocket",
"(",
"destHostPorts",
")",
";",
"}",
"if",
"(",
"!",
"isValidAddress",
"(",
"localAddress",
")",
")",
"{",
"localAddress",
"=",
"getLocalAddressByNetworkInterface",
"(",
")",
";",
"}",
"if",
"(",
"isValidAddress",
"(",
"localAddress",
")",
")",
"{",
"LOCAL_ADDRESS",
"=",
"localAddress",
";",
"}",
"return",
"localAddress",
";",
"}"
]
| <pre>
1. check if you already have ip
2. get ip from hostname
3. get ip from socket
4. get ip from network interface
</pre>
@param destHostPorts a map of ports
@return local ip | [
"<pre",
">",
"1",
".",
"check",
"if",
"you",
"already",
"have",
"ip",
"2",
".",
"get",
"ip",
"from",
"hostname",
"3",
".",
"get",
"ip",
"from",
"socket",
"4",
".",
"get",
"ip",
"from",
"network",
"interface",
"<",
"/",
"pre",
">"
]
| train | https://github.com/networknt/light-4j/blob/2a60257c60663684c8f6dc8b5ea3cf184e534db6/utility/src/main/java/com/networknt/utility/NetUtils.java#L75-L94 |
igniterealtime/Smack | smack-extensions/src/main/java/org/jivesoftware/smackx/caps/EntityCapsManager.java | EntityCapsManager.addDiscoverInfoByNode | static void addDiscoverInfoByNode(String nodeVer, DiscoverInfo info) {
"""
Add DiscoverInfo to the database.
@param nodeVer
The node and verification String (e.g.
"http://psi-im.org#q07IKJEyjvHSyhy//CH0CxmKi8w=").
@param info
DiscoverInfo for the specified node.
"""
CAPS_CACHE.put(nodeVer, info);
if (persistentCache != null)
persistentCache.addDiscoverInfoByNodePersistent(nodeVer, info);
} | java | static void addDiscoverInfoByNode(String nodeVer, DiscoverInfo info) {
CAPS_CACHE.put(nodeVer, info);
if (persistentCache != null)
persistentCache.addDiscoverInfoByNodePersistent(nodeVer, info);
} | [
"static",
"void",
"addDiscoverInfoByNode",
"(",
"String",
"nodeVer",
",",
"DiscoverInfo",
"info",
")",
"{",
"CAPS_CACHE",
".",
"put",
"(",
"nodeVer",
",",
"info",
")",
";",
"if",
"(",
"persistentCache",
"!=",
"null",
")",
"persistentCache",
".",
"addDiscoverInfoByNodePersistent",
"(",
"nodeVer",
",",
"info",
")",
";",
"}"
]
| Add DiscoverInfo to the database.
@param nodeVer
The node and verification String (e.g.
"http://psi-im.org#q07IKJEyjvHSyhy//CH0CxmKi8w=").
@param info
DiscoverInfo for the specified node. | [
"Add",
"DiscoverInfo",
"to",
"the",
"database",
"."
]
| train | https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/caps/EntityCapsManager.java#L183-L188 |
inkstand-io/scribble | scribble-inject/src/main/java/io/inkstand/scribble/inject/Injection.java | Injection.injectInto | private void injectInto(final Object target, final boolean oneMatch) throws AssertionError {
"""
Injects the value of the Injection into the target.
@param target
the target for the injection operation
@param oneMatch
if set to <code>true</code>, the method returns after one injection operation has been performed.
If set to <code>false</code> the injection value is injected into all matching fields.
@throws AssertionError
if the value could not be inject because the field is not accessible.
"""
boolean success = false;
for (final Field field : this.collectFieldCandidates(target)) {
if (this.isMatching(field)) {
Object val = getValue(field);
try {
field.setAccessible(true);
this.inject(target, field, val);
success = true;
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new AssertionError("Injection of " + val + " into " + target + " failed", e);
}
if (oneMatch) {
return;
}
}
}
assertTrue("No matching field for injection found", success);
} | java | private void injectInto(final Object target, final boolean oneMatch) throws AssertionError {
boolean success = false;
for (final Field field : this.collectFieldCandidates(target)) {
if (this.isMatching(field)) {
Object val = getValue(field);
try {
field.setAccessible(true);
this.inject(target, field, val);
success = true;
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new AssertionError("Injection of " + val + " into " + target + " failed", e);
}
if (oneMatch) {
return;
}
}
}
assertTrue("No matching field for injection found", success);
} | [
"private",
"void",
"injectInto",
"(",
"final",
"Object",
"target",
",",
"final",
"boolean",
"oneMatch",
")",
"throws",
"AssertionError",
"{",
"boolean",
"success",
"=",
"false",
";",
"for",
"(",
"final",
"Field",
"field",
":",
"this",
".",
"collectFieldCandidates",
"(",
"target",
")",
")",
"{",
"if",
"(",
"this",
".",
"isMatching",
"(",
"field",
")",
")",
"{",
"Object",
"val",
"=",
"getValue",
"(",
"field",
")",
";",
"try",
"{",
"field",
".",
"setAccessible",
"(",
"true",
")",
";",
"this",
".",
"inject",
"(",
"target",
",",
"field",
",",
"val",
")",
";",
"success",
"=",
"true",
";",
"}",
"catch",
"(",
"IllegalArgumentException",
"|",
"IllegalAccessException",
"e",
")",
"{",
"throw",
"new",
"AssertionError",
"(",
"\"Injection of \"",
"+",
"val",
"+",
"\" into \"",
"+",
"target",
"+",
"\" failed\"",
",",
"e",
")",
";",
"}",
"if",
"(",
"oneMatch",
")",
"{",
"return",
";",
"}",
"}",
"}",
"assertTrue",
"(",
"\"No matching field for injection found\"",
",",
"success",
")",
";",
"}"
]
| Injects the value of the Injection into the target.
@param target
the target for the injection operation
@param oneMatch
if set to <code>true</code>, the method returns after one injection operation has been performed.
If set to <code>false</code> the injection value is injected into all matching fields.
@throws AssertionError
if the value could not be inject because the field is not accessible. | [
"Injects",
"the",
"value",
"of",
"the",
"Injection",
"into",
"the",
"target",
"."
]
| train | https://github.com/inkstand-io/scribble/blob/66e67553bad4b1ff817e1715fd1d3dd833406744/scribble-inject/src/main/java/io/inkstand/scribble/inject/Injection.java#L157-L177 |
Azure/azure-sdk-for-java | compute/resource-manager/v2017_03_30/src/main/java/com/microsoft/azure/management/compute/v2017_03_30/implementation/VirtualMachineScaleSetsInner.java | VirtualMachineScaleSetsInner.deleteInstancesAsync | public Observable<OperationStatusResponseInner> deleteInstancesAsync(String resourceGroupName, String vmScaleSetName, List<String> instanceIds) {
"""
Deletes virtual machines in a VM scale set.
@param resourceGroupName The name of the resource group.
@param vmScaleSetName The name of the VM scale set.
@param instanceIds The virtual machine scale set instance ids.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request
"""
return deleteInstancesWithServiceResponseAsync(resourceGroupName, vmScaleSetName, instanceIds).map(new Func1<ServiceResponse<OperationStatusResponseInner>, OperationStatusResponseInner>() {
@Override
public OperationStatusResponseInner call(ServiceResponse<OperationStatusResponseInner> response) {
return response.body();
}
});
} | java | public Observable<OperationStatusResponseInner> deleteInstancesAsync(String resourceGroupName, String vmScaleSetName, List<String> instanceIds) {
return deleteInstancesWithServiceResponseAsync(resourceGroupName, vmScaleSetName, instanceIds).map(new Func1<ServiceResponse<OperationStatusResponseInner>, OperationStatusResponseInner>() {
@Override
public OperationStatusResponseInner call(ServiceResponse<OperationStatusResponseInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"OperationStatusResponseInner",
">",
"deleteInstancesAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"vmScaleSetName",
",",
"List",
"<",
"String",
">",
"instanceIds",
")",
"{",
"return",
"deleteInstancesWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"vmScaleSetName",
",",
"instanceIds",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"OperationStatusResponseInner",
">",
",",
"OperationStatusResponseInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"OperationStatusResponseInner",
"call",
"(",
"ServiceResponse",
"<",
"OperationStatusResponseInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Deletes virtual machines in a VM scale set.
@param resourceGroupName The name of the resource group.
@param vmScaleSetName The name of the VM scale set.
@param instanceIds The virtual machine scale set instance ids.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request | [
"Deletes",
"virtual",
"machines",
"in",
"a",
"VM",
"scale",
"set",
"."
]
| train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/compute/resource-manager/v2017_03_30/src/main/java/com/microsoft/azure/management/compute/v2017_03_30/implementation/VirtualMachineScaleSetsInner.java#L1147-L1154 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/XPathContext.java | XPathContext.setErrorListener | public void setErrorListener(ErrorListener listener) throws IllegalArgumentException {
"""
Set the ErrorListener where errors and warnings are to be reported.
@param listener A non-null ErrorListener reference.
"""
if (listener == null)
throw new IllegalArgumentException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_NULL_ERROR_HANDLER, null)); //"Null error handler");
m_errorListener = listener;
} | java | public void setErrorListener(ErrorListener listener) throws IllegalArgumentException
{
if (listener == null)
throw new IllegalArgumentException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_NULL_ERROR_HANDLER, null)); //"Null error handler");
m_errorListener = listener;
} | [
"public",
"void",
"setErrorListener",
"(",
"ErrorListener",
"listener",
")",
"throws",
"IllegalArgumentException",
"{",
"if",
"(",
"listener",
"==",
"null",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"XSLMessages",
".",
"createXPATHMessage",
"(",
"XPATHErrorResources",
".",
"ER_NULL_ERROR_HANDLER",
",",
"null",
")",
")",
";",
"//\"Null error handler\");",
"m_errorListener",
"=",
"listener",
";",
"}"
]
| Set the ErrorListener where errors and warnings are to be reported.
@param listener A non-null ErrorListener reference. | [
"Set",
"the",
"ErrorListener",
"where",
"errors",
"and",
"warnings",
"are",
"to",
"be",
"reported",
"."
]
| train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/XPathContext.java#L569-L574 |
b3log/latke | latke-core/src/main/java/org/b3log/latke/util/Crypts.java | Crypts.decryptByAES | public static String decryptByAES(final String content, final String key) {
"""
Decrypts by AES.
@param content the specified content to decrypt
@param key the specified key
@return original content
@see #encryptByAES(java.lang.String, java.lang.String)
"""
try {
final byte[] data = Hex.decodeHex(content.toCharArray());
final KeyGenerator kgen = KeyGenerator.getInstance("AES");
final SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(key.getBytes());
kgen.init(128, secureRandom);
final SecretKey secretKey = kgen.generateKey();
final byte[] enCodeFormat = secretKey.getEncoded();
final SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat, "AES");
final Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, keySpec);
final byte[] result = cipher.doFinal(data);
return new String(result, "UTF-8");
} catch (final Exception e) {
LOGGER.log(Level.WARN, "Decrypt failed");
return null;
}
} | java | public static String decryptByAES(final String content, final String key) {
try {
final byte[] data = Hex.decodeHex(content.toCharArray());
final KeyGenerator kgen = KeyGenerator.getInstance("AES");
final SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(key.getBytes());
kgen.init(128, secureRandom);
final SecretKey secretKey = kgen.generateKey();
final byte[] enCodeFormat = secretKey.getEncoded();
final SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat, "AES");
final Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, keySpec);
final byte[] result = cipher.doFinal(data);
return new String(result, "UTF-8");
} catch (final Exception e) {
LOGGER.log(Level.WARN, "Decrypt failed");
return null;
}
} | [
"public",
"static",
"String",
"decryptByAES",
"(",
"final",
"String",
"content",
",",
"final",
"String",
"key",
")",
"{",
"try",
"{",
"final",
"byte",
"[",
"]",
"data",
"=",
"Hex",
".",
"decodeHex",
"(",
"content",
".",
"toCharArray",
"(",
")",
")",
";",
"final",
"KeyGenerator",
"kgen",
"=",
"KeyGenerator",
".",
"getInstance",
"(",
"\"AES\"",
")",
";",
"final",
"SecureRandom",
"secureRandom",
"=",
"SecureRandom",
".",
"getInstance",
"(",
"\"SHA1PRNG\"",
")",
";",
"secureRandom",
".",
"setSeed",
"(",
"key",
".",
"getBytes",
"(",
")",
")",
";",
"kgen",
".",
"init",
"(",
"128",
",",
"secureRandom",
")",
";",
"final",
"SecretKey",
"secretKey",
"=",
"kgen",
".",
"generateKey",
"(",
")",
";",
"final",
"byte",
"[",
"]",
"enCodeFormat",
"=",
"secretKey",
".",
"getEncoded",
"(",
")",
";",
"final",
"SecretKeySpec",
"keySpec",
"=",
"new",
"SecretKeySpec",
"(",
"enCodeFormat",
",",
"\"AES\"",
")",
";",
"final",
"Cipher",
"cipher",
"=",
"Cipher",
".",
"getInstance",
"(",
"\"AES\"",
")",
";",
"cipher",
".",
"init",
"(",
"Cipher",
".",
"DECRYPT_MODE",
",",
"keySpec",
")",
";",
"final",
"byte",
"[",
"]",
"result",
"=",
"cipher",
".",
"doFinal",
"(",
"data",
")",
";",
"return",
"new",
"String",
"(",
"result",
",",
"\"UTF-8\"",
")",
";",
"}",
"catch",
"(",
"final",
"Exception",
"e",
")",
"{",
"LOGGER",
".",
"log",
"(",
"Level",
".",
"WARN",
",",
"\"Decrypt failed\"",
")",
";",
"return",
"null",
";",
"}",
"}"
]
| Decrypts by AES.
@param content the specified content to decrypt
@param key the specified key
@return original content
@see #encryptByAES(java.lang.String, java.lang.String) | [
"Decrypts",
"by",
"AES",
"."
]
| train | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/util/Crypts.java#L101-L121 |
alkacon/opencms-core | src/org/opencms/ade/galleries/CmsSiteSelectorOptionBuilder.java | CmsSiteSelectorOptionBuilder.addOption | private void addOption(Type type, String siteRoot, String message) {
"""
Internal helper method for adding an option.<p>
@param type the option type
@param siteRoot the site root
@param message the message for the option
"""
if (m_usedSiteRoots.contains(CmsStringUtil.joinPaths(siteRoot, "/"))) {
return;
}
CmsSiteSelectorOption option = new CmsSiteSelectorOption(type, siteRoot, m_siteRoot.equals(siteRoot), message);
// make sure to insert the root site is first and the shared site as second entry
if (Type.root.equals(type)) {
m_options.add(0, option);
} else if (Type.shared.equals(type)) {
if (!m_options.isEmpty() && Type.root.equals(m_options.get(0).getType())) {
m_options.add(1, option);
} else {
m_options.add(0, option);
}
} else {
m_options.add(option);
}
m_usedSiteRoots.add(CmsStringUtil.joinPaths(siteRoot, "/"));
} | java | private void addOption(Type type, String siteRoot, String message) {
if (m_usedSiteRoots.contains(CmsStringUtil.joinPaths(siteRoot, "/"))) {
return;
}
CmsSiteSelectorOption option = new CmsSiteSelectorOption(type, siteRoot, m_siteRoot.equals(siteRoot), message);
// make sure to insert the root site is first and the shared site as second entry
if (Type.root.equals(type)) {
m_options.add(0, option);
} else if (Type.shared.equals(type)) {
if (!m_options.isEmpty() && Type.root.equals(m_options.get(0).getType())) {
m_options.add(1, option);
} else {
m_options.add(0, option);
}
} else {
m_options.add(option);
}
m_usedSiteRoots.add(CmsStringUtil.joinPaths(siteRoot, "/"));
} | [
"private",
"void",
"addOption",
"(",
"Type",
"type",
",",
"String",
"siteRoot",
",",
"String",
"message",
")",
"{",
"if",
"(",
"m_usedSiteRoots",
".",
"contains",
"(",
"CmsStringUtil",
".",
"joinPaths",
"(",
"siteRoot",
",",
"\"/\"",
")",
")",
")",
"{",
"return",
";",
"}",
"CmsSiteSelectorOption",
"option",
"=",
"new",
"CmsSiteSelectorOption",
"(",
"type",
",",
"siteRoot",
",",
"m_siteRoot",
".",
"equals",
"(",
"siteRoot",
")",
",",
"message",
")",
";",
"// make sure to insert the root site is first and the shared site as second entry",
"if",
"(",
"Type",
".",
"root",
".",
"equals",
"(",
"type",
")",
")",
"{",
"m_options",
".",
"add",
"(",
"0",
",",
"option",
")",
";",
"}",
"else",
"if",
"(",
"Type",
".",
"shared",
".",
"equals",
"(",
"type",
")",
")",
"{",
"if",
"(",
"!",
"m_options",
".",
"isEmpty",
"(",
")",
"&&",
"Type",
".",
"root",
".",
"equals",
"(",
"m_options",
".",
"get",
"(",
"0",
")",
".",
"getType",
"(",
")",
")",
")",
"{",
"m_options",
".",
"add",
"(",
"1",
",",
"option",
")",
";",
"}",
"else",
"{",
"m_options",
".",
"add",
"(",
"0",
",",
"option",
")",
";",
"}",
"}",
"else",
"{",
"m_options",
".",
"add",
"(",
"option",
")",
";",
"}",
"m_usedSiteRoots",
".",
"add",
"(",
"CmsStringUtil",
".",
"joinPaths",
"(",
"siteRoot",
",",
"\"/\"",
")",
")",
";",
"}"
]
| Internal helper method for adding an option.<p>
@param type the option type
@param siteRoot the site root
@param message the message for the option | [
"Internal",
"helper",
"method",
"for",
"adding",
"an",
"option",
".",
"<p",
">"
]
| train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/galleries/CmsSiteSelectorOptionBuilder.java#L212-L232 |
Wolfgang-Schuetzelhofer/jcypher | src/main/java/iot/jcypher/query/LiteralMapList.java | LiteralMapList.select | public LiteralMapList select(JcPrimitive key, Object value) {
"""
Answer a LiteralMapList containing only literal maps with the given key and value
@param key
@param value
@return
"""
LiteralMapList ret = new LiteralMapList();
for (LiteralMap lm : this) {
if (isEqual(value, lm.get(ValueAccess.getName(key))))
ret.add(lm);
}
return ret;
} | java | public LiteralMapList select(JcPrimitive key, Object value) {
LiteralMapList ret = new LiteralMapList();
for (LiteralMap lm : this) {
if (isEqual(value, lm.get(ValueAccess.getName(key))))
ret.add(lm);
}
return ret;
} | [
"public",
"LiteralMapList",
"select",
"(",
"JcPrimitive",
"key",
",",
"Object",
"value",
")",
"{",
"LiteralMapList",
"ret",
"=",
"new",
"LiteralMapList",
"(",
")",
";",
"for",
"(",
"LiteralMap",
"lm",
":",
"this",
")",
"{",
"if",
"(",
"isEqual",
"(",
"value",
",",
"lm",
".",
"get",
"(",
"ValueAccess",
".",
"getName",
"(",
"key",
")",
")",
")",
")",
"ret",
".",
"add",
"(",
"lm",
")",
";",
"}",
"return",
"ret",
";",
"}"
]
| Answer a LiteralMapList containing only literal maps with the given key and value
@param key
@param value
@return | [
"Answer",
"a",
"LiteralMapList",
"containing",
"only",
"literal",
"maps",
"with",
"the",
"given",
"key",
"and",
"value"
]
| train | https://github.com/Wolfgang-Schuetzelhofer/jcypher/blob/0f36914b4d6993a004cc235bb18dd3e02a59d253/src/main/java/iot/jcypher/query/LiteralMapList.java#L47-L54 |
biojava/biojava | biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/ProfeatProperties.java | ProfeatProperties.getComposition | public static double getComposition(ProteinSequence sequence, ATTRIBUTE attribute, GROUPING group) throws Exception {
"""
An adaptor method which returns the composition of the specific grouping for the given attribute.
@param sequence
a protein sequence consisting of non-ambiguous characters only
@param attribute
one of the seven attributes (Hydrophobicity, Volume, Polarity, Polarizability, Charge, SecondaryStructure or SolventAccessibility)
@param group
the grouping to be computed
@return
returns the composition of the specific grouping for the given attribute
@throws Exception
throws Exception if attribute or group are unknown
"""
return new ProfeatPropertiesImpl().getComposition(sequence, attribute, group);
} | java | public static double getComposition(ProteinSequence sequence, ATTRIBUTE attribute, GROUPING group) throws Exception{
return new ProfeatPropertiesImpl().getComposition(sequence, attribute, group);
} | [
"public",
"static",
"double",
"getComposition",
"(",
"ProteinSequence",
"sequence",
",",
"ATTRIBUTE",
"attribute",
",",
"GROUPING",
"group",
")",
"throws",
"Exception",
"{",
"return",
"new",
"ProfeatPropertiesImpl",
"(",
")",
".",
"getComposition",
"(",
"sequence",
",",
"attribute",
",",
"group",
")",
";",
"}"
]
| An adaptor method which returns the composition of the specific grouping for the given attribute.
@param sequence
a protein sequence consisting of non-ambiguous characters only
@param attribute
one of the seven attributes (Hydrophobicity, Volume, Polarity, Polarizability, Charge, SecondaryStructure or SolventAccessibility)
@param group
the grouping to be computed
@return
returns the composition of the specific grouping for the given attribute
@throws Exception
throws Exception if attribute or group are unknown | [
"An",
"adaptor",
"method",
"which",
"returns",
"the",
"composition",
"of",
"the",
"specific",
"grouping",
"for",
"the",
"given",
"attribute",
"."
]
| train | https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/ProfeatProperties.java#L56-L58 |
apache/groovy | src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java | DefaultGroovyMethods.rightShift | public static Number rightShift(Number self, Number operand) {
"""
Implementation of the right shift operator for integral types. Non integral
Number types throw UnsupportedOperationException.
@param self a Number object
@param operand the shift distance by which to right shift the number
@return the resulting number
@since 1.5.0
"""
return NumberMath.rightShift(self, operand);
} | java | public static Number rightShift(Number self, Number operand) {
return NumberMath.rightShift(self, operand);
} | [
"public",
"static",
"Number",
"rightShift",
"(",
"Number",
"self",
",",
"Number",
"operand",
")",
"{",
"return",
"NumberMath",
".",
"rightShift",
"(",
"self",
",",
"operand",
")",
";",
"}"
]
| Implementation of the right shift operator for integral types. Non integral
Number types throw UnsupportedOperationException.
@param self a Number object
@param operand the shift distance by which to right shift the number
@return the resulting number
@since 1.5.0 | [
"Implementation",
"of",
"the",
"right",
"shift",
"operator",
"for",
"integral",
"types",
".",
"Non",
"integral",
"Number",
"types",
"throw",
"UnsupportedOperationException",
"."
]
| train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L13582-L13584 |
jglobus/JGlobus | ssl-proxies/src/main/java/org/globus/gsi/bc/BouncyCastleUtil.java | BouncyCastleUtil.getCertificateType | public static GSIConstants.CertificateType getCertificateType(X509Certificate cert,
TrustedCertificates trustedCerts)
throws CertificateException {
"""
Returns certificate type of the given certificate.
Please see {@link #getCertificateType(TBSCertificateStructure,
TrustedCertificates) getCertificateType} for details for
determining the certificate type.
@param cert the certificate to get the type of.
@param trustedCerts the trusted certificates to double check the
{@link GSIConstants#EEC GSIConstants.EEC}
certificate against.
@return the certificate type as determined by
{@link #getCertificateType(TBSCertificateStructure,
TrustedCertificates) getCertificateType}.
@exception CertificateException if something goes wrong.
@deprecated
"""
try {
return getCertificateType(cert, TrustedCertificatesUtil.createCertStore(trustedCerts));
} catch (Exception e) {
throw new CertificateException("", e);
}
} | java | public static GSIConstants.CertificateType getCertificateType(X509Certificate cert,
TrustedCertificates trustedCerts)
throws CertificateException {
try {
return getCertificateType(cert, TrustedCertificatesUtil.createCertStore(trustedCerts));
} catch (Exception e) {
throw new CertificateException("", e);
}
} | [
"public",
"static",
"GSIConstants",
".",
"CertificateType",
"getCertificateType",
"(",
"X509Certificate",
"cert",
",",
"TrustedCertificates",
"trustedCerts",
")",
"throws",
"CertificateException",
"{",
"try",
"{",
"return",
"getCertificateType",
"(",
"cert",
",",
"TrustedCertificatesUtil",
".",
"createCertStore",
"(",
"trustedCerts",
")",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"CertificateException",
"(",
"\"\"",
",",
"e",
")",
";",
"}",
"}"
]
| Returns certificate type of the given certificate.
Please see {@link #getCertificateType(TBSCertificateStructure,
TrustedCertificates) getCertificateType} for details for
determining the certificate type.
@param cert the certificate to get the type of.
@param trustedCerts the trusted certificates to double check the
{@link GSIConstants#EEC GSIConstants.EEC}
certificate against.
@return the certificate type as determined by
{@link #getCertificateType(TBSCertificateStructure,
TrustedCertificates) getCertificateType}.
@exception CertificateException if something goes wrong.
@deprecated | [
"Returns",
"certificate",
"type",
"of",
"the",
"given",
"certificate",
".",
"Please",
"see",
"{",
"@link",
"#getCertificateType",
"(",
"TBSCertificateStructure",
"TrustedCertificates",
")",
"getCertificateType",
"}",
"for",
"details",
"for",
"determining",
"the",
"certificate",
"type",
"."
]
| train | https://github.com/jglobus/JGlobus/blob/e14f6f6636544fd84298f9cec749d626ea971930/ssl-proxies/src/main/java/org/globus/gsi/bc/BouncyCastleUtil.java#L156-L164 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/AzureFirewallsInner.java | AzureFirewallsInner.beginDelete | public void beginDelete(String resourceGroupName, String azureFirewallName) {
"""
Deletes the specified Azure Firewall.
@param resourceGroupName The name of the resource group.
@param azureFirewallName The name of the Azure Firewall.
@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
"""
beginDeleteWithServiceResponseAsync(resourceGroupName, azureFirewallName).toBlocking().single().body();
} | java | public void beginDelete(String resourceGroupName, String azureFirewallName) {
beginDeleteWithServiceResponseAsync(resourceGroupName, azureFirewallName).toBlocking().single().body();
} | [
"public",
"void",
"beginDelete",
"(",
"String",
"resourceGroupName",
",",
"String",
"azureFirewallName",
")",
"{",
"beginDeleteWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"azureFirewallName",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
"body",
"(",
")",
";",
"}"
]
| Deletes the specified Azure Firewall.
@param resourceGroupName The name of the resource group.
@param azureFirewallName The name of the Azure Firewall.
@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 | [
"Deletes",
"the",
"specified",
"Azure",
"Firewall",
"."
]
| train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/AzureFirewallsInner.java#L180-L182 |
forge/core | parser-java/api/src/main/java/org/jboss/forge/addon/parser/java/beans/ProjectOperations.java | ProjectOperations.getProjectEnums | public List<JavaResource> getProjectEnums(Project project) {
"""
Returns all the {@link JavaEnumSource} objects from the given {@link Project}
"""
final List<JavaResource> enums = new ArrayList<>();
if (project != null)
{
project.getFacet(JavaSourceFacet.class).visitJavaSources(new JavaResourceVisitor()
{
@Override
public void visit(VisitContext context, JavaResource resource)
{
try
{
JavaSource<?> javaSource = resource.getJavaType();
if (javaSource.isEnum())
{
enums.add(resource);
}
}
catch (ResourceException | FileNotFoundException e)
{
// ignore
}
}
});
}
return enums;
} | java | public List<JavaResource> getProjectEnums(Project project)
{
final List<JavaResource> enums = new ArrayList<>();
if (project != null)
{
project.getFacet(JavaSourceFacet.class).visitJavaSources(new JavaResourceVisitor()
{
@Override
public void visit(VisitContext context, JavaResource resource)
{
try
{
JavaSource<?> javaSource = resource.getJavaType();
if (javaSource.isEnum())
{
enums.add(resource);
}
}
catch (ResourceException | FileNotFoundException e)
{
// ignore
}
}
});
}
return enums;
} | [
"public",
"List",
"<",
"JavaResource",
">",
"getProjectEnums",
"(",
"Project",
"project",
")",
"{",
"final",
"List",
"<",
"JavaResource",
">",
"enums",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"if",
"(",
"project",
"!=",
"null",
")",
"{",
"project",
".",
"getFacet",
"(",
"JavaSourceFacet",
".",
"class",
")",
".",
"visitJavaSources",
"(",
"new",
"JavaResourceVisitor",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"visit",
"(",
"VisitContext",
"context",
",",
"JavaResource",
"resource",
")",
"{",
"try",
"{",
"JavaSource",
"<",
"?",
">",
"javaSource",
"=",
"resource",
".",
"getJavaType",
"(",
")",
";",
"if",
"(",
"javaSource",
".",
"isEnum",
"(",
")",
")",
"{",
"enums",
".",
"add",
"(",
"resource",
")",
";",
"}",
"}",
"catch",
"(",
"ResourceException",
"|",
"FileNotFoundException",
"e",
")",
"{",
"// ignore",
"}",
"}",
"}",
")",
";",
"}",
"return",
"enums",
";",
"}"
]
| Returns all the {@link JavaEnumSource} objects from the given {@link Project} | [
"Returns",
"all",
"the",
"{"
]
| train | https://github.com/forge/core/blob/e140eb03bbe2b3409478ad70c86c3edbef6d9a0c/parser-java/api/src/main/java/org/jboss/forge/addon/parser/java/beans/ProjectOperations.java#L75-L101 |
google/error-prone-javac | src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/util/Extern.java | Extern.readPackageList | private void readPackageList(InputStream input, String path, boolean relative)
throws IOException {
"""
Read the file "package-list" and for each package name found, create
Extern object and associate it with the package name in the map.
@param input InputStream from the "package-list" file.
@param path URL or the directory path to the packages.
@param relative Is path relative?
@throws IOException if there is a problem reading or closing the stream
"""
try (BufferedReader in = new BufferedReader(new InputStreamReader(input))) {
StringBuilder strbuf = new StringBuilder();
int c;
while ((c = in.read()) >= 0) {
char ch = (char) c;
if (ch == '\n' || ch == '\r') {
if (strbuf.length() > 0) {
String packname = strbuf.toString();
String packpath = path
+ packname.replace('.', '/') + '/';
Item ignore = new Item(packname, packpath, relative);
strbuf.setLength(0);
}
} else {
strbuf.append(ch);
}
}
}
} | java | private void readPackageList(InputStream input, String path, boolean relative)
throws IOException {
try (BufferedReader in = new BufferedReader(new InputStreamReader(input))) {
StringBuilder strbuf = new StringBuilder();
int c;
while ((c = in.read()) >= 0) {
char ch = (char) c;
if (ch == '\n' || ch == '\r') {
if (strbuf.length() > 0) {
String packname = strbuf.toString();
String packpath = path
+ packname.replace('.', '/') + '/';
Item ignore = new Item(packname, packpath, relative);
strbuf.setLength(0);
}
} else {
strbuf.append(ch);
}
}
}
} | [
"private",
"void",
"readPackageList",
"(",
"InputStream",
"input",
",",
"String",
"path",
",",
"boolean",
"relative",
")",
"throws",
"IOException",
"{",
"try",
"(",
"BufferedReader",
"in",
"=",
"new",
"BufferedReader",
"(",
"new",
"InputStreamReader",
"(",
"input",
")",
")",
")",
"{",
"StringBuilder",
"strbuf",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"int",
"c",
";",
"while",
"(",
"(",
"c",
"=",
"in",
".",
"read",
"(",
")",
")",
">=",
"0",
")",
"{",
"char",
"ch",
"=",
"(",
"char",
")",
"c",
";",
"if",
"(",
"ch",
"==",
"'",
"'",
"||",
"ch",
"==",
"'",
"'",
")",
"{",
"if",
"(",
"strbuf",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"String",
"packname",
"=",
"strbuf",
".",
"toString",
"(",
")",
";",
"String",
"packpath",
"=",
"path",
"+",
"packname",
".",
"replace",
"(",
"'",
"'",
",",
"'",
"'",
")",
"+",
"'",
"'",
";",
"Item",
"ignore",
"=",
"new",
"Item",
"(",
"packname",
",",
"packpath",
",",
"relative",
")",
";",
"strbuf",
".",
"setLength",
"(",
"0",
")",
";",
"}",
"}",
"else",
"{",
"strbuf",
".",
"append",
"(",
"ch",
")",
";",
"}",
"}",
"}",
"}"
]
| Read the file "package-list" and for each package name found, create
Extern object and associate it with the package name in the map.
@param input InputStream from the "package-list" file.
@param path URL or the directory path to the packages.
@param relative Is path relative?
@throws IOException if there is a problem reading or closing the stream | [
"Read",
"the",
"file",
"package",
"-",
"list",
"and",
"for",
"each",
"package",
"name",
"found",
"create",
"Extern",
"object",
"and",
"associate",
"it",
"with",
"the",
"package",
"name",
"in",
"the",
"map",
"."
]
| train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/util/Extern.java#L291-L311 |
xcesco/kripton | kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/grammars/jql/JQLBuilder.java | JQLBuilder.forEachParameter | private static void forEachParameter(SQLiteModelMethod method, OnMethodParameterListener listener) {
"""
For each parameter.
@param method
the method
@param listener
the listener
"""
for (VariableElement p : method.getElement().getParameters()) {
listener.onMethodParameter(p);
}
} | java | private static void forEachParameter(SQLiteModelMethod method, OnMethodParameterListener listener) {
for (VariableElement p : method.getElement().getParameters()) {
listener.onMethodParameter(p);
}
} | [
"private",
"static",
"void",
"forEachParameter",
"(",
"SQLiteModelMethod",
"method",
",",
"OnMethodParameterListener",
"listener",
")",
"{",
"for",
"(",
"VariableElement",
"p",
":",
"method",
".",
"getElement",
"(",
")",
".",
"getParameters",
"(",
")",
")",
"{",
"listener",
".",
"onMethodParameter",
"(",
"p",
")",
";",
"}",
"}"
]
| For each parameter.
@param method
the method
@param listener
the listener | [
"For",
"each",
"parameter",
"."
]
| train | https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/grammars/jql/JQLBuilder.java#L1106-L1110 |
jboss/jboss-el-api_spec | src/main/java/javax/el/ELProcessor.java | ELProcessor.setVariable | public void setVariable(String var, String expression) {
"""
Assign an EL expression to an EL variable. The expression is parsed,
but not evaluated, and the parsed expression is mapped to the EL
variable in the local variable map.
Any previously assigned expression to the same variable will be replaced.
If the expression is <code>null</code>, the variable will be removed.
@param var The name of the variable.
@param expression The EL expression to be assigned to the variable.
"""
ValueExpression exp = factory.createValueExpression(
elManager.getELContext(),
bracket(expression), Object.class);
elManager.setVariable(var, exp);
} | java | public void setVariable(String var, String expression) {
ValueExpression exp = factory.createValueExpression(
elManager.getELContext(),
bracket(expression), Object.class);
elManager.setVariable(var, exp);
} | [
"public",
"void",
"setVariable",
"(",
"String",
"var",
",",
"String",
"expression",
")",
"{",
"ValueExpression",
"exp",
"=",
"factory",
".",
"createValueExpression",
"(",
"elManager",
".",
"getELContext",
"(",
")",
",",
"bracket",
"(",
"expression",
")",
",",
"Object",
".",
"class",
")",
";",
"elManager",
".",
"setVariable",
"(",
"var",
",",
"exp",
")",
";",
"}"
]
| Assign an EL expression to an EL variable. The expression is parsed,
but not evaluated, and the parsed expression is mapped to the EL
variable in the local variable map.
Any previously assigned expression to the same variable will be replaced.
If the expression is <code>null</code>, the variable will be removed.
@param var The name of the variable.
@param expression The EL expression to be assigned to the variable. | [
"Assign",
"an",
"EL",
"expression",
"to",
"an",
"EL",
"variable",
".",
"The",
"expression",
"is",
"parsed",
"but",
"not",
"evaluated",
"and",
"the",
"parsed",
"expression",
"is",
"mapped",
"to",
"the",
"EL",
"variable",
"in",
"the",
"local",
"variable",
"map",
".",
"Any",
"previously",
"assigned",
"expression",
"to",
"the",
"same",
"variable",
"will",
"be",
"replaced",
".",
"If",
"the",
"expression",
"is",
"<code",
">",
"null<",
"/",
"code",
">",
"the",
"variable",
"will",
"be",
"removed",
"."
]
| train | https://github.com/jboss/jboss-el-api_spec/blob/4cef117cae3ccf9f76439845687a8d219ad2eb43/src/main/java/javax/el/ELProcessor.java#L166-L171 |
datasalt/pangool | core/src/main/java/com/datasalt/pangool/tuplemr/TupleMRBuilder.java | TupleMRBuilder.addInput | public void addInput(Path path, InputFormat inputFormat, TupleMapper inputProcessor) {
"""
Defines an input as in {@link PangoolMultipleInputs}
@see PangoolMultipleInputs
"""
multipleInputs.addInput(new Input(path, inputFormat, inputProcessor, new HashMap<String, String>()));
} | java | public void addInput(Path path, InputFormat inputFormat, TupleMapper inputProcessor) {
multipleInputs.addInput(new Input(path, inputFormat, inputProcessor, new HashMap<String, String>()));
} | [
"public",
"void",
"addInput",
"(",
"Path",
"path",
",",
"InputFormat",
"inputFormat",
",",
"TupleMapper",
"inputProcessor",
")",
"{",
"multipleInputs",
".",
"addInput",
"(",
"new",
"Input",
"(",
"path",
",",
"inputFormat",
",",
"inputProcessor",
",",
"new",
"HashMap",
"<",
"String",
",",
"String",
">",
"(",
")",
")",
")",
";",
"}"
]
| Defines an input as in {@link PangoolMultipleInputs}
@see PangoolMultipleInputs | [
"Defines",
"an",
"input",
"as",
"in",
"{",
"@link",
"PangoolMultipleInputs",
"}"
]
| train | https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/tuplemr/TupleMRBuilder.java#L213-L215 |
rhuss/jolokia | agent/core/src/main/java/org/jolokia/backend/MBeanServers.java | MBeanServers.handleNotification | public synchronized void handleNotification(Notification notification, Object handback) {
"""
Fetch Jolokia MBeanServer when it gets registered, remove it if being unregistered
@param notification notification emitted
@param handback not used here
"""
String type = notification.getType();
if (REGISTRATION_NOTIFICATION.equals(type)) {
jolokiaMBeanServer = lookupJolokiaMBeanServer();
// We need to add the listener provided during construction time to add the Jolokia MBeanServer
// so that it is kept updated, too.
if (jolokiaMBeanServerListener != null) {
JmxUtil.addMBeanRegistrationListener(jolokiaMBeanServer, jolokiaMBeanServerListener, null);
}
} else if (UNREGISTRATION_NOTIFICATION.equals(type)) {
jolokiaMBeanServer = null;
}
allMBeanServers.clear();
if (jolokiaMBeanServer != null) {
allMBeanServers.add(jolokiaMBeanServer);
}
allMBeanServers.addAll(detectedMBeanServers);
} | java | public synchronized void handleNotification(Notification notification, Object handback) {
String type = notification.getType();
if (REGISTRATION_NOTIFICATION.equals(type)) {
jolokiaMBeanServer = lookupJolokiaMBeanServer();
// We need to add the listener provided during construction time to add the Jolokia MBeanServer
// so that it is kept updated, too.
if (jolokiaMBeanServerListener != null) {
JmxUtil.addMBeanRegistrationListener(jolokiaMBeanServer, jolokiaMBeanServerListener, null);
}
} else if (UNREGISTRATION_NOTIFICATION.equals(type)) {
jolokiaMBeanServer = null;
}
allMBeanServers.clear();
if (jolokiaMBeanServer != null) {
allMBeanServers.add(jolokiaMBeanServer);
}
allMBeanServers.addAll(detectedMBeanServers);
} | [
"public",
"synchronized",
"void",
"handleNotification",
"(",
"Notification",
"notification",
",",
"Object",
"handback",
")",
"{",
"String",
"type",
"=",
"notification",
".",
"getType",
"(",
")",
";",
"if",
"(",
"REGISTRATION_NOTIFICATION",
".",
"equals",
"(",
"type",
")",
")",
"{",
"jolokiaMBeanServer",
"=",
"lookupJolokiaMBeanServer",
"(",
")",
";",
"// We need to add the listener provided during construction time to add the Jolokia MBeanServer",
"// so that it is kept updated, too.",
"if",
"(",
"jolokiaMBeanServerListener",
"!=",
"null",
")",
"{",
"JmxUtil",
".",
"addMBeanRegistrationListener",
"(",
"jolokiaMBeanServer",
",",
"jolokiaMBeanServerListener",
",",
"null",
")",
";",
"}",
"}",
"else",
"if",
"(",
"UNREGISTRATION_NOTIFICATION",
".",
"equals",
"(",
"type",
")",
")",
"{",
"jolokiaMBeanServer",
"=",
"null",
";",
"}",
"allMBeanServers",
".",
"clear",
"(",
")",
";",
"if",
"(",
"jolokiaMBeanServer",
"!=",
"null",
")",
"{",
"allMBeanServers",
".",
"add",
"(",
"jolokiaMBeanServer",
")",
";",
"}",
"allMBeanServers",
".",
"addAll",
"(",
"detectedMBeanServers",
")",
";",
"}"
]
| Fetch Jolokia MBeanServer when it gets registered, remove it if being unregistered
@param notification notification emitted
@param handback not used here | [
"Fetch",
"Jolokia",
"MBeanServer",
"when",
"it",
"gets",
"registered",
"remove",
"it",
"if",
"being",
"unregistered"
]
| train | https://github.com/rhuss/jolokia/blob/dc95e7bef859b1829776c5a84c8f7738f5d7d9c3/agent/core/src/main/java/org/jolokia/backend/MBeanServers.java#L77-L95 |
Impetus/Kundera | src/kundera-couchdb/src/main/java/com/impetus/client/couchdb/CouchDBUtils.java | CouchDBUtils.getDesignDocument | private static CouchDBDesignDocument getDesignDocument(HttpClient httpClient, HttpHost httpHost, Gson gson,
String tableName, String schemaName) {
"""
Gets the design document.
@param httpClient
the http client
@param httpHost
the http host
@param gson
the gson
@param tableName
the table name
@param schemaName
the schema name
@return the design document
"""
HttpResponse response = null;
try
{
String id = CouchDBConstants.DESIGN + tableName;
URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),
CouchDBConstants.URL_SEPARATOR + schemaName.toLowerCase() + CouchDBConstants.URL_SEPARATOR + id,
null, null);
HttpGet get = new HttpGet(uri);
get.addHeader("Accept", "application/json");
response = httpClient.execute(httpHost, get, CouchDBUtils.getContext(httpHost));
InputStream content = response.getEntity().getContent();
Reader reader = new InputStreamReader(content);
JsonObject jsonObject = gson.fromJson(reader, JsonObject.class);
return gson.fromJson(jsonObject, CouchDBDesignDocument.class);
}
catch (Exception e)
{
log.error("Error while fetching design document object, Caused by: .", e);
throw new KunderaException(e);
}
finally
{
CouchDBUtils.closeContent(response);
}
} | java | private static CouchDBDesignDocument getDesignDocument(HttpClient httpClient, HttpHost httpHost, Gson gson,
String tableName, String schemaName)
{
HttpResponse response = null;
try
{
String id = CouchDBConstants.DESIGN + tableName;
URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),
CouchDBConstants.URL_SEPARATOR + schemaName.toLowerCase() + CouchDBConstants.URL_SEPARATOR + id,
null, null);
HttpGet get = new HttpGet(uri);
get.addHeader("Accept", "application/json");
response = httpClient.execute(httpHost, get, CouchDBUtils.getContext(httpHost));
InputStream content = response.getEntity().getContent();
Reader reader = new InputStreamReader(content);
JsonObject jsonObject = gson.fromJson(reader, JsonObject.class);
return gson.fromJson(jsonObject, CouchDBDesignDocument.class);
}
catch (Exception e)
{
log.error("Error while fetching design document object, Caused by: .", e);
throw new KunderaException(e);
}
finally
{
CouchDBUtils.closeContent(response);
}
} | [
"private",
"static",
"CouchDBDesignDocument",
"getDesignDocument",
"(",
"HttpClient",
"httpClient",
",",
"HttpHost",
"httpHost",
",",
"Gson",
"gson",
",",
"String",
"tableName",
",",
"String",
"schemaName",
")",
"{",
"HttpResponse",
"response",
"=",
"null",
";",
"try",
"{",
"String",
"id",
"=",
"CouchDBConstants",
".",
"DESIGN",
"+",
"tableName",
";",
"URI",
"uri",
"=",
"new",
"URI",
"(",
"CouchDBConstants",
".",
"PROTOCOL",
",",
"null",
",",
"httpHost",
".",
"getHostName",
"(",
")",
",",
"httpHost",
".",
"getPort",
"(",
")",
",",
"CouchDBConstants",
".",
"URL_SEPARATOR",
"+",
"schemaName",
".",
"toLowerCase",
"(",
")",
"+",
"CouchDBConstants",
".",
"URL_SEPARATOR",
"+",
"id",
",",
"null",
",",
"null",
")",
";",
"HttpGet",
"get",
"=",
"new",
"HttpGet",
"(",
"uri",
")",
";",
"get",
".",
"addHeader",
"(",
"\"Accept\"",
",",
"\"application/json\"",
")",
";",
"response",
"=",
"httpClient",
".",
"execute",
"(",
"httpHost",
",",
"get",
",",
"CouchDBUtils",
".",
"getContext",
"(",
"httpHost",
")",
")",
";",
"InputStream",
"content",
"=",
"response",
".",
"getEntity",
"(",
")",
".",
"getContent",
"(",
")",
";",
"Reader",
"reader",
"=",
"new",
"InputStreamReader",
"(",
"content",
")",
";",
"JsonObject",
"jsonObject",
"=",
"gson",
".",
"fromJson",
"(",
"reader",
",",
"JsonObject",
".",
"class",
")",
";",
"return",
"gson",
".",
"fromJson",
"(",
"jsonObject",
",",
"CouchDBDesignDocument",
".",
"class",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"log",
".",
"error",
"(",
"\"Error while fetching design document object, Caused by: .\"",
",",
"e",
")",
";",
"throw",
"new",
"KunderaException",
"(",
"e",
")",
";",
"}",
"finally",
"{",
"CouchDBUtils",
".",
"closeContent",
"(",
"response",
")",
";",
"}",
"}"
]
| Gets the design document.
@param httpClient
the http client
@param httpHost
the http host
@param gson
the gson
@param tableName
the table name
@param schemaName
the schema name
@return the design document | [
"Gets",
"the",
"design",
"document",
"."
]
| train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-couchdb/src/main/java/com/impetus/client/couchdb/CouchDBUtils.java#L258-L287 |
roskart/dropwizard-jaxws | dropwizard-jaxws/src/main/java/com/roskart/dropwizard/jaxws/JAXWSBundle.java | JAXWSBundle.getClient | @Deprecated
public <T> T getClient(Class<T> serviceClass, String address, Handler...handlers) {
"""
Factory method for creating JAX-WS clients.
@param serviceClass Service interface class.
@param address Endpoint URL address.
@param handlers Client side JAX-WS handlers. Optional.
@param <T> Service interface type.
@return JAX-WS client proxy.
@deprecated Use the {@link #getClient(ClientBuilder)} getClient} method instead.
"""
checkArgument(serviceClass != null, "ServiceClass is null");
checkArgument(address != null, "Address is null");
checkArgument((address).trim().length() > 0, "Address is empty");
return jaxwsEnvironment.getClient(
new ClientBuilder<>(serviceClass, address).handlers(handlers));
} | java | @Deprecated
public <T> T getClient(Class<T> serviceClass, String address, Handler...handlers) {
checkArgument(serviceClass != null, "ServiceClass is null");
checkArgument(address != null, "Address is null");
checkArgument((address).trim().length() > 0, "Address is empty");
return jaxwsEnvironment.getClient(
new ClientBuilder<>(serviceClass, address).handlers(handlers));
} | [
"@",
"Deprecated",
"public",
"<",
"T",
">",
"T",
"getClient",
"(",
"Class",
"<",
"T",
">",
"serviceClass",
",",
"String",
"address",
",",
"Handler",
"...",
"handlers",
")",
"{",
"checkArgument",
"(",
"serviceClass",
"!=",
"null",
",",
"\"ServiceClass is null\"",
")",
";",
"checkArgument",
"(",
"address",
"!=",
"null",
",",
"\"Address is null\"",
")",
";",
"checkArgument",
"(",
"(",
"address",
")",
".",
"trim",
"(",
")",
".",
"length",
"(",
")",
">",
"0",
",",
"\"Address is empty\"",
")",
";",
"return",
"jaxwsEnvironment",
".",
"getClient",
"(",
"new",
"ClientBuilder",
"<>",
"(",
"serviceClass",
",",
"address",
")",
".",
"handlers",
"(",
"handlers",
")",
")",
";",
"}"
]
| Factory method for creating JAX-WS clients.
@param serviceClass Service interface class.
@param address Endpoint URL address.
@param handlers Client side JAX-WS handlers. Optional.
@param <T> Service interface type.
@return JAX-WS client proxy.
@deprecated Use the {@link #getClient(ClientBuilder)} getClient} method instead. | [
"Factory",
"method",
"for",
"creating",
"JAX",
"-",
"WS",
"clients",
".",
"@param",
"serviceClass",
"Service",
"interface",
"class",
".",
"@param",
"address",
"Endpoint",
"URL",
"address",
".",
"@param",
"handlers",
"Client",
"side",
"JAX",
"-",
"WS",
"handlers",
".",
"Optional",
".",
"@param",
"<T",
">",
"Service",
"interface",
"type",
".",
"@return",
"JAX",
"-",
"WS",
"client",
"proxy",
"."
]
| train | https://github.com/roskart/dropwizard-jaxws/blob/972eb63ba9626f3282d4a1d6127dc2b60b28f2bc/dropwizard-jaxws/src/main/java/com/roskart/dropwizard/jaxws/JAXWSBundle.java#L161-L168 |
apache/incubator-zipkin | zipkin-server/src/main/java/zipkin2/server/internal/ZipkinQueryApiV2.java | ZipkinQueryApiV2.maybeCacheNames | AggregatedHttpMessage maybeCacheNames(boolean shouldCacheControl, List<String> values) {
"""
We cache names if there are more than 3 names. This helps people getting started: if we cache
empty results, users have more questions. We assume caching becomes a concern when zipkin is in
active use, and active use usually implies more than 3 services.
"""
Collections.sort(values);
byte[] body = JsonCodec.writeList(QUOTED_STRING_WRITER, values);
HttpHeaders headers = HttpHeaders.of(200)
.contentType(MediaType.JSON)
.setInt(HttpHeaderNames.CONTENT_LENGTH, body.length);
if (shouldCacheControl) {
headers = headers.add(
HttpHeaderNames.CACHE_CONTROL,
CacheControl.maxAge(namesMaxAge, TimeUnit.SECONDS).mustRevalidate().getHeaderValue()
);
}
return AggregatedHttpMessage.of(headers, HttpData.of(body));
} | java | AggregatedHttpMessage maybeCacheNames(boolean shouldCacheControl, List<String> values) {
Collections.sort(values);
byte[] body = JsonCodec.writeList(QUOTED_STRING_WRITER, values);
HttpHeaders headers = HttpHeaders.of(200)
.contentType(MediaType.JSON)
.setInt(HttpHeaderNames.CONTENT_LENGTH, body.length);
if (shouldCacheControl) {
headers = headers.add(
HttpHeaderNames.CACHE_CONTROL,
CacheControl.maxAge(namesMaxAge, TimeUnit.SECONDS).mustRevalidate().getHeaderValue()
);
}
return AggregatedHttpMessage.of(headers, HttpData.of(body));
} | [
"AggregatedHttpMessage",
"maybeCacheNames",
"(",
"boolean",
"shouldCacheControl",
",",
"List",
"<",
"String",
">",
"values",
")",
"{",
"Collections",
".",
"sort",
"(",
"values",
")",
";",
"byte",
"[",
"]",
"body",
"=",
"JsonCodec",
".",
"writeList",
"(",
"QUOTED_STRING_WRITER",
",",
"values",
")",
";",
"HttpHeaders",
"headers",
"=",
"HttpHeaders",
".",
"of",
"(",
"200",
")",
".",
"contentType",
"(",
"MediaType",
".",
"JSON",
")",
".",
"setInt",
"(",
"HttpHeaderNames",
".",
"CONTENT_LENGTH",
",",
"body",
".",
"length",
")",
";",
"if",
"(",
"shouldCacheControl",
")",
"{",
"headers",
"=",
"headers",
".",
"add",
"(",
"HttpHeaderNames",
".",
"CACHE_CONTROL",
",",
"CacheControl",
".",
"maxAge",
"(",
"namesMaxAge",
",",
"TimeUnit",
".",
"SECONDS",
")",
".",
"mustRevalidate",
"(",
")",
".",
"getHeaderValue",
"(",
")",
")",
";",
"}",
"return",
"AggregatedHttpMessage",
".",
"of",
"(",
"headers",
",",
"HttpData",
".",
"of",
"(",
"body",
")",
")",
";",
"}"
]
| We cache names if there are more than 3 names. This helps people getting started: if we cache
empty results, users have more questions. We assume caching becomes a concern when zipkin is in
active use, and active use usually implies more than 3 services. | [
"We",
"cache",
"names",
"if",
"there",
"are",
"more",
"than",
"3",
"names",
".",
"This",
"helps",
"people",
"getting",
"started",
":",
"if",
"we",
"cache",
"empty",
"results",
"users",
"have",
"more",
"questions",
".",
"We",
"assume",
"caching",
"becomes",
"a",
"concern",
"when",
"zipkin",
"is",
"in",
"active",
"use",
"and",
"active",
"use",
"usually",
"implies",
"more",
"than",
"3",
"services",
"."
]
| train | https://github.com/apache/incubator-zipkin/blob/89b2fab983fc626b3be32ce9d7cf64b3f01f1a87/zipkin-server/src/main/java/zipkin2/server/internal/ZipkinQueryApiV2.java#L177-L190 |
googleads/googleads-java-lib | examples/adwords_axis/src/main/java/adwords/axis/v201809/misc/UploadImageAsset.java | UploadImageAsset.runExample | public static void runExample(AdWordsServicesInterface adWordsServices, AdWordsSession session)
throws IOException {
"""
Runs the example.
@param adWordsServices the services factory.
@param session the session.
@throws ApiException if the API request failed with one or more service errors.
@throws RemoteException if the API request failed due to other errors.
@throws IOException if unable to get media data from the URL.
"""
// Get the AssetService.
AssetServiceInterface assetService = adWordsServices.get(session, AssetServiceInterface.class);
// Create the image asset.
ImageAsset image = new ImageAsset();
// Optional: Provide a unique friendly name to identify your asset. If you specify the assetName
// field, then both the asset name and the image being uploaded should be unique, and should not
// match another ACTIVE asset in this customer account.
// image.setAssetName("Jupiter Trip #" + System.currentTimeMillis());
image.setImageData(
com.google.api.ads.common.lib.utils.Media.getMediaDataFromUrl("https://goo.gl/3b9Wfh"));
// Create the operation.
AssetOperation operation = new AssetOperation();
operation.setOperator(Operator.ADD);
operation.setOperand(image);
// Create the asset.
AssetReturnValue result = assetService.mutate(new AssetOperation[] {operation});
// Display the results.
if (result != null && result.getValue() != null && result.getValue().length > 0) {
Asset newAsset = result.getValue(0);
System.out.printf(
"Image asset with ID %d and name '%s' was created.%n",
newAsset.getAssetId(), newAsset.getAssetName());
} else {
System.out.println("No image asset was created.");
}
} | java | public static void runExample(AdWordsServicesInterface adWordsServices, AdWordsSession session)
throws IOException {
// Get the AssetService.
AssetServiceInterface assetService = adWordsServices.get(session, AssetServiceInterface.class);
// Create the image asset.
ImageAsset image = new ImageAsset();
// Optional: Provide a unique friendly name to identify your asset. If you specify the assetName
// field, then both the asset name and the image being uploaded should be unique, and should not
// match another ACTIVE asset in this customer account.
// image.setAssetName("Jupiter Trip #" + System.currentTimeMillis());
image.setImageData(
com.google.api.ads.common.lib.utils.Media.getMediaDataFromUrl("https://goo.gl/3b9Wfh"));
// Create the operation.
AssetOperation operation = new AssetOperation();
operation.setOperator(Operator.ADD);
operation.setOperand(image);
// Create the asset.
AssetReturnValue result = assetService.mutate(new AssetOperation[] {operation});
// Display the results.
if (result != null && result.getValue() != null && result.getValue().length > 0) {
Asset newAsset = result.getValue(0);
System.out.printf(
"Image asset with ID %d and name '%s' was created.%n",
newAsset.getAssetId(), newAsset.getAssetName());
} else {
System.out.println("No image asset was created.");
}
} | [
"public",
"static",
"void",
"runExample",
"(",
"AdWordsServicesInterface",
"adWordsServices",
",",
"AdWordsSession",
"session",
")",
"throws",
"IOException",
"{",
"// Get the AssetService.",
"AssetServiceInterface",
"assetService",
"=",
"adWordsServices",
".",
"get",
"(",
"session",
",",
"AssetServiceInterface",
".",
"class",
")",
";",
"// Create the image asset.",
"ImageAsset",
"image",
"=",
"new",
"ImageAsset",
"(",
")",
";",
"// Optional: Provide a unique friendly name to identify your asset. If you specify the assetName",
"// field, then both the asset name and the image being uploaded should be unique, and should not",
"// match another ACTIVE asset in this customer account.",
"// image.setAssetName(\"Jupiter Trip #\" + System.currentTimeMillis());",
"image",
".",
"setImageData",
"(",
"com",
".",
"google",
".",
"api",
".",
"ads",
".",
"common",
".",
"lib",
".",
"utils",
".",
"Media",
".",
"getMediaDataFromUrl",
"(",
"\"https://goo.gl/3b9Wfh\"",
")",
")",
";",
"// Create the operation.",
"AssetOperation",
"operation",
"=",
"new",
"AssetOperation",
"(",
")",
";",
"operation",
".",
"setOperator",
"(",
"Operator",
".",
"ADD",
")",
";",
"operation",
".",
"setOperand",
"(",
"image",
")",
";",
"// Create the asset.",
"AssetReturnValue",
"result",
"=",
"assetService",
".",
"mutate",
"(",
"new",
"AssetOperation",
"[",
"]",
"{",
"operation",
"}",
")",
";",
"// Display the results.",
"if",
"(",
"result",
"!=",
"null",
"&&",
"result",
".",
"getValue",
"(",
")",
"!=",
"null",
"&&",
"result",
".",
"getValue",
"(",
")",
".",
"length",
">",
"0",
")",
"{",
"Asset",
"newAsset",
"=",
"result",
".",
"getValue",
"(",
"0",
")",
";",
"System",
".",
"out",
".",
"printf",
"(",
"\"Image asset with ID %d and name '%s' was created.%n\"",
",",
"newAsset",
".",
"getAssetId",
"(",
")",
",",
"newAsset",
".",
"getAssetName",
"(",
")",
")",
";",
"}",
"else",
"{",
"System",
".",
"out",
".",
"println",
"(",
"\"No image asset was created.\"",
")",
";",
"}",
"}"
]
| Runs the example.
@param adWordsServices the services factory.
@param session the session.
@throws ApiException if the API request failed with one or more service errors.
@throws RemoteException if the API request failed due to other errors.
@throws IOException if unable to get media data from the URL. | [
"Runs",
"the",
"example",
"."
]
| train | https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/examples/adwords_axis/src/main/java/adwords/axis/v201809/misc/UploadImageAsset.java#L114-L145 |
jayantk/jklol | src/com/jayantkrish/jklol/models/VariableNumMap.java | VariableNumMap.addMapping | public final VariableNumMap addMapping(int num, String name, Variable var) {
"""
Adds a single number/variable mapping to this map.
@param num
@param var
@return
"""
return union(VariableNumMap.singleton(num, name, var));
} | java | public final VariableNumMap addMapping(int num, String name, Variable var) {
return union(VariableNumMap.singleton(num, name, var));
} | [
"public",
"final",
"VariableNumMap",
"addMapping",
"(",
"int",
"num",
",",
"String",
"name",
",",
"Variable",
"var",
")",
"{",
"return",
"union",
"(",
"VariableNumMap",
".",
"singleton",
"(",
"num",
",",
"name",
",",
"var",
")",
")",
";",
"}"
]
| Adds a single number/variable mapping to this map.
@param num
@param var
@return | [
"Adds",
"a",
"single",
"number",
"/",
"variable",
"mapping",
"to",
"this",
"map",
"."
]
| train | https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/models/VariableNumMap.java#L713-L715 |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/streaming/ConnectionHandler.java | ConnectionHandler.initiateOnReceivingSide | public void initiateOnReceivingSide(Socket socket, boolean isForOutgoing, int version) throws IOException {
"""
Set up outgoing message handler on receiving side.
@param socket socket to use for {@link org.apache.cassandra.streaming.ConnectionHandler.OutgoingMessageHandler}.
@param version Streaming message version
@throws IOException
"""
if (isForOutgoing)
outgoing.start(socket, version);
else
incoming.start(socket, version);
} | java | public void initiateOnReceivingSide(Socket socket, boolean isForOutgoing, int version) throws IOException
{
if (isForOutgoing)
outgoing.start(socket, version);
else
incoming.start(socket, version);
} | [
"public",
"void",
"initiateOnReceivingSide",
"(",
"Socket",
"socket",
",",
"boolean",
"isForOutgoing",
",",
"int",
"version",
")",
"throws",
"IOException",
"{",
"if",
"(",
"isForOutgoing",
")",
"outgoing",
".",
"start",
"(",
"socket",
",",
"version",
")",
";",
"else",
"incoming",
".",
"start",
"(",
"socket",
",",
"version",
")",
";",
"}"
]
| Set up outgoing message handler on receiving side.
@param socket socket to use for {@link org.apache.cassandra.streaming.ConnectionHandler.OutgoingMessageHandler}.
@param version Streaming message version
@throws IOException | [
"Set",
"up",
"outgoing",
"message",
"handler",
"on",
"receiving",
"side",
"."
]
| train | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/streaming/ConnectionHandler.java#L96-L102 |
sagiegurari/fax4j | src/main/java/org/fax4j/spi/FaxClientSpiProxyImpl.java | FaxClientSpiProxyImpl.invokeInterceptors | @Override
protected void invokeInterceptors(FaxClientSpiProxyEventType eventType,Method method,Object[] arguments,Object output,Throwable throwable) {
"""
This function invokes the interceptor for the given event.
@param eventType
The event type
@param method
The method invoked
@param arguments
The method arguments
@param output
The method output
@param throwable
The throwable while invoking the method
"""
try
{
this.invokeInterceptorsImpl(eventType,method,arguments,output,throwable);
}
catch(Throwable ignore)
{
//ignore
}
} | java | @Override
protected void invokeInterceptors(FaxClientSpiProxyEventType eventType,Method method,Object[] arguments,Object output,Throwable throwable)
{
try
{
this.invokeInterceptorsImpl(eventType,method,arguments,output,throwable);
}
catch(Throwable ignore)
{
//ignore
}
} | [
"@",
"Override",
"protected",
"void",
"invokeInterceptors",
"(",
"FaxClientSpiProxyEventType",
"eventType",
",",
"Method",
"method",
",",
"Object",
"[",
"]",
"arguments",
",",
"Object",
"output",
",",
"Throwable",
"throwable",
")",
"{",
"try",
"{",
"this",
".",
"invokeInterceptorsImpl",
"(",
"eventType",
",",
"method",
",",
"arguments",
",",
"output",
",",
"throwable",
")",
";",
"}",
"catch",
"(",
"Throwable",
"ignore",
")",
"{",
"//ignore",
"}",
"}"
]
| This function invokes the interceptor for the given event.
@param eventType
The event type
@param method
The method invoked
@param arguments
The method arguments
@param output
The method output
@param throwable
The throwable while invoking the method | [
"This",
"function",
"invokes",
"the",
"interceptor",
"for",
"the",
"given",
"event",
"."
]
| train | https://github.com/sagiegurari/fax4j/blob/42fa51acabe7bf279e27ab3dd1cf76146b27955f/src/main/java/org/fax4j/spi/FaxClientSpiProxyImpl.java#L105-L116 |
pushbit/sprockets | src/main/java/net/sf/sprockets/lang/Classes.java | Classes.getTypeArgument | @Nullable
public static Type getTypeArgument(Class<?> cls, String typeParameter) {
"""
<p>
Get the Type that has been specified by the class or an ancestor for the generic type
parameter. For example:
</p>
<pre>{@code
class StringList extends ArrayList<String>
Classes.getTypeArgument(StringList.class, "E")
// returns: class java.lang.String
}</pre>
@return null if the type parameter was not found
"""
while (cls != Object.class) { // walk up the Class hierarchy, searching for the type param
Class<?> parent = cls.getSuperclass();
Type parentType = cls.getGenericSuperclass();
if (parentType instanceof ParameterizedType) {
Type[] args = ((ParameterizedType) parentType).getActualTypeArguments();
TypeVariable<?>[] params = parent.getTypeParameters();
for (int i = 0, length = params.length; i < length; i++) {
if (params[i].getName().equals(typeParameter)) {
return args[i];
}
}
}
cls = parent;
}
return null;
} | java | @Nullable
public static Type getTypeArgument(Class<?> cls, String typeParameter) {
while (cls != Object.class) { // walk up the Class hierarchy, searching for the type param
Class<?> parent = cls.getSuperclass();
Type parentType = cls.getGenericSuperclass();
if (parentType instanceof ParameterizedType) {
Type[] args = ((ParameterizedType) parentType).getActualTypeArguments();
TypeVariable<?>[] params = parent.getTypeParameters();
for (int i = 0, length = params.length; i < length; i++) {
if (params[i].getName().equals(typeParameter)) {
return args[i];
}
}
}
cls = parent;
}
return null;
} | [
"@",
"Nullable",
"public",
"static",
"Type",
"getTypeArgument",
"(",
"Class",
"<",
"?",
">",
"cls",
",",
"String",
"typeParameter",
")",
"{",
"while",
"(",
"cls",
"!=",
"Object",
".",
"class",
")",
"{",
"// walk up the Class hierarchy, searching for the type param",
"Class",
"<",
"?",
">",
"parent",
"=",
"cls",
".",
"getSuperclass",
"(",
")",
";",
"Type",
"parentType",
"=",
"cls",
".",
"getGenericSuperclass",
"(",
")",
";",
"if",
"(",
"parentType",
"instanceof",
"ParameterizedType",
")",
"{",
"Type",
"[",
"]",
"args",
"=",
"(",
"(",
"ParameterizedType",
")",
"parentType",
")",
".",
"getActualTypeArguments",
"(",
")",
";",
"TypeVariable",
"<",
"?",
">",
"[",
"]",
"params",
"=",
"parent",
".",
"getTypeParameters",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
",",
"length",
"=",
"params",
".",
"length",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"params",
"[",
"i",
"]",
".",
"getName",
"(",
")",
".",
"equals",
"(",
"typeParameter",
")",
")",
"{",
"return",
"args",
"[",
"i",
"]",
";",
"}",
"}",
"}",
"cls",
"=",
"parent",
";",
"}",
"return",
"null",
";",
"}"
]
| <p>
Get the Type that has been specified by the class or an ancestor for the generic type
parameter. For example:
</p>
<pre>{@code
class StringList extends ArrayList<String>
Classes.getTypeArgument(StringList.class, "E")
// returns: class java.lang.String
}</pre>
@return null if the type parameter was not found | [
"<p",
">",
"Get",
"the",
"Type",
"that",
"has",
"been",
"specified",
"by",
"the",
"class",
"or",
"an",
"ancestor",
"for",
"the",
"generic",
"type",
"parameter",
".",
"For",
"example",
":",
"<",
"/",
"p",
">",
"<pre",
">",
"{",
"@code",
"class",
"StringList",
"extends",
"ArrayList<String",
">"
]
| train | https://github.com/pushbit/sprockets/blob/5d967317cbb2374c69d33271d3c7b7311e1ea4ac/src/main/java/net/sf/sprockets/lang/Classes.java#L73-L90 |
lessthanoptimal/BoofCV | main/boofcv-calibration/src/main/java/boofcv/alg/geo/selfcalib/EstimatePlaneAtInfinityGivenK.java | EstimatePlaneAtInfinityGivenK.computeRotation | static void computeRotation(DMatrix3 t , DMatrix3x3 R ) {
"""
Computes rotators which rotate t into [|t|,0,0]
@param t Input the vector, Output vector after rotator has been applied
"""
for (int i = 1; i >= 0; i--) {
double a = t.get(i,0);
double b = t.get(i+1,0);
// compute the rotator such that [a,b] = [||X||,0]
double r = Math.sqrt(a*a + b*b);
double q11 = a/r;
double q21 = b/r;
// apply rotator to t and R
t.set(i,0,r);
t.set(i+1,0,0);
if( i == 1 ) {
R.a11 = 1; R.a12 = 0; R.a13 = 0;
R.a21 = 0; R.a22 = q11; R.a23 = q21;
R.a31 = 0; R.a32 = -q21; R.a33 = q11;
} else {
R.a11 = q11; R.a12 = R.a22*q21; R.a13 = R.a23*q21;
R.a21 = -q21; R.a22 = R.a22*q11; R.a23 = R.a23*q11;
}
}
} | java | static void computeRotation(DMatrix3 t , DMatrix3x3 R ) {
for (int i = 1; i >= 0; i--) {
double a = t.get(i,0);
double b = t.get(i+1,0);
// compute the rotator such that [a,b] = [||X||,0]
double r = Math.sqrt(a*a + b*b);
double q11 = a/r;
double q21 = b/r;
// apply rotator to t and R
t.set(i,0,r);
t.set(i+1,0,0);
if( i == 1 ) {
R.a11 = 1; R.a12 = 0; R.a13 = 0;
R.a21 = 0; R.a22 = q11; R.a23 = q21;
R.a31 = 0; R.a32 = -q21; R.a33 = q11;
} else {
R.a11 = q11; R.a12 = R.a22*q21; R.a13 = R.a23*q21;
R.a21 = -q21; R.a22 = R.a22*q11; R.a23 = R.a23*q11;
}
}
} | [
"static",
"void",
"computeRotation",
"(",
"DMatrix3",
"t",
",",
"DMatrix3x3",
"R",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
")",
"{",
"double",
"a",
"=",
"t",
".",
"get",
"(",
"i",
",",
"0",
")",
";",
"double",
"b",
"=",
"t",
".",
"get",
"(",
"i",
"+",
"1",
",",
"0",
")",
";",
"// compute the rotator such that [a,b] = [||X||,0]",
"double",
"r",
"=",
"Math",
".",
"sqrt",
"(",
"a",
"*",
"a",
"+",
"b",
"*",
"b",
")",
";",
"double",
"q11",
"=",
"a",
"/",
"r",
";",
"double",
"q21",
"=",
"b",
"/",
"r",
";",
"// apply rotator to t and R",
"t",
".",
"set",
"(",
"i",
",",
"0",
",",
"r",
")",
";",
"t",
".",
"set",
"(",
"i",
"+",
"1",
",",
"0",
",",
"0",
")",
";",
"if",
"(",
"i",
"==",
"1",
")",
"{",
"R",
".",
"a11",
"=",
"1",
";",
"R",
".",
"a12",
"=",
"0",
";",
"R",
".",
"a13",
"=",
"0",
";",
"R",
".",
"a21",
"=",
"0",
";",
"R",
".",
"a22",
"=",
"q11",
";",
"R",
".",
"a23",
"=",
"q21",
";",
"R",
".",
"a31",
"=",
"0",
";",
"R",
".",
"a32",
"=",
"-",
"q21",
";",
"R",
".",
"a33",
"=",
"q11",
";",
"}",
"else",
"{",
"R",
".",
"a11",
"=",
"q11",
";",
"R",
".",
"a12",
"=",
"R",
".",
"a22",
"*",
"q21",
";",
"R",
".",
"a13",
"=",
"R",
".",
"a23",
"*",
"q21",
";",
"R",
".",
"a21",
"=",
"-",
"q21",
";",
"R",
".",
"a22",
"=",
"R",
".",
"a22",
"*",
"q11",
";",
"R",
".",
"a23",
"=",
"R",
".",
"a23",
"*",
"q11",
";",
"}",
"}",
"}"
]
| Computes rotators which rotate t into [|t|,0,0]
@param t Input the vector, Output vector after rotator has been applied | [
"Computes",
"rotators",
"which",
"rotate",
"t",
"into",
"[",
"|t|",
"0",
"0",
"]"
]
| train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-calibration/src/main/java/boofcv/alg/geo/selfcalib/EstimatePlaneAtInfinityGivenK.java#L123-L146 |
bartprokop/rxtx | src/main/java/gnu/io/CommPortIdentifier.java | CommPortIdentifier.addPortName | public static void addPortName(String s, int type, CommDriver c) {
"""
addPortName accept: Name of the port s, Port type, reverence to
RXTXCommDriver. perform: place a new CommPortIdentifier in the linked
list return: none. exceptions: none. comments:
@param s - port name
@param type - port type
@param c - reference for ComDriver
"""
LOGGER.fine("CommPortIdentifier:addPortName(" + s + ")");
// TODO (by Alexander Graf) the usage of the constructor with a null
// value for the port is a major design problem. Rxtx currently creates
// the port objects on a per-open basis. This clashes with the design
// idea of the comm API where a port object is created by the driver
// once and given to the CommPortIdentifier constructor.
// This problem is again introduced by the poor design of the comm APIs
// SPI.
AddIdentifierToList(new CommPortIdentifier(s, null, type, c));
} | java | public static void addPortName(String s, int type, CommDriver c) {
LOGGER.fine("CommPortIdentifier:addPortName(" + s + ")");
// TODO (by Alexander Graf) the usage of the constructor with a null
// value for the port is a major design problem. Rxtx currently creates
// the port objects on a per-open basis. This clashes with the design
// idea of the comm API where a port object is created by the driver
// once and given to the CommPortIdentifier constructor.
// This problem is again introduced by the poor design of the comm APIs
// SPI.
AddIdentifierToList(new CommPortIdentifier(s, null, type, c));
} | [
"public",
"static",
"void",
"addPortName",
"(",
"String",
"s",
",",
"int",
"type",
",",
"CommDriver",
"c",
")",
"{",
"LOGGER",
".",
"fine",
"(",
"\"CommPortIdentifier:addPortName(\"",
"+",
"s",
"+",
"\")\"",
")",
";",
"// TODO (by Alexander Graf) the usage of the constructor with a null",
"// value for the port is a major design problem. Rxtx currently creates",
"// the port objects on a per-open basis. This clashes with the design",
"// idea of the comm API where a port object is created by the driver",
"// once and given to the CommPortIdentifier constructor.",
"// This problem is again introduced by the poor design of the comm APIs",
"// SPI.",
"AddIdentifierToList",
"(",
"new",
"CommPortIdentifier",
"(",
"s",
",",
"null",
",",
"type",
",",
"c",
")",
")",
";",
"}"
]
| addPortName accept: Name of the port s, Port type, reverence to
RXTXCommDriver. perform: place a new CommPortIdentifier in the linked
list return: none. exceptions: none. comments:
@param s - port name
@param type - port type
@param c - reference for ComDriver | [
"addPortName",
"accept",
":",
"Name",
"of",
"the",
"port",
"s",
"Port",
"type",
"reverence",
"to",
"RXTXCommDriver",
".",
"perform",
":",
"place",
"a",
"new",
"CommPortIdentifier",
"in",
"the",
"linked",
"list",
"return",
":",
"none",
".",
"exceptions",
":",
"none",
".",
"comments",
":"
]
| train | https://github.com/bartprokop/rxtx/blob/7b2c7857c262743e9dd15e9779c880b93c650890/src/main/java/gnu/io/CommPortIdentifier.java#L183-L193 |
SahaginOrg/sahagin-java | src/main/java/org/sahagin/runlib/runresultsgen/RunResultsGenerateHookSetter.java | RunResultsGenerateHookSetter.isLineLastStament | private boolean isLineLastStament(TestMethod method, int codeLineIndex) {
"""
This may return false since multiple statement can be found in a line.
"""
CodeLine codeLine = method.getCodeBody().get(codeLineIndex);
if (codeLineIndex == method.getCodeBody().size() - 1) {
return true;
}
CodeLine nextCodeLine = method.getCodeBody().get(codeLineIndex + 1);
assert codeLine.getEndLine() <= nextCodeLine.getStartLine();
if (codeLine.getEndLine() == nextCodeLine.getStartLine()) {
// if next statement exists in the same line,
// this statement is not the last statement for the line
return false;
}
return true;
} | java | private boolean isLineLastStament(TestMethod method, int codeLineIndex) {
CodeLine codeLine = method.getCodeBody().get(codeLineIndex);
if (codeLineIndex == method.getCodeBody().size() - 1) {
return true;
}
CodeLine nextCodeLine = method.getCodeBody().get(codeLineIndex + 1);
assert codeLine.getEndLine() <= nextCodeLine.getStartLine();
if (codeLine.getEndLine() == nextCodeLine.getStartLine()) {
// if next statement exists in the same line,
// this statement is not the last statement for the line
return false;
}
return true;
} | [
"private",
"boolean",
"isLineLastStament",
"(",
"TestMethod",
"method",
",",
"int",
"codeLineIndex",
")",
"{",
"CodeLine",
"codeLine",
"=",
"method",
".",
"getCodeBody",
"(",
")",
".",
"get",
"(",
"codeLineIndex",
")",
";",
"if",
"(",
"codeLineIndex",
"==",
"method",
".",
"getCodeBody",
"(",
")",
".",
"size",
"(",
")",
"-",
"1",
")",
"{",
"return",
"true",
";",
"}",
"CodeLine",
"nextCodeLine",
"=",
"method",
".",
"getCodeBody",
"(",
")",
".",
"get",
"(",
"codeLineIndex",
"+",
"1",
")",
";",
"assert",
"codeLine",
".",
"getEndLine",
"(",
")",
"<=",
"nextCodeLine",
".",
"getStartLine",
"(",
")",
";",
"if",
"(",
"codeLine",
".",
"getEndLine",
"(",
")",
"==",
"nextCodeLine",
".",
"getStartLine",
"(",
")",
")",
"{",
"// if next statement exists in the same line,",
"// this statement is not the last statement for the line",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
]
| This may return false since multiple statement can be found in a line. | [
"This",
"may",
"return",
"false",
"since",
"multiple",
"statement",
"can",
"be",
"found",
"in",
"a",
"line",
"."
]
| train | https://github.com/SahaginOrg/sahagin-java/blob/7ace428adebe3466ceb5826bc9681f8e3d52be68/src/main/java/org/sahagin/runlib/runresultsgen/RunResultsGenerateHookSetter.java#L110-L124 |
lievendoclo/Valkyrie-RCP | valkyrie-rcp-core/src/main/java/org/valkyriercp/widget/table/ClassUtils.java | ClassUtils.getWriterForProperty | public static Writer getWriterForProperty(final Class<?> beanClass, final String propertyName) {
"""
Create a {@link Writer} for the given property. A property may be nested using the dot character.
@param clazz
the type containing the property.
@param propertyName
the name of the property.
@return a Writer for the property.
"""
int splitPoint = propertyName.indexOf('.');
if (splitPoint > 0)
{
String firstPart = propertyName.substring(0, splitPoint);
String secondPart = propertyName.substring(splitPoint + 1);
return new NestedWriter(beanClass, firstPart, secondPart);
}
return new SimpleWriter(beanClass, propertyName);
} | java | public static Writer getWriterForProperty(final Class<?> beanClass, final String propertyName)
{
int splitPoint = propertyName.indexOf('.');
if (splitPoint > 0)
{
String firstPart = propertyName.substring(0, splitPoint);
String secondPart = propertyName.substring(splitPoint + 1);
return new NestedWriter(beanClass, firstPart, secondPart);
}
return new SimpleWriter(beanClass, propertyName);
} | [
"public",
"static",
"Writer",
"getWriterForProperty",
"(",
"final",
"Class",
"<",
"?",
">",
"beanClass",
",",
"final",
"String",
"propertyName",
")",
"{",
"int",
"splitPoint",
"=",
"propertyName",
".",
"indexOf",
"(",
"'",
"'",
")",
";",
"if",
"(",
"splitPoint",
">",
"0",
")",
"{",
"String",
"firstPart",
"=",
"propertyName",
".",
"substring",
"(",
"0",
",",
"splitPoint",
")",
";",
"String",
"secondPart",
"=",
"propertyName",
".",
"substring",
"(",
"splitPoint",
"+",
"1",
")",
";",
"return",
"new",
"NestedWriter",
"(",
"beanClass",
",",
"firstPart",
",",
"secondPart",
")",
";",
"}",
"return",
"new",
"SimpleWriter",
"(",
"beanClass",
",",
"propertyName",
")",
";",
"}"
]
| Create a {@link Writer} for the given property. A property may be nested using the dot character.
@param clazz
the type containing the property.
@param propertyName
the name of the property.
@return a Writer for the property. | [
"Create",
"a",
"{",
"@link",
"Writer",
"}",
"for",
"the",
"given",
"property",
".",
"A",
"property",
"may",
"be",
"nested",
"using",
"the",
"dot",
"character",
"."
]
| train | https://github.com/lievendoclo/Valkyrie-RCP/blob/6aad6e640b348cda8f3b0841f6e42025233f1eb8/valkyrie-rcp-core/src/main/java/org/valkyriercp/widget/table/ClassUtils.java#L160-L170 |
Netflix/Hystrix | hystrix-core/src/main/java/com/netflix/hystrix/HystrixCommandMetrics.java | HystrixCommandMetrics.getInstance | public static HystrixCommandMetrics getInstance(HystrixCommandKey key, HystrixCommandGroupKey commandGroup, HystrixThreadPoolKey threadPoolKey, HystrixCommandProperties properties) {
"""
Get or create the {@link HystrixCommandMetrics} instance for a given {@link HystrixCommandKey}.
<p>
This is thread-safe and ensures only 1 {@link HystrixCommandMetrics} per {@link HystrixCommandKey}.
@param key
{@link HystrixCommandKey} of {@link HystrixCommand} instance requesting the {@link HystrixCommandMetrics}
@param commandGroup
Pass-thru to {@link HystrixCommandMetrics} instance on first time when constructed
@param properties
Pass-thru to {@link HystrixCommandMetrics} instance on first time when constructed
@return {@link HystrixCommandMetrics}
"""
// attempt to retrieve from cache first
HystrixCommandMetrics commandMetrics = metrics.get(key.name());
if (commandMetrics != null) {
return commandMetrics;
} else {
synchronized (HystrixCommandMetrics.class) {
HystrixCommandMetrics existingMetrics = metrics.get(key.name());
if (existingMetrics != null) {
return existingMetrics;
} else {
HystrixThreadPoolKey nonNullThreadPoolKey;
if (threadPoolKey == null) {
nonNullThreadPoolKey = HystrixThreadPoolKey.Factory.asKey(commandGroup.name());
} else {
nonNullThreadPoolKey = threadPoolKey;
}
HystrixCommandMetrics newCommandMetrics = new HystrixCommandMetrics(key, commandGroup, nonNullThreadPoolKey, properties, HystrixPlugins.getInstance().getEventNotifier());
metrics.putIfAbsent(key.name(), newCommandMetrics);
return newCommandMetrics;
}
}
}
} | java | public static HystrixCommandMetrics getInstance(HystrixCommandKey key, HystrixCommandGroupKey commandGroup, HystrixThreadPoolKey threadPoolKey, HystrixCommandProperties properties) {
// attempt to retrieve from cache first
HystrixCommandMetrics commandMetrics = metrics.get(key.name());
if (commandMetrics != null) {
return commandMetrics;
} else {
synchronized (HystrixCommandMetrics.class) {
HystrixCommandMetrics existingMetrics = metrics.get(key.name());
if (existingMetrics != null) {
return existingMetrics;
} else {
HystrixThreadPoolKey nonNullThreadPoolKey;
if (threadPoolKey == null) {
nonNullThreadPoolKey = HystrixThreadPoolKey.Factory.asKey(commandGroup.name());
} else {
nonNullThreadPoolKey = threadPoolKey;
}
HystrixCommandMetrics newCommandMetrics = new HystrixCommandMetrics(key, commandGroup, nonNullThreadPoolKey, properties, HystrixPlugins.getInstance().getEventNotifier());
metrics.putIfAbsent(key.name(), newCommandMetrics);
return newCommandMetrics;
}
}
}
} | [
"public",
"static",
"HystrixCommandMetrics",
"getInstance",
"(",
"HystrixCommandKey",
"key",
",",
"HystrixCommandGroupKey",
"commandGroup",
",",
"HystrixThreadPoolKey",
"threadPoolKey",
",",
"HystrixCommandProperties",
"properties",
")",
"{",
"// attempt to retrieve from cache first",
"HystrixCommandMetrics",
"commandMetrics",
"=",
"metrics",
".",
"get",
"(",
"key",
".",
"name",
"(",
")",
")",
";",
"if",
"(",
"commandMetrics",
"!=",
"null",
")",
"{",
"return",
"commandMetrics",
";",
"}",
"else",
"{",
"synchronized",
"(",
"HystrixCommandMetrics",
".",
"class",
")",
"{",
"HystrixCommandMetrics",
"existingMetrics",
"=",
"metrics",
".",
"get",
"(",
"key",
".",
"name",
"(",
")",
")",
";",
"if",
"(",
"existingMetrics",
"!=",
"null",
")",
"{",
"return",
"existingMetrics",
";",
"}",
"else",
"{",
"HystrixThreadPoolKey",
"nonNullThreadPoolKey",
";",
"if",
"(",
"threadPoolKey",
"==",
"null",
")",
"{",
"nonNullThreadPoolKey",
"=",
"HystrixThreadPoolKey",
".",
"Factory",
".",
"asKey",
"(",
"commandGroup",
".",
"name",
"(",
")",
")",
";",
"}",
"else",
"{",
"nonNullThreadPoolKey",
"=",
"threadPoolKey",
";",
"}",
"HystrixCommandMetrics",
"newCommandMetrics",
"=",
"new",
"HystrixCommandMetrics",
"(",
"key",
",",
"commandGroup",
",",
"nonNullThreadPoolKey",
",",
"properties",
",",
"HystrixPlugins",
".",
"getInstance",
"(",
")",
".",
"getEventNotifier",
"(",
")",
")",
";",
"metrics",
".",
"putIfAbsent",
"(",
"key",
".",
"name",
"(",
")",
",",
"newCommandMetrics",
")",
";",
"return",
"newCommandMetrics",
";",
"}",
"}",
"}",
"}"
]
| Get or create the {@link HystrixCommandMetrics} instance for a given {@link HystrixCommandKey}.
<p>
This is thread-safe and ensures only 1 {@link HystrixCommandMetrics} per {@link HystrixCommandKey}.
@param key
{@link HystrixCommandKey} of {@link HystrixCommand} instance requesting the {@link HystrixCommandMetrics}
@param commandGroup
Pass-thru to {@link HystrixCommandMetrics} instance on first time when constructed
@param properties
Pass-thru to {@link HystrixCommandMetrics} instance on first time when constructed
@return {@link HystrixCommandMetrics} | [
"Get",
"or",
"create",
"the",
"{",
"@link",
"HystrixCommandMetrics",
"}",
"instance",
"for",
"a",
"given",
"{",
"@link",
"HystrixCommandKey",
"}",
".",
"<p",
">",
"This",
"is",
"thread",
"-",
"safe",
"and",
"ensures",
"only",
"1",
"{",
"@link",
"HystrixCommandMetrics",
"}",
"per",
"{",
"@link",
"HystrixCommandKey",
"}",
"."
]
| train | https://github.com/Netflix/Hystrix/blob/3cb21589895e9f8f87cfcdbc9d96d9f63d48b848/hystrix-core/src/main/java/com/netflix/hystrix/HystrixCommandMetrics.java#L117-L140 |
codeprimate-software/cp-elements | src/main/java/org/cp/elements/lang/ElementsExceptionsFactory.java | ElementsExceptionsFactory.newParseException | public static ParseException newParseException(Throwable cause, String message, Object... args) {
"""
Constructs and initializes a new {@link ParseException} with the given {@link Throwable cause}
and {@link String message} formatted with the given {@link Object[] arguments}.
@param cause {@link Throwable} identified as the reason this {@link ParseException} was thrown.
@param message {@link String} describing the {@link ParseException exception}.
@param args {@link Object[] arguments} used to replace format placeholders in the {@link String message}.
@return a new {@link ParseException} with the given {@link Throwable cause} and {@link String message}.
@see org.cp.elements.text.ParseException
"""
return new ParseException(format(message, args), cause);
} | java | public static ParseException newParseException(Throwable cause, String message, Object... args) {
return new ParseException(format(message, args), cause);
} | [
"public",
"static",
"ParseException",
"newParseException",
"(",
"Throwable",
"cause",
",",
"String",
"message",
",",
"Object",
"...",
"args",
")",
"{",
"return",
"new",
"ParseException",
"(",
"format",
"(",
"message",
",",
"args",
")",
",",
"cause",
")",
";",
"}"
]
| Constructs and initializes a new {@link ParseException} with the given {@link Throwable cause}
and {@link String message} formatted with the given {@link Object[] arguments}.
@param cause {@link Throwable} identified as the reason this {@link ParseException} was thrown.
@param message {@link String} describing the {@link ParseException exception}.
@param args {@link Object[] arguments} used to replace format placeholders in the {@link String message}.
@return a new {@link ParseException} with the given {@link Throwable cause} and {@link String message}.
@see org.cp.elements.text.ParseException | [
"Constructs",
"and",
"initializes",
"a",
"new",
"{",
"@link",
"ParseException",
"}",
"with",
"the",
"given",
"{",
"@link",
"Throwable",
"cause",
"}",
"and",
"{",
"@link",
"String",
"message",
"}",
"formatted",
"with",
"the",
"given",
"{",
"@link",
"Object",
"[]",
"arguments",
"}",
"."
]
| train | https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/ElementsExceptionsFactory.java#L745-L747 |
jcuda/jcufft | JCufftJava/src/main/java/jcuda/jcufft/JCufft.java | JCufft.cufftPlanMany | public static int cufftPlanMany(cufftHandle plan, int rank, int n[],
int inembed[], int istride, int idist,
int onembed[], int ostride, int odist,
int type, int batch) {
"""
<pre>
Creates a FFT plan configuration of dimension rank, with sizes
specified in the array n.
cufftResult cufftPlanMany(cufftHandle *plan, int rank, int *n,
int *inembed, int istride, int idist,
int *onembed, int ostride, int odist,
cufftType type, int batch );
The batch input parameter tells CUFFT how many transforms to
configure in parallel. With this function, batched plans of
any dimension may be created. Input parameters inembed, istride,
and idist and output parameters onembed, ostride, and odist
will allow setup of noncontiguous input data in a future version.
Note that for CUFFT 3.0, these parameters are ignored and the
layout of batched data must be side-by-side and not interleaved.
Input
----
plan Pointer to a cufftHandle object
rank Dimensionality of the transform (1, 2, or 3)
n An array of size rank, describing the size of each dimension
inembed Unused: pass NULL
istride Unused: pass 1
idist Unused: pass 0
onembed Unused: pass NULL
ostride Unused: pass 1
odist Unused: pass 0
type Transform data type (e.g., CUFFT_C2C, as per other CUFFT calls)
batch Batch size for this transform
Output
----
plan Contains a CUFFT plan handle
Return Values
----
CUFFT_SETUP_FAILED CUFFT library failed to initialize.
CUFFT_INVALID_SIZE Parameter is not a supported size.
CUFFT_INVALID_TYPE The type parameter is not supported
</pre>
"""
return checkResult(cufftPlanManyNative(plan, rank, n, inembed, istride, idist, onembed, ostride, odist, type, batch));
} | java | public static int cufftPlanMany(cufftHandle plan, int rank, int n[],
int inembed[], int istride, int idist,
int onembed[], int ostride, int odist,
int type, int batch)
{
return checkResult(cufftPlanManyNative(plan, rank, n, inembed, istride, idist, onembed, ostride, odist, type, batch));
} | [
"public",
"static",
"int",
"cufftPlanMany",
"(",
"cufftHandle",
"plan",
",",
"int",
"rank",
",",
"int",
"n",
"[",
"]",
",",
"int",
"inembed",
"[",
"]",
",",
"int",
"istride",
",",
"int",
"idist",
",",
"int",
"onembed",
"[",
"]",
",",
"int",
"ostride",
",",
"int",
"odist",
",",
"int",
"type",
",",
"int",
"batch",
")",
"{",
"return",
"checkResult",
"(",
"cufftPlanManyNative",
"(",
"plan",
",",
"rank",
",",
"n",
",",
"inembed",
",",
"istride",
",",
"idist",
",",
"onembed",
",",
"ostride",
",",
"odist",
",",
"type",
",",
"batch",
")",
")",
";",
"}"
]
| <pre>
Creates a FFT plan configuration of dimension rank, with sizes
specified in the array n.
cufftResult cufftPlanMany(cufftHandle *plan, int rank, int *n,
int *inembed, int istride, int idist,
int *onembed, int ostride, int odist,
cufftType type, int batch );
The batch input parameter tells CUFFT how many transforms to
configure in parallel. With this function, batched plans of
any dimension may be created. Input parameters inembed, istride,
and idist and output parameters onembed, ostride, and odist
will allow setup of noncontiguous input data in a future version.
Note that for CUFFT 3.0, these parameters are ignored and the
layout of batched data must be side-by-side and not interleaved.
Input
----
plan Pointer to a cufftHandle object
rank Dimensionality of the transform (1, 2, or 3)
n An array of size rank, describing the size of each dimension
inembed Unused: pass NULL
istride Unused: pass 1
idist Unused: pass 0
onembed Unused: pass NULL
ostride Unused: pass 1
odist Unused: pass 0
type Transform data type (e.g., CUFFT_C2C, as per other CUFFT calls)
batch Batch size for this transform
Output
----
plan Contains a CUFFT plan handle
Return Values
----
CUFFT_SETUP_FAILED CUFFT library failed to initialize.
CUFFT_INVALID_SIZE Parameter is not a supported size.
CUFFT_INVALID_TYPE The type parameter is not supported
</pre> | [
"<pre",
">",
"Creates",
"a",
"FFT",
"plan",
"configuration",
"of",
"dimension",
"rank",
"with",
"sizes",
"specified",
"in",
"the",
"array",
"n",
"."
]
| train | https://github.com/jcuda/jcufft/blob/833c87ffb0864f7ee7270fddef8af57f48939b3a/JCufftJava/src/main/java/jcuda/jcufft/JCufft.java#L349-L355 |
scravy/java-pair | src/main/java/de/scravy/pair/Pairs.java | Pairs.toArray | public static <CommonSuperType, First extends CommonSuperType, Second extends CommonSuperType>
CommonSuperType[] toArray(final Pair<First, Second> pair,
final Class<CommonSuperType> commonSuperType) {
"""
Transform a pair into an array of the common super type of both components.
@param pair
The pair.
@param commonSuperType
A common super type that both First and Second inherit from.
@return The array of the common super type with length 2.
"""
@SuppressWarnings("unchecked")
final CommonSuperType[] array = (CommonSuperType[]) Array.newInstance(
commonSuperType, 2);
return toArray(pair, array, 0);
} | java | public static <CommonSuperType, First extends CommonSuperType, Second extends CommonSuperType>
CommonSuperType[] toArray(final Pair<First, Second> pair,
final Class<CommonSuperType> commonSuperType) {
@SuppressWarnings("unchecked")
final CommonSuperType[] array = (CommonSuperType[]) Array.newInstance(
commonSuperType, 2);
return toArray(pair, array, 0);
} | [
"public",
"static",
"<",
"CommonSuperType",
",",
"First",
"extends",
"CommonSuperType",
",",
"Second",
"extends",
"CommonSuperType",
">",
"CommonSuperType",
"[",
"]",
"toArray",
"(",
"final",
"Pair",
"<",
"First",
",",
"Second",
">",
"pair",
",",
"final",
"Class",
"<",
"CommonSuperType",
">",
"commonSuperType",
")",
"{",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"final",
"CommonSuperType",
"[",
"]",
"array",
"=",
"(",
"CommonSuperType",
"[",
"]",
")",
"Array",
".",
"newInstance",
"(",
"commonSuperType",
",",
"2",
")",
";",
"return",
"toArray",
"(",
"pair",
",",
"array",
",",
"0",
")",
";",
"}"
]
| Transform a pair into an array of the common super type of both components.
@param pair
The pair.
@param commonSuperType
A common super type that both First and Second inherit from.
@return The array of the common super type with length 2. | [
"Transform",
"a",
"pair",
"into",
"an",
"array",
"of",
"the",
"common",
"super",
"type",
"of",
"both",
"components",
"."
]
| train | https://github.com/scravy/java-pair/blob/d8792e86c4f8e977826a4ccb940e4416a1119ccb/src/main/java/de/scravy/pair/Pairs.java#L97-L104 |
Omertron/api-thetvdb | src/main/java/com/omertron/thetvdbapi/TheTVDBApi.java | TheTVDBApi.getSeasonYear | public String getSeasonYear(String id, int seasonNbr, String language) throws TvDbException {
"""
Get a list of banners for the series id
@param id
@param seasonNbr
@param language
@return
@throws com.omertron.thetvdbapi.TvDbException
"""
String year = null;
Episode episode = getEpisode(id, seasonNbr, 1, language);
if (episode != null && StringUtils.isNotBlank(episode.getFirstAired())) {
Date date;
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
date = dateFormat.parse(episode.getFirstAired());
} catch (ParseException ex) {
LOG.trace("Failed to transform date: {}", episode.getFirstAired(), ex);
date = null;
}
if (date != null) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
year = String.valueOf(cal.get(Calendar.YEAR));
}
}
return year;
} | java | public String getSeasonYear(String id, int seasonNbr, String language) throws TvDbException {
String year = null;
Episode episode = getEpisode(id, seasonNbr, 1, language);
if (episode != null && StringUtils.isNotBlank(episode.getFirstAired())) {
Date date;
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
date = dateFormat.parse(episode.getFirstAired());
} catch (ParseException ex) {
LOG.trace("Failed to transform date: {}", episode.getFirstAired(), ex);
date = null;
}
if (date != null) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
year = String.valueOf(cal.get(Calendar.YEAR));
}
}
return year;
} | [
"public",
"String",
"getSeasonYear",
"(",
"String",
"id",
",",
"int",
"seasonNbr",
",",
"String",
"language",
")",
"throws",
"TvDbException",
"{",
"String",
"year",
"=",
"null",
";",
"Episode",
"episode",
"=",
"getEpisode",
"(",
"id",
",",
"seasonNbr",
",",
"1",
",",
"language",
")",
";",
"if",
"(",
"episode",
"!=",
"null",
"&&",
"StringUtils",
".",
"isNotBlank",
"(",
"episode",
".",
"getFirstAired",
"(",
")",
")",
")",
"{",
"Date",
"date",
";",
"try",
"{",
"SimpleDateFormat",
"dateFormat",
"=",
"new",
"SimpleDateFormat",
"(",
"\"yyyy-MM-dd\"",
")",
";",
"date",
"=",
"dateFormat",
".",
"parse",
"(",
"episode",
".",
"getFirstAired",
"(",
")",
")",
";",
"}",
"catch",
"(",
"ParseException",
"ex",
")",
"{",
"LOG",
".",
"trace",
"(",
"\"Failed to transform date: {}\"",
",",
"episode",
".",
"getFirstAired",
"(",
")",
",",
"ex",
")",
";",
"date",
"=",
"null",
";",
"}",
"if",
"(",
"date",
"!=",
"null",
")",
"{",
"Calendar",
"cal",
"=",
"Calendar",
".",
"getInstance",
"(",
")",
";",
"cal",
".",
"setTime",
"(",
"date",
")",
";",
"year",
"=",
"String",
".",
"valueOf",
"(",
"cal",
".",
"get",
"(",
"Calendar",
".",
"YEAR",
")",
")",
";",
"}",
"}",
"return",
"year",
";",
"}"
]
| Get a list of banners for the series id
@param id
@param seasonNbr
@param language
@return
@throws com.omertron.thetvdbapi.TvDbException | [
"Get",
"a",
"list",
"of",
"banners",
"for",
"the",
"series",
"id"
]
| train | https://github.com/Omertron/api-thetvdb/blob/2ff9f9580e76043f19d2fc3234d87e16a95fa485/src/main/java/com/omertron/thetvdbapi/TheTVDBApi.java#L268-L291 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.