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
sequencelengths 20
832
| func_documentation_string
stringlengths 61
2k
| func_documentation_tokens
sequencelengths 1
647
| split_name
stringclasses 1
value | func_code_url
stringlengths 102
339
|
---|---|---|---|---|---|---|---|---|---|---|
OpenLiberty/open-liberty | dev/com.ibm.ws.ejbcontainer/src/com/ibm/ws/ejbcontainer/osgi/internal/naming/EJBJavaColonNamingHelper.java | EJBJavaColonNamingHelper.addAppBinding | public synchronized void addAppBinding(ModuleMetaData mmd, String name, EJBBinding bindingObject) {
"""
Add a java:app binding object to the mapping.
@param name lookup name
@param bindingObject object to use to instantiate EJB at lookup time.
@return
@throws NamingException
"""
Lock writeLock = javaColonLock.writeLock();
writeLock.lock();
try {
JavaColonNamespaceBindings<EJBBinding> bindings = getAppBindingMap(mmd.getApplicationMetaData());
bindings.bind(name, bindingObject);
} finally {
writeLock.unlock();
}
} | java | public synchronized void addAppBinding(ModuleMetaData mmd, String name, EJBBinding bindingObject) {
Lock writeLock = javaColonLock.writeLock();
writeLock.lock();
try {
JavaColonNamespaceBindings<EJBBinding> bindings = getAppBindingMap(mmd.getApplicationMetaData());
bindings.bind(name, bindingObject);
} finally {
writeLock.unlock();
}
} | [
"public",
"synchronized",
"void",
"addAppBinding",
"(",
"ModuleMetaData",
"mmd",
",",
"String",
"name",
",",
"EJBBinding",
"bindingObject",
")",
"{",
"Lock",
"writeLock",
"=",
"javaColonLock",
".",
"writeLock",
"(",
")",
";",
"writeLock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"JavaColonNamespaceBindings",
"<",
"EJBBinding",
">",
"bindings",
"=",
"getAppBindingMap",
"(",
"mmd",
".",
"getApplicationMetaData",
"(",
")",
")",
";",
"bindings",
".",
"bind",
"(",
"name",
",",
"bindingObject",
")",
";",
"}",
"finally",
"{",
"writeLock",
".",
"unlock",
"(",
")",
";",
"}",
"}"
] | Add a java:app binding object to the mapping.
@param name lookup name
@param bindingObject object to use to instantiate EJB at lookup time.
@return
@throws NamingException | [
"Add",
"a",
"java",
":",
"app",
"binding",
"object",
"to",
"the",
"mapping",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ejbcontainer/src/com/ibm/ws/ejbcontainer/osgi/internal/naming/EJBJavaColonNamingHelper.java#L384-L395 |
Cornutum/tcases | tcases-lib/src/main/java/org/cornutum/tcases/generator/TupleGenerator.java | TupleGenerator.getBaseFailureCases | private List<TestCaseDef> getBaseFailureCases( FunctionInputDef inputDef, VarTupleSet validTuples, VarTupleSet failureTuples, List<TestCaseDef> baseCases) {
"""
Returns a set of failure {@link TestCaseDef test case definitions} that extend the given base test cases.
"""
logger_.debug( "{}: Extending base failure test cases", inputDef);
Iterator<TestCaseDef> failureBaseCases =
IteratorUtils.filteredIterator(
baseCases.iterator(),
testCase -> testCase.getInvalidVar() != null);
List<TestCaseDef> testCases = extendBaseCases( inputDef, validTuples, failureBaseCases);
// Consume all failure values used.
for( TestCaseDef testCase : testCases)
{
VarDef failureVar = testCase.getInvalidVar();
failureTuples.used( new Tuple( new VarBindingDef( failureVar, testCase.getValue( failureVar))));
}
logger_.info( "{}: Extended {} base failure test cases", inputDef, testCases.size());
return testCases;
} | java | private List<TestCaseDef> getBaseFailureCases( FunctionInputDef inputDef, VarTupleSet validTuples, VarTupleSet failureTuples, List<TestCaseDef> baseCases)
{
logger_.debug( "{}: Extending base failure test cases", inputDef);
Iterator<TestCaseDef> failureBaseCases =
IteratorUtils.filteredIterator(
baseCases.iterator(),
testCase -> testCase.getInvalidVar() != null);
List<TestCaseDef> testCases = extendBaseCases( inputDef, validTuples, failureBaseCases);
// Consume all failure values used.
for( TestCaseDef testCase : testCases)
{
VarDef failureVar = testCase.getInvalidVar();
failureTuples.used( new Tuple( new VarBindingDef( failureVar, testCase.getValue( failureVar))));
}
logger_.info( "{}: Extended {} base failure test cases", inputDef, testCases.size());
return testCases;
} | [
"private",
"List",
"<",
"TestCaseDef",
">",
"getBaseFailureCases",
"(",
"FunctionInputDef",
"inputDef",
",",
"VarTupleSet",
"validTuples",
",",
"VarTupleSet",
"failureTuples",
",",
"List",
"<",
"TestCaseDef",
">",
"baseCases",
")",
"{",
"logger_",
".",
"debug",
"(",
"\"{}: Extending base failure test cases\"",
",",
"inputDef",
")",
";",
"Iterator",
"<",
"TestCaseDef",
">",
"failureBaseCases",
"=",
"IteratorUtils",
".",
"filteredIterator",
"(",
"baseCases",
".",
"iterator",
"(",
")",
",",
"testCase",
"->",
"testCase",
".",
"getInvalidVar",
"(",
")",
"!=",
"null",
")",
";",
"List",
"<",
"TestCaseDef",
">",
"testCases",
"=",
"extendBaseCases",
"(",
"inputDef",
",",
"validTuples",
",",
"failureBaseCases",
")",
";",
"// Consume all failure values used.",
"for",
"(",
"TestCaseDef",
"testCase",
":",
"testCases",
")",
"{",
"VarDef",
"failureVar",
"=",
"testCase",
".",
"getInvalidVar",
"(",
")",
";",
"failureTuples",
".",
"used",
"(",
"new",
"Tuple",
"(",
"new",
"VarBindingDef",
"(",
"failureVar",
",",
"testCase",
".",
"getValue",
"(",
"failureVar",
")",
")",
")",
")",
";",
"}",
"logger_",
".",
"info",
"(",
"\"{}: Extended {} base failure test cases\"",
",",
"inputDef",
",",
"testCases",
".",
"size",
"(",
")",
")",
";",
"return",
"testCases",
";",
"}"
] | Returns a set of failure {@link TestCaseDef test case definitions} that extend the given base test cases. | [
"Returns",
"a",
"set",
"of",
"failure",
"{"
] | train | https://github.com/Cornutum/tcases/blob/21e15cf107fa149620c40f4bda1829c1224fcfb1/tcases-lib/src/main/java/org/cornutum/tcases/generator/TupleGenerator.java#L294-L314 |
box/box-java-sdk | src/main/java/com/box/sdk/MetadataTemplate.java | MetadataTemplate.createMetadataTemplate | public static MetadataTemplate createMetadataTemplate(BoxAPIConnection api, String scope, String templateKey,
String displayName, boolean hidden, List<Field> fields) {
"""
Creates new metadata template.
@param api the API connection to be used.
@param scope the scope of the object.
@param templateKey a unique identifier for the template.
@param displayName the display name of the field.
@param hidden whether this template is hidden in the UI.
@param fields the ordered set of fields for the template
@return the metadata template returned from the server.
"""
JsonObject jsonObject = new JsonObject();
jsonObject.add("scope", scope);
jsonObject.add("displayName", displayName);
jsonObject.add("hidden", hidden);
if (templateKey != null) {
jsonObject.add("templateKey", templateKey);
}
JsonArray fieldsArray = new JsonArray();
if (fields != null && !fields.isEmpty()) {
for (Field field : fields) {
JsonObject fieldObj = getFieldJsonObject(field);
fieldsArray.add(fieldObj);
}
jsonObject.add("fields", fieldsArray);
}
URL url = METADATA_TEMPLATE_SCHEMA_URL_TEMPLATE.build(api.getBaseURL());
BoxJSONRequest request = new BoxJSONRequest(api, url, "POST");
request.setBody(jsonObject.toString());
BoxJSONResponse response = (BoxJSONResponse) request.send();
JsonObject responseJSON = JsonObject.readFrom(response.getJSON());
return new MetadataTemplate(responseJSON);
} | java | public static MetadataTemplate createMetadataTemplate(BoxAPIConnection api, String scope, String templateKey,
String displayName, boolean hidden, List<Field> fields) {
JsonObject jsonObject = new JsonObject();
jsonObject.add("scope", scope);
jsonObject.add("displayName", displayName);
jsonObject.add("hidden", hidden);
if (templateKey != null) {
jsonObject.add("templateKey", templateKey);
}
JsonArray fieldsArray = new JsonArray();
if (fields != null && !fields.isEmpty()) {
for (Field field : fields) {
JsonObject fieldObj = getFieldJsonObject(field);
fieldsArray.add(fieldObj);
}
jsonObject.add("fields", fieldsArray);
}
URL url = METADATA_TEMPLATE_SCHEMA_URL_TEMPLATE.build(api.getBaseURL());
BoxJSONRequest request = new BoxJSONRequest(api, url, "POST");
request.setBody(jsonObject.toString());
BoxJSONResponse response = (BoxJSONResponse) request.send();
JsonObject responseJSON = JsonObject.readFrom(response.getJSON());
return new MetadataTemplate(responseJSON);
} | [
"public",
"static",
"MetadataTemplate",
"createMetadataTemplate",
"(",
"BoxAPIConnection",
"api",
",",
"String",
"scope",
",",
"String",
"templateKey",
",",
"String",
"displayName",
",",
"boolean",
"hidden",
",",
"List",
"<",
"Field",
">",
"fields",
")",
"{",
"JsonObject",
"jsonObject",
"=",
"new",
"JsonObject",
"(",
")",
";",
"jsonObject",
".",
"add",
"(",
"\"scope\"",
",",
"scope",
")",
";",
"jsonObject",
".",
"add",
"(",
"\"displayName\"",
",",
"displayName",
")",
";",
"jsonObject",
".",
"add",
"(",
"\"hidden\"",
",",
"hidden",
")",
";",
"if",
"(",
"templateKey",
"!=",
"null",
")",
"{",
"jsonObject",
".",
"add",
"(",
"\"templateKey\"",
",",
"templateKey",
")",
";",
"}",
"JsonArray",
"fieldsArray",
"=",
"new",
"JsonArray",
"(",
")",
";",
"if",
"(",
"fields",
"!=",
"null",
"&&",
"!",
"fields",
".",
"isEmpty",
"(",
")",
")",
"{",
"for",
"(",
"Field",
"field",
":",
"fields",
")",
"{",
"JsonObject",
"fieldObj",
"=",
"getFieldJsonObject",
"(",
"field",
")",
";",
"fieldsArray",
".",
"add",
"(",
"fieldObj",
")",
";",
"}",
"jsonObject",
".",
"add",
"(",
"\"fields\"",
",",
"fieldsArray",
")",
";",
"}",
"URL",
"url",
"=",
"METADATA_TEMPLATE_SCHEMA_URL_TEMPLATE",
".",
"build",
"(",
"api",
".",
"getBaseURL",
"(",
")",
")",
";",
"BoxJSONRequest",
"request",
"=",
"new",
"BoxJSONRequest",
"(",
"api",
",",
"url",
",",
"\"POST\"",
")",
";",
"request",
".",
"setBody",
"(",
"jsonObject",
".",
"toString",
"(",
")",
")",
";",
"BoxJSONResponse",
"response",
"=",
"(",
"BoxJSONResponse",
")",
"request",
".",
"send",
"(",
")",
";",
"JsonObject",
"responseJSON",
"=",
"JsonObject",
".",
"readFrom",
"(",
"response",
".",
"getJSON",
"(",
")",
")",
";",
"return",
"new",
"MetadataTemplate",
"(",
"responseJSON",
")",
";",
"}"
] | Creates new metadata template.
@param api the API connection to be used.
@param scope the scope of the object.
@param templateKey a unique identifier for the template.
@param displayName the display name of the field.
@param hidden whether this template is hidden in the UI.
@param fields the ordered set of fields for the template
@return the metadata template returned from the server. | [
"Creates",
"new",
"metadata",
"template",
"."
] | train | https://github.com/box/box-java-sdk/blob/35b4ba69417f9d6a002c19dfaab57527750ef349/src/main/java/com/box/sdk/MetadataTemplate.java#L198-L229 |
jcuda/jcudnn | JCudnnJava/src/main/java/jcuda/jcudnn/JCudnn.java | JCudnn.cudnnLRNCrossChannelForward | public static int cudnnLRNCrossChannelForward(
cudnnHandle handle,
cudnnLRNDescriptor normDesc,
int lrnMode,
Pointer alpha,
cudnnTensorDescriptor xDesc,
Pointer x,
Pointer beta,
cudnnTensorDescriptor yDesc,
Pointer y) {
"""
LRN cross-channel forward computation. Double parameters cast to tensor data type
"""
return checkResult(cudnnLRNCrossChannelForwardNative(handle, normDesc, lrnMode, alpha, xDesc, x, beta, yDesc, y));
} | java | public static int cudnnLRNCrossChannelForward(
cudnnHandle handle,
cudnnLRNDescriptor normDesc,
int lrnMode,
Pointer alpha,
cudnnTensorDescriptor xDesc,
Pointer x,
Pointer beta,
cudnnTensorDescriptor yDesc,
Pointer y)
{
return checkResult(cudnnLRNCrossChannelForwardNative(handle, normDesc, lrnMode, alpha, xDesc, x, beta, yDesc, y));
} | [
"public",
"static",
"int",
"cudnnLRNCrossChannelForward",
"(",
"cudnnHandle",
"handle",
",",
"cudnnLRNDescriptor",
"normDesc",
",",
"int",
"lrnMode",
",",
"Pointer",
"alpha",
",",
"cudnnTensorDescriptor",
"xDesc",
",",
"Pointer",
"x",
",",
"Pointer",
"beta",
",",
"cudnnTensorDescriptor",
"yDesc",
",",
"Pointer",
"y",
")",
"{",
"return",
"checkResult",
"(",
"cudnnLRNCrossChannelForwardNative",
"(",
"handle",
",",
"normDesc",
",",
"lrnMode",
",",
"alpha",
",",
"xDesc",
",",
"x",
",",
"beta",
",",
"yDesc",
",",
"y",
")",
")",
";",
"}"
] | LRN cross-channel forward computation. Double parameters cast to tensor data type | [
"LRN",
"cross",
"-",
"channel",
"forward",
"computation",
".",
"Double",
"parameters",
"cast",
"to",
"tensor",
"data",
"type"
] | train | https://github.com/jcuda/jcudnn/blob/ce71f2fc02817cecace51a80e6db5f0c7f10cffc/JCudnnJava/src/main/java/jcuda/jcudnn/JCudnn.java#L2054-L2066 |
cdk/cdk | base/standard/src/main/java/org/openscience/cdk/tools/manipulator/ChemModelManipulator.java | ChemModelManipulator.setAtomProperties | public static void setAtomProperties(IChemModel chemModel, Object propKey, Object propVal) {
"""
Sets the AtomProperties of all Atoms inside an IChemModel.
@param chemModel The IChemModel object.
@param propKey The key of the property.
@param propVal The value of the property.
"""
if (chemModel.getMoleculeSet() != null) {
MoleculeSetManipulator.setAtomProperties(chemModel.getMoleculeSet(), propKey, propVal);
}
if (chemModel.getReactionSet() != null) {
ReactionSetManipulator.setAtomProperties(chemModel.getReactionSet(), propKey, propVal);
}
if (chemModel.getCrystal() != null) {
AtomContainerManipulator.setAtomProperties(chemModel.getCrystal(), propKey, propVal);
}
} | java | public static void setAtomProperties(IChemModel chemModel, Object propKey, Object propVal) {
if (chemModel.getMoleculeSet() != null) {
MoleculeSetManipulator.setAtomProperties(chemModel.getMoleculeSet(), propKey, propVal);
}
if (chemModel.getReactionSet() != null) {
ReactionSetManipulator.setAtomProperties(chemModel.getReactionSet(), propKey, propVal);
}
if (chemModel.getCrystal() != null) {
AtomContainerManipulator.setAtomProperties(chemModel.getCrystal(), propKey, propVal);
}
} | [
"public",
"static",
"void",
"setAtomProperties",
"(",
"IChemModel",
"chemModel",
",",
"Object",
"propKey",
",",
"Object",
"propVal",
")",
"{",
"if",
"(",
"chemModel",
".",
"getMoleculeSet",
"(",
")",
"!=",
"null",
")",
"{",
"MoleculeSetManipulator",
".",
"setAtomProperties",
"(",
"chemModel",
".",
"getMoleculeSet",
"(",
")",
",",
"propKey",
",",
"propVal",
")",
";",
"}",
"if",
"(",
"chemModel",
".",
"getReactionSet",
"(",
")",
"!=",
"null",
")",
"{",
"ReactionSetManipulator",
".",
"setAtomProperties",
"(",
"chemModel",
".",
"getReactionSet",
"(",
")",
",",
"propKey",
",",
"propVal",
")",
";",
"}",
"if",
"(",
"chemModel",
".",
"getCrystal",
"(",
")",
"!=",
"null",
")",
"{",
"AtomContainerManipulator",
".",
"setAtomProperties",
"(",
"chemModel",
".",
"getCrystal",
"(",
")",
",",
"propKey",
",",
"propVal",
")",
";",
"}",
"}"
] | Sets the AtomProperties of all Atoms inside an IChemModel.
@param chemModel The IChemModel object.
@param propKey The key of the property.
@param propVal The value of the property. | [
"Sets",
"the",
"AtomProperties",
"of",
"all",
"Atoms",
"inside",
"an",
"IChemModel",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/standard/src/main/java/org/openscience/cdk/tools/manipulator/ChemModelManipulator.java#L285-L295 |
feedzai/pdb | src/main/java/com/feedzai/commons/sql/abstraction/engine/AbstractDatabaseEngine.java | AbstractDatabaseEngine.executePS | @Override
public synchronized void executePS(final String name) throws DatabaseEngineException, ConnectionResetException {
"""
Executes the specified prepared statement.
@param name The prepared statement name.
@throws DatabaseEngineException If something goes wrong while executing.
@throws ConnectionResetException If the connection is down and reestablishment occurs. If this happens, the user must reset the parameters and re-execute
the query.
"""
final PreparedStatementCapsule ps = stmts.get(name);
if (ps == null) {
throw new DatabaseEngineRuntimeException(String.format("PreparedStatement named '%s' does not exist", name));
}
try {
ps.ps.execute();
} catch (final SQLException e) {
logger.error("Error executing prepared statement", e);
if (checkConnection(conn) || !properties.isReconnectOnLost()) {
throw new DatabaseEngineException(String.format("Something went wrong executing the prepared statement '%s'", name), e);
}
// At this point maybe it is an error with the connection, so we try to re-establish it.
try {
getConnection();
} catch (final Exception e2) {
throw new DatabaseEngineException("Connection is down", e2);
}
throw new ConnectionResetException("Connection was lost, you must reset the prepared statement parameters and re-execute the statement");
}
} | java | @Override
public synchronized void executePS(final String name) throws DatabaseEngineException, ConnectionResetException {
final PreparedStatementCapsule ps = stmts.get(name);
if (ps == null) {
throw new DatabaseEngineRuntimeException(String.format("PreparedStatement named '%s' does not exist", name));
}
try {
ps.ps.execute();
} catch (final SQLException e) {
logger.error("Error executing prepared statement", e);
if (checkConnection(conn) || !properties.isReconnectOnLost()) {
throw new DatabaseEngineException(String.format("Something went wrong executing the prepared statement '%s'", name), e);
}
// At this point maybe it is an error with the connection, so we try to re-establish it.
try {
getConnection();
} catch (final Exception e2) {
throw new DatabaseEngineException("Connection is down", e2);
}
throw new ConnectionResetException("Connection was lost, you must reset the prepared statement parameters and re-execute the statement");
}
} | [
"@",
"Override",
"public",
"synchronized",
"void",
"executePS",
"(",
"final",
"String",
"name",
")",
"throws",
"DatabaseEngineException",
",",
"ConnectionResetException",
"{",
"final",
"PreparedStatementCapsule",
"ps",
"=",
"stmts",
".",
"get",
"(",
"name",
")",
";",
"if",
"(",
"ps",
"==",
"null",
")",
"{",
"throw",
"new",
"DatabaseEngineRuntimeException",
"(",
"String",
".",
"format",
"(",
"\"PreparedStatement named '%s' does not exist\"",
",",
"name",
")",
")",
";",
"}",
"try",
"{",
"ps",
".",
"ps",
".",
"execute",
"(",
")",
";",
"}",
"catch",
"(",
"final",
"SQLException",
"e",
")",
"{",
"logger",
".",
"error",
"(",
"\"Error executing prepared statement\"",
",",
"e",
")",
";",
"if",
"(",
"checkConnection",
"(",
"conn",
")",
"||",
"!",
"properties",
".",
"isReconnectOnLost",
"(",
")",
")",
"{",
"throw",
"new",
"DatabaseEngineException",
"(",
"String",
".",
"format",
"(",
"\"Something went wrong executing the prepared statement '%s'\"",
",",
"name",
")",
",",
"e",
")",
";",
"}",
"// At this point maybe it is an error with the connection, so we try to re-establish it.",
"try",
"{",
"getConnection",
"(",
")",
";",
"}",
"catch",
"(",
"final",
"Exception",
"e2",
")",
"{",
"throw",
"new",
"DatabaseEngineException",
"(",
"\"Connection is down\"",
",",
"e2",
")",
";",
"}",
"throw",
"new",
"ConnectionResetException",
"(",
"\"Connection was lost, you must reset the prepared statement parameters and re-execute the statement\"",
")",
";",
"}",
"}"
] | Executes the specified prepared statement.
@param name The prepared statement name.
@throws DatabaseEngineException If something goes wrong while executing.
@throws ConnectionResetException If the connection is down and reestablishment occurs. If this happens, the user must reset the parameters and re-execute
the query. | [
"Executes",
"the",
"specified",
"prepared",
"statement",
"."
] | train | https://github.com/feedzai/pdb/blob/fe07ca08417e0ddcd620a36aa1fdbca7f338be98/src/main/java/com/feedzai/commons/sql/abstraction/engine/AbstractDatabaseEngine.java#L1724-L1749 |
grails/grails-core | grails-core/src/main/groovy/org/grails/compiler/injection/GrailsASTUtils.java | GrailsASTUtils.applyDefaultMethodTarget | public static MethodCallExpression applyDefaultMethodTarget(final MethodCallExpression methodCallExpression, final Class<?> targetClass) {
"""
Set the method target of a MethodCallExpression to the first matching method with same number of arguments.
This doesn't check argument types.
@param methodCallExpression
@param targetClass
@return The method call expression
"""
return applyDefaultMethodTarget(methodCallExpression, ClassHelper.make(targetClass).getPlainNodeReference());
} | java | public static MethodCallExpression applyDefaultMethodTarget(final MethodCallExpression methodCallExpression, final Class<?> targetClass) {
return applyDefaultMethodTarget(methodCallExpression, ClassHelper.make(targetClass).getPlainNodeReference());
} | [
"public",
"static",
"MethodCallExpression",
"applyDefaultMethodTarget",
"(",
"final",
"MethodCallExpression",
"methodCallExpression",
",",
"final",
"Class",
"<",
"?",
">",
"targetClass",
")",
"{",
"return",
"applyDefaultMethodTarget",
"(",
"methodCallExpression",
",",
"ClassHelper",
".",
"make",
"(",
"targetClass",
")",
".",
"getPlainNodeReference",
"(",
")",
")",
";",
"}"
] | Set the method target of a MethodCallExpression to the first matching method with same number of arguments.
This doesn't check argument types.
@param methodCallExpression
@param targetClass
@return The method call expression | [
"Set",
"the",
"method",
"target",
"of",
"a",
"MethodCallExpression",
"to",
"the",
"first",
"matching",
"method",
"with",
"same",
"number",
"of",
"arguments",
".",
"This",
"doesn",
"t",
"check",
"argument",
"types",
"."
] | train | https://github.com/grails/grails-core/blob/c0b08aa995b0297143b75d05642abba8cb7b4122/grails-core/src/main/groovy/org/grails/compiler/injection/GrailsASTUtils.java#L1211-L1213 |
tvesalainen/util | security/src/main/java/org/vesalainen/net/ssl/SSLSocketChannel.java | SSLSocketChannel.open | public static SSLSocketChannel open(SocketChannel socketChannel, SSLContext sslContext, ByteBuffer consumed, boolean autoClose) throws IOException {
"""
Creates SSLSocketChannel over connected SocketChannel using given
SSLContext. Connection is in server mode, but can be changed before read/write.
@param socketChannel
@param sslContext
@param consumed If not null, ByteBuffer's remaining can contain bytes
that are consumed by SocketChannel, but are part of SSL connection. Bytes
are moved from this buffer. This buffers hasRemaining is false after call.
@param autoClose If true the SocketChannel is closed when SSLSocketChannel
is closed.
@return
@throws IOException
"""
SSLEngine engine = sslContext.createSSLEngine();
engine.setUseClientMode(false);
SSLSocketChannel sslSocketChannel = new SSLSocketChannel(socketChannel, engine, consumed, !autoClose);
return sslSocketChannel;
} | java | public static SSLSocketChannel open(SocketChannel socketChannel, SSLContext sslContext, ByteBuffer consumed, boolean autoClose) throws IOException
{
SSLEngine engine = sslContext.createSSLEngine();
engine.setUseClientMode(false);
SSLSocketChannel sslSocketChannel = new SSLSocketChannel(socketChannel, engine, consumed, !autoClose);
return sslSocketChannel;
} | [
"public",
"static",
"SSLSocketChannel",
"open",
"(",
"SocketChannel",
"socketChannel",
",",
"SSLContext",
"sslContext",
",",
"ByteBuffer",
"consumed",
",",
"boolean",
"autoClose",
")",
"throws",
"IOException",
"{",
"SSLEngine",
"engine",
"=",
"sslContext",
".",
"createSSLEngine",
"(",
")",
";",
"engine",
".",
"setUseClientMode",
"(",
"false",
")",
";",
"SSLSocketChannel",
"sslSocketChannel",
"=",
"new",
"SSLSocketChannel",
"(",
"socketChannel",
",",
"engine",
",",
"consumed",
",",
"!",
"autoClose",
")",
";",
"return",
"sslSocketChannel",
";",
"}"
] | Creates SSLSocketChannel over connected SocketChannel using given
SSLContext. Connection is in server mode, but can be changed before read/write.
@param socketChannel
@param sslContext
@param consumed If not null, ByteBuffer's remaining can contain bytes
that are consumed by SocketChannel, but are part of SSL connection. Bytes
are moved from this buffer. This buffers hasRemaining is false after call.
@param autoClose If true the SocketChannel is closed when SSLSocketChannel
is closed.
@return
@throws IOException | [
"Creates",
"SSLSocketChannel",
"over",
"connected",
"SocketChannel",
"using",
"given",
"SSLContext",
".",
"Connection",
"is",
"in",
"server",
"mode",
"but",
"can",
"be",
"changed",
"before",
"read",
"/",
"write",
"."
] | train | https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/security/src/main/java/org/vesalainen/net/ssl/SSLSocketChannel.java#L126-L132 |
gliga/ekstazi | ekstazi-maven-plugin/src/main/java/org/ekstazi/maven/DynamicSelectEkstaziMojo.java | DynamicSelectEkstaziMojo.executeThis | private void executeThis() throws MojoExecutionException {
"""
Implements 'select' that does not require changes to any
existing plugin in configuration file(s).
"""
// Try to attach agent that will modify Surefire.
if (AgentLoader.loadEkstaziAgent()) {
// Prepare initial list of options and set property.
System.setProperty(AbstractMojoInterceptor.ARGLINE_INTERNAL_PROP, prepareEkstaziOptions());
// Find non affected classes and set property.
List<String> nonAffectedClasses = computeNonAffectedClasses();
System.setProperty(AbstractMojoInterceptor.EXCLUDES_INTERNAL_PROP, Arrays.toString(nonAffectedClasses.toArray(new String[0])));
} else {
throw new MojoExecutionException("Ekstazi cannot attach to the JVM, please specify Ekstazi 'restore' explicitly.");
}
} | java | private void executeThis() throws MojoExecutionException {
// Try to attach agent that will modify Surefire.
if (AgentLoader.loadEkstaziAgent()) {
// Prepare initial list of options and set property.
System.setProperty(AbstractMojoInterceptor.ARGLINE_INTERNAL_PROP, prepareEkstaziOptions());
// Find non affected classes and set property.
List<String> nonAffectedClasses = computeNonAffectedClasses();
System.setProperty(AbstractMojoInterceptor.EXCLUDES_INTERNAL_PROP, Arrays.toString(nonAffectedClasses.toArray(new String[0])));
} else {
throw new MojoExecutionException("Ekstazi cannot attach to the JVM, please specify Ekstazi 'restore' explicitly.");
}
} | [
"private",
"void",
"executeThis",
"(",
")",
"throws",
"MojoExecutionException",
"{",
"// Try to attach agent that will modify Surefire.",
"if",
"(",
"AgentLoader",
".",
"loadEkstaziAgent",
"(",
")",
")",
"{",
"// Prepare initial list of options and set property.",
"System",
".",
"setProperty",
"(",
"AbstractMojoInterceptor",
".",
"ARGLINE_INTERNAL_PROP",
",",
"prepareEkstaziOptions",
"(",
")",
")",
";",
"// Find non affected classes and set property.",
"List",
"<",
"String",
">",
"nonAffectedClasses",
"=",
"computeNonAffectedClasses",
"(",
")",
";",
"System",
".",
"setProperty",
"(",
"AbstractMojoInterceptor",
".",
"EXCLUDES_INTERNAL_PROP",
",",
"Arrays",
".",
"toString",
"(",
"nonAffectedClasses",
".",
"toArray",
"(",
"new",
"String",
"[",
"0",
"]",
")",
")",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"MojoExecutionException",
"(",
"\"Ekstazi cannot attach to the JVM, please specify Ekstazi 'restore' explicitly.\"",
")",
";",
"}",
"}"
] | Implements 'select' that does not require changes to any
existing plugin in configuration file(s). | [
"Implements",
"select",
"that",
"does",
"not",
"require",
"changes",
"to",
"any",
"existing",
"plugin",
"in",
"configuration",
"file",
"(",
"s",
")",
"."
] | train | https://github.com/gliga/ekstazi/blob/5bf4d39a13305afe62f8b8d2d7b4c573d37d42a1/ekstazi-maven-plugin/src/main/java/org/ekstazi/maven/DynamicSelectEkstaziMojo.java#L81-L92 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-firestore/src/main/java/com/google/cloud/firestore/BasePath.java | BasePath.getParent | @Nullable
B getParent() {
"""
Returns the path of the parent element.
@return The new Path or null if we are already at the root.
"""
ImmutableList<String> parts = getSegments();
if (parts.isEmpty()) {
return null;
}
return createPathWithSegments(parts.subList(0, parts.size() - 1));
} | java | @Nullable
B getParent() {
ImmutableList<String> parts = getSegments();
if (parts.isEmpty()) {
return null;
}
return createPathWithSegments(parts.subList(0, parts.size() - 1));
} | [
"@",
"Nullable",
"B",
"getParent",
"(",
")",
"{",
"ImmutableList",
"<",
"String",
">",
"parts",
"=",
"getSegments",
"(",
")",
";",
"if",
"(",
"parts",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"null",
";",
"}",
"return",
"createPathWithSegments",
"(",
"parts",
".",
"subList",
"(",
"0",
",",
"parts",
".",
"size",
"(",
")",
"-",
"1",
")",
")",
";",
"}"
] | Returns the path of the parent element.
@return The new Path or null if we are already at the root. | [
"Returns",
"the",
"path",
"of",
"the",
"parent",
"element",
"."
] | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-firestore/src/main/java/com/google/cloud/firestore/BasePath.java#L42-L49 |
citrusframework/citrus | modules/citrus-core/src/main/java/com/consol/citrus/config/xml/AbstractEndpointParser.java | AbstractEndpointParser.parseEndpointConfiguration | protected void parseEndpointConfiguration(BeanDefinitionBuilder endpointConfigurationBuilder, Element element, ParserContext parserContext) {
"""
Subclasses can override this parsing method in order to provide proper endpoint configuration bean definition properties.
@param endpointConfigurationBuilder
@param element
@param parserContext
@return
"""
BeanDefinitionParserUtils.setPropertyValue(endpointConfigurationBuilder, element.getAttribute("timeout"), "timeout");
} | java | protected void parseEndpointConfiguration(BeanDefinitionBuilder endpointConfigurationBuilder, Element element, ParserContext parserContext) {
BeanDefinitionParserUtils.setPropertyValue(endpointConfigurationBuilder, element.getAttribute("timeout"), "timeout");
} | [
"protected",
"void",
"parseEndpointConfiguration",
"(",
"BeanDefinitionBuilder",
"endpointConfigurationBuilder",
",",
"Element",
"element",
",",
"ParserContext",
"parserContext",
")",
"{",
"BeanDefinitionParserUtils",
".",
"setPropertyValue",
"(",
"endpointConfigurationBuilder",
",",
"element",
".",
"getAttribute",
"(",
"\"timeout\"",
")",
",",
"\"timeout\"",
")",
";",
"}"
] | Subclasses can override this parsing method in order to provide proper endpoint configuration bean definition properties.
@param endpointConfigurationBuilder
@param element
@param parserContext
@return | [
"Subclasses",
"can",
"override",
"this",
"parsing",
"method",
"in",
"order",
"to",
"provide",
"proper",
"endpoint",
"configuration",
"bean",
"definition",
"properties",
"."
] | train | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/config/xml/AbstractEndpointParser.java#L74-L76 |
elki-project/elki | elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/correlation/HiCO.java | HiCO.adjust | private void adjust(double[][] v, double[] vector, int corrDim) {
"""
Inserts the specified vector into the given orthonormal matrix
<code>v</code> at column <code>corrDim</code>. After insertion the matrix
<code>v</code> is orthonormalized and column <code>corrDim</code> of matrix
<code>e_czech</code> is set to the <code>corrDim</code>-th unit vector.
@param v the orthonormal matrix of the eigenvectors
@param vector the vector to be inserted
@param corrDim the column at which the vector should be inserted
"""
double[] sum = new double[v.length];
for(int k = 0; k < corrDim; k++) {
plusTimesEquals(sum, v[k], transposeTimes(vector, v[k]));
}
v[corrDim] = normalizeEquals(minus(vector, sum));
} | java | private void adjust(double[][] v, double[] vector, int corrDim) {
double[] sum = new double[v.length];
for(int k = 0; k < corrDim; k++) {
plusTimesEquals(sum, v[k], transposeTimes(vector, v[k]));
}
v[corrDim] = normalizeEquals(minus(vector, sum));
} | [
"private",
"void",
"adjust",
"(",
"double",
"[",
"]",
"[",
"]",
"v",
",",
"double",
"[",
"]",
"vector",
",",
"int",
"corrDim",
")",
"{",
"double",
"[",
"]",
"sum",
"=",
"new",
"double",
"[",
"v",
".",
"length",
"]",
";",
"for",
"(",
"int",
"k",
"=",
"0",
";",
"k",
"<",
"corrDim",
";",
"k",
"++",
")",
"{",
"plusTimesEquals",
"(",
"sum",
",",
"v",
"[",
"k",
"]",
",",
"transposeTimes",
"(",
"vector",
",",
"v",
"[",
"k",
"]",
")",
")",
";",
"}",
"v",
"[",
"corrDim",
"]",
"=",
"normalizeEquals",
"(",
"minus",
"(",
"vector",
",",
"sum",
")",
")",
";",
"}"
] | Inserts the specified vector into the given orthonormal matrix
<code>v</code> at column <code>corrDim</code>. After insertion the matrix
<code>v</code> is orthonormalized and column <code>corrDim</code> of matrix
<code>e_czech</code> is set to the <code>corrDim</code>-th unit vector.
@param v the orthonormal matrix of the eigenvectors
@param vector the vector to be inserted
@param corrDim the column at which the vector should be inserted | [
"Inserts",
"the",
"specified",
"vector",
"into",
"the",
"given",
"orthonormal",
"matrix",
"<code",
">",
"v<",
"/",
"code",
">",
"at",
"column",
"<code",
">",
"corrDim<",
"/",
"code",
">",
".",
"After",
"insertion",
"the",
"matrix",
"<code",
">",
"v<",
"/",
"code",
">",
"is",
"orthonormalized",
"and",
"column",
"<code",
">",
"corrDim<",
"/",
"code",
">",
"of",
"matrix",
"<code",
">",
"e_czech<",
"/",
"code",
">",
"is",
"set",
"to",
"the",
"<code",
">",
"corrDim<",
"/",
"code",
">",
"-",
"th",
"unit",
"vector",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/correlation/HiCO.java#L364-L370 |
apache/incubator-shardingsphere | sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/SQLExecuteTemplate.java | SQLExecuteTemplate.executeGroup | public <T> List<T> executeGroup(final Collection<ShardingExecuteGroup<? extends StatementExecuteUnit>> sqlExecuteGroups, final SQLExecuteCallback<T> callback) throws SQLException {
"""
Execute group.
@param sqlExecuteGroups SQL execute groups
@param callback SQL execute callback
@param <T> class type of return value
@return execute result
@throws SQLException SQL exception
"""
return executeGroup(sqlExecuteGroups, null, callback);
} | java | public <T> List<T> executeGroup(final Collection<ShardingExecuteGroup<? extends StatementExecuteUnit>> sqlExecuteGroups, final SQLExecuteCallback<T> callback) throws SQLException {
return executeGroup(sqlExecuteGroups, null, callback);
} | [
"public",
"<",
"T",
">",
"List",
"<",
"T",
">",
"executeGroup",
"(",
"final",
"Collection",
"<",
"ShardingExecuteGroup",
"<",
"?",
"extends",
"StatementExecuteUnit",
">",
">",
"sqlExecuteGroups",
",",
"final",
"SQLExecuteCallback",
"<",
"T",
">",
"callback",
")",
"throws",
"SQLException",
"{",
"return",
"executeGroup",
"(",
"sqlExecuteGroups",
",",
"null",
",",
"callback",
")",
";",
"}"
] | Execute group.
@param sqlExecuteGroups SQL execute groups
@param callback SQL execute callback
@param <T> class type of return value
@return execute result
@throws SQLException SQL exception | [
"Execute",
"group",
"."
] | train | https://github.com/apache/incubator-shardingsphere/blob/f88fd29fc345dfb31fdce12e9e96cbfa0fd2402d/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/SQLExecuteTemplate.java#L55-L57 |
sporniket/core | sporniket-core-io/src/main/java/com/sporniket/libre/io/TextLoader.java | TextLoader.append | public StringBuffer append(InputStream source, StringBuffer buffer) throws IOException {
"""
Load a text from the specified file and put it in the provided StringBuffer.
@param source source stream.
@param buffer buffer to load text into.
@return the buffer
@throws IOException if there is a problem to deal with.
"""
Reader _reader = FileTools.createReaderForInputStream(source, getEncoding());
return append(_reader, buffer);
} | java | public StringBuffer append(InputStream source, StringBuffer buffer) throws IOException
{
Reader _reader = FileTools.createReaderForInputStream(source, getEncoding());
return append(_reader, buffer);
} | [
"public",
"StringBuffer",
"append",
"(",
"InputStream",
"source",
",",
"StringBuffer",
"buffer",
")",
"throws",
"IOException",
"{",
"Reader",
"_reader",
"=",
"FileTools",
".",
"createReaderForInputStream",
"(",
"source",
",",
"getEncoding",
"(",
")",
")",
";",
"return",
"append",
"(",
"_reader",
",",
"buffer",
")",
";",
"}"
] | Load a text from the specified file and put it in the provided StringBuffer.
@param source source stream.
@param buffer buffer to load text into.
@return the buffer
@throws IOException if there is a problem to deal with. | [
"Load",
"a",
"text",
"from",
"the",
"specified",
"file",
"and",
"put",
"it",
"in",
"the",
"provided",
"StringBuffer",
"."
] | train | https://github.com/sporniket/core/blob/3480ebd72a07422fcc09971be2607ee25efb2c26/sporniket-core-io/src/main/java/com/sporniket/libre/io/TextLoader.java#L174-L178 |
Mthwate/DatLib | src/main/java/com/mthwate/datlib/HashUtils.java | HashUtils.hashHex | public static String hashHex(byte[] data, String alg) throws NoSuchAlgorithmException {
"""
Hashes data with the specified hashing algorithm. Returns a hexadecimal result.
@since 1.1
@param data the data to hash
@param alg the hashing algorithm to use
@return the hexadecimal hash of the data
@throws NoSuchAlgorithmException the algorithm is not supported by existing providers
"""
return toHex(hash(data, alg));
} | java | public static String hashHex(byte[] data, String alg) throws NoSuchAlgorithmException {
return toHex(hash(data, alg));
} | [
"public",
"static",
"String",
"hashHex",
"(",
"byte",
"[",
"]",
"data",
",",
"String",
"alg",
")",
"throws",
"NoSuchAlgorithmException",
"{",
"return",
"toHex",
"(",
"hash",
"(",
"data",
",",
"alg",
")",
")",
";",
"}"
] | Hashes data with the specified hashing algorithm. Returns a hexadecimal result.
@since 1.1
@param data the data to hash
@param alg the hashing algorithm to use
@return the hexadecimal hash of the data
@throws NoSuchAlgorithmException the algorithm is not supported by existing providers | [
"Hashes",
"data",
"with",
"the",
"specified",
"hashing",
"algorithm",
".",
"Returns",
"a",
"hexadecimal",
"result",
"."
] | train | https://github.com/Mthwate/DatLib/blob/f0b3a9f9cf6fdc773d4f86234ebd95986c9b6077/src/main/java/com/mthwate/datlib/HashUtils.java#L50-L52 |
b3dgs/lionengine | lionengine-game/src/main/java/com/b3dgs/lionengine/game/background/Parallax.java | Parallax.setScreenSize | public final void setScreenSize(int screenWidth, int screenHeight) {
"""
Set the screen size. Used to know the parallax amplitude, and the overall surface to render in order to fill the
screen.
@param screenWidth The screen width.
@param screenHeight The screen height.
"""
this.screenWidth = screenWidth;
this.screenHeight = screenHeight;
final int w = (int) Math.ceil(screenWidth / (surface.getWidth() * 0.6 * factH)) + 1;
amplitude = (int) Math.ceil(w / 2.0) + 1;
} | java | public final void setScreenSize(int screenWidth, int screenHeight)
{
this.screenWidth = screenWidth;
this.screenHeight = screenHeight;
final int w = (int) Math.ceil(screenWidth / (surface.getWidth() * 0.6 * factH)) + 1;
amplitude = (int) Math.ceil(w / 2.0) + 1;
} | [
"public",
"final",
"void",
"setScreenSize",
"(",
"int",
"screenWidth",
",",
"int",
"screenHeight",
")",
"{",
"this",
".",
"screenWidth",
"=",
"screenWidth",
";",
"this",
".",
"screenHeight",
"=",
"screenHeight",
";",
"final",
"int",
"w",
"=",
"(",
"int",
")",
"Math",
".",
"ceil",
"(",
"screenWidth",
"/",
"(",
"surface",
".",
"getWidth",
"(",
")",
"*",
"0.6",
"*",
"factH",
")",
")",
"+",
"1",
";",
"amplitude",
"=",
"(",
"int",
")",
"Math",
".",
"ceil",
"(",
"w",
"/",
"2.0",
")",
"+",
"1",
";",
"}"
] | Set the screen size. Used to know the parallax amplitude, and the overall surface to render in order to fill the
screen.
@param screenWidth The screen width.
@param screenHeight The screen height. | [
"Set",
"the",
"screen",
"size",
".",
"Used",
"to",
"know",
"the",
"parallax",
"amplitude",
"and",
"the",
"overall",
"surface",
"to",
"render",
"in",
"order",
"to",
"fill",
"the",
"screen",
"."
] | train | https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/background/Parallax.java#L110-L116 |
raydac/java-comment-preprocessor | jcp/src/main/java/com/igormaznitsa/jcp/context/PreprocessorContext.java | PreprocessorContext.removeLocalVariable | @Nonnull
public PreprocessorContext removeLocalVariable(@Nonnull final String name) {
"""
Remove a local variable value from the context.
@param name the variable name, must not be null, remember that the name will be normalized and will be entirely in lower case
@return this preprocessor context
@see Value
"""
assertNotNull("Variable name is null", name);
final String normalized = assertNotNull(PreprocessorUtils.normalizeVariableName(name));
if (normalized.isEmpty()) {
throw makeException("Empty variable name", null);
}
if (mapVariableNameToSpecialVarProcessor.containsKey(normalized) || globalVarTable.containsKey(normalized)) {
throw makeException("Attempting to remove either a global variable or a special variable as a local one [" + normalized + ']', null);
}
if (isVerbose()) {
logForVerbose("Removing local variable '" + normalized + "\'");
}
localVarTable.remove(normalized);
return this;
} | java | @Nonnull
public PreprocessorContext removeLocalVariable(@Nonnull final String name) {
assertNotNull("Variable name is null", name);
final String normalized = assertNotNull(PreprocessorUtils.normalizeVariableName(name));
if (normalized.isEmpty()) {
throw makeException("Empty variable name", null);
}
if (mapVariableNameToSpecialVarProcessor.containsKey(normalized) || globalVarTable.containsKey(normalized)) {
throw makeException("Attempting to remove either a global variable or a special variable as a local one [" + normalized + ']', null);
}
if (isVerbose()) {
logForVerbose("Removing local variable '" + normalized + "\'");
}
localVarTable.remove(normalized);
return this;
} | [
"@",
"Nonnull",
"public",
"PreprocessorContext",
"removeLocalVariable",
"(",
"@",
"Nonnull",
"final",
"String",
"name",
")",
"{",
"assertNotNull",
"(",
"\"Variable name is null\"",
",",
"name",
")",
";",
"final",
"String",
"normalized",
"=",
"assertNotNull",
"(",
"PreprocessorUtils",
".",
"normalizeVariableName",
"(",
"name",
")",
")",
";",
"if",
"(",
"normalized",
".",
"isEmpty",
"(",
")",
")",
"{",
"throw",
"makeException",
"(",
"\"Empty variable name\"",
",",
"null",
")",
";",
"}",
"if",
"(",
"mapVariableNameToSpecialVarProcessor",
".",
"containsKey",
"(",
"normalized",
")",
"||",
"globalVarTable",
".",
"containsKey",
"(",
"normalized",
")",
")",
"{",
"throw",
"makeException",
"(",
"\"Attempting to remove either a global variable or a special variable as a local one [\"",
"+",
"normalized",
"+",
"'",
"'",
",",
"null",
")",
";",
"}",
"if",
"(",
"isVerbose",
"(",
")",
")",
"{",
"logForVerbose",
"(",
"\"Removing local variable '\"",
"+",
"normalized",
"+",
"\"\\'\"",
")",
";",
"}",
"localVarTable",
".",
"remove",
"(",
"normalized",
")",
";",
"return",
"this",
";",
"}"
] | Remove a local variable value from the context.
@param name the variable name, must not be null, remember that the name will be normalized and will be entirely in lower case
@return this preprocessor context
@see Value | [
"Remove",
"a",
"local",
"variable",
"value",
"from",
"the",
"context",
"."
] | train | https://github.com/raydac/java-comment-preprocessor/blob/83ac87b575ac084914d77695a8c8673de3b8300c/jcp/src/main/java/com/igormaznitsa/jcp/context/PreprocessorContext.java#L479-L497 |
TheHortonMachine/hortonmachine | hmachine/src/main/java/org/hortonmachine/hmachine/modules/hydrogeomorphology/adige/utils/AdigeUtilities.java | AdigeUtilities.doRouting | public static double doRouting( double discharge, IHillSlope hillslope, int routingType ) {
"""
Method to do the routing of a discharge along the link of {@link IHillSlope}.
@param discharge the discharge to be transported.
@param hillslope the current hillslope.
@param routingType the routing type to use:
<ul>
<li>2 = No Chezi explicitly</li>
<li>3 = Chezi explicitly</li>
<li>4 = Manning equation</li>
</ul>
@return the routing cuencas coefficient.
"""
double linkWidth = hillslope.getLinkWidth(8.66, 0.6, 0.0);
double linkLength = hillslope.getLinkLength();
double linkSlope = hillslope.getLinkSlope();
double chezLawExpon = -1. / 3.;
double chezLawCoeff = 200. / Math.pow(0.000357911, chezLawExpon);
double linkChezy = hillslope.getLinkChezi(chezLawCoeff, chezLawExpon);
double K_Q = 0;
/* ROUTING RATE (K_Q) and CHANNEL VELOCITY (vc) */
// System.out.println(routingtype);
switch( routingType ) {
case 2: /* No Chezi explicitly */
K_Q = 8.796 * Math.pow(discharge, 1 / 3.) * Math.pow(linkWidth, -1 / 3.) * Math.pow(linkLength, -1)
* Math.pow(linkSlope, 2 / 9.); // units
// 1/s*/
break;
case 3: /* Chezi explicit */
// System.out.println("Chezy");
K_Q = 3 / 2. * Math.pow(discharge, 1. / 3.) * Math.pow(linkChezy, 2. / 3.) * Math.pow(linkWidth, -1. / 3.)
* Math.pow(linkLength, -1) * Math.pow(linkSlope, 1. / 3.); // units 1/s
break;
case 4: /* Mannings equation */
double flowdepth = (1. / 3.) * Math.pow(discharge, 1. / 3.); // depth
// m,
// input m^3/s;
// general
// observed
// relation for
// gc from
// molnar and
// ramirez 1998
double hydrad = (flowdepth * linkWidth) / (2.f * flowdepth + linkWidth); // m
double mannings_n = 1; // 0.030f; // mannings n suggested by Jason via his
// observations at
// Whitewater for high flows. Low flows will have higher
// n ... up to 2x more.
K_Q = (Math.pow(hydrad, 2. / 3.) * Math.pow(linkSlope, 1 / 2.) / mannings_n) // m/s
// ;
// this
// term
// is v
// from
// mannings
// eqn
* Math.pow(linkLength, -1); // 1/s
break;
}
return K_Q;
} | java | public static double doRouting( double discharge, IHillSlope hillslope, int routingType ) {
double linkWidth = hillslope.getLinkWidth(8.66, 0.6, 0.0);
double linkLength = hillslope.getLinkLength();
double linkSlope = hillslope.getLinkSlope();
double chezLawExpon = -1. / 3.;
double chezLawCoeff = 200. / Math.pow(0.000357911, chezLawExpon);
double linkChezy = hillslope.getLinkChezi(chezLawCoeff, chezLawExpon);
double K_Q = 0;
/* ROUTING RATE (K_Q) and CHANNEL VELOCITY (vc) */
// System.out.println(routingtype);
switch( routingType ) {
case 2: /* No Chezi explicitly */
K_Q = 8.796 * Math.pow(discharge, 1 / 3.) * Math.pow(linkWidth, -1 / 3.) * Math.pow(linkLength, -1)
* Math.pow(linkSlope, 2 / 9.); // units
// 1/s*/
break;
case 3: /* Chezi explicit */
// System.out.println("Chezy");
K_Q = 3 / 2. * Math.pow(discharge, 1. / 3.) * Math.pow(linkChezy, 2. / 3.) * Math.pow(linkWidth, -1. / 3.)
* Math.pow(linkLength, -1) * Math.pow(linkSlope, 1. / 3.); // units 1/s
break;
case 4: /* Mannings equation */
double flowdepth = (1. / 3.) * Math.pow(discharge, 1. / 3.); // depth
// m,
// input m^3/s;
// general
// observed
// relation for
// gc from
// molnar and
// ramirez 1998
double hydrad = (flowdepth * linkWidth) / (2.f * flowdepth + linkWidth); // m
double mannings_n = 1; // 0.030f; // mannings n suggested by Jason via his
// observations at
// Whitewater for high flows. Low flows will have higher
// n ... up to 2x more.
K_Q = (Math.pow(hydrad, 2. / 3.) * Math.pow(linkSlope, 1 / 2.) / mannings_n) // m/s
// ;
// this
// term
// is v
// from
// mannings
// eqn
* Math.pow(linkLength, -1); // 1/s
break;
}
return K_Q;
} | [
"public",
"static",
"double",
"doRouting",
"(",
"double",
"discharge",
",",
"IHillSlope",
"hillslope",
",",
"int",
"routingType",
")",
"{",
"double",
"linkWidth",
"=",
"hillslope",
".",
"getLinkWidth",
"(",
"8.66",
",",
"0.6",
",",
"0.0",
")",
";",
"double",
"linkLength",
"=",
"hillslope",
".",
"getLinkLength",
"(",
")",
";",
"double",
"linkSlope",
"=",
"hillslope",
".",
"getLinkSlope",
"(",
")",
";",
"double",
"chezLawExpon",
"=",
"-",
"1.",
"/",
"3.",
";",
"double",
"chezLawCoeff",
"=",
"200.",
"/",
"Math",
".",
"pow",
"(",
"0.000357911",
",",
"chezLawExpon",
")",
";",
"double",
"linkChezy",
"=",
"hillslope",
".",
"getLinkChezi",
"(",
"chezLawCoeff",
",",
"chezLawExpon",
")",
";",
"double",
"K_Q",
"=",
"0",
";",
"/* ROUTING RATE (K_Q) and CHANNEL VELOCITY (vc) */",
"// System.out.println(routingtype);",
"switch",
"(",
"routingType",
")",
"{",
"case",
"2",
":",
"/* No Chezi explicitly */",
"K_Q",
"=",
"8.796",
"*",
"Math",
".",
"pow",
"(",
"discharge",
",",
"1",
"/",
"3.",
")",
"*",
"Math",
".",
"pow",
"(",
"linkWidth",
",",
"-",
"1",
"/",
"3.",
")",
"*",
"Math",
".",
"pow",
"(",
"linkLength",
",",
"-",
"1",
")",
"*",
"Math",
".",
"pow",
"(",
"linkSlope",
",",
"2",
"/",
"9.",
")",
";",
"// units",
"// 1/s*/",
"break",
";",
"case",
"3",
":",
"/* Chezi explicit */",
"// System.out.println(\"Chezy\");",
"K_Q",
"=",
"3",
"/",
"2.",
"*",
"Math",
".",
"pow",
"(",
"discharge",
",",
"1.",
"/",
"3.",
")",
"*",
"Math",
".",
"pow",
"(",
"linkChezy",
",",
"2.",
"/",
"3.",
")",
"*",
"Math",
".",
"pow",
"(",
"linkWidth",
",",
"-",
"1.",
"/",
"3.",
")",
"*",
"Math",
".",
"pow",
"(",
"linkLength",
",",
"-",
"1",
")",
"*",
"Math",
".",
"pow",
"(",
"linkSlope",
",",
"1.",
"/",
"3.",
")",
";",
"// units 1/s",
"break",
";",
"case",
"4",
":",
"/* Mannings equation */",
"double",
"flowdepth",
"=",
"(",
"1.",
"/",
"3.",
")",
"*",
"Math",
".",
"pow",
"(",
"discharge",
",",
"1.",
"/",
"3.",
")",
";",
"// depth",
"// m,",
"// input m^3/s;",
"// general",
"// observed",
"// relation for",
"// gc from",
"// molnar and",
"// ramirez 1998",
"double",
"hydrad",
"=",
"(",
"flowdepth",
"*",
"linkWidth",
")",
"/",
"(",
"2.f",
"*",
"flowdepth",
"+",
"linkWidth",
")",
";",
"// m",
"double",
"mannings_n",
"=",
"1",
";",
"// 0.030f; // mannings n suggested by Jason via his",
"// observations at",
"// Whitewater for high flows. Low flows will have higher",
"// n ... up to 2x more.",
"K_Q",
"=",
"(",
"Math",
".",
"pow",
"(",
"hydrad",
",",
"2.",
"/",
"3.",
")",
"*",
"Math",
".",
"pow",
"(",
"linkSlope",
",",
"1",
"/",
"2.",
")",
"/",
"mannings_n",
")",
"// m/s",
"// ;",
"// this",
"// term",
"// is v",
"// from",
"// mannings",
"// eqn",
"*",
"Math",
".",
"pow",
"(",
"linkLength",
",",
"-",
"1",
")",
";",
"// 1/s",
"break",
";",
"}",
"return",
"K_Q",
";",
"}"
] | Method to do the routing of a discharge along the link of {@link IHillSlope}.
@param discharge the discharge to be transported.
@param hillslope the current hillslope.
@param routingType the routing type to use:
<ul>
<li>2 = No Chezi explicitly</li>
<li>3 = Chezi explicitly</li>
<li>4 = Manning equation</li>
</ul>
@return the routing cuencas coefficient. | [
"Method",
"to",
"do",
"the",
"routing",
"of",
"a",
"discharge",
"along",
"the",
"link",
"of",
"{",
"@link",
"IHillSlope",
"}",
"."
] | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/hmachine/src/main/java/org/hortonmachine/hmachine/modules/hydrogeomorphology/adige/utils/AdigeUtilities.java#L187-L241 |
johncarl81/transfuse | transfuse-support/src/main/java/org/androidtransfuse/util/Contract.java | Contract.atSize | public static void atSize(final Collection<?> collection, final int size, final String collectionName) {
"""
Checks that a collection is of a given size
@param collection the collection to check
@param size the size of the collection
@param collectionName the name of the collection
@throws IllegalArgumentException if collection is null or if the collection size is not as expected
"""
notNull(collection, collectionName);
notNegative(size, "size");
if (collection.size() != size) {
throw new IllegalArgumentException("expecting " + maskNullArgument(collectionName) + " to be of size " + size + ".");
}
} | java | public static void atSize(final Collection<?> collection, final int size, final String collectionName) {
notNull(collection, collectionName);
notNegative(size, "size");
if (collection.size() != size) {
throw new IllegalArgumentException("expecting " + maskNullArgument(collectionName) + " to be of size " + size + ".");
}
} | [
"public",
"static",
"void",
"atSize",
"(",
"final",
"Collection",
"<",
"?",
">",
"collection",
",",
"final",
"int",
"size",
",",
"final",
"String",
"collectionName",
")",
"{",
"notNull",
"(",
"collection",
",",
"collectionName",
")",
";",
"notNegative",
"(",
"size",
",",
"\"size\"",
")",
";",
"if",
"(",
"collection",
".",
"size",
"(",
")",
"!=",
"size",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"expecting \"",
"+",
"maskNullArgument",
"(",
"collectionName",
")",
"+",
"\" to be of size \"",
"+",
"size",
"+",
"\".\"",
")",
";",
"}",
"}"
] | Checks that a collection is of a given size
@param collection the collection to check
@param size the size of the collection
@param collectionName the name of the collection
@throws IllegalArgumentException if collection is null or if the collection size is not as expected | [
"Checks",
"that",
"a",
"collection",
"is",
"of",
"a",
"given",
"size"
] | train | https://github.com/johncarl81/transfuse/blob/a5f837504797a6c4f8628f7e1dde09b8e6368c8b/transfuse-support/src/main/java/org/androidtransfuse/util/Contract.java#L67-L74 |
Azure/azure-sdk-for-java | sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/DatabasesInner.java | DatabasesInner.createImportOperationAsync | public Observable<ImportExportResponseInner> createImportOperationAsync(String resourceGroupName, String serverName, String databaseName, ImportExtensionRequest parameters) {
"""
Creates an import operation that imports a bacpac into an existing database. The existing database must be empty.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@param databaseName The name of the database to import into
@param parameters The required parameters for importing a Bacpac into a database.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request
"""
return createImportOperationWithServiceResponseAsync(resourceGroupName, serverName, databaseName, parameters).map(new Func1<ServiceResponse<ImportExportResponseInner>, ImportExportResponseInner>() {
@Override
public ImportExportResponseInner call(ServiceResponse<ImportExportResponseInner> response) {
return response.body();
}
});
} | java | public Observable<ImportExportResponseInner> createImportOperationAsync(String resourceGroupName, String serverName, String databaseName, ImportExtensionRequest parameters) {
return createImportOperationWithServiceResponseAsync(resourceGroupName, serverName, databaseName, parameters).map(new Func1<ServiceResponse<ImportExportResponseInner>, ImportExportResponseInner>() {
@Override
public ImportExportResponseInner call(ServiceResponse<ImportExportResponseInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"ImportExportResponseInner",
">",
"createImportOperationAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"serverName",
",",
"String",
"databaseName",
",",
"ImportExtensionRequest",
"parameters",
")",
"{",
"return",
"createImportOperationWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"serverName",
",",
"databaseName",
",",
"parameters",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"ImportExportResponseInner",
">",
",",
"ImportExportResponseInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"ImportExportResponseInner",
"call",
"(",
"ServiceResponse",
"<",
"ImportExportResponseInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Creates an import operation that imports a bacpac into an existing database. The existing database must be empty.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@param databaseName The name of the database to import into
@param parameters The required parameters for importing a Bacpac into a database.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request | [
"Creates",
"an",
"import",
"operation",
"that",
"imports",
"a",
"bacpac",
"into",
"an",
"existing",
"database",
".",
"The",
"existing",
"database",
"must",
"be",
"empty",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/DatabasesInner.java#L1939-L1946 |
hazelcast/hazelcast | hazelcast/src/main/java/com/hazelcast/internal/partition/impl/AbstractPartitionPrimaryReplicaAntiEntropyTask.java | AbstractPartitionPrimaryReplicaAntiEntropyTask.retainAndGetNamespaces | final Collection<ServiceNamespace> retainAndGetNamespaces() {
"""
works only on primary. backups are retained in PartitionBackupReplicaAntiEntropyTask
"""
PartitionReplicationEvent event = new PartitionReplicationEvent(partitionId, 0);
Collection<FragmentedMigrationAwareService> services = nodeEngine.getServices(FragmentedMigrationAwareService.class);
Set<ServiceNamespace> namespaces = new HashSet<>();
for (FragmentedMigrationAwareService service : services) {
Collection<ServiceNamespace> serviceNamespaces = service.getAllServiceNamespaces(event);
if (serviceNamespaces != null) {
namespaces.addAll(serviceNamespaces);
}
}
namespaces.add(NonFragmentedServiceNamespace.INSTANCE);
PartitionReplicaManager replicaManager = partitionService.getReplicaManager();
replicaManager.retainNamespaces(partitionId, namespaces);
return replicaManager.getNamespaces(partitionId);
} | java | final Collection<ServiceNamespace> retainAndGetNamespaces() {
PartitionReplicationEvent event = new PartitionReplicationEvent(partitionId, 0);
Collection<FragmentedMigrationAwareService> services = nodeEngine.getServices(FragmentedMigrationAwareService.class);
Set<ServiceNamespace> namespaces = new HashSet<>();
for (FragmentedMigrationAwareService service : services) {
Collection<ServiceNamespace> serviceNamespaces = service.getAllServiceNamespaces(event);
if (serviceNamespaces != null) {
namespaces.addAll(serviceNamespaces);
}
}
namespaces.add(NonFragmentedServiceNamespace.INSTANCE);
PartitionReplicaManager replicaManager = partitionService.getReplicaManager();
replicaManager.retainNamespaces(partitionId, namespaces);
return replicaManager.getNamespaces(partitionId);
} | [
"final",
"Collection",
"<",
"ServiceNamespace",
">",
"retainAndGetNamespaces",
"(",
")",
"{",
"PartitionReplicationEvent",
"event",
"=",
"new",
"PartitionReplicationEvent",
"(",
"partitionId",
",",
"0",
")",
";",
"Collection",
"<",
"FragmentedMigrationAwareService",
">",
"services",
"=",
"nodeEngine",
".",
"getServices",
"(",
"FragmentedMigrationAwareService",
".",
"class",
")",
";",
"Set",
"<",
"ServiceNamespace",
">",
"namespaces",
"=",
"new",
"HashSet",
"<>",
"(",
")",
";",
"for",
"(",
"FragmentedMigrationAwareService",
"service",
":",
"services",
")",
"{",
"Collection",
"<",
"ServiceNamespace",
">",
"serviceNamespaces",
"=",
"service",
".",
"getAllServiceNamespaces",
"(",
"event",
")",
";",
"if",
"(",
"serviceNamespaces",
"!=",
"null",
")",
"{",
"namespaces",
".",
"addAll",
"(",
"serviceNamespaces",
")",
";",
"}",
"}",
"namespaces",
".",
"add",
"(",
"NonFragmentedServiceNamespace",
".",
"INSTANCE",
")",
";",
"PartitionReplicaManager",
"replicaManager",
"=",
"partitionService",
".",
"getReplicaManager",
"(",
")",
";",
"replicaManager",
".",
"retainNamespaces",
"(",
"partitionId",
",",
"namespaces",
")",
";",
"return",
"replicaManager",
".",
"getNamespaces",
"(",
"partitionId",
")",
";",
"}"
] | works only on primary. backups are retained in PartitionBackupReplicaAntiEntropyTask | [
"works",
"only",
"on",
"primary",
".",
"backups",
"are",
"retained",
"in",
"PartitionBackupReplicaAntiEntropyTask"
] | train | https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/internal/partition/impl/AbstractPartitionPrimaryReplicaAntiEntropyTask.java#L66-L82 |
h2oai/h2o-3 | h2o-core/src/main/java/water/util/ReflectionUtils.java | ReflectionUtils.findNamedField | public static Field findNamedField(Object o, String field_name) {
"""
Return the Field for the specified name.
<p>
Java reflection will either give you all the public fields all the way up the class hierarchy (getField()),
or will give you all the private/protected/public only in the single class (getDeclaredField()).
This method uses the latter but walks up the class hierarchy.
"""
Class clz = o.getClass();
Field f = null;
do {
try {
f = clz.getDeclaredField(field_name);
f.setAccessible(true);
return f;
}
catch (NoSuchFieldException e) {
// fall through and try our parent
}
clz = clz.getSuperclass();
} while (clz != Object.class);
return null;
} | java | public static Field findNamedField(Object o, String field_name) {
Class clz = o.getClass();
Field f = null;
do {
try {
f = clz.getDeclaredField(field_name);
f.setAccessible(true);
return f;
}
catch (NoSuchFieldException e) {
// fall through and try our parent
}
clz = clz.getSuperclass();
} while (clz != Object.class);
return null;
} | [
"public",
"static",
"Field",
"findNamedField",
"(",
"Object",
"o",
",",
"String",
"field_name",
")",
"{",
"Class",
"clz",
"=",
"o",
".",
"getClass",
"(",
")",
";",
"Field",
"f",
"=",
"null",
";",
"do",
"{",
"try",
"{",
"f",
"=",
"clz",
".",
"getDeclaredField",
"(",
"field_name",
")",
";",
"f",
".",
"setAccessible",
"(",
"true",
")",
";",
"return",
"f",
";",
"}",
"catch",
"(",
"NoSuchFieldException",
"e",
")",
"{",
"// fall through and try our parent",
"}",
"clz",
"=",
"clz",
".",
"getSuperclass",
"(",
")",
";",
"}",
"while",
"(",
"clz",
"!=",
"Object",
".",
"class",
")",
";",
"return",
"null",
";",
"}"
] | Return the Field for the specified name.
<p>
Java reflection will either give you all the public fields all the way up the class hierarchy (getField()),
or will give you all the private/protected/public only in the single class (getDeclaredField()).
This method uses the latter but walks up the class hierarchy. | [
"Return",
"the",
"Field",
"for",
"the",
"specified",
"name",
".",
"<p",
">",
"Java",
"reflection",
"will",
"either",
"give",
"you",
"all",
"the",
"public",
"fields",
"all",
"the",
"way",
"up",
"the",
"class",
"hierarchy",
"(",
"getField",
"()",
")",
"or",
"will",
"give",
"you",
"all",
"the",
"private",
"/",
"protected",
"/",
"public",
"only",
"in",
"the",
"single",
"class",
"(",
"getDeclaredField",
"()",
")",
".",
"This",
"method",
"uses",
"the",
"latter",
"but",
"walks",
"up",
"the",
"class",
"hierarchy",
"."
] | train | https://github.com/h2oai/h2o-3/blob/845eb49dfeaadf638b6e2f779d82fac996391fad/h2o-core/src/main/java/water/util/ReflectionUtils.java#L115-L131 |
datacleaner/DataCleaner | desktop/ui/src/main/java/org/datacleaner/panels/DCSplashPanel.java | DCSplashPanel.wrapContent | protected JScrollPane wrapContent(final JComponent panel) {
"""
Wraps a content panel in a scroll pane and applies a maximum width to the
content to keep it nicely in place on the screen.
@param panel
@return
"""
panel.setMaximumSize(new Dimension(WIDTH_CONTENT, Integer.MAX_VALUE));
panel.setAlignmentX(Component.LEFT_ALIGNMENT);
final DCPanel wrappingPanel = new DCPanel();
final BoxLayout layout = new BoxLayout(wrappingPanel, BoxLayout.PAGE_AXIS);
wrappingPanel.setLayout(layout);
wrappingPanel.add(panel);
wrappingPanel.setBorder(new EmptyBorder(0, MARGIN_LEFT, 0, 0));
return WidgetUtils.scrolleable(wrappingPanel);
} | java | protected JScrollPane wrapContent(final JComponent panel) {
panel.setMaximumSize(new Dimension(WIDTH_CONTENT, Integer.MAX_VALUE));
panel.setAlignmentX(Component.LEFT_ALIGNMENT);
final DCPanel wrappingPanel = new DCPanel();
final BoxLayout layout = new BoxLayout(wrappingPanel, BoxLayout.PAGE_AXIS);
wrappingPanel.setLayout(layout);
wrappingPanel.add(panel);
wrappingPanel.setBorder(new EmptyBorder(0, MARGIN_LEFT, 0, 0));
return WidgetUtils.scrolleable(wrappingPanel);
} | [
"protected",
"JScrollPane",
"wrapContent",
"(",
"final",
"JComponent",
"panel",
")",
"{",
"panel",
".",
"setMaximumSize",
"(",
"new",
"Dimension",
"(",
"WIDTH_CONTENT",
",",
"Integer",
".",
"MAX_VALUE",
")",
")",
";",
"panel",
".",
"setAlignmentX",
"(",
"Component",
".",
"LEFT_ALIGNMENT",
")",
";",
"final",
"DCPanel",
"wrappingPanel",
"=",
"new",
"DCPanel",
"(",
")",
";",
"final",
"BoxLayout",
"layout",
"=",
"new",
"BoxLayout",
"(",
"wrappingPanel",
",",
"BoxLayout",
".",
"PAGE_AXIS",
")",
";",
"wrappingPanel",
".",
"setLayout",
"(",
"layout",
")",
";",
"wrappingPanel",
".",
"add",
"(",
"panel",
")",
";",
"wrappingPanel",
".",
"setBorder",
"(",
"new",
"EmptyBorder",
"(",
"0",
",",
"MARGIN_LEFT",
",",
"0",
",",
"0",
")",
")",
";",
"return",
"WidgetUtils",
".",
"scrolleable",
"(",
"wrappingPanel",
")",
";",
"}"
] | Wraps a content panel in a scroll pane and applies a maximum width to the
content to keep it nicely in place on the screen.
@param panel
@return | [
"Wraps",
"a",
"content",
"panel",
"in",
"a",
"scroll",
"pane",
"and",
"applies",
"a",
"maximum",
"width",
"to",
"the",
"content",
"to",
"keep",
"it",
"nicely",
"in",
"place",
"on",
"the",
"screen",
"."
] | train | https://github.com/datacleaner/DataCleaner/blob/9aa01fdac3560cef51c55df3cb2ac5c690b57639/desktop/ui/src/main/java/org/datacleaner/panels/DCSplashPanel.java#L147-L158 |
openbase/jul | visual/javafx/src/main/java/org/openbase/jul/visual/javafx/geometry/svg/SVGIcon.java | SVGIcon.setBackgroundIconColorAnimated | public void setBackgroundIconColorAnimated(final Color color, final int cycleCount) {
"""
Allows to set a new color to the backgroundIcon icon and setAnimation its change (by a FadeTransition).
@param color the color for the backgroundIcon icon to be setfeature-rights-and-access-management
@param cycleCount the number of times the animation should be played (use Animation.INDEFINITE for endless)
"""
if (backgroundIcon == null) {
LOGGER.warn("Background modification skipped because background icon not set!");
return;
}
stopBackgroundIconColorFadeAnimation();
backgroundFadeIcon.setFill(color);
backgroundIconColorFadeAnimation = Animations.createFadeTransition(backgroundFadeIcon, JFXConstants.TRANSPARENCY_FULLY, JFXConstants.TRANSPARENCY_NONE, cycleCount, JFXConstants.ANIMATION_DURATION_FADE_DEFAULT);
backgroundIconColorFadeAnimation.setOnFinished(event -> {
backgroundFadeIcon.setFill(color);
backgroundFadeIcon.setOpacity(JFXConstants.TRANSPARENCY_FULLY);
});
backgroundIconColorFadeAnimation.play();
} | java | public void setBackgroundIconColorAnimated(final Color color, final int cycleCount) {
if (backgroundIcon == null) {
LOGGER.warn("Background modification skipped because background icon not set!");
return;
}
stopBackgroundIconColorFadeAnimation();
backgroundFadeIcon.setFill(color);
backgroundIconColorFadeAnimation = Animations.createFadeTransition(backgroundFadeIcon, JFXConstants.TRANSPARENCY_FULLY, JFXConstants.TRANSPARENCY_NONE, cycleCount, JFXConstants.ANIMATION_DURATION_FADE_DEFAULT);
backgroundIconColorFadeAnimation.setOnFinished(event -> {
backgroundFadeIcon.setFill(color);
backgroundFadeIcon.setOpacity(JFXConstants.TRANSPARENCY_FULLY);
});
backgroundIconColorFadeAnimation.play();
} | [
"public",
"void",
"setBackgroundIconColorAnimated",
"(",
"final",
"Color",
"color",
",",
"final",
"int",
"cycleCount",
")",
"{",
"if",
"(",
"backgroundIcon",
"==",
"null",
")",
"{",
"LOGGER",
".",
"warn",
"(",
"\"Background modification skipped because background icon not set!\"",
")",
";",
"return",
";",
"}",
"stopBackgroundIconColorFadeAnimation",
"(",
")",
";",
"backgroundFadeIcon",
".",
"setFill",
"(",
"color",
")",
";",
"backgroundIconColorFadeAnimation",
"=",
"Animations",
".",
"createFadeTransition",
"(",
"backgroundFadeIcon",
",",
"JFXConstants",
".",
"TRANSPARENCY_FULLY",
",",
"JFXConstants",
".",
"TRANSPARENCY_NONE",
",",
"cycleCount",
",",
"JFXConstants",
".",
"ANIMATION_DURATION_FADE_DEFAULT",
")",
";",
"backgroundIconColorFadeAnimation",
".",
"setOnFinished",
"(",
"event",
"->",
"{",
"backgroundFadeIcon",
".",
"setFill",
"(",
"color",
")",
";",
"backgroundFadeIcon",
".",
"setOpacity",
"(",
"JFXConstants",
".",
"TRANSPARENCY_FULLY",
")",
";",
"}",
")",
";",
"backgroundIconColorFadeAnimation",
".",
"play",
"(",
")",
";",
"}"
] | Allows to set a new color to the backgroundIcon icon and setAnimation its change (by a FadeTransition).
@param color the color for the backgroundIcon icon to be setfeature-rights-and-access-management
@param cycleCount the number of times the animation should be played (use Animation.INDEFINITE for endless) | [
"Allows",
"to",
"set",
"a",
"new",
"color",
"to",
"the",
"backgroundIcon",
"icon",
"and",
"setAnimation",
"its",
"change",
"(",
"by",
"a",
"FadeTransition",
")",
"."
] | train | https://github.com/openbase/jul/blob/662e98c3a853085e475be54c3be3deb72193c72d/visual/javafx/src/main/java/org/openbase/jul/visual/javafx/geometry/svg/SVGIcon.java#L334-L347 |
jpush/jmessage-api-java-client | src/main/java/cn/jmessage/api/chatroom/ChatRoomClient.java | ChatRoomClient.addChatRoomMember | public ResponseWrapper addChatRoomMember(long roomId, Members members)
throws APIConnectionException, APIRequestException {
"""
Add members to chat room
@param roomId chat room id
@param members {@link Members}
@return No content
@throws APIConnectionException connect exception
@throws APIRequestException request exception
"""
Preconditions.checkArgument(roomId > 0, "room id is invalid");
Preconditions.checkArgument(members != null, "members should not be empty");
return _httpClient.sendPut(_baseUrl + mChatRoomPath + "/" + roomId + "/members", members.toString());
} | java | public ResponseWrapper addChatRoomMember(long roomId, Members members)
throws APIConnectionException, APIRequestException {
Preconditions.checkArgument(roomId > 0, "room id is invalid");
Preconditions.checkArgument(members != null, "members should not be empty");
return _httpClient.sendPut(_baseUrl + mChatRoomPath + "/" + roomId + "/members", members.toString());
} | [
"public",
"ResponseWrapper",
"addChatRoomMember",
"(",
"long",
"roomId",
",",
"Members",
"members",
")",
"throws",
"APIConnectionException",
",",
"APIRequestException",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"roomId",
">",
"0",
",",
"\"room id is invalid\"",
")",
";",
"Preconditions",
".",
"checkArgument",
"(",
"members",
"!=",
"null",
",",
"\"members should not be empty\"",
")",
";",
"return",
"_httpClient",
".",
"sendPut",
"(",
"_baseUrl",
"+",
"mChatRoomPath",
"+",
"\"/\"",
"+",
"roomId",
"+",
"\"/members\"",
",",
"members",
".",
"toString",
"(",
")",
")",
";",
"}"
] | Add members to chat room
@param roomId chat room id
@param members {@link Members}
@return No content
@throws APIConnectionException connect exception
@throws APIRequestException request exception | [
"Add",
"members",
"to",
"chat",
"room"
] | train | https://github.com/jpush/jmessage-api-java-client/blob/767f5fb15e9fe5a546c00f6e68b64f6dd53c617c/src/main/java/cn/jmessage/api/chatroom/ChatRoomClient.java#L210-L215 |
alkacon/opencms-core | src/org/opencms/search/CmsSearchIndex.java | CmsSearchIndex.appendDateCreatedFilter | protected BooleanQuery.Builder appendDateCreatedFilter(BooleanQuery.Builder filter, long startTime, long endTime) {
"""
Appends a date of creation filter to the given filter clause that matches the
given time range.<p>
If the start time is equal to {@link Long#MIN_VALUE} and the end time is equal to {@link Long#MAX_VALUE}
than the original filter is left unchanged.<p>
The original filter parameter is extended and also provided as return value.<p>
@param filter the filter to extend
@param startTime start time of the range to search in
@param endTime end time of the range to search in
@return the extended filter clause
"""
// create special optimized sub-filter for the date last modified search
Query dateFilter = createDateRangeFilter(CmsSearchField.FIELD_DATE_CREATED_LOOKUP, startTime, endTime);
if (dateFilter != null) {
// extend main filter with the created date filter
filter.add(new BooleanClause(dateFilter, BooleanClause.Occur.MUST));
}
return filter;
} | java | protected BooleanQuery.Builder appendDateCreatedFilter(BooleanQuery.Builder filter, long startTime, long endTime) {
// create special optimized sub-filter for the date last modified search
Query dateFilter = createDateRangeFilter(CmsSearchField.FIELD_DATE_CREATED_LOOKUP, startTime, endTime);
if (dateFilter != null) {
// extend main filter with the created date filter
filter.add(new BooleanClause(dateFilter, BooleanClause.Occur.MUST));
}
return filter;
} | [
"protected",
"BooleanQuery",
".",
"Builder",
"appendDateCreatedFilter",
"(",
"BooleanQuery",
".",
"Builder",
"filter",
",",
"long",
"startTime",
",",
"long",
"endTime",
")",
"{",
"// create special optimized sub-filter for the date last modified search",
"Query",
"dateFilter",
"=",
"createDateRangeFilter",
"(",
"CmsSearchField",
".",
"FIELD_DATE_CREATED_LOOKUP",
",",
"startTime",
",",
"endTime",
")",
";",
"if",
"(",
"dateFilter",
"!=",
"null",
")",
"{",
"// extend main filter with the created date filter",
"filter",
".",
"add",
"(",
"new",
"BooleanClause",
"(",
"dateFilter",
",",
"BooleanClause",
".",
"Occur",
".",
"MUST",
")",
")",
";",
"}",
"return",
"filter",
";",
"}"
] | Appends a date of creation filter to the given filter clause that matches the
given time range.<p>
If the start time is equal to {@link Long#MIN_VALUE} and the end time is equal to {@link Long#MAX_VALUE}
than the original filter is left unchanged.<p>
The original filter parameter is extended and also provided as return value.<p>
@param filter the filter to extend
@param startTime start time of the range to search in
@param endTime end time of the range to search in
@return the extended filter clause | [
"Appends",
"a",
"date",
"of",
"creation",
"filter",
"to",
"the",
"given",
"filter",
"clause",
"that",
"matches",
"the",
"given",
"time",
"range",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/search/CmsSearchIndex.java#L1310-L1320 |
apache/flink | flink-runtime/src/main/java/org/apache/flink/runtime/state/KeyGroupRangeAssignment.java | KeyGroupRangeAssignment.assignKeyToParallelOperator | public static int assignKeyToParallelOperator(Object key, int maxParallelism, int parallelism) {
"""
Assigns the given key to a parallel operator index.
@param key the key to assign
@param maxParallelism the maximum supported parallelism, aka the number of key-groups.
@param parallelism the current parallelism of the operator
@return the index of the parallel operator to which the given key should be routed.
"""
return computeOperatorIndexForKeyGroup(maxParallelism, parallelism, assignToKeyGroup(key, maxParallelism));
} | java | public static int assignKeyToParallelOperator(Object key, int maxParallelism, int parallelism) {
return computeOperatorIndexForKeyGroup(maxParallelism, parallelism, assignToKeyGroup(key, maxParallelism));
} | [
"public",
"static",
"int",
"assignKeyToParallelOperator",
"(",
"Object",
"key",
",",
"int",
"maxParallelism",
",",
"int",
"parallelism",
")",
"{",
"return",
"computeOperatorIndexForKeyGroup",
"(",
"maxParallelism",
",",
"parallelism",
",",
"assignToKeyGroup",
"(",
"key",
",",
"maxParallelism",
")",
")",
";",
"}"
] | Assigns the given key to a parallel operator index.
@param key the key to assign
@param maxParallelism the maximum supported parallelism, aka the number of key-groups.
@param parallelism the current parallelism of the operator
@return the index of the parallel operator to which the given key should be routed. | [
"Assigns",
"the",
"given",
"key",
"to",
"a",
"parallel",
"operator",
"index",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/state/KeyGroupRangeAssignment.java#L47-L49 |
TheHortonMachine/hortonmachine | gears/src/main/java/org/hortonmachine/gears/utils/style/sld/RequestUtils.java | RequestUtils.getBufferedXMLReader | public static BufferedReader getBufferedXMLReader(InputStream stream, int xmlLookahead)
throws IOException {
"""
Wraps an xml input xstream in a buffered reader specifying a lookahead that can be used to
preparse some of the xml document, resetting it back to its original state for actual
parsing.
@param stream The original xml stream.
@param xmlLookahead The number of bytes to support for parse. If more than this number of
bytes are preparsed the stream can not be properly reset.
@return The buffered reader.
"""
// create a buffer so we can reset the input stream
BufferedInputStream input = new BufferedInputStream(stream);
input.mark(xmlLookahead);
// create object to hold encoding info
EncodingInfo encoding = new EncodingInfo();
// call this method to set the encoding info
XmlCharsetDetector.getCharsetAwareReader(input, encoding);
// call this method to create the reader
Reader reader = XmlCharsetDetector.createReader(input, encoding);
// rest the input
input.reset();
return getBufferedXMLReader(reader, xmlLookahead);
} | java | public static BufferedReader getBufferedXMLReader(InputStream stream, int xmlLookahead)
throws IOException {
// create a buffer so we can reset the input stream
BufferedInputStream input = new BufferedInputStream(stream);
input.mark(xmlLookahead);
// create object to hold encoding info
EncodingInfo encoding = new EncodingInfo();
// call this method to set the encoding info
XmlCharsetDetector.getCharsetAwareReader(input, encoding);
// call this method to create the reader
Reader reader = XmlCharsetDetector.createReader(input, encoding);
// rest the input
input.reset();
return getBufferedXMLReader(reader, xmlLookahead);
} | [
"public",
"static",
"BufferedReader",
"getBufferedXMLReader",
"(",
"InputStream",
"stream",
",",
"int",
"xmlLookahead",
")",
"throws",
"IOException",
"{",
"// create a buffer so we can reset the input stream",
"BufferedInputStream",
"input",
"=",
"new",
"BufferedInputStream",
"(",
"stream",
")",
";",
"input",
".",
"mark",
"(",
"xmlLookahead",
")",
";",
"// create object to hold encoding info",
"EncodingInfo",
"encoding",
"=",
"new",
"EncodingInfo",
"(",
")",
";",
"// call this method to set the encoding info",
"XmlCharsetDetector",
".",
"getCharsetAwareReader",
"(",
"input",
",",
"encoding",
")",
";",
"// call this method to create the reader",
"Reader",
"reader",
"=",
"XmlCharsetDetector",
".",
"createReader",
"(",
"input",
",",
"encoding",
")",
";",
"// rest the input",
"input",
".",
"reset",
"(",
")",
";",
"return",
"getBufferedXMLReader",
"(",
"reader",
",",
"xmlLookahead",
")",
";",
"}"
] | Wraps an xml input xstream in a buffered reader specifying a lookahead that can be used to
preparse some of the xml document, resetting it back to its original state for actual
parsing.
@param stream The original xml stream.
@param xmlLookahead The number of bytes to support for parse. If more than this number of
bytes are preparsed the stream can not be properly reset.
@return The buffered reader. | [
"Wraps",
"an",
"xml",
"input",
"xstream",
"in",
"a",
"buffered",
"reader",
"specifying",
"a",
"lookahead",
"that",
"can",
"be",
"used",
"to",
"preparse",
"some",
"of",
"the",
"xml",
"document",
"resetting",
"it",
"back",
"to",
"its",
"original",
"state",
"for",
"actual",
"parsing",
"."
] | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/style/sld/RequestUtils.java#L212-L232 |
alexvasilkov/AndroidCommons | library/src/main/java/com/alexvasilkov/android/commons/prefs/PreferencesHelper.java | PreferencesHelper.putStringArray | @NonNull
public static SharedPreferences.Editor putStringArray(@NonNull SharedPreferences.Editor editor,
@NonNull String key, @Nullable String[] values) {
"""
Stores strings array as single string. Uses {@link #DEFAULT_DELIMITER} as delimiter.
"""
return putStringArray(editor, key, values, DEFAULT_DELIMITER);
} | java | @NonNull
public static SharedPreferences.Editor putStringArray(@NonNull SharedPreferences.Editor editor,
@NonNull String key, @Nullable String[] values) {
return putStringArray(editor, key, values, DEFAULT_DELIMITER);
} | [
"@",
"NonNull",
"public",
"static",
"SharedPreferences",
".",
"Editor",
"putStringArray",
"(",
"@",
"NonNull",
"SharedPreferences",
".",
"Editor",
"editor",
",",
"@",
"NonNull",
"String",
"key",
",",
"@",
"Nullable",
"String",
"[",
"]",
"values",
")",
"{",
"return",
"putStringArray",
"(",
"editor",
",",
"key",
",",
"values",
",",
"DEFAULT_DELIMITER",
")",
";",
"}"
] | Stores strings array as single string. Uses {@link #DEFAULT_DELIMITER} as delimiter. | [
"Stores",
"strings",
"array",
"as",
"single",
"string",
".",
"Uses",
"{"
] | train | https://github.com/alexvasilkov/AndroidCommons/blob/aca9f6d5acfc6bd3694984b7f89956e1a0146ddb/library/src/main/java/com/alexvasilkov/android/commons/prefs/PreferencesHelper.java#L80-L84 |
alipay/sofa-rpc | extension-impl/extension-common/src/main/java/com/alipay/sofa/rpc/common/SofaConfigs.java | SofaConfigs.getStringValue | public static String getStringValue(String appName, String key, String defaultValue) {
"""
获取配置值
@param appName 应用名
@param key 配置项
@param defaultValue 默认值
@return 配置
"""
String ret = getStringValue0(appName, key);
return StringUtils.isEmpty(ret) ? defaultValue : ret.trim();
} | java | public static String getStringValue(String appName, String key, String defaultValue) {
String ret = getStringValue0(appName, key);
return StringUtils.isEmpty(ret) ? defaultValue : ret.trim();
} | [
"public",
"static",
"String",
"getStringValue",
"(",
"String",
"appName",
",",
"String",
"key",
",",
"String",
"defaultValue",
")",
"{",
"String",
"ret",
"=",
"getStringValue0",
"(",
"appName",
",",
"key",
")",
";",
"return",
"StringUtils",
".",
"isEmpty",
"(",
"ret",
")",
"?",
"defaultValue",
":",
"ret",
".",
"trim",
"(",
")",
";",
"}"
] | 获取配置值
@param appName 应用名
@param key 配置项
@param defaultValue 默认值
@return 配置 | [
"获取配置值"
] | train | https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/extension-impl/extension-common/src/main/java/com/alipay/sofa/rpc/common/SofaConfigs.java#L171-L174 |
jayantk/jklol | src/com/jayantkrish/jklol/sequence/ListLocalContext.java | ListLocalContext.getItem | @Override
public I getItem(int relativeOffset, Function<? super Integer, I> endFunction) {
"""
Gets an item to the left or right of the central item in this
context. Negative offsets get an item on the left (e.g., -2 gets
the second item on the left) and positive offsets get an item on
the right. If {@code relativeOffset} refers to a word off the end
of the sequence, then {@code endFunction} is invoked to produce the
return value.
@param relativeOffset
@return
"""
int index = wordIndex + relativeOffset;
if (index < 0) {
return endFunction.apply(index);
} else if (index >= items.size()) {
int endWordIndex = index - (items.size() - 1);
return endFunction.apply(endWordIndex);
} else {
return items.get(index);
}
} | java | @Override
public I getItem(int relativeOffset, Function<? super Integer, I> endFunction) {
int index = wordIndex + relativeOffset;
if (index < 0) {
return endFunction.apply(index);
} else if (index >= items.size()) {
int endWordIndex = index - (items.size() - 1);
return endFunction.apply(endWordIndex);
} else {
return items.get(index);
}
} | [
"@",
"Override",
"public",
"I",
"getItem",
"(",
"int",
"relativeOffset",
",",
"Function",
"<",
"?",
"super",
"Integer",
",",
"I",
">",
"endFunction",
")",
"{",
"int",
"index",
"=",
"wordIndex",
"+",
"relativeOffset",
";",
"if",
"(",
"index",
"<",
"0",
")",
"{",
"return",
"endFunction",
".",
"apply",
"(",
"index",
")",
";",
"}",
"else",
"if",
"(",
"index",
">=",
"items",
".",
"size",
"(",
")",
")",
"{",
"int",
"endWordIndex",
"=",
"index",
"-",
"(",
"items",
".",
"size",
"(",
")",
"-",
"1",
")",
";",
"return",
"endFunction",
".",
"apply",
"(",
"endWordIndex",
")",
";",
"}",
"else",
"{",
"return",
"items",
".",
"get",
"(",
"index",
")",
";",
"}",
"}"
] | Gets an item to the left or right of the central item in this
context. Negative offsets get an item on the left (e.g., -2 gets
the second item on the left) and positive offsets get an item on
the right. If {@code relativeOffset} refers to a word off the end
of the sequence, then {@code endFunction} is invoked to produce the
return value.
@param relativeOffset
@return | [
"Gets",
"an",
"item",
"to",
"the",
"left",
"or",
"right",
"of",
"the",
"central",
"item",
"in",
"this",
"context",
".",
"Negative",
"offsets",
"get",
"an",
"item",
"on",
"the",
"left",
"(",
"e",
".",
"g",
".",
"-",
"2",
"gets",
"the",
"second",
"item",
"on",
"the",
"left",
")",
"and",
"positive",
"offsets",
"get",
"an",
"item",
"on",
"the",
"right",
".",
"If",
"{",
"@code",
"relativeOffset",
"}",
"refers",
"to",
"a",
"word",
"off",
"the",
"end",
"of",
"the",
"sequence",
"then",
"{",
"@code",
"endFunction",
"}",
"is",
"invoked",
"to",
"produce",
"the",
"return",
"value",
"."
] | train | https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/sequence/ListLocalContext.java#L40-L52 |
Samsung/GearVRf | GVRf/Framework/framework/src/main/java/org/gearvrf/GVRTextureCapturer.java | GVRTextureCapturer.setCapture | public void setCapture(boolean capture, float fps) {
"""
Starts or stops capturing.
@param capture If true, capturing is started. If false, it is stopped.
@param fps Capturing FPS (frames per second).
"""
capturing = capture;
NativeTextureCapturer.setCapture(getNative(), capture, fps);
} | java | public void setCapture(boolean capture, float fps) {
capturing = capture;
NativeTextureCapturer.setCapture(getNative(), capture, fps);
} | [
"public",
"void",
"setCapture",
"(",
"boolean",
"capture",
",",
"float",
"fps",
")",
"{",
"capturing",
"=",
"capture",
";",
"NativeTextureCapturer",
".",
"setCapture",
"(",
"getNative",
"(",
")",
",",
"capture",
",",
"fps",
")",
";",
"}"
] | Starts or stops capturing.
@param capture If true, capturing is started. If false, it is stopped.
@param fps Capturing FPS (frames per second). | [
"Starts",
"or",
"stops",
"capturing",
"."
] | train | https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Framework/framework/src/main/java/org/gearvrf/GVRTextureCapturer.java#L122-L125 |
hypercube1024/firefly | firefly-db/src/main/java/com/firefly/db/init/ScriptUtils.java | ScriptUtils.readScript | private static String readScript(EncodedResource resource, String commentPrefix, String separator)
throws IOException {
"""
Read a script from the provided resource, using the supplied comment
prefix and statement separator, and build a {@code String} containing the
lines.
<p>
Lines <em>beginning</em> with the comment prefix are excluded from the
results; however, line comments anywhere else — for example, within
a statement — will be included in the results.
@param resource the {@code EncodedResource} containing the script to be
processed
@param commentPrefix the prefix that identifies comments in the SQL script —
typically "--"
@param separator the statement separator in the SQL script — typically
";"
@return a {@code String} containing the script lines
@throws IOException in case of I/O errors
"""
LineNumberReader lnr = new LineNumberReader(resource.getReader());
try {
return readScript(lnr, commentPrefix, separator);
} finally {
lnr.close();
}
} | java | private static String readScript(EncodedResource resource, String commentPrefix, String separator)
throws IOException {
LineNumberReader lnr = new LineNumberReader(resource.getReader());
try {
return readScript(lnr, commentPrefix, separator);
} finally {
lnr.close();
}
} | [
"private",
"static",
"String",
"readScript",
"(",
"EncodedResource",
"resource",
",",
"String",
"commentPrefix",
",",
"String",
"separator",
")",
"throws",
"IOException",
"{",
"LineNumberReader",
"lnr",
"=",
"new",
"LineNumberReader",
"(",
"resource",
".",
"getReader",
"(",
")",
")",
";",
"try",
"{",
"return",
"readScript",
"(",
"lnr",
",",
"commentPrefix",
",",
"separator",
")",
";",
"}",
"finally",
"{",
"lnr",
".",
"close",
"(",
")",
";",
"}",
"}"
] | Read a script from the provided resource, using the supplied comment
prefix and statement separator, and build a {@code String} containing the
lines.
<p>
Lines <em>beginning</em> with the comment prefix are excluded from the
results; however, line comments anywhere else — for example, within
a statement — will be included in the results.
@param resource the {@code EncodedResource} containing the script to be
processed
@param commentPrefix the prefix that identifies comments in the SQL script —
typically "--"
@param separator the statement separator in the SQL script — typically
";"
@return a {@code String} containing the script lines
@throws IOException in case of I/O errors | [
"Read",
"a",
"script",
"from",
"the",
"provided",
"resource",
"using",
"the",
"supplied",
"comment",
"prefix",
"and",
"statement",
"separator",
"and",
"build",
"a",
"{",
"@code",
"String",
"}",
"containing",
"the",
"lines",
".",
"<p",
">",
"Lines",
"<em",
">",
"beginning<",
"/",
"em",
">",
"with",
"the",
"comment",
"prefix",
"are",
"excluded",
"from",
"the",
"results",
";",
"however",
"line",
"comments",
"anywhere",
"else",
"&mdash",
";",
"for",
"example",
"within",
"a",
"statement",
"&mdash",
";",
"will",
"be",
"included",
"in",
"the",
"results",
"."
] | train | https://github.com/hypercube1024/firefly/blob/ed3fc75b7c54a65b1e7d8141d01b49144bb423a3/firefly-db/src/main/java/com/firefly/db/init/ScriptUtils.java#L266-L275 |
dustin/java-memcached-client | src/main/java/net/spy/memcached/MemcachedClient.java | MemcachedClient.asyncDecr | @Override
public OperationFuture<Long> asyncDecr(String key, int by, long def,
int exp) {
"""
Asynchronous decrement.
@param key key to decrement
@param by the amount to decrement the value by
@param def the default value (if the counter does not exist)
@param exp the expiration of this object
@return a future with the decremented value, or -1 if the decrement failed.
@throws IllegalStateException in the rare circumstance where queue is too
full to accept any more requests
"""
return asyncMutate(Mutator.decr, key, by, def, exp);
} | java | @Override
public OperationFuture<Long> asyncDecr(String key, int by, long def,
int exp) {
return asyncMutate(Mutator.decr, key, by, def, exp);
} | [
"@",
"Override",
"public",
"OperationFuture",
"<",
"Long",
">",
"asyncDecr",
"(",
"String",
"key",
",",
"int",
"by",
",",
"long",
"def",
",",
"int",
"exp",
")",
"{",
"return",
"asyncMutate",
"(",
"Mutator",
".",
"decr",
",",
"key",
",",
"by",
",",
"def",
",",
"exp",
")",
";",
"}"
] | Asynchronous decrement.
@param key key to decrement
@param by the amount to decrement the value by
@param def the default value (if the counter does not exist)
@param exp the expiration of this object
@return a future with the decremented value, or -1 if the decrement failed.
@throws IllegalStateException in the rare circumstance where queue is too
full to accept any more requests | [
"Asynchronous",
"decrement",
"."
] | train | https://github.com/dustin/java-memcached-client/blob/c232307ad8e0c7ccc926e495dd7d5aad2d713318/src/main/java/net/spy/memcached/MemcachedClient.java#L2127-L2131 |
bazaarvoice/jolt | cli/src/main/java/com/bazaarvoice/jolt/JoltCliUtilities.java | JoltCliUtilities.readJsonInput | public static Object readJsonInput( File file, boolean suppressOutput ) {
"""
This method will read in JSON, either from the given file or from standard in
if the file is null. An object contain the ingested input is returned.
@param file the file to read the input from, or null to use standard in
@param suppressOutput suppress output of error messages to standard out
@return Object containing input if successful or null if an error occured
"""
Object jsonObject;
if ( file == null ) {
try {
jsonObject = JsonUtils.jsonToMap( System.in );
} catch ( Exception e ) {
printToStandardOut( "Failed to process standard input.", suppressOutput );
return null;
}
} else {
jsonObject = createJsonObjectFromFile( file, suppressOutput );
}
return jsonObject;
} | java | public static Object readJsonInput( File file, boolean suppressOutput ) {
Object jsonObject;
if ( file == null ) {
try {
jsonObject = JsonUtils.jsonToMap( System.in );
} catch ( Exception e ) {
printToStandardOut( "Failed to process standard input.", suppressOutput );
return null;
}
} else {
jsonObject = createJsonObjectFromFile( file, suppressOutput );
}
return jsonObject;
} | [
"public",
"static",
"Object",
"readJsonInput",
"(",
"File",
"file",
",",
"boolean",
"suppressOutput",
")",
"{",
"Object",
"jsonObject",
";",
"if",
"(",
"file",
"==",
"null",
")",
"{",
"try",
"{",
"jsonObject",
"=",
"JsonUtils",
".",
"jsonToMap",
"(",
"System",
".",
"in",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"printToStandardOut",
"(",
"\"Failed to process standard input.\"",
",",
"suppressOutput",
")",
";",
"return",
"null",
";",
"}",
"}",
"else",
"{",
"jsonObject",
"=",
"createJsonObjectFromFile",
"(",
"file",
",",
"suppressOutput",
")",
";",
"}",
"return",
"jsonObject",
";",
"}"
] | This method will read in JSON, either from the given file or from standard in
if the file is null. An object contain the ingested input is returned.
@param file the file to read the input from, or null to use standard in
@param suppressOutput suppress output of error messages to standard out
@return Object containing input if successful or null if an error occured | [
"This",
"method",
"will",
"read",
"in",
"JSON",
"either",
"from",
"the",
"given",
"file",
"or",
"from",
"standard",
"in",
"if",
"the",
"file",
"is",
"null",
".",
"An",
"object",
"contain",
"the",
"ingested",
"input",
"is",
"returned",
"."
] | train | https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/cli/src/main/java/com/bazaarvoice/jolt/JoltCliUtilities.java#L96-L109 |
ACRA/acra | acra-dialog/src/main/java/org/acra/dialog/BaseCrashReportDialog.java | BaseCrashReportDialog.sendCrash | protected final void sendCrash(@Nullable String comment, @Nullable String userEmail) {
"""
Send crash report given user's comment and email address.
@param comment Comment (may be null) provided by the user.
@param userEmail Email address (may be null) provided by the client.
"""
new Thread(() -> {
final CrashReportPersister persister = new CrashReportPersister();
try {
if (ACRA.DEV_LOGGING) ACRA.log.d(LOG_TAG, "Add user comment to " + reportFile);
final CrashReportData crashData = persister.load(reportFile);
crashData.put(USER_COMMENT, comment == null ? "" : comment);
crashData.put(USER_EMAIL, userEmail == null ? "" : userEmail);
persister.store(crashData, reportFile);
} catch (IOException | JSONException e) {
ACRA.log.w(LOG_TAG, "User comment not added: ", e);
}
// Start the report sending task
new SchedulerStarter(this, config).scheduleReports(reportFile, false);
}).start();
} | java | protected final void sendCrash(@Nullable String comment, @Nullable String userEmail) {
new Thread(() -> {
final CrashReportPersister persister = new CrashReportPersister();
try {
if (ACRA.DEV_LOGGING) ACRA.log.d(LOG_TAG, "Add user comment to " + reportFile);
final CrashReportData crashData = persister.load(reportFile);
crashData.put(USER_COMMENT, comment == null ? "" : comment);
crashData.put(USER_EMAIL, userEmail == null ? "" : userEmail);
persister.store(crashData, reportFile);
} catch (IOException | JSONException e) {
ACRA.log.w(LOG_TAG, "User comment not added: ", e);
}
// Start the report sending task
new SchedulerStarter(this, config).scheduleReports(reportFile, false);
}).start();
} | [
"protected",
"final",
"void",
"sendCrash",
"(",
"@",
"Nullable",
"String",
"comment",
",",
"@",
"Nullable",
"String",
"userEmail",
")",
"{",
"new",
"Thread",
"(",
"(",
")",
"->",
"{",
"final",
"CrashReportPersister",
"persister",
"=",
"new",
"CrashReportPersister",
"(",
")",
";",
"try",
"{",
"if",
"(",
"ACRA",
".",
"DEV_LOGGING",
")",
"ACRA",
".",
"log",
".",
"d",
"(",
"LOG_TAG",
",",
"\"Add user comment to \"",
"+",
"reportFile",
")",
";",
"final",
"CrashReportData",
"crashData",
"=",
"persister",
".",
"load",
"(",
"reportFile",
")",
";",
"crashData",
".",
"put",
"(",
"USER_COMMENT",
",",
"comment",
"==",
"null",
"?",
"\"\"",
":",
"comment",
")",
";",
"crashData",
".",
"put",
"(",
"USER_EMAIL",
",",
"userEmail",
"==",
"null",
"?",
"\"\"",
":",
"userEmail",
")",
";",
"persister",
".",
"store",
"(",
"crashData",
",",
"reportFile",
")",
";",
"}",
"catch",
"(",
"IOException",
"|",
"JSONException",
"e",
")",
"{",
"ACRA",
".",
"log",
".",
"w",
"(",
"LOG_TAG",
",",
"\"User comment not added: \"",
",",
"e",
")",
";",
"}",
"// Start the report sending task",
"new",
"SchedulerStarter",
"(",
"this",
",",
"config",
")",
".",
"scheduleReports",
"(",
"reportFile",
",",
"false",
")",
";",
"}",
")",
".",
"start",
"(",
")",
";",
"}"
] | Send crash report given user's comment and email address.
@param comment Comment (may be null) provided by the user.
@param userEmail Email address (may be null) provided by the client. | [
"Send",
"crash",
"report",
"given",
"user",
"s",
"comment",
"and",
"email",
"address",
"."
] | train | https://github.com/ACRA/acra/blob/bfa3235ab110328c5ab2f792ddf8ee87be4a32d1/acra-dialog/src/main/java/org/acra/dialog/BaseCrashReportDialog.java#L122-L138 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/util/ReUtil.java | ReUtil.extractMultiAndDelPre | public static String extractMultiAndDelPre(Pattern pattern, Holder<CharSequence> contentHolder, String template) {
"""
从content中匹配出多个值并根据template生成新的字符串<br>
匹配结束后会删除匹配内容之前的内容(包括匹配内容)<br>
例如:<br>
content 2013年5月 pattern (.*?)年(.*?)月 template: $1-$2 return 2013-5
@param pattern 匹配正则
@param contentHolder 被匹配的内容的Holder,value为内容正文,经过这个方法的原文将被去掉匹配之前的内容
@param template 生成内容模板,变量 $1 表示group1的内容,以此类推
@return 新字符串
"""
if (null == contentHolder || null == pattern || null == template) {
return null;
}
HashSet<String> varNums = findAll(PatternPool.GROUP_VAR, template, 1, new HashSet<String>());
final CharSequence content = contentHolder.get();
Matcher matcher = pattern.matcher(content);
if (matcher.find()) {
for (String var : varNums) {
int group = Integer.parseInt(var);
template = template.replace("$" + var, matcher.group(group));
}
contentHolder.set(StrUtil.sub(content, matcher.end(), content.length()));
return template;
}
return null;
} | java | public static String extractMultiAndDelPre(Pattern pattern, Holder<CharSequence> contentHolder, String template) {
if (null == contentHolder || null == pattern || null == template) {
return null;
}
HashSet<String> varNums = findAll(PatternPool.GROUP_VAR, template, 1, new HashSet<String>());
final CharSequence content = contentHolder.get();
Matcher matcher = pattern.matcher(content);
if (matcher.find()) {
for (String var : varNums) {
int group = Integer.parseInt(var);
template = template.replace("$" + var, matcher.group(group));
}
contentHolder.set(StrUtil.sub(content, matcher.end(), content.length()));
return template;
}
return null;
} | [
"public",
"static",
"String",
"extractMultiAndDelPre",
"(",
"Pattern",
"pattern",
",",
"Holder",
"<",
"CharSequence",
">",
"contentHolder",
",",
"String",
"template",
")",
"{",
"if",
"(",
"null",
"==",
"contentHolder",
"||",
"null",
"==",
"pattern",
"||",
"null",
"==",
"template",
")",
"{",
"return",
"null",
";",
"}",
"HashSet",
"<",
"String",
">",
"varNums",
"=",
"findAll",
"(",
"PatternPool",
".",
"GROUP_VAR",
",",
"template",
",",
"1",
",",
"new",
"HashSet",
"<",
"String",
">",
"(",
")",
")",
";",
"final",
"CharSequence",
"content",
"=",
"contentHolder",
".",
"get",
"(",
")",
";",
"Matcher",
"matcher",
"=",
"pattern",
".",
"matcher",
"(",
"content",
")",
";",
"if",
"(",
"matcher",
".",
"find",
"(",
")",
")",
"{",
"for",
"(",
"String",
"var",
":",
"varNums",
")",
"{",
"int",
"group",
"=",
"Integer",
".",
"parseInt",
"(",
"var",
")",
";",
"template",
"=",
"template",
".",
"replace",
"(",
"\"$\"",
"+",
"var",
",",
"matcher",
".",
"group",
"(",
"group",
")",
")",
";",
"}",
"contentHolder",
".",
"set",
"(",
"StrUtil",
".",
"sub",
"(",
"content",
",",
"matcher",
".",
"end",
"(",
")",
",",
"content",
".",
"length",
"(",
")",
")",
")",
";",
"return",
"template",
";",
"}",
"return",
"null",
";",
"}"
] | 从content中匹配出多个值并根据template生成新的字符串<br>
匹配结束后会删除匹配内容之前的内容(包括匹配内容)<br>
例如:<br>
content 2013年5月 pattern (.*?)年(.*?)月 template: $1-$2 return 2013-5
@param pattern 匹配正则
@param contentHolder 被匹配的内容的Holder,value为内容正文,经过这个方法的原文将被去掉匹配之前的内容
@param template 生成内容模板,变量 $1 表示group1的内容,以此类推
@return 新字符串 | [
"从content中匹配出多个值并根据template生成新的字符串<br",
">",
"匹配结束后会删除匹配内容之前的内容(包括匹配内容)<br",
">",
"例如:<br",
">",
"content",
"2013年5月",
"pattern",
"(",
".",
"*",
"?",
")",
"年",
"(",
".",
"*",
"?",
")",
"月",
"template:",
"$1",
"-",
"$2",
"return",
"2013",
"-",
"5"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/ReUtil.java#L230-L248 |
pravega/pravega | segmentstore/server/src/main/java/io/pravega/segmentstore/server/tables/WriterTableProcessor.java | WriterTableProcessor.readFromInMemorySegment | private InputStream readFromInMemorySegment(DirectSegmentAccess segment, long startOffset, long endOffset, TimeoutTimer timer) {
"""
Reads from the Segment between the given offsets. This method assumes all the data is readily available in the cache,
otherwise it will block synchronously for Storage retrieval.
@param segment The Segment to read from.
@param startOffset The offset to start reading from.
@param endOffset The offset to stop reading at.
@param timer Timer for the operation.
@return An Enumeration of InputStreams representing the read data.
"""
long readOffset = startOffset;
long remainingLength = endOffset - startOffset;
ArrayList<InputStream> inputs = new ArrayList<>();
while (remainingLength > 0) {
int readLength = (int) Math.min(remainingLength, Integer.MAX_VALUE);
try (ReadResult readResult = segment.read(readOffset, readLength, timer.getRemaining())) {
inputs.addAll(readResult.readRemaining(readLength, timer.getRemaining()));
assert readResult.getConsumedLength() == readLength : "Expecting a full read (from memory).";
remainingLength -= readResult.getConsumedLength();
readOffset += readResult.getConsumedLength();
}
}
return new SequenceInputStream(Iterators.asEnumeration(inputs.iterator()));
} | java | private InputStream readFromInMemorySegment(DirectSegmentAccess segment, long startOffset, long endOffset, TimeoutTimer timer) {
long readOffset = startOffset;
long remainingLength = endOffset - startOffset;
ArrayList<InputStream> inputs = new ArrayList<>();
while (remainingLength > 0) {
int readLength = (int) Math.min(remainingLength, Integer.MAX_VALUE);
try (ReadResult readResult = segment.read(readOffset, readLength, timer.getRemaining())) {
inputs.addAll(readResult.readRemaining(readLength, timer.getRemaining()));
assert readResult.getConsumedLength() == readLength : "Expecting a full read (from memory).";
remainingLength -= readResult.getConsumedLength();
readOffset += readResult.getConsumedLength();
}
}
return new SequenceInputStream(Iterators.asEnumeration(inputs.iterator()));
} | [
"private",
"InputStream",
"readFromInMemorySegment",
"(",
"DirectSegmentAccess",
"segment",
",",
"long",
"startOffset",
",",
"long",
"endOffset",
",",
"TimeoutTimer",
"timer",
")",
"{",
"long",
"readOffset",
"=",
"startOffset",
";",
"long",
"remainingLength",
"=",
"endOffset",
"-",
"startOffset",
";",
"ArrayList",
"<",
"InputStream",
">",
"inputs",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"while",
"(",
"remainingLength",
">",
"0",
")",
"{",
"int",
"readLength",
"=",
"(",
"int",
")",
"Math",
".",
"min",
"(",
"remainingLength",
",",
"Integer",
".",
"MAX_VALUE",
")",
";",
"try",
"(",
"ReadResult",
"readResult",
"=",
"segment",
".",
"read",
"(",
"readOffset",
",",
"readLength",
",",
"timer",
".",
"getRemaining",
"(",
")",
")",
")",
"{",
"inputs",
".",
"addAll",
"(",
"readResult",
".",
"readRemaining",
"(",
"readLength",
",",
"timer",
".",
"getRemaining",
"(",
")",
")",
")",
";",
"assert",
"readResult",
".",
"getConsumedLength",
"(",
")",
"==",
"readLength",
":",
"\"Expecting a full read (from memory).\"",
";",
"remainingLength",
"-=",
"readResult",
".",
"getConsumedLength",
"(",
")",
";",
"readOffset",
"+=",
"readResult",
".",
"getConsumedLength",
"(",
")",
";",
"}",
"}",
"return",
"new",
"SequenceInputStream",
"(",
"Iterators",
".",
"asEnumeration",
"(",
"inputs",
".",
"iterator",
"(",
")",
")",
")",
";",
"}"
] | Reads from the Segment between the given offsets. This method assumes all the data is readily available in the cache,
otherwise it will block synchronously for Storage retrieval.
@param segment The Segment to read from.
@param startOffset The offset to start reading from.
@param endOffset The offset to stop reading at.
@param timer Timer for the operation.
@return An Enumeration of InputStreams representing the read data. | [
"Reads",
"from",
"the",
"Segment",
"between",
"the",
"given",
"offsets",
".",
"This",
"method",
"assumes",
"all",
"the",
"data",
"is",
"readily",
"available",
"in",
"the",
"cache",
"otherwise",
"it",
"will",
"block",
"synchronously",
"for",
"Storage",
"retrieval",
"."
] | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/server/src/main/java/io/pravega/segmentstore/server/tables/WriterTableProcessor.java#L385-L400 |
operasoftware/operaprestodriver | src/com/opera/core/systems/OperaSettings.java | OperaSettings.emulate | public void emulate(EmulationProfile profile) {
"""
Specify a prepared configuration for Opera Mobile to use. For this configuration to be
recognized, {@link #getProduct()} must evaluate to {@link OperaProduct#MOBILE}.
@param profile the mobile configuration to use
"""
options.get(EMULATION_PROFILE).setValue(profile);
if (profile != null) {
Dimension resolution = profile.getResolution();
arguments().add("-windowsize",
String.format("%dx%d", resolution.getWidth(), resolution.getHeight()));
arguments().add(new OperaArgument("-ppi", profile.getPPI()));
if (profile.getIME() == EmulationProfile.IME.KEYPAD) {
arguments().add("-notouchwithtouchevents");
} else if (profile.getIME() == EmulationProfile.IME.TABLET) {
arguments().add(new OperaArgument("-tabletui"));
}
arguments().add("-user-agent-string", profile.getUserAgent());
arguments().add(new OperaArgument("-profile-name", profile.getProfileName()));
}
} | java | public void emulate(EmulationProfile profile) {
options.get(EMULATION_PROFILE).setValue(profile);
if (profile != null) {
Dimension resolution = profile.getResolution();
arguments().add("-windowsize",
String.format("%dx%d", resolution.getWidth(), resolution.getHeight()));
arguments().add(new OperaArgument("-ppi", profile.getPPI()));
if (profile.getIME() == EmulationProfile.IME.KEYPAD) {
arguments().add("-notouchwithtouchevents");
} else if (profile.getIME() == EmulationProfile.IME.TABLET) {
arguments().add(new OperaArgument("-tabletui"));
}
arguments().add("-user-agent-string", profile.getUserAgent());
arguments().add(new OperaArgument("-profile-name", profile.getProfileName()));
}
} | [
"public",
"void",
"emulate",
"(",
"EmulationProfile",
"profile",
")",
"{",
"options",
".",
"get",
"(",
"EMULATION_PROFILE",
")",
".",
"setValue",
"(",
"profile",
")",
";",
"if",
"(",
"profile",
"!=",
"null",
")",
"{",
"Dimension",
"resolution",
"=",
"profile",
".",
"getResolution",
"(",
")",
";",
"arguments",
"(",
")",
".",
"add",
"(",
"\"-windowsize\"",
",",
"String",
".",
"format",
"(",
"\"%dx%d\"",
",",
"resolution",
".",
"getWidth",
"(",
")",
",",
"resolution",
".",
"getHeight",
"(",
")",
")",
")",
";",
"arguments",
"(",
")",
".",
"add",
"(",
"new",
"OperaArgument",
"(",
"\"-ppi\"",
",",
"profile",
".",
"getPPI",
"(",
")",
")",
")",
";",
"if",
"(",
"profile",
".",
"getIME",
"(",
")",
"==",
"EmulationProfile",
".",
"IME",
".",
"KEYPAD",
")",
"{",
"arguments",
"(",
")",
".",
"add",
"(",
"\"-notouchwithtouchevents\"",
")",
";",
"}",
"else",
"if",
"(",
"profile",
".",
"getIME",
"(",
")",
"==",
"EmulationProfile",
".",
"IME",
".",
"TABLET",
")",
"{",
"arguments",
"(",
")",
".",
"add",
"(",
"new",
"OperaArgument",
"(",
"\"-tabletui\"",
")",
")",
";",
"}",
"arguments",
"(",
")",
".",
"add",
"(",
"\"-user-agent-string\"",
",",
"profile",
".",
"getUserAgent",
"(",
")",
")",
";",
"arguments",
"(",
")",
".",
"add",
"(",
"new",
"OperaArgument",
"(",
"\"-profile-name\"",
",",
"profile",
".",
"getProfileName",
"(",
")",
")",
")",
";",
"}",
"}"
] | Specify a prepared configuration for Opera Mobile to use. For this configuration to be
recognized, {@link #getProduct()} must evaluate to {@link OperaProduct#MOBILE}.
@param profile the mobile configuration to use | [
"Specify",
"a",
"prepared",
"configuration",
"for",
"Opera",
"Mobile",
"to",
"use",
".",
"For",
"this",
"configuration",
"to",
"be",
"recognized",
"{",
"@link",
"#getProduct",
"()",
"}",
"must",
"evaluate",
"to",
"{",
"@link",
"OperaProduct#MOBILE",
"}",
"."
] | train | https://github.com/operasoftware/operaprestodriver/blob/1ccceda80f1c1a0489171d17dcaa6e7b18fb4c01/src/com/opera/core/systems/OperaSettings.java#L1209-L1225 |
Azure/azure-sdk-for-java | kusto/resource-manager/v2018_09_07_preview/src/main/java/com/microsoft/azure/management/kusto/v2018_09_07_preview/implementation/ClustersInner.java | ClustersInner.beginStopAsync | public Observable<Void> beginStopAsync(String resourceGroupName, String clusterName) {
"""
Stops a Kusto cluster.
@param resourceGroupName The name of the resource group containing the Kusto cluster.
@param clusterName The name of the Kusto cluster.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceResponse} object if successful.
"""
return beginStopWithServiceResponseAsync(resourceGroupName, clusterName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | java | public Observable<Void> beginStopAsync(String resourceGroupName, String clusterName) {
return beginStopWithServiceResponseAsync(resourceGroupName, clusterName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Void",
">",
"beginStopAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"clusterName",
")",
"{",
"return",
"beginStopWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"clusterName",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"Void",
">",
",",
"Void",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"Void",
"call",
"(",
"ServiceResponse",
"<",
"Void",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Stops a Kusto cluster.
@param resourceGroupName The name of the resource group containing the Kusto cluster.
@param clusterName The name of the Kusto cluster.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceResponse} object if successful. | [
"Stops",
"a",
"Kusto",
"cluster",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/kusto/resource-manager/v2018_09_07_preview/src/main/java/com/microsoft/azure/management/kusto/v2018_09_07_preview/implementation/ClustersInner.java#L821-L828 |
Swagger2Markup/swagger2markup | src/main/java/io/github/swagger2markup/internal/utils/ExamplesUtil.java | ExamplesUtil.generateExampleForRefModel | private static Object generateExampleForRefModel(boolean generateMissingExamples, String simpleRef, Map<String, Model> definitions, DocumentResolver definitionDocumentResolver, MarkupDocBuilder markupDocBuilder, Map<String, Integer> refStack) {
"""
Generates an example object from a simple reference
@param generateMissingExamples specifies the missing examples should be generated
@param simpleRef the simple reference string
@param definitions the map of definitions
@param markupDocBuilder the markup builder
@param refStack map to detect cyclic references
@return returns an Object or Map of examples
"""
Model model = definitions.get(simpleRef);
Object example = null;
if (model != null) {
example = model.getExample();
if (example == null && generateMissingExamples) {
if (!refStack.containsKey(simpleRef)) {
refStack.put(simpleRef, 1);
} else {
refStack.put(simpleRef, refStack.get(simpleRef) + 1);
}
if (refStack.get(simpleRef) <= MAX_RECURSION_TO_DISPLAY) {
if (model instanceof ComposedModel) {
//FIXME: getProperties() may throw NullPointerException
example = exampleMapForProperties(((ObjectType) ModelUtils.getType(model, definitions, definitionDocumentResolver)).getProperties(), definitions, definitionDocumentResolver, markupDocBuilder, new HashMap<>());
} else {
example = exampleMapForProperties(model.getProperties(), definitions, definitionDocumentResolver, markupDocBuilder, refStack);
}
} else {
return "...";
}
refStack.put(simpleRef, refStack.get(simpleRef) - 1);
}
}
return example;
} | java | private static Object generateExampleForRefModel(boolean generateMissingExamples, String simpleRef, Map<String, Model> definitions, DocumentResolver definitionDocumentResolver, MarkupDocBuilder markupDocBuilder, Map<String, Integer> refStack) {
Model model = definitions.get(simpleRef);
Object example = null;
if (model != null) {
example = model.getExample();
if (example == null && generateMissingExamples) {
if (!refStack.containsKey(simpleRef)) {
refStack.put(simpleRef, 1);
} else {
refStack.put(simpleRef, refStack.get(simpleRef) + 1);
}
if (refStack.get(simpleRef) <= MAX_RECURSION_TO_DISPLAY) {
if (model instanceof ComposedModel) {
//FIXME: getProperties() may throw NullPointerException
example = exampleMapForProperties(((ObjectType) ModelUtils.getType(model, definitions, definitionDocumentResolver)).getProperties(), definitions, definitionDocumentResolver, markupDocBuilder, new HashMap<>());
} else {
example = exampleMapForProperties(model.getProperties(), definitions, definitionDocumentResolver, markupDocBuilder, refStack);
}
} else {
return "...";
}
refStack.put(simpleRef, refStack.get(simpleRef) - 1);
}
}
return example;
} | [
"private",
"static",
"Object",
"generateExampleForRefModel",
"(",
"boolean",
"generateMissingExamples",
",",
"String",
"simpleRef",
",",
"Map",
"<",
"String",
",",
"Model",
">",
"definitions",
",",
"DocumentResolver",
"definitionDocumentResolver",
",",
"MarkupDocBuilder",
"markupDocBuilder",
",",
"Map",
"<",
"String",
",",
"Integer",
">",
"refStack",
")",
"{",
"Model",
"model",
"=",
"definitions",
".",
"get",
"(",
"simpleRef",
")",
";",
"Object",
"example",
"=",
"null",
";",
"if",
"(",
"model",
"!=",
"null",
")",
"{",
"example",
"=",
"model",
".",
"getExample",
"(",
")",
";",
"if",
"(",
"example",
"==",
"null",
"&&",
"generateMissingExamples",
")",
"{",
"if",
"(",
"!",
"refStack",
".",
"containsKey",
"(",
"simpleRef",
")",
")",
"{",
"refStack",
".",
"put",
"(",
"simpleRef",
",",
"1",
")",
";",
"}",
"else",
"{",
"refStack",
".",
"put",
"(",
"simpleRef",
",",
"refStack",
".",
"get",
"(",
"simpleRef",
")",
"+",
"1",
")",
";",
"}",
"if",
"(",
"refStack",
".",
"get",
"(",
"simpleRef",
")",
"<=",
"MAX_RECURSION_TO_DISPLAY",
")",
"{",
"if",
"(",
"model",
"instanceof",
"ComposedModel",
")",
"{",
"//FIXME: getProperties() may throw NullPointerException",
"example",
"=",
"exampleMapForProperties",
"(",
"(",
"(",
"ObjectType",
")",
"ModelUtils",
".",
"getType",
"(",
"model",
",",
"definitions",
",",
"definitionDocumentResolver",
")",
")",
".",
"getProperties",
"(",
")",
",",
"definitions",
",",
"definitionDocumentResolver",
",",
"markupDocBuilder",
",",
"new",
"HashMap",
"<>",
"(",
")",
")",
";",
"}",
"else",
"{",
"example",
"=",
"exampleMapForProperties",
"(",
"model",
".",
"getProperties",
"(",
")",
",",
"definitions",
",",
"definitionDocumentResolver",
",",
"markupDocBuilder",
",",
"refStack",
")",
";",
"}",
"}",
"else",
"{",
"return",
"\"...\"",
";",
"}",
"refStack",
".",
"put",
"(",
"simpleRef",
",",
"refStack",
".",
"get",
"(",
"simpleRef",
")",
"-",
"1",
")",
";",
"}",
"}",
"return",
"example",
";",
"}"
] | Generates an example object from a simple reference
@param generateMissingExamples specifies the missing examples should be generated
@param simpleRef the simple reference string
@param definitions the map of definitions
@param markupDocBuilder the markup builder
@param refStack map to detect cyclic references
@return returns an Object or Map of examples | [
"Generates",
"an",
"example",
"object",
"from",
"a",
"simple",
"reference"
] | train | https://github.com/Swagger2Markup/swagger2markup/blob/da83465f19a2f8a0f1fba873b5762bca8587896b/src/main/java/io/github/swagger2markup/internal/utils/ExamplesUtil.java#L215-L240 |
Jasig/uPortal | uPortal-events/src/main/java/org/apereo/portal/events/aggr/EventDateTimeUtils.java | EventDateTimeUtils.findDateRangeSorted | public static <DR extends DateRange<DT>, DT> DR findDateRangeSorted(
ReadableInstant instant, List<DR> dateRanges) {
"""
Same function as {@link #findDateRange(ReadableInstant, Collection)} optimized for working on
a pre-sorted List of date ranges by doing a binary search. The List must be sorted by {@link
DateRange#getStart()}
"""
if (dateRanges.isEmpty()) {
return null;
}
if (!(dateRanges instanceof RandomAccess)) {
// Not random access not much use doing a binary search
return findDateRange(instant, dateRanges);
}
int low = 0;
int high = dateRanges.size() - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
final DR dateRange = dateRanges.get(mid);
final int cmp = dateRange.compareTo(instant);
if (cmp == -1) low = mid + 1;
else if (cmp == 1) high = mid - 1;
else return dateRange;
}
return null;
} | java | public static <DR extends DateRange<DT>, DT> DR findDateRangeSorted(
ReadableInstant instant, List<DR> dateRanges) {
if (dateRanges.isEmpty()) {
return null;
}
if (!(dateRanges instanceof RandomAccess)) {
// Not random access not much use doing a binary search
return findDateRange(instant, dateRanges);
}
int low = 0;
int high = dateRanges.size() - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
final DR dateRange = dateRanges.get(mid);
final int cmp = dateRange.compareTo(instant);
if (cmp == -1) low = mid + 1;
else if (cmp == 1) high = mid - 1;
else return dateRange;
}
return null;
} | [
"public",
"static",
"<",
"DR",
"extends",
"DateRange",
"<",
"DT",
">",
",",
"DT",
">",
"DR",
"findDateRangeSorted",
"(",
"ReadableInstant",
"instant",
",",
"List",
"<",
"DR",
">",
"dateRanges",
")",
"{",
"if",
"(",
"dateRanges",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"!",
"(",
"dateRanges",
"instanceof",
"RandomAccess",
")",
")",
"{",
"// Not random access not much use doing a binary search",
"return",
"findDateRange",
"(",
"instant",
",",
"dateRanges",
")",
";",
"}",
"int",
"low",
"=",
"0",
";",
"int",
"high",
"=",
"dateRanges",
".",
"size",
"(",
")",
"-",
"1",
";",
"while",
"(",
"low",
"<=",
"high",
")",
"{",
"int",
"mid",
"=",
"(",
"low",
"+",
"high",
")",
">>>",
"1",
";",
"final",
"DR",
"dateRange",
"=",
"dateRanges",
".",
"get",
"(",
"mid",
")",
";",
"final",
"int",
"cmp",
"=",
"dateRange",
".",
"compareTo",
"(",
"instant",
")",
";",
"if",
"(",
"cmp",
"==",
"-",
"1",
")",
"low",
"=",
"mid",
"+",
"1",
";",
"else",
"if",
"(",
"cmp",
"==",
"1",
")",
"high",
"=",
"mid",
"-",
"1",
";",
"else",
"return",
"dateRange",
";",
"}",
"return",
"null",
";",
"}"
] | Same function as {@link #findDateRange(ReadableInstant, Collection)} optimized for working on
a pre-sorted List of date ranges by doing a binary search. The List must be sorted by {@link
DateRange#getStart()} | [
"Same",
"function",
"as",
"{"
] | train | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-events/src/main/java/org/apereo/portal/events/aggr/EventDateTimeUtils.java#L161-L186 |
hypfvieh/java-utils | src/main/java/com/github/hypfvieh/util/SystemUtil.java | SystemUtil.createTempDirectory | public static File createTempDirectory(String _path, String _name, boolean _deleteOnExit) {
"""
Creates a new temporary directory in the given path.
@param _path path
@param _name directory name
@param _deleteOnExit delete directory on jvm shutdown
@return created Directory, null if directory/file was already existing
"""
File outputDir = new File(concatFilePath(_path, _name));
if (!outputDir.exists()) {
try {
Files.createDirectory(Paths.get(outputDir.toString()));
} catch (IOException _ex) {
LOGGER.error("Error while creating temp directory: ", _ex);
}
} else {
return null;
}
if (_deleteOnExit) {
outputDir.deleteOnExit();
}
return outputDir;
} | java | public static File createTempDirectory(String _path, String _name, boolean _deleteOnExit) {
File outputDir = new File(concatFilePath(_path, _name));
if (!outputDir.exists()) {
try {
Files.createDirectory(Paths.get(outputDir.toString()));
} catch (IOException _ex) {
LOGGER.error("Error while creating temp directory: ", _ex);
}
} else {
return null;
}
if (_deleteOnExit) {
outputDir.deleteOnExit();
}
return outputDir;
} | [
"public",
"static",
"File",
"createTempDirectory",
"(",
"String",
"_path",
",",
"String",
"_name",
",",
"boolean",
"_deleteOnExit",
")",
"{",
"File",
"outputDir",
"=",
"new",
"File",
"(",
"concatFilePath",
"(",
"_path",
",",
"_name",
")",
")",
";",
"if",
"(",
"!",
"outputDir",
".",
"exists",
"(",
")",
")",
"{",
"try",
"{",
"Files",
".",
"createDirectory",
"(",
"Paths",
".",
"get",
"(",
"outputDir",
".",
"toString",
"(",
")",
")",
")",
";",
"}",
"catch",
"(",
"IOException",
"_ex",
")",
"{",
"LOGGER",
".",
"error",
"(",
"\"Error while creating temp directory: \"",
",",
"_ex",
")",
";",
"}",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"_deleteOnExit",
")",
"{",
"outputDir",
".",
"deleteOnExit",
"(",
")",
";",
"}",
"return",
"outputDir",
";",
"}"
] | Creates a new temporary directory in the given path.
@param _path path
@param _name directory name
@param _deleteOnExit delete directory on jvm shutdown
@return created Directory, null if directory/file was already existing | [
"Creates",
"a",
"new",
"temporary",
"directory",
"in",
"the",
"given",
"path",
"."
] | train | https://github.com/hypfvieh/java-utils/blob/407c32d6b485596d4d2b644f5f7fc7a02d0169c6/src/main/java/com/github/hypfvieh/util/SystemUtil.java#L200-L216 |
h2oai/h2o-3 | h2o-core/src/main/java/water/rapids/Session.java | Session.addRefCnt | private int addRefCnt(Key<Vec> vec, int i) {
"""
RefCnt +i this Vec; Global Refs can be alive with zero internal counts
"""
return _addRefCnt(vec, i) + (GLOBALS.contains(vec) ? 1 : 0);
} | java | private int addRefCnt(Key<Vec> vec, int i) {
return _addRefCnt(vec, i) + (GLOBALS.contains(vec) ? 1 : 0);
} | [
"private",
"int",
"addRefCnt",
"(",
"Key",
"<",
"Vec",
">",
"vec",
",",
"int",
"i",
")",
"{",
"return",
"_addRefCnt",
"(",
"vec",
",",
"i",
")",
"+",
"(",
"GLOBALS",
".",
"contains",
"(",
"vec",
")",
"?",
"1",
":",
"0",
")",
";",
"}"
] | RefCnt +i this Vec; Global Refs can be alive with zero internal counts | [
"RefCnt",
"+",
"i",
"this",
"Vec",
";",
"Global",
"Refs",
"can",
"be",
"alive",
"with",
"zero",
"internal",
"counts"
] | train | https://github.com/h2oai/h2o-3/blob/845eb49dfeaadf638b6e2f779d82fac996391fad/h2o-core/src/main/java/water/rapids/Session.java#L187-L189 |
gallandarakhneorg/afc | advanced/gis/gisroad/src/main/java/org/arakhne/afc/gis/road/primitive/RoadNetworkConstants.java | RoadNetworkConstants.setPreferredAttributeValuesForTrafficDirection | public static void setPreferredAttributeValuesForTrafficDirection(TrafficDirection direction, String... values) {
"""
Set the preferred values of traffic direction
used in the attributes for the traffic direction on the roads.
@param direction a direction
@param values are the values for the given direction.
"""
setPreferredAttributeValuesForTrafficDirection(direction, Arrays.asList(values));
} | java | public static void setPreferredAttributeValuesForTrafficDirection(TrafficDirection direction, String... values) {
setPreferredAttributeValuesForTrafficDirection(direction, Arrays.asList(values));
} | [
"public",
"static",
"void",
"setPreferredAttributeValuesForTrafficDirection",
"(",
"TrafficDirection",
"direction",
",",
"String",
"...",
"values",
")",
"{",
"setPreferredAttributeValuesForTrafficDirection",
"(",
"direction",
",",
"Arrays",
".",
"asList",
"(",
"values",
")",
")",
";",
"}"
] | Set the preferred values of traffic direction
used in the attributes for the traffic direction on the roads.
@param direction a direction
@param values are the values for the given direction. | [
"Set",
"the",
"preferred",
"values",
"of",
"traffic",
"direction",
"used",
"in",
"the",
"attributes",
"for",
"the",
"traffic",
"direction",
"on",
"the",
"roads",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/gis/gisroad/src/main/java/org/arakhne/afc/gis/road/primitive/RoadNetworkConstants.java#L579-L581 |
box/box-android-sdk | box-content-sdk/src/main/java/com/box/androidsdk/content/utils/SdkUtils.java | SdkUtils.getAssetFile | public static String getAssetFile(final Context context, final String assetName) {
"""
Helper method for reading an asset file into a string.
@param context current context.
@param assetName the asset name
@return a string representation of a file in assets.
"""
// if the file is not found create it and return that.
// if we do not have a file we copy our asset out to create one.
AssetManager assetManager = context.getAssets();
BufferedReader in = null;
try {
StringBuilder buf = new StringBuilder();
InputStream is = assetManager.open(assetName);
in = new BufferedReader(new InputStreamReader(is));
String str;
boolean isFirst = true;
while ((str = in.readLine()) != null) {
if (isFirst)
isFirst = false;
else
buf.append('\n');
buf.append(str);
}
return buf.toString();
} catch (IOException e) {
BoxLogUtils.e("getAssetFile", assetName, e);
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e) {
BoxLogUtils.e("getAssetFile", assetName, e);
}
}
// should never get here unless the asset file is inaccessible or cannot be copied out.
return null;
} | java | public static String getAssetFile(final Context context, final String assetName) {
// if the file is not found create it and return that.
// if we do not have a file we copy our asset out to create one.
AssetManager assetManager = context.getAssets();
BufferedReader in = null;
try {
StringBuilder buf = new StringBuilder();
InputStream is = assetManager.open(assetName);
in = new BufferedReader(new InputStreamReader(is));
String str;
boolean isFirst = true;
while ((str = in.readLine()) != null) {
if (isFirst)
isFirst = false;
else
buf.append('\n');
buf.append(str);
}
return buf.toString();
} catch (IOException e) {
BoxLogUtils.e("getAssetFile", assetName, e);
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e) {
BoxLogUtils.e("getAssetFile", assetName, e);
}
}
// should never get here unless the asset file is inaccessible or cannot be copied out.
return null;
} | [
"public",
"static",
"String",
"getAssetFile",
"(",
"final",
"Context",
"context",
",",
"final",
"String",
"assetName",
")",
"{",
"// if the file is not found create it and return that.",
"// if we do not have a file we copy our asset out to create one.",
"AssetManager",
"assetManager",
"=",
"context",
".",
"getAssets",
"(",
")",
";",
"BufferedReader",
"in",
"=",
"null",
";",
"try",
"{",
"StringBuilder",
"buf",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"InputStream",
"is",
"=",
"assetManager",
".",
"open",
"(",
"assetName",
")",
";",
"in",
"=",
"new",
"BufferedReader",
"(",
"new",
"InputStreamReader",
"(",
"is",
")",
")",
";",
"String",
"str",
";",
"boolean",
"isFirst",
"=",
"true",
";",
"while",
"(",
"(",
"str",
"=",
"in",
".",
"readLine",
"(",
")",
")",
"!=",
"null",
")",
"{",
"if",
"(",
"isFirst",
")",
"isFirst",
"=",
"false",
";",
"else",
"buf",
".",
"append",
"(",
"'",
"'",
")",
";",
"buf",
".",
"append",
"(",
"str",
")",
";",
"}",
"return",
"buf",
".",
"toString",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"BoxLogUtils",
".",
"e",
"(",
"\"getAssetFile\"",
",",
"assetName",
",",
"e",
")",
";",
"}",
"finally",
"{",
"try",
"{",
"if",
"(",
"in",
"!=",
"null",
")",
"{",
"in",
".",
"close",
"(",
")",
";",
"}",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"BoxLogUtils",
".",
"e",
"(",
"\"getAssetFile\"",
",",
"assetName",
",",
"e",
")",
";",
"}",
"}",
"// should never get here unless the asset file is inaccessible or cannot be copied out.",
"return",
"null",
";",
"}"
] | Helper method for reading an asset file into a string.
@param context current context.
@param assetName the asset name
@return a string representation of a file in assets. | [
"Helper",
"method",
"for",
"reading",
"an",
"asset",
"file",
"into",
"a",
"string",
"."
] | train | https://github.com/box/box-android-sdk/blob/a621ad5ddebf23067fec27529130d72718fc0e88/box-content-sdk/src/main/java/com/box/androidsdk/content/utils/SdkUtils.java#L453-L486 |
mikepenz/FastAdapter | app/src/main/java/com/mikepenz/fastadapter/app/helpers/HeaderPositionCalculator.java | HeaderPositionCalculator.getFirstViewUnobscuredByHeader | private View getFirstViewUnobscuredByHeader(RecyclerView parent, View firstHeader) {
"""
Returns the first item currently in the RecyclerView that is not obscured by a header.
@param parent Recyclerview containing all the list items
@return first item that is fully beneath a header
"""
boolean isReverseLayout = mOrientationProvider.isReverseLayout(parent);
int step = isReverseLayout ? -1 : 1;
int from = isReverseLayout ? parent.getChildCount() - 1 : 0;
for (int i = from; i >= 0 && i <= parent.getChildCount() - 1; i += step) {
View child = parent.getChildAt(i);
if (!itemIsObscuredByHeader(parent, child, firstHeader, mOrientationProvider.getOrientation(parent))) {
return child;
}
}
return null;
} | java | private View getFirstViewUnobscuredByHeader(RecyclerView parent, View firstHeader) {
boolean isReverseLayout = mOrientationProvider.isReverseLayout(parent);
int step = isReverseLayout ? -1 : 1;
int from = isReverseLayout ? parent.getChildCount() - 1 : 0;
for (int i = from; i >= 0 && i <= parent.getChildCount() - 1; i += step) {
View child = parent.getChildAt(i);
if (!itemIsObscuredByHeader(parent, child, firstHeader, mOrientationProvider.getOrientation(parent))) {
return child;
}
}
return null;
} | [
"private",
"View",
"getFirstViewUnobscuredByHeader",
"(",
"RecyclerView",
"parent",
",",
"View",
"firstHeader",
")",
"{",
"boolean",
"isReverseLayout",
"=",
"mOrientationProvider",
".",
"isReverseLayout",
"(",
"parent",
")",
";",
"int",
"step",
"=",
"isReverseLayout",
"?",
"-",
"1",
":",
"1",
";",
"int",
"from",
"=",
"isReverseLayout",
"?",
"parent",
".",
"getChildCount",
"(",
")",
"-",
"1",
":",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"from",
";",
"i",
">=",
"0",
"&&",
"i",
"<=",
"parent",
".",
"getChildCount",
"(",
")",
"-",
"1",
";",
"i",
"+=",
"step",
")",
"{",
"View",
"child",
"=",
"parent",
".",
"getChildAt",
"(",
"i",
")",
";",
"if",
"(",
"!",
"itemIsObscuredByHeader",
"(",
"parent",
",",
"child",
",",
"firstHeader",
",",
"mOrientationProvider",
".",
"getOrientation",
"(",
"parent",
")",
")",
")",
"{",
"return",
"child",
";",
"}",
"}",
"return",
"null",
";",
"}"
] | Returns the first item currently in the RecyclerView that is not obscured by a header.
@param parent Recyclerview containing all the list items
@return first item that is fully beneath a header | [
"Returns",
"the",
"first",
"item",
"currently",
"in",
"the",
"RecyclerView",
"that",
"is",
"not",
"obscured",
"by",
"a",
"header",
"."
] | train | https://github.com/mikepenz/FastAdapter/blob/3b2412abe001ba58422e0125846b704d4dba4ae9/app/src/main/java/com/mikepenz/fastadapter/app/helpers/HeaderPositionCalculator.java#L209-L220 |
agmip/agmip-common-functions | src/main/java/org/agmip/functions/PTSaxton2006.java | PTSaxton2006.getSLDUL | public static String getSLDUL(String[] soilParas) {
"""
For calculating SLDUL
@param soilParas should include 1. Sand weight percentage by layer
([0,100]%), 2. Clay weight percentage by layer ([0,100]%), 3. Organic
matter weight percentage by layer ([0,100]%), (= SLOC * 1.72)
@return Soil water, drained upper limit, fraction
"""
if (soilParas != null && soilParas.length >= 3) {
return divide(calcMoisture33Kpa(soilParas[0], soilParas[1], soilParas[2]), "100", 3);
} else {
return null;
}
} | java | public static String getSLDUL(String[] soilParas) {
if (soilParas != null && soilParas.length >= 3) {
return divide(calcMoisture33Kpa(soilParas[0], soilParas[1], soilParas[2]), "100", 3);
} else {
return null;
}
} | [
"public",
"static",
"String",
"getSLDUL",
"(",
"String",
"[",
"]",
"soilParas",
")",
"{",
"if",
"(",
"soilParas",
"!=",
"null",
"&&",
"soilParas",
".",
"length",
">=",
"3",
")",
"{",
"return",
"divide",
"(",
"calcMoisture33Kpa",
"(",
"soilParas",
"[",
"0",
"]",
",",
"soilParas",
"[",
"1",
"]",
",",
"soilParas",
"[",
"2",
"]",
")",
",",
"\"100\"",
",",
"3",
")",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}"
] | For calculating SLDUL
@param soilParas should include 1. Sand weight percentage by layer
([0,100]%), 2. Clay weight percentage by layer ([0,100]%), 3. Organic
matter weight percentage by layer ([0,100]%), (= SLOC * 1.72)
@return Soil water, drained upper limit, fraction | [
"For",
"calculating",
"SLDUL"
] | train | https://github.com/agmip/agmip-common-functions/blob/4efa3042178841b026ca6fba9c96da02fbfb9a8e/src/main/java/org/agmip/functions/PTSaxton2006.java#L47-L53 |
hyperledger/fabric-sdk-java | src/main/java/org/hyperledger/fabric/sdk/NetworkConfig.java | NetworkConfig.extractProperties | private static Properties extractProperties(JsonObject json, String fieldName) {
"""
Extracts all defined properties of the specified field and returns a Properties object
"""
Properties props = new Properties();
// Extract any other grpc options
JsonObject options = getJsonObject(json, fieldName);
if (options != null) {
for (Entry<String, JsonValue> entry : options.entrySet()) {
String key = entry.getKey();
JsonValue value = entry.getValue();
props.setProperty(key, getJsonValue(value));
}
}
return props;
} | java | private static Properties extractProperties(JsonObject json, String fieldName) {
Properties props = new Properties();
// Extract any other grpc options
JsonObject options = getJsonObject(json, fieldName);
if (options != null) {
for (Entry<String, JsonValue> entry : options.entrySet()) {
String key = entry.getKey();
JsonValue value = entry.getValue();
props.setProperty(key, getJsonValue(value));
}
}
return props;
} | [
"private",
"static",
"Properties",
"extractProperties",
"(",
"JsonObject",
"json",
",",
"String",
"fieldName",
")",
"{",
"Properties",
"props",
"=",
"new",
"Properties",
"(",
")",
";",
"// Extract any other grpc options",
"JsonObject",
"options",
"=",
"getJsonObject",
"(",
"json",
",",
"fieldName",
")",
";",
"if",
"(",
"options",
"!=",
"null",
")",
"{",
"for",
"(",
"Entry",
"<",
"String",
",",
"JsonValue",
">",
"entry",
":",
"options",
".",
"entrySet",
"(",
")",
")",
"{",
"String",
"key",
"=",
"entry",
".",
"getKey",
"(",
")",
";",
"JsonValue",
"value",
"=",
"entry",
".",
"getValue",
"(",
")",
";",
"props",
".",
"setProperty",
"(",
"key",
",",
"getJsonValue",
"(",
"value",
")",
")",
";",
"}",
"}",
"return",
"props",
";",
"}"
] | Extracts all defined properties of the specified field and returns a Properties object | [
"Extracts",
"all",
"defined",
"properties",
"of",
"the",
"specified",
"field",
"and",
"returns",
"a",
"Properties",
"object"
] | train | https://github.com/hyperledger/fabric-sdk-java/blob/4a2d7b3408b8b0a1ed812aa36942c438159c37a0/src/main/java/org/hyperledger/fabric/sdk/NetworkConfig.java#L1008-L1022 |
mockito/mockito | src/main/java/org/mockito/internal/matchers/apachecommons/EqualsBuilder.java | EqualsBuilder.reflectionEquals | public static boolean reflectionEquals(Object lhs, Object rhs, boolean testTransients, Class<?> reflectUpToClass) {
"""
<p>This method uses reflection to determine if the two <code>Object</code>s
are equal.</p>
<p>It uses <code>AccessibleObject.setAccessible</code> to gain access to private
fields. This means that it will throw a security exception if run under
a security manager, if the permissions are not set up correctly. It is also
not as efficient as testing explicitly.</p>
<p>If the testTransients parameter is set to <code>true</code>, transient
members will be tested, otherwise they are ignored, as they are likely
derived fields, and not part of the value of the <code>Object</code>.</p>
<p>Static fields will not be included. Superclass fields will be appended
up to and including the specified superclass. A null superclass is treated
as java.lang.Object.</p>
@param lhs <code>this</code> object
@param rhs the other object
@param testTransients whether to include transient fields
@param reflectUpToClass the superclass to reflect up to (inclusive),
may be <code>null</code>
@return <code>true</code> if the two Objects have tested equals.
@since 2.1.0
"""
return reflectionEquals(lhs, rhs, testTransients, reflectUpToClass, null);
} | java | public static boolean reflectionEquals(Object lhs, Object rhs, boolean testTransients, Class<?> reflectUpToClass) {
return reflectionEquals(lhs, rhs, testTransients, reflectUpToClass, null);
} | [
"public",
"static",
"boolean",
"reflectionEquals",
"(",
"Object",
"lhs",
",",
"Object",
"rhs",
",",
"boolean",
"testTransients",
",",
"Class",
"<",
"?",
">",
"reflectUpToClass",
")",
"{",
"return",
"reflectionEquals",
"(",
"lhs",
",",
"rhs",
",",
"testTransients",
",",
"reflectUpToClass",
",",
"null",
")",
";",
"}"
] | <p>This method uses reflection to determine if the two <code>Object</code>s
are equal.</p>
<p>It uses <code>AccessibleObject.setAccessible</code> to gain access to private
fields. This means that it will throw a security exception if run under
a security manager, if the permissions are not set up correctly. It is also
not as efficient as testing explicitly.</p>
<p>If the testTransients parameter is set to <code>true</code>, transient
members will be tested, otherwise they are ignored, as they are likely
derived fields, and not part of the value of the <code>Object</code>.</p>
<p>Static fields will not be included. Superclass fields will be appended
up to and including the specified superclass. A null superclass is treated
as java.lang.Object.</p>
@param lhs <code>this</code> object
@param rhs the other object
@param testTransients whether to include transient fields
@param reflectUpToClass the superclass to reflect up to (inclusive),
may be <code>null</code>
@return <code>true</code> if the two Objects have tested equals.
@since 2.1.0 | [
"<p",
">",
"This",
"method",
"uses",
"reflection",
"to",
"determine",
"if",
"the",
"two",
"<code",
">",
"Object<",
"/",
"code",
">",
"s",
"are",
"equal",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/mockito/mockito/blob/c5e2b80af76e3192cae7c9550b70c4d1ab312034/src/main/java/org/mockito/internal/matchers/apachecommons/EqualsBuilder.java#L191-L193 |
kevinherron/opc-ua-stack | stack-core/src/main/java/com/digitalpetri/opcua/stack/core/types/builtin/DataValue.java | DataValue.derivedValue | public static DataValue derivedValue(DataValue from, TimestampsToReturn timestamps) {
"""
Derive a new {@link DataValue} from a given {@link DataValue}.
@param from the {@link DataValue} to derive from.
@param timestamps the timestamps to return in the derived value.
@return a derived {@link DataValue}.
"""
boolean includeSource = timestamps == TimestampsToReturn.Source || timestamps == TimestampsToReturn.Both;
boolean includeServer = timestamps == TimestampsToReturn.Server || timestamps == TimestampsToReturn.Both;
return new DataValue(
from.value,
from.status,
includeSource ? from.sourceTime : null,
includeServer ? from.serverTime : null
);
} | java | public static DataValue derivedValue(DataValue from, TimestampsToReturn timestamps) {
boolean includeSource = timestamps == TimestampsToReturn.Source || timestamps == TimestampsToReturn.Both;
boolean includeServer = timestamps == TimestampsToReturn.Server || timestamps == TimestampsToReturn.Both;
return new DataValue(
from.value,
from.status,
includeSource ? from.sourceTime : null,
includeServer ? from.serverTime : null
);
} | [
"public",
"static",
"DataValue",
"derivedValue",
"(",
"DataValue",
"from",
",",
"TimestampsToReturn",
"timestamps",
")",
"{",
"boolean",
"includeSource",
"=",
"timestamps",
"==",
"TimestampsToReturn",
".",
"Source",
"||",
"timestamps",
"==",
"TimestampsToReturn",
".",
"Both",
";",
"boolean",
"includeServer",
"=",
"timestamps",
"==",
"TimestampsToReturn",
".",
"Server",
"||",
"timestamps",
"==",
"TimestampsToReturn",
".",
"Both",
";",
"return",
"new",
"DataValue",
"(",
"from",
".",
"value",
",",
"from",
".",
"status",
",",
"includeSource",
"?",
"from",
".",
"sourceTime",
":",
"null",
",",
"includeServer",
"?",
"from",
".",
"serverTime",
":",
"null",
")",
";",
"}"
] | Derive a new {@link DataValue} from a given {@link DataValue}.
@param from the {@link DataValue} to derive from.
@param timestamps the timestamps to return in the derived value.
@return a derived {@link DataValue}. | [
"Derive",
"a",
"new",
"{",
"@link",
"DataValue",
"}",
"from",
"a",
"given",
"{",
"@link",
"DataValue",
"}",
"."
] | train | https://github.com/kevinherron/opc-ua-stack/blob/007f4e5c4ff102814bec17bb7c41f27e2e52f2fd/stack-core/src/main/java/com/digitalpetri/opcua/stack/core/types/builtin/DataValue.java#L136-L146 |
orbisgis/h2gis | h2gis-functions/src/main/java/org/h2gis/functions/io/kml/KMLGeometry.java | KMLGeometry.toKMLGeometry | public static void toKMLGeometry(Geometry geometry, ExtrudeMode extrude, int altitudeModeEnum, StringBuilder sb) throws SQLException {
"""
Convert JTS geometry to a kml geometry representation.
@param geometry
@param extrude
@param altitudeModeEnum
@param sb
"""
if (geometry instanceof Point) {
toKMLPoint((Point) geometry, extrude, altitudeModeEnum, sb);
} else if (geometry instanceof LineString) {
toKMLLineString((LineString) geometry, extrude, altitudeModeEnum, sb);
} else if (geometry instanceof Polygon) {
toKMLPolygon((Polygon) geometry, extrude, altitudeModeEnum, sb);
} else if (geometry instanceof GeometryCollection) {
toKMLMultiGeometry((GeometryCollection) geometry, extrude, altitudeModeEnum, sb);
} else {
throw new SQLException("This geometry type is not supported : " + geometry.toString());
}
} | java | public static void toKMLGeometry(Geometry geometry, ExtrudeMode extrude, int altitudeModeEnum, StringBuilder sb) throws SQLException {
if (geometry instanceof Point) {
toKMLPoint((Point) geometry, extrude, altitudeModeEnum, sb);
} else if (geometry instanceof LineString) {
toKMLLineString((LineString) geometry, extrude, altitudeModeEnum, sb);
} else if (geometry instanceof Polygon) {
toKMLPolygon((Polygon) geometry, extrude, altitudeModeEnum, sb);
} else if (geometry instanceof GeometryCollection) {
toKMLMultiGeometry((GeometryCollection) geometry, extrude, altitudeModeEnum, sb);
} else {
throw new SQLException("This geometry type is not supported : " + geometry.toString());
}
} | [
"public",
"static",
"void",
"toKMLGeometry",
"(",
"Geometry",
"geometry",
",",
"ExtrudeMode",
"extrude",
",",
"int",
"altitudeModeEnum",
",",
"StringBuilder",
"sb",
")",
"throws",
"SQLException",
"{",
"if",
"(",
"geometry",
"instanceof",
"Point",
")",
"{",
"toKMLPoint",
"(",
"(",
"Point",
")",
"geometry",
",",
"extrude",
",",
"altitudeModeEnum",
",",
"sb",
")",
";",
"}",
"else",
"if",
"(",
"geometry",
"instanceof",
"LineString",
")",
"{",
"toKMLLineString",
"(",
"(",
"LineString",
")",
"geometry",
",",
"extrude",
",",
"altitudeModeEnum",
",",
"sb",
")",
";",
"}",
"else",
"if",
"(",
"geometry",
"instanceof",
"Polygon",
")",
"{",
"toKMLPolygon",
"(",
"(",
"Polygon",
")",
"geometry",
",",
"extrude",
",",
"altitudeModeEnum",
",",
"sb",
")",
";",
"}",
"else",
"if",
"(",
"geometry",
"instanceof",
"GeometryCollection",
")",
"{",
"toKMLMultiGeometry",
"(",
"(",
"GeometryCollection",
")",
"geometry",
",",
"extrude",
",",
"altitudeModeEnum",
",",
"sb",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"SQLException",
"(",
"\"This geometry type is not supported : \"",
"+",
"geometry",
".",
"toString",
"(",
")",
")",
";",
"}",
"}"
] | Convert JTS geometry to a kml geometry representation.
@param geometry
@param extrude
@param altitudeModeEnum
@param sb | [
"Convert",
"JTS",
"geometry",
"to",
"a",
"kml",
"geometry",
"representation",
"."
] | train | https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/io/kml/KMLGeometry.java#L56-L68 |
scaleset/scaleset-geo | src/main/java/com/scaleset/geo/math/GoogleMapsTileMath.java | GoogleMapsTileMath.tileBbox | public Envelope tileBbox(int tx, int ty, int zoomLevel) {
"""
Returns the EPSG:3857 bounding of the specified tile coordinate
@param tx The tile x coordinate
@param ty The tile y coordinate
@param zoomLevel The tile zoom level
@return the EPSG:3857 bounding box
"""
Coordinate topLeft = tileTopLeft(tx, ty, zoomLevel);
// upperLeft of tx+1,ty+1 == lowRight
Coordinate lowerRight = tileTopLeft(tx + 1, ty + 1, zoomLevel);
Envelope result = new Envelope(topLeft, lowerRight);
return result;
} | java | public Envelope tileBbox(int tx, int ty, int zoomLevel) {
Coordinate topLeft = tileTopLeft(tx, ty, zoomLevel);
// upperLeft of tx+1,ty+1 == lowRight
Coordinate lowerRight = tileTopLeft(tx + 1, ty + 1, zoomLevel);
Envelope result = new Envelope(topLeft, lowerRight);
return result;
} | [
"public",
"Envelope",
"tileBbox",
"(",
"int",
"tx",
",",
"int",
"ty",
",",
"int",
"zoomLevel",
")",
"{",
"Coordinate",
"topLeft",
"=",
"tileTopLeft",
"(",
"tx",
",",
"ty",
",",
"zoomLevel",
")",
";",
"// upperLeft of tx+1,ty+1 == lowRight",
"Coordinate",
"lowerRight",
"=",
"tileTopLeft",
"(",
"tx",
"+",
"1",
",",
"ty",
"+",
"1",
",",
"zoomLevel",
")",
";",
"Envelope",
"result",
"=",
"new",
"Envelope",
"(",
"topLeft",
",",
"lowerRight",
")",
";",
"return",
"result",
";",
"}"
] | Returns the EPSG:3857 bounding of the specified tile coordinate
@param tx The tile x coordinate
@param ty The tile y coordinate
@param zoomLevel The tile zoom level
@return the EPSG:3857 bounding box | [
"Returns",
"the",
"EPSG",
":",
"3857",
"bounding",
"of",
"the",
"specified",
"tile",
"coordinate"
] | train | https://github.com/scaleset/scaleset-geo/blob/5cff2349668037dc287928a6c1a1f67c76d96b02/src/main/java/com/scaleset/geo/math/GoogleMapsTileMath.java#L285-L291 |
RobotiumTech/robotium | robotium-solo/src/main/java/com/robotium/solo/Solo.java | Solo.getView | public View getView(int id, int index) {
"""
Returns a View matching the specified resource id and index.
@param id the R.id of the {@link View} to return
@param index the index of the {@link View}. {@code 0} if only one is available
@return a {@link View} matching the specified id and index
"""
if(config.commandLogging){
Log.d(config.commandLoggingTag, "getView("+id+", "+index+")");
}
View viewToReturn = getter.getView(id, index);
if(viewToReturn == null) {
String resourceName = "";
try {
resourceName = instrumentation.getTargetContext().getResources().getResourceEntryName(id);
} catch (Exception e) {
Log.d(config.commandLoggingTag, "unable to get resource entry name for ("+id+")");
}
int match = index + 1;
if(match > 1){
Assert.fail(match + " Views with id: '" + id + "', resource name: '" + resourceName + "' are not found!");
}
else {
Assert.fail("View with id: '" + id + "', resource name: '" + resourceName + "' is not found!");
}
}
return viewToReturn;
} | java | public View getView(int id, int index){
if(config.commandLogging){
Log.d(config.commandLoggingTag, "getView("+id+", "+index+")");
}
View viewToReturn = getter.getView(id, index);
if(viewToReturn == null) {
String resourceName = "";
try {
resourceName = instrumentation.getTargetContext().getResources().getResourceEntryName(id);
} catch (Exception e) {
Log.d(config.commandLoggingTag, "unable to get resource entry name for ("+id+")");
}
int match = index + 1;
if(match > 1){
Assert.fail(match + " Views with id: '" + id + "', resource name: '" + resourceName + "' are not found!");
}
else {
Assert.fail("View with id: '" + id + "', resource name: '" + resourceName + "' is not found!");
}
}
return viewToReturn;
} | [
"public",
"View",
"getView",
"(",
"int",
"id",
",",
"int",
"index",
")",
"{",
"if",
"(",
"config",
".",
"commandLogging",
")",
"{",
"Log",
".",
"d",
"(",
"config",
".",
"commandLoggingTag",
",",
"\"getView(\"",
"+",
"id",
"+",
"\", \"",
"+",
"index",
"+",
"\")\"",
")",
";",
"}",
"View",
"viewToReturn",
"=",
"getter",
".",
"getView",
"(",
"id",
",",
"index",
")",
";",
"if",
"(",
"viewToReturn",
"==",
"null",
")",
"{",
"String",
"resourceName",
"=",
"\"\"",
";",
"try",
"{",
"resourceName",
"=",
"instrumentation",
".",
"getTargetContext",
"(",
")",
".",
"getResources",
"(",
")",
".",
"getResourceEntryName",
"(",
"id",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"Log",
".",
"d",
"(",
"config",
".",
"commandLoggingTag",
",",
"\"unable to get resource entry name for (\"",
"+",
"id",
"+",
"\")\"",
")",
";",
"}",
"int",
"match",
"=",
"index",
"+",
"1",
";",
"if",
"(",
"match",
">",
"1",
")",
"{",
"Assert",
".",
"fail",
"(",
"match",
"+",
"\" Views with id: '\"",
"+",
"id",
"+",
"\"', resource name: '\"",
"+",
"resourceName",
"+",
"\"' are not found!\"",
")",
";",
"}",
"else",
"{",
"Assert",
".",
"fail",
"(",
"\"View with id: '\"",
"+",
"id",
"+",
"\"', resource name: '\"",
"+",
"resourceName",
"+",
"\"' is not found!\"",
")",
";",
"}",
"}",
"return",
"viewToReturn",
";",
"}"
] | Returns a View matching the specified resource id and index.
@param id the R.id of the {@link View} to return
@param index the index of the {@link View}. {@code 0} if only one is available
@return a {@link View} matching the specified id and index | [
"Returns",
"a",
"View",
"matching",
"the",
"specified",
"resource",
"id",
"and",
"index",
"."
] | train | https://github.com/RobotiumTech/robotium/blob/75e567c38f26a6a87dc8bef90b3886a20e28d291/robotium-solo/src/main/java/com/robotium/solo/Solo.java#L3041-L3064 |
hector-client/hector | core/src/main/java/me/prettyprint/cassandra/service/template/SuperCfTemplate.java | SuperCfTemplate.querySuperColumns | public SuperCfResult<K, SN, N> querySuperColumns(K key, HSlicePredicate<SN> predicate) {
"""
Query super columns using the provided predicate instead of the internal one
@param key
@param predicate
@return
"""
return doExecuteSlice(key,null,predicate);
} | java | public SuperCfResult<K, SN, N> querySuperColumns(K key, HSlicePredicate<SN> predicate) {
return doExecuteSlice(key,null,predicate);
} | [
"public",
"SuperCfResult",
"<",
"K",
",",
"SN",
",",
"N",
">",
"querySuperColumns",
"(",
"K",
"key",
",",
"HSlicePredicate",
"<",
"SN",
">",
"predicate",
")",
"{",
"return",
"doExecuteSlice",
"(",
"key",
",",
"null",
",",
"predicate",
")",
";",
"}"
] | Query super columns using the provided predicate instead of the internal one
@param key
@param predicate
@return | [
"Query",
"super",
"columns",
"using",
"the",
"provided",
"predicate",
"instead",
"of",
"the",
"internal",
"one"
] | train | https://github.com/hector-client/hector/blob/a302e68ca8d91b45d332e8c9afd7d98030b54de1/core/src/main/java/me/prettyprint/cassandra/service/template/SuperCfTemplate.java#L146-L148 |
headius/invokebinder | src/main/java/com/headius/invokebinder/Binder.java | Binder.invokeVirtual | public MethodHandle invokeVirtual(MethodHandles.Lookup lookup, String name) throws NoSuchMethodException, IllegalAccessException {
"""
Apply the chain of transforms and bind them to a virtual method specified
using the end signature plus the given class and name. The method will
be retrieved using the given Lookup and must match the end signature
exactly.
If the final handle's type does not exactly match the initial type for
this Binder, an additional cast will be attempted.
@param lookup the MethodHandles.Lookup to use to look up the method
@param name the name of the method to invoke
@return the full handle chain, bound to the given method
@throws java.lang.NoSuchMethodException if the method does not exist
@throws java.lang.IllegalAccessException if the method is not accessible
"""
return invoke(lookup.findVirtual(type().parameterType(0), name, type().dropParameterTypes(0, 1)));
} | java | public MethodHandle invokeVirtual(MethodHandles.Lookup lookup, String name) throws NoSuchMethodException, IllegalAccessException {
return invoke(lookup.findVirtual(type().parameterType(0), name, type().dropParameterTypes(0, 1)));
} | [
"public",
"MethodHandle",
"invokeVirtual",
"(",
"MethodHandles",
".",
"Lookup",
"lookup",
",",
"String",
"name",
")",
"throws",
"NoSuchMethodException",
",",
"IllegalAccessException",
"{",
"return",
"invoke",
"(",
"lookup",
".",
"findVirtual",
"(",
"type",
"(",
")",
".",
"parameterType",
"(",
"0",
")",
",",
"name",
",",
"type",
"(",
")",
".",
"dropParameterTypes",
"(",
"0",
",",
"1",
")",
")",
")",
";",
"}"
] | Apply the chain of transforms and bind them to a virtual method specified
using the end signature plus the given class and name. The method will
be retrieved using the given Lookup and must match the end signature
exactly.
If the final handle's type does not exactly match the initial type for
this Binder, an additional cast will be attempted.
@param lookup the MethodHandles.Lookup to use to look up the method
@param name the name of the method to invoke
@return the full handle chain, bound to the given method
@throws java.lang.NoSuchMethodException if the method does not exist
@throws java.lang.IllegalAccessException if the method is not accessible | [
"Apply",
"the",
"chain",
"of",
"transforms",
"and",
"bind",
"them",
"to",
"a",
"virtual",
"method",
"specified",
"using",
"the",
"end",
"signature",
"plus",
"the",
"given",
"class",
"and",
"name",
".",
"The",
"method",
"will",
"be",
"retrieved",
"using",
"the",
"given",
"Lookup",
"and",
"must",
"match",
"the",
"end",
"signature",
"exactly",
"."
] | train | https://github.com/headius/invokebinder/blob/ce6bfeb8e33265480daa7b797989dd915d51238d/src/main/java/com/headius/invokebinder/Binder.java#L1254-L1256 |
igniterealtime/Smack | smack-core/src/main/java/org/jivesoftware/smack/util/PacketUtil.java | PacketUtil.packetExtensionfromCollection | @Deprecated
public static <PE extends ExtensionElement> PE packetExtensionfromCollection(
Collection<ExtensionElement> collection, String element,
String namespace) {
"""
Get a extension element from a collection.
@param collection
@param element
@param namespace
@param <PE>
@return the extension element
@deprecated use {@link #extensionElementFrom(Collection, String, String)} instead.
"""
return extensionElementFrom(collection, element, namespace);
} | java | @Deprecated
public static <PE extends ExtensionElement> PE packetExtensionfromCollection(
Collection<ExtensionElement> collection, String element,
String namespace) {
return extensionElementFrom(collection, element, namespace);
} | [
"@",
"Deprecated",
"public",
"static",
"<",
"PE",
"extends",
"ExtensionElement",
">",
"PE",
"packetExtensionfromCollection",
"(",
"Collection",
"<",
"ExtensionElement",
">",
"collection",
",",
"String",
"element",
",",
"String",
"namespace",
")",
"{",
"return",
"extensionElementFrom",
"(",
"collection",
",",
"element",
",",
"namespace",
")",
";",
"}"
] | Get a extension element from a collection.
@param collection
@param element
@param namespace
@param <PE>
@return the extension element
@deprecated use {@link #extensionElementFrom(Collection, String, String)} instead. | [
"Get",
"a",
"extension",
"element",
"from",
"a",
"collection",
"."
] | train | https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-core/src/main/java/org/jivesoftware/smack/util/PacketUtil.java#L34-L39 |
pmwmedia/tinylog | tinylog-impl/src/main/java/org/tinylog/writers/JdbcWriter.java | JdbcWriter.getTable | private static String getTable(final Map<String, String> properties) {
"""
Extracts the database table name from configuration.
@param properties
Configuration for writer
@return Name of database table
@throws IllegalArgumentException
Table is not defined in configuration
"""
String table = properties.get("table");
if (table == null) {
throw new IllegalArgumentException("Name of database table is missing for JDBC writer");
} else {
return table;
}
} | java | private static String getTable(final Map<String, String> properties) {
String table = properties.get("table");
if (table == null) {
throw new IllegalArgumentException("Name of database table is missing for JDBC writer");
} else {
return table;
}
} | [
"private",
"static",
"String",
"getTable",
"(",
"final",
"Map",
"<",
"String",
",",
"String",
">",
"properties",
")",
"{",
"String",
"table",
"=",
"properties",
".",
"get",
"(",
"\"table\"",
")",
";",
"if",
"(",
"table",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Name of database table is missing for JDBC writer\"",
")",
";",
"}",
"else",
"{",
"return",
"table",
";",
"}",
"}"
] | Extracts the database table name from configuration.
@param properties
Configuration for writer
@return Name of database table
@throws IllegalArgumentException
Table is not defined in configuration | [
"Extracts",
"the",
"database",
"table",
"name",
"from",
"configuration",
"."
] | train | https://github.com/pmwmedia/tinylog/blob/d03d4ef84a1310155037e08ca8822a91697d1086/tinylog-impl/src/main/java/org/tinylog/writers/JdbcWriter.java#L341-L348 |
pravega/pravega | controller/src/main/java/io/pravega/controller/task/Stream/StreamTransactionMetadataTasks.java | StreamTransactionMetadataTasks.sealTxnBody | CompletableFuture<TxnStatus> sealTxnBody(final String host,
final String scope,
final String stream,
final boolean commit,
final UUID txnId,
final Version version,
final OperationContext ctx) {
"""
Seals a txn and transitions it to COMMITTING (resp. ABORTING) state if commit param is true (resp. false).
Post-condition:
1. If seal completes successfully, then
(a) txn state is COMMITTING/ABORTING,
(b) CommitEvent/AbortEvent is present in the commit stream/abort stream,
(c) txn is removed from host-txn index,
(d) txn is removed from the timeout service.
2. If process fails after transitioning txn to COMMITTING/ABORTING state, but before responding to client, then
since txn is present in the host-txn index, some other controller process shall put CommitEvent/AbortEvent to
commit stream/abort stream.
@param host host id. It is different from hostId iff invoked from TxnSweeper for aborting orphaned txn.
@param scope scope name.
@param stream stream name.
@param commit boolean indicating whether to commit txn.
@param txnId txn id.
@param version expected version of txn node in store.
@param ctx context.
@return Txn status after sealing it.
"""
TxnResource resource = new TxnResource(scope, stream, txnId);
Optional<Version> versionOpt = Optional.ofNullable(version);
// Step 1. Add txn to current host's index, if it is not already present
CompletableFuture<Void> addIndex = host.equals(hostId) && !timeoutService.containsTxn(scope, stream, txnId) ?
// PS: txn version in index does not matter, because if update is successful,
// then txn would no longer be open.
streamMetadataStore.addTxnToIndex(hostId, resource, version) :
CompletableFuture.completedFuture(null);
addIndex.whenComplete((v, e) -> {
if (e != null) {
log.debug("Txn={}, already present/newly added to host-txn index of host={}", txnId, hostId);
} else {
log.debug("Txn={}, added txn to host-txn index of host={}", txnId, hostId);
}
});
// Step 2. Seal txn
CompletableFuture<AbstractMap.SimpleEntry<TxnStatus, Integer>> sealFuture = addIndex.thenComposeAsync(x ->
streamMetadataStore.sealTransaction(scope, stream, txnId, commit, versionOpt, ctx, executor), executor)
.whenComplete((v, e) -> {
if (e != null) {
log.debug("Txn={}, failed sealing txn", txnId);
} else {
log.debug("Txn={}, sealed successfully, commit={}", txnId, commit);
}
});
// Step 3. write event to corresponding stream.
return sealFuture.thenComposeAsync(pair -> {
TxnStatus status = pair.getKey();
switch (status) {
case COMMITTING:
return writeCommitEvent(scope, stream, pair.getValue(), txnId, status);
case ABORTING:
return writeAbortEvent(scope, stream, pair.getValue(), txnId, status);
case ABORTED:
case COMMITTED:
return CompletableFuture.completedFuture(status);
case OPEN:
case UNKNOWN:
default:
// Not possible after successful streamStore.sealTransaction call, because otherwise an
// exception would be thrown.
return CompletableFuture.completedFuture(status);
}
}, executor).thenComposeAsync(status -> {
// Step 4. Remove txn from timeoutService, and from the index.
timeoutService.removeTxn(scope, stream, txnId);
log.debug("Txn={}, removed from timeout service", txnId);
return streamMetadataStore.removeTxnFromIndex(host, resource, true).whenComplete((v, e) -> {
if (e != null) {
log.debug("Txn={}, failed removing txn from host-txn index of host={}", txnId, hostId);
} else {
log.debug("Txn={}, removed txn from host-txn index of host={}", txnId, hostId);
}
}).thenApply(x -> status);
}, executor);
} | java | CompletableFuture<TxnStatus> sealTxnBody(final String host,
final String scope,
final String stream,
final boolean commit,
final UUID txnId,
final Version version,
final OperationContext ctx) {
TxnResource resource = new TxnResource(scope, stream, txnId);
Optional<Version> versionOpt = Optional.ofNullable(version);
// Step 1. Add txn to current host's index, if it is not already present
CompletableFuture<Void> addIndex = host.equals(hostId) && !timeoutService.containsTxn(scope, stream, txnId) ?
// PS: txn version in index does not matter, because if update is successful,
// then txn would no longer be open.
streamMetadataStore.addTxnToIndex(hostId, resource, version) :
CompletableFuture.completedFuture(null);
addIndex.whenComplete((v, e) -> {
if (e != null) {
log.debug("Txn={}, already present/newly added to host-txn index of host={}", txnId, hostId);
} else {
log.debug("Txn={}, added txn to host-txn index of host={}", txnId, hostId);
}
});
// Step 2. Seal txn
CompletableFuture<AbstractMap.SimpleEntry<TxnStatus, Integer>> sealFuture = addIndex.thenComposeAsync(x ->
streamMetadataStore.sealTransaction(scope, stream, txnId, commit, versionOpt, ctx, executor), executor)
.whenComplete((v, e) -> {
if (e != null) {
log.debug("Txn={}, failed sealing txn", txnId);
} else {
log.debug("Txn={}, sealed successfully, commit={}", txnId, commit);
}
});
// Step 3. write event to corresponding stream.
return sealFuture.thenComposeAsync(pair -> {
TxnStatus status = pair.getKey();
switch (status) {
case COMMITTING:
return writeCommitEvent(scope, stream, pair.getValue(), txnId, status);
case ABORTING:
return writeAbortEvent(scope, stream, pair.getValue(), txnId, status);
case ABORTED:
case COMMITTED:
return CompletableFuture.completedFuture(status);
case OPEN:
case UNKNOWN:
default:
// Not possible after successful streamStore.sealTransaction call, because otherwise an
// exception would be thrown.
return CompletableFuture.completedFuture(status);
}
}, executor).thenComposeAsync(status -> {
// Step 4. Remove txn from timeoutService, and from the index.
timeoutService.removeTxn(scope, stream, txnId);
log.debug("Txn={}, removed from timeout service", txnId);
return streamMetadataStore.removeTxnFromIndex(host, resource, true).whenComplete((v, e) -> {
if (e != null) {
log.debug("Txn={}, failed removing txn from host-txn index of host={}", txnId, hostId);
} else {
log.debug("Txn={}, removed txn from host-txn index of host={}", txnId, hostId);
}
}).thenApply(x -> status);
}, executor);
} | [
"CompletableFuture",
"<",
"TxnStatus",
">",
"sealTxnBody",
"(",
"final",
"String",
"host",
",",
"final",
"String",
"scope",
",",
"final",
"String",
"stream",
",",
"final",
"boolean",
"commit",
",",
"final",
"UUID",
"txnId",
",",
"final",
"Version",
"version",
",",
"final",
"OperationContext",
"ctx",
")",
"{",
"TxnResource",
"resource",
"=",
"new",
"TxnResource",
"(",
"scope",
",",
"stream",
",",
"txnId",
")",
";",
"Optional",
"<",
"Version",
">",
"versionOpt",
"=",
"Optional",
".",
"ofNullable",
"(",
"version",
")",
";",
"// Step 1. Add txn to current host's index, if it is not already present",
"CompletableFuture",
"<",
"Void",
">",
"addIndex",
"=",
"host",
".",
"equals",
"(",
"hostId",
")",
"&&",
"!",
"timeoutService",
".",
"containsTxn",
"(",
"scope",
",",
"stream",
",",
"txnId",
")",
"?",
"// PS: txn version in index does not matter, because if update is successful,",
"// then txn would no longer be open.",
"streamMetadataStore",
".",
"addTxnToIndex",
"(",
"hostId",
",",
"resource",
",",
"version",
")",
":",
"CompletableFuture",
".",
"completedFuture",
"(",
"null",
")",
";",
"addIndex",
".",
"whenComplete",
"(",
"(",
"v",
",",
"e",
")",
"->",
"{",
"if",
"(",
"e",
"!=",
"null",
")",
"{",
"log",
".",
"debug",
"(",
"\"Txn={}, already present/newly added to host-txn index of host={}\"",
",",
"txnId",
",",
"hostId",
")",
";",
"}",
"else",
"{",
"log",
".",
"debug",
"(",
"\"Txn={}, added txn to host-txn index of host={}\"",
",",
"txnId",
",",
"hostId",
")",
";",
"}",
"}",
")",
";",
"// Step 2. Seal txn",
"CompletableFuture",
"<",
"AbstractMap",
".",
"SimpleEntry",
"<",
"TxnStatus",
",",
"Integer",
">",
">",
"sealFuture",
"=",
"addIndex",
".",
"thenComposeAsync",
"(",
"x",
"->",
"streamMetadataStore",
".",
"sealTransaction",
"(",
"scope",
",",
"stream",
",",
"txnId",
",",
"commit",
",",
"versionOpt",
",",
"ctx",
",",
"executor",
")",
",",
"executor",
")",
".",
"whenComplete",
"(",
"(",
"v",
",",
"e",
")",
"->",
"{",
"if",
"(",
"e",
"!=",
"null",
")",
"{",
"log",
".",
"debug",
"(",
"\"Txn={}, failed sealing txn\"",
",",
"txnId",
")",
";",
"}",
"else",
"{",
"log",
".",
"debug",
"(",
"\"Txn={}, sealed successfully, commit={}\"",
",",
"txnId",
",",
"commit",
")",
";",
"}",
"}",
")",
";",
"// Step 3. write event to corresponding stream.",
"return",
"sealFuture",
".",
"thenComposeAsync",
"(",
"pair",
"->",
"{",
"TxnStatus",
"status",
"=",
"pair",
".",
"getKey",
"(",
")",
";",
"switch",
"(",
"status",
")",
"{",
"case",
"COMMITTING",
":",
"return",
"writeCommitEvent",
"(",
"scope",
",",
"stream",
",",
"pair",
".",
"getValue",
"(",
")",
",",
"txnId",
",",
"status",
")",
";",
"case",
"ABORTING",
":",
"return",
"writeAbortEvent",
"(",
"scope",
",",
"stream",
",",
"pair",
".",
"getValue",
"(",
")",
",",
"txnId",
",",
"status",
")",
";",
"case",
"ABORTED",
":",
"case",
"COMMITTED",
":",
"return",
"CompletableFuture",
".",
"completedFuture",
"(",
"status",
")",
";",
"case",
"OPEN",
":",
"case",
"UNKNOWN",
":",
"default",
":",
"// Not possible after successful streamStore.sealTransaction call, because otherwise an",
"// exception would be thrown.",
"return",
"CompletableFuture",
".",
"completedFuture",
"(",
"status",
")",
";",
"}",
"}",
",",
"executor",
")",
".",
"thenComposeAsync",
"(",
"status",
"->",
"{",
"// Step 4. Remove txn from timeoutService, and from the index.",
"timeoutService",
".",
"removeTxn",
"(",
"scope",
",",
"stream",
",",
"txnId",
")",
";",
"log",
".",
"debug",
"(",
"\"Txn={}, removed from timeout service\"",
",",
"txnId",
")",
";",
"return",
"streamMetadataStore",
".",
"removeTxnFromIndex",
"(",
"host",
",",
"resource",
",",
"true",
")",
".",
"whenComplete",
"(",
"(",
"v",
",",
"e",
")",
"->",
"{",
"if",
"(",
"e",
"!=",
"null",
")",
"{",
"log",
".",
"debug",
"(",
"\"Txn={}, failed removing txn from host-txn index of host={}\"",
",",
"txnId",
",",
"hostId",
")",
";",
"}",
"else",
"{",
"log",
".",
"debug",
"(",
"\"Txn={}, removed txn from host-txn index of host={}\"",
",",
"txnId",
",",
"hostId",
")",
";",
"}",
"}",
")",
".",
"thenApply",
"(",
"x",
"->",
"status",
")",
";",
"}",
",",
"executor",
")",
";",
"}"
] | Seals a txn and transitions it to COMMITTING (resp. ABORTING) state if commit param is true (resp. false).
Post-condition:
1. If seal completes successfully, then
(a) txn state is COMMITTING/ABORTING,
(b) CommitEvent/AbortEvent is present in the commit stream/abort stream,
(c) txn is removed from host-txn index,
(d) txn is removed from the timeout service.
2. If process fails after transitioning txn to COMMITTING/ABORTING state, but before responding to client, then
since txn is present in the host-txn index, some other controller process shall put CommitEvent/AbortEvent to
commit stream/abort stream.
@param host host id. It is different from hostId iff invoked from TxnSweeper for aborting orphaned txn.
@param scope scope name.
@param stream stream name.
@param commit boolean indicating whether to commit txn.
@param txnId txn id.
@param version expected version of txn node in store.
@param ctx context.
@return Txn status after sealing it. | [
"Seals",
"a",
"txn",
"and",
"transitions",
"it",
"to",
"COMMITTING",
"(",
"resp",
".",
"ABORTING",
")",
"state",
"if",
"commit",
"param",
"is",
"true",
"(",
"resp",
".",
"false",
")",
"."
] | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/controller/src/main/java/io/pravega/controller/task/Stream/StreamTransactionMetadataTasks.java#L539-L605 |
m-m-m/util | reflect/src/main/java/net/sf/mmm/util/reflect/base/ManifestLoader.java | ManifestLoader.getValue | public static String getValue(Manifest manifest, Attributes.Name name) {
"""
This method gets an attribute-value from a {@link Manifest} in a pragmatic way. It tries to
{@link Attributes#getValue(java.util.jar.Attributes.Name) get} the value from the
{@link Manifest#getMainAttributes() main-attributes}. If NOT available it searches all other
{@link Manifest#getEntries() available attribute entries} for the value and returns the first one found
in deterministic but unspecified order.
@param manifest is the {@link Manifest} where to get the attribute-value from.
@param name is the {@link java.util.jar.Attributes.Name} of the requested attribute.
@return the requested value or {@code null} if NOT available.
@since 2.0.0
"""
String value = manifest.getMainAttributes().getValue(name);
if (value == null) {
for (Attributes attributes : manifest.getEntries().values()) {
value = attributes.getValue(name);
}
}
return value;
} | java | public static String getValue(Manifest manifest, Attributes.Name name) {
String value = manifest.getMainAttributes().getValue(name);
if (value == null) {
for (Attributes attributes : manifest.getEntries().values()) {
value = attributes.getValue(name);
}
}
return value;
} | [
"public",
"static",
"String",
"getValue",
"(",
"Manifest",
"manifest",
",",
"Attributes",
".",
"Name",
"name",
")",
"{",
"String",
"value",
"=",
"manifest",
".",
"getMainAttributes",
"(",
")",
".",
"getValue",
"(",
"name",
")",
";",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"for",
"(",
"Attributes",
"attributes",
":",
"manifest",
".",
"getEntries",
"(",
")",
".",
"values",
"(",
")",
")",
"{",
"value",
"=",
"attributes",
".",
"getValue",
"(",
"name",
")",
";",
"}",
"}",
"return",
"value",
";",
"}"
] | This method gets an attribute-value from a {@link Manifest} in a pragmatic way. It tries to
{@link Attributes#getValue(java.util.jar.Attributes.Name) get} the value from the
{@link Manifest#getMainAttributes() main-attributes}. If NOT available it searches all other
{@link Manifest#getEntries() available attribute entries} for the value and returns the first one found
in deterministic but unspecified order.
@param manifest is the {@link Manifest} where to get the attribute-value from.
@param name is the {@link java.util.jar.Attributes.Name} of the requested attribute.
@return the requested value or {@code null} if NOT available.
@since 2.0.0 | [
"This",
"method",
"gets",
"an",
"attribute",
"-",
"value",
"from",
"a",
"{",
"@link",
"Manifest",
"}",
"in",
"a",
"pragmatic",
"way",
".",
"It",
"tries",
"to",
"{",
"@link",
"Attributes#getValue",
"(",
"java",
".",
"util",
".",
"jar",
".",
"Attributes",
".",
"Name",
")",
"get",
"}",
"the",
"value",
"from",
"the",
"{",
"@link",
"Manifest#getMainAttributes",
"()",
"main",
"-",
"attributes",
"}",
".",
"If",
"NOT",
"available",
"it",
"searches",
"all",
"other",
"{",
"@link",
"Manifest#getEntries",
"()",
"available",
"attribute",
"entries",
"}",
"for",
"the",
"value",
"and",
"returns",
"the",
"first",
"one",
"found",
"in",
"deterministic",
"but",
"unspecified",
"order",
"."
] | train | https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/reflect/src/main/java/net/sf/mmm/util/reflect/base/ManifestLoader.java#L179-L188 |
rhuss/jolokia | agent/core/src/main/java/org/jolokia/handler/list/MBeanInfoData.java | MBeanInfoData.addMBeanInfo | public void addMBeanInfo(MBeanInfo mBeanInfo, ObjectName pName)
throws InstanceNotFoundException, IntrospectionException, ReflectionException, IOException {
"""
Add information about an MBean as obtained from an {@link MBeanInfo} descriptor. The information added
can be restricted by a given path (which has already be prepared as a stack). Also, a max depth as given in the
constructor restricts the size of the map from the top.
@param mBeanInfo the MBean info
@param pName the object name of the MBean
"""
JSONObject mBeansMap = getOrCreateJSONObject(infoMap, pName.getDomain());
JSONObject mBeanMap = getOrCreateJSONObject(mBeansMap, getKeyPropertyString(pName));
// Trim down stack to get rid of domain/property list
Stack<String> stack = truncatePathStack(2);
if (stack.empty()) {
addFullMBeanInfo(mBeanMap, mBeanInfo);
} else {
addPartialMBeanInfo(mBeanMap, mBeanInfo,stack);
}
// Trim if required
if (mBeanMap.size() == 0) {
mBeansMap.remove(getKeyPropertyString(pName));
if (mBeansMap.size() == 0) {
infoMap.remove(pName.getDomain());
}
}
} | java | public void addMBeanInfo(MBeanInfo mBeanInfo, ObjectName pName)
throws InstanceNotFoundException, IntrospectionException, ReflectionException, IOException {
JSONObject mBeansMap = getOrCreateJSONObject(infoMap, pName.getDomain());
JSONObject mBeanMap = getOrCreateJSONObject(mBeansMap, getKeyPropertyString(pName));
// Trim down stack to get rid of domain/property list
Stack<String> stack = truncatePathStack(2);
if (stack.empty()) {
addFullMBeanInfo(mBeanMap, mBeanInfo);
} else {
addPartialMBeanInfo(mBeanMap, mBeanInfo,stack);
}
// Trim if required
if (mBeanMap.size() == 0) {
mBeansMap.remove(getKeyPropertyString(pName));
if (mBeansMap.size() == 0) {
infoMap.remove(pName.getDomain());
}
}
} | [
"public",
"void",
"addMBeanInfo",
"(",
"MBeanInfo",
"mBeanInfo",
",",
"ObjectName",
"pName",
")",
"throws",
"InstanceNotFoundException",
",",
"IntrospectionException",
",",
"ReflectionException",
",",
"IOException",
"{",
"JSONObject",
"mBeansMap",
"=",
"getOrCreateJSONObject",
"(",
"infoMap",
",",
"pName",
".",
"getDomain",
"(",
")",
")",
";",
"JSONObject",
"mBeanMap",
"=",
"getOrCreateJSONObject",
"(",
"mBeansMap",
",",
"getKeyPropertyString",
"(",
"pName",
")",
")",
";",
"// Trim down stack to get rid of domain/property list",
"Stack",
"<",
"String",
">",
"stack",
"=",
"truncatePathStack",
"(",
"2",
")",
";",
"if",
"(",
"stack",
".",
"empty",
"(",
")",
")",
"{",
"addFullMBeanInfo",
"(",
"mBeanMap",
",",
"mBeanInfo",
")",
";",
"}",
"else",
"{",
"addPartialMBeanInfo",
"(",
"mBeanMap",
",",
"mBeanInfo",
",",
"stack",
")",
";",
"}",
"// Trim if required",
"if",
"(",
"mBeanMap",
".",
"size",
"(",
")",
"==",
"0",
")",
"{",
"mBeansMap",
".",
"remove",
"(",
"getKeyPropertyString",
"(",
"pName",
")",
")",
";",
"if",
"(",
"mBeansMap",
".",
"size",
"(",
")",
"==",
"0",
")",
"{",
"infoMap",
".",
"remove",
"(",
"pName",
".",
"getDomain",
"(",
")",
")",
";",
"}",
"}",
"}"
] | Add information about an MBean as obtained from an {@link MBeanInfo} descriptor. The information added
can be restricted by a given path (which has already be prepared as a stack). Also, a max depth as given in the
constructor restricts the size of the map from the top.
@param mBeanInfo the MBean info
@param pName the object name of the MBean | [
"Add",
"information",
"about",
"an",
"MBean",
"as",
"obtained",
"from",
"an",
"{",
"@link",
"MBeanInfo",
"}",
"descriptor",
".",
"The",
"information",
"added",
"can",
"be",
"restricted",
"by",
"a",
"given",
"path",
"(",
"which",
"has",
"already",
"be",
"prepared",
"as",
"a",
"stack",
")",
".",
"Also",
"a",
"max",
"depth",
"as",
"given",
"in",
"the",
"constructor",
"restricts",
"the",
"size",
"of",
"the",
"map",
"from",
"the",
"top",
"."
] | train | https://github.com/rhuss/jolokia/blob/dc95e7bef859b1829776c5a84c8f7738f5d7d9c3/agent/core/src/main/java/org/jolokia/handler/list/MBeanInfoData.java#L171-L190 |
magro/memcached-session-manager | core/src/main/java/de/javakaffee/web/msm/SessionIdFormat.java | SessionIdFormat.changeJvmRoute | @Nonnull
public String changeJvmRoute( @Nonnull final String sessionId, @Nonnull final String newJvmRoute ) {
"""
Change the provided session id (optionally already including a jvmRoute) so that it
contains the provided newJvmRoute.
@param sessionId
the session id that may contain a former jvmRoute.
@param newJvmRoute
the new jvm route.
@return the sessionId which now contains the new jvmRoute instead the
former one.
"""
return stripJvmRoute( sessionId ) + "." + newJvmRoute;
} | java | @Nonnull
public String changeJvmRoute( @Nonnull final String sessionId, @Nonnull final String newJvmRoute ) {
return stripJvmRoute( sessionId ) + "." + newJvmRoute;
} | [
"@",
"Nonnull",
"public",
"String",
"changeJvmRoute",
"(",
"@",
"Nonnull",
"final",
"String",
"sessionId",
",",
"@",
"Nonnull",
"final",
"String",
"newJvmRoute",
")",
"{",
"return",
"stripJvmRoute",
"(",
"sessionId",
")",
"+",
"\".\"",
"+",
"newJvmRoute",
";",
"}"
] | Change the provided session id (optionally already including a jvmRoute) so that it
contains the provided newJvmRoute.
@param sessionId
the session id that may contain a former jvmRoute.
@param newJvmRoute
the new jvm route.
@return the sessionId which now contains the new jvmRoute instead the
former one. | [
"Change",
"the",
"provided",
"session",
"id",
"(",
"optionally",
"already",
"including",
"a",
"jvmRoute",
")",
"so",
"that",
"it",
"contains",
"the",
"provided",
"newJvmRoute",
"."
] | train | https://github.com/magro/memcached-session-manager/blob/716e147c9840ab10298c4d2b9edd0662058331e6/core/src/main/java/de/javakaffee/web/msm/SessionIdFormat.java#L132-L135 |
lingochamp/okdownload | okdownload-filedownloader/src/main/java/com/liulishuo/filedownloader/notification/FileDownloadNotificationHelper.java | FileDownloadNotificationHelper.showIndeterminate | public void showIndeterminate(final int id, int status) {
"""
Show the notification with indeterminate progress.
@param id The download id.
@param status {@link FileDownloadStatus}
"""
final BaseNotificationItem notification = get(id);
if (notification == null) {
return;
}
notification.updateStatus(status);
notification.show(false);
} | java | public void showIndeterminate(final int id, int status) {
final BaseNotificationItem notification = get(id);
if (notification == null) {
return;
}
notification.updateStatus(status);
notification.show(false);
} | [
"public",
"void",
"showIndeterminate",
"(",
"final",
"int",
"id",
",",
"int",
"status",
")",
"{",
"final",
"BaseNotificationItem",
"notification",
"=",
"get",
"(",
"id",
")",
";",
"if",
"(",
"notification",
"==",
"null",
")",
"{",
"return",
";",
"}",
"notification",
".",
"updateStatus",
"(",
"status",
")",
";",
"notification",
".",
"show",
"(",
"false",
")",
";",
"}"
] | Show the notification with indeterminate progress.
@param id The download id.
@param status {@link FileDownloadStatus} | [
"Show",
"the",
"notification",
"with",
"indeterminate",
"progress",
"."
] | train | https://github.com/lingochamp/okdownload/blob/403e2c814556ef7f2fade1f5bee83a02a5eaecb2/okdownload-filedownloader/src/main/java/com/liulishuo/filedownloader/notification/FileDownloadNotificationHelper.java#L96-L105 |
d-sauer/JCalcAPI | src/main/java/org/jdice/calc/Num.java | Num.cleanNumber | private static String cleanNumber(String value, char decimalSeparator) {
"""
Remove from string number representation all character except numbers and
decimal point. <br>
And replace given decimalSeparator with '.'
<pre>
("44,551.06", '.') => 44551.06
("1 255 844,551.06", '.') => 1255844551.06
("44,551..06", '.') => 44551.06
</pre>
@param decimalSeparator
@param value
"""
String regex = "[^0-9-" + decimalSeparator + "]";
if (decimalSeparator == '.')
regex = regex.replace(".", "\\.");
String strip = value.replaceAll(regex, "");
strip = strip.replace(decimalSeparator + "", Properties.DEFAULT_DECIMAL_SEPARATOR + "");
return strip;
} | java | private static String cleanNumber(String value, char decimalSeparator) {
String regex = "[^0-9-" + decimalSeparator + "]";
if (decimalSeparator == '.')
regex = regex.replace(".", "\\.");
String strip = value.replaceAll(regex, "");
strip = strip.replace(decimalSeparator + "", Properties.DEFAULT_DECIMAL_SEPARATOR + "");
return strip;
} | [
"private",
"static",
"String",
"cleanNumber",
"(",
"String",
"value",
",",
"char",
"decimalSeparator",
")",
"{",
"String",
"regex",
"=",
"\"[^0-9-\"",
"+",
"decimalSeparator",
"+",
"\"]\"",
";",
"if",
"(",
"decimalSeparator",
"==",
"'",
"'",
")",
"regex",
"=",
"regex",
".",
"replace",
"(",
"\".\"",
",",
"\"\\\\.\"",
")",
";",
"String",
"strip",
"=",
"value",
".",
"replaceAll",
"(",
"regex",
",",
"\"\"",
")",
";",
"strip",
"=",
"strip",
".",
"replace",
"(",
"decimalSeparator",
"+",
"\"\"",
",",
"Properties",
".",
"DEFAULT_DECIMAL_SEPARATOR",
"+",
"\"\"",
")",
";",
"return",
"strip",
";",
"}"
] | Remove from string number representation all character except numbers and
decimal point. <br>
And replace given decimalSeparator with '.'
<pre>
("44,551.06", '.') => 44551.06
("1 255 844,551.06", '.') => 1255844551.06
("44,551..06", '.') => 44551.06
</pre>
@param decimalSeparator
@param value | [
"Remove",
"from",
"string",
"number",
"representation",
"all",
"character",
"except",
"numbers",
"and",
"decimal",
"point",
".",
"<br",
">",
"And",
"replace",
"given",
"decimalSeparator",
"with",
"."
] | train | https://github.com/d-sauer/JCalcAPI/blob/36ae1f9adfe611a6f1bd8ef87cf1dc0ec88ac035/src/main/java/org/jdice/calc/Num.java#L915-L923 |
mkolisnyk/cucumber-reports | cucumber-runner/src/main/java/com/github/mkolisnyk/cucumber/assertions/LazyAssert.java | LazyAssert.assertEquals | public static void assertEquals(String message, Object expected,
Object actual) {
"""
Asserts that two objects are equal. If they are not, an
{@link LazyAssertionError} is thrown with the given message. If
<code>expected</code> and <code>actual</code> are <code>null</code>,
they are considered equal.
@param message the identifying message for the {@link LazyAssertionError} (<code>null</code>
okay)
@param expected expected value
@param actual actual value
"""
if (equalsRegardingNull(expected, actual)) {
return;
} else if (expected instanceof String && actual instanceof String) {
String cleanMessage = "";
if (StringUtils.isNotBlank(message)) {
cleanMessage = message;
}
throw new ComparisonFailure(cleanMessage, (String) expected,
(String) actual);
} else {
failNotEquals(message, expected, actual);
}
} | java | public static void assertEquals(String message, Object expected,
Object actual) {
if (equalsRegardingNull(expected, actual)) {
return;
} else if (expected instanceof String && actual instanceof String) {
String cleanMessage = "";
if (StringUtils.isNotBlank(message)) {
cleanMessage = message;
}
throw new ComparisonFailure(cleanMessage, (String) expected,
(String) actual);
} else {
failNotEquals(message, expected, actual);
}
} | [
"public",
"static",
"void",
"assertEquals",
"(",
"String",
"message",
",",
"Object",
"expected",
",",
"Object",
"actual",
")",
"{",
"if",
"(",
"equalsRegardingNull",
"(",
"expected",
",",
"actual",
")",
")",
"{",
"return",
";",
"}",
"else",
"if",
"(",
"expected",
"instanceof",
"String",
"&&",
"actual",
"instanceof",
"String",
")",
"{",
"String",
"cleanMessage",
"=",
"\"\"",
";",
"if",
"(",
"StringUtils",
".",
"isNotBlank",
"(",
"message",
")",
")",
"{",
"cleanMessage",
"=",
"message",
";",
"}",
"throw",
"new",
"ComparisonFailure",
"(",
"cleanMessage",
",",
"(",
"String",
")",
"expected",
",",
"(",
"String",
")",
"actual",
")",
";",
"}",
"else",
"{",
"failNotEquals",
"(",
"message",
",",
"expected",
",",
"actual",
")",
";",
"}",
"}"
] | Asserts that two objects are equal. If they are not, an
{@link LazyAssertionError} is thrown with the given message. If
<code>expected</code> and <code>actual</code> are <code>null</code>,
they are considered equal.
@param message the identifying message for the {@link LazyAssertionError} (<code>null</code>
okay)
@param expected expected value
@param actual actual value | [
"Asserts",
"that",
"two",
"objects",
"are",
"equal",
".",
"If",
"they",
"are",
"not",
"an",
"{",
"@link",
"LazyAssertionError",
"}",
"is",
"thrown",
"with",
"the",
"given",
"message",
".",
"If",
"<code",
">",
"expected<",
"/",
"code",
">",
"and",
"<code",
">",
"actual<",
"/",
"code",
">",
"are",
"<code",
">",
"null<",
"/",
"code",
">",
"they",
"are",
"considered",
"equal",
"."
] | train | https://github.com/mkolisnyk/cucumber-reports/blob/9c9a32f15f0bf1eb1d3d181a11bae9c5eec84a8e/cucumber-runner/src/main/java/com/github/mkolisnyk/cucumber/assertions/LazyAssert.java#L112-L126 |
TheHortonMachine/hortonmachine | gears/src/main/java/oms3/ngmf/util/IOCase.java | IOCase.checkEndsWith | public boolean checkEndsWith(String str, String end) {
"""
Checks if one string ends with another using the case-sensitivity rule.
<p>
This method mimics {@link String#endsWith} but takes case-sensitivity
into account.
@param str the string to check, not null
@param end the end to compare against, not null
@return true if equal using the case rules
@throws NullPointerException if either string is null
"""
int endLen = end.length();
return str.regionMatches(!sensitive, str.length() - endLen, end, 0, endLen);
} | java | public boolean checkEndsWith(String str, String end) {
int endLen = end.length();
return str.regionMatches(!sensitive, str.length() - endLen, end, 0, endLen);
} | [
"public",
"boolean",
"checkEndsWith",
"(",
"String",
"str",
",",
"String",
"end",
")",
"{",
"int",
"endLen",
"=",
"end",
".",
"length",
"(",
")",
";",
"return",
"str",
".",
"regionMatches",
"(",
"!",
"sensitive",
",",
"str",
".",
"length",
"(",
")",
"-",
"endLen",
",",
"end",
",",
"0",
",",
"endLen",
")",
";",
"}"
] | Checks if one string ends with another using the case-sensitivity rule.
<p>
This method mimics {@link String#endsWith} but takes case-sensitivity
into account.
@param str the string to check, not null
@param end the end to compare against, not null
@return true if equal using the case rules
@throws NullPointerException if either string is null | [
"Checks",
"if",
"one",
"string",
"ends",
"with",
"another",
"using",
"the",
"case",
"-",
"sensitivity",
"rule",
".",
"<p",
">",
"This",
"method",
"mimics",
"{",
"@link",
"String#endsWith",
"}",
"but",
"takes",
"case",
"-",
"sensitivity",
"into",
"account",
"."
] | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/oms3/ngmf/util/IOCase.java#L193-L196 |
jsurfer/JsonSurfer | jsurfer-core/src/main/java/org/jsfr/json/JsonSurfer.java | JsonSurfer.collectAll | public Collection<Object> collectAll(InputStream inputStream, JsonPath... paths) {
"""
Collect all matched value into a collection
@param inputStream Json reader
@param paths JsonPath
@return All matched value
"""
return collectAll(inputStream, Object.class, paths);
} | java | public Collection<Object> collectAll(InputStream inputStream, JsonPath... paths) {
return collectAll(inputStream, Object.class, paths);
} | [
"public",
"Collection",
"<",
"Object",
">",
"collectAll",
"(",
"InputStream",
"inputStream",
",",
"JsonPath",
"...",
"paths",
")",
"{",
"return",
"collectAll",
"(",
"inputStream",
",",
"Object",
".",
"class",
",",
"paths",
")",
";",
"}"
] | Collect all matched value into a collection
@param inputStream Json reader
@param paths JsonPath
@return All matched value | [
"Collect",
"all",
"matched",
"value",
"into",
"a",
"collection"
] | train | https://github.com/jsurfer/JsonSurfer/blob/52bd75a453338b86e115092803da140bf99cee62/jsurfer-core/src/main/java/org/jsfr/json/JsonSurfer.java#L358-L360 |
census-instrumentation/opencensus-java | api/src/main/java/io/opencensus/trace/TraceOptions.java | TraceOptions.fromBytes | @Deprecated
public static TraceOptions fromBytes(byte[] src, int srcOffset) {
"""
Returns a {@code TraceOptions} whose representation is copied from the {@code src} beginning at
the {@code srcOffset} offset.
@param src the buffer where the representation of the {@code TraceOptions} is copied.
@param srcOffset the offset in the buffer where the representation of the {@code TraceOptions}
begins.
@return a {@code TraceOptions} whose representation is copied from the buffer.
@throws NullPointerException if {@code src} is null.
@throws IndexOutOfBoundsException if {@code srcOffset+TraceOptions.SIZE} is greater than {@code
src.length}.
@since 0.5
@deprecated use {@link #fromByte(byte)}.
"""
Utils.checkIndex(srcOffset, src.length);
return fromByte(src[srcOffset]);
} | java | @Deprecated
public static TraceOptions fromBytes(byte[] src, int srcOffset) {
Utils.checkIndex(srcOffset, src.length);
return fromByte(src[srcOffset]);
} | [
"@",
"Deprecated",
"public",
"static",
"TraceOptions",
"fromBytes",
"(",
"byte",
"[",
"]",
"src",
",",
"int",
"srcOffset",
")",
"{",
"Utils",
".",
"checkIndex",
"(",
"srcOffset",
",",
"src",
".",
"length",
")",
";",
"return",
"fromByte",
"(",
"src",
"[",
"srcOffset",
"]",
")",
";",
"}"
] | Returns a {@code TraceOptions} whose representation is copied from the {@code src} beginning at
the {@code srcOffset} offset.
@param src the buffer where the representation of the {@code TraceOptions} is copied.
@param srcOffset the offset in the buffer where the representation of the {@code TraceOptions}
begins.
@return a {@code TraceOptions} whose representation is copied from the buffer.
@throws NullPointerException if {@code src} is null.
@throws IndexOutOfBoundsException if {@code srcOffset+TraceOptions.SIZE} is greater than {@code
src.length}.
@since 0.5
@deprecated use {@link #fromByte(byte)}. | [
"Returns",
"a",
"{",
"@code",
"TraceOptions",
"}",
"whose",
"representation",
"is",
"copied",
"from",
"the",
"{",
"@code",
"src",
"}",
"beginning",
"at",
"the",
"{",
"@code",
"srcOffset",
"}",
"offset",
"."
] | train | https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/api/src/main/java/io/opencensus/trace/TraceOptions.java#L101-L105 |
mikepenz/MaterialDrawer | library/src/main/java/com/mikepenz/materialdrawer/DrawerUtils.java | DrawerUtils.getStickyFooterPositionByIdentifier | public static int getStickyFooterPositionByIdentifier(DrawerBuilder drawer, long identifier) {
"""
calculates the position of an drawerItem inside the footer. searching by it's identifier
@param identifier
@return
"""
if (identifier != -1) {
if (drawer.mStickyFooterView != null && drawer.mStickyFooterView instanceof LinearLayout) {
LinearLayout footer = (LinearLayout) drawer.mStickyFooterView;
int shadowOffset = 0;
for (int i = 0; i < footer.getChildCount(); i++) {
Object o = footer.getChildAt(i).getTag(R.id.material_drawer_item);
//count up the shadowOffset to return the correct position of the given item
if (o == null && drawer.mStickyFooterDivider) {
shadowOffset = shadowOffset + 1;
}
if (o != null && o instanceof IDrawerItem && ((IDrawerItem) o).getIdentifier() == identifier) {
return i - shadowOffset;
}
}
}
}
return -1;
} | java | public static int getStickyFooterPositionByIdentifier(DrawerBuilder drawer, long identifier) {
if (identifier != -1) {
if (drawer.mStickyFooterView != null && drawer.mStickyFooterView instanceof LinearLayout) {
LinearLayout footer = (LinearLayout) drawer.mStickyFooterView;
int shadowOffset = 0;
for (int i = 0; i < footer.getChildCount(); i++) {
Object o = footer.getChildAt(i).getTag(R.id.material_drawer_item);
//count up the shadowOffset to return the correct position of the given item
if (o == null && drawer.mStickyFooterDivider) {
shadowOffset = shadowOffset + 1;
}
if (o != null && o instanceof IDrawerItem && ((IDrawerItem) o).getIdentifier() == identifier) {
return i - shadowOffset;
}
}
}
}
return -1;
} | [
"public",
"static",
"int",
"getStickyFooterPositionByIdentifier",
"(",
"DrawerBuilder",
"drawer",
",",
"long",
"identifier",
")",
"{",
"if",
"(",
"identifier",
"!=",
"-",
"1",
")",
"{",
"if",
"(",
"drawer",
".",
"mStickyFooterView",
"!=",
"null",
"&&",
"drawer",
".",
"mStickyFooterView",
"instanceof",
"LinearLayout",
")",
"{",
"LinearLayout",
"footer",
"=",
"(",
"LinearLayout",
")",
"drawer",
".",
"mStickyFooterView",
";",
"int",
"shadowOffset",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"footer",
".",
"getChildCount",
"(",
")",
";",
"i",
"++",
")",
"{",
"Object",
"o",
"=",
"footer",
".",
"getChildAt",
"(",
"i",
")",
".",
"getTag",
"(",
"R",
".",
"id",
".",
"material_drawer_item",
")",
";",
"//count up the shadowOffset to return the correct position of the given item",
"if",
"(",
"o",
"==",
"null",
"&&",
"drawer",
".",
"mStickyFooterDivider",
")",
"{",
"shadowOffset",
"=",
"shadowOffset",
"+",
"1",
";",
"}",
"if",
"(",
"o",
"!=",
"null",
"&&",
"o",
"instanceof",
"IDrawerItem",
"&&",
"(",
"(",
"IDrawerItem",
")",
"o",
")",
".",
"getIdentifier",
"(",
")",
"==",
"identifier",
")",
"{",
"return",
"i",
"-",
"shadowOffset",
";",
"}",
"}",
"}",
"}",
"return",
"-",
"1",
";",
"}"
] | calculates the position of an drawerItem inside the footer. searching by it's identifier
@param identifier
@return | [
"calculates",
"the",
"position",
"of",
"an",
"drawerItem",
"inside",
"the",
"footer",
".",
"searching",
"by",
"it",
"s",
"identifier"
] | train | https://github.com/mikepenz/MaterialDrawer/blob/f4fb31635767edead0a01cee7b7588942b89d8d9/library/src/main/java/com/mikepenz/materialdrawer/DrawerUtils.java#L160-L182 |
eclipse/xtext-extras | org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/typesystem/util/MultimapJoiner.java | MultimapJoiner.join | public String join(Iterable<? extends Entry<?, ? extends Collection<?>>> entries) {
"""
Returns a string containing the string representation of each entry in {@code entries}, using the previously
configured separator and key-value separator.
"""
return appendTo(new StringBuilder(), entries).toString();
} | java | public String join(Iterable<? extends Entry<?, ? extends Collection<?>>> entries) {
return appendTo(new StringBuilder(), entries).toString();
} | [
"public",
"String",
"join",
"(",
"Iterable",
"<",
"?",
"extends",
"Entry",
"<",
"?",
",",
"?",
"extends",
"Collection",
"<",
"?",
">",
">",
">",
"entries",
")",
"{",
"return",
"appendTo",
"(",
"new",
"StringBuilder",
"(",
")",
",",
"entries",
")",
".",
"toString",
"(",
")",
";",
"}"
] | Returns a string containing the string representation of each entry in {@code entries}, using the previously
configured separator and key-value separator. | [
"Returns",
"a",
"string",
"containing",
"the",
"string",
"representation",
"of",
"each",
"entry",
"in",
"{"
] | train | https://github.com/eclipse/xtext-extras/blob/451359541295323a29f5855e633f770cec02069a/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/typesystem/util/MultimapJoiner.java#L125-L127 |
motown-io/motown | ocpp/view-model/src/main/java/io/motown/ocpp/viewmodel/domain/DomainService.java | DomainService.startTransaction | public void startTransaction(ChargingStationId chargingStationId, EvseId evseId, IdentifyingToken idTag, FutureEventCallback futureEventCallback,
AddOnIdentity addOnIdentity) {
"""
Generates a transaction identifier and starts a transaction by dispatching a StartTransactionCommand.
@param chargingStationId identifier of the charging station.
@param evseId evse identifier on which the transaction is started.
@param idTag the identification which started the transaction.
@param futureEventCallback will be called once the authorize result event occurs.
@param addOnIdentity identity of the add on that calls this method.
"""
ChargingStation chargingStation = this.checkChargingStationExistsAndIsRegisteredAndConfigured(chargingStationId);
if (evseId.getNumberedId() > chargingStation.getNumberOfEvses()) {
throw new IllegalStateException("Cannot start transaction on a unknown evse.");
}
// authorize the token, the future contains the call to start the transaction
authorize(chargingStationId, idTag.getToken(), futureEventCallback, addOnIdentity);
} | java | public void startTransaction(ChargingStationId chargingStationId, EvseId evseId, IdentifyingToken idTag, FutureEventCallback futureEventCallback,
AddOnIdentity addOnIdentity) {
ChargingStation chargingStation = this.checkChargingStationExistsAndIsRegisteredAndConfigured(chargingStationId);
if (evseId.getNumberedId() > chargingStation.getNumberOfEvses()) {
throw new IllegalStateException("Cannot start transaction on a unknown evse.");
}
// authorize the token, the future contains the call to start the transaction
authorize(chargingStationId, idTag.getToken(), futureEventCallback, addOnIdentity);
} | [
"public",
"void",
"startTransaction",
"(",
"ChargingStationId",
"chargingStationId",
",",
"EvseId",
"evseId",
",",
"IdentifyingToken",
"idTag",
",",
"FutureEventCallback",
"futureEventCallback",
",",
"AddOnIdentity",
"addOnIdentity",
")",
"{",
"ChargingStation",
"chargingStation",
"=",
"this",
".",
"checkChargingStationExistsAndIsRegisteredAndConfigured",
"(",
"chargingStationId",
")",
";",
"if",
"(",
"evseId",
".",
"getNumberedId",
"(",
")",
">",
"chargingStation",
".",
"getNumberOfEvses",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Cannot start transaction on a unknown evse.\"",
")",
";",
"}",
"// authorize the token, the future contains the call to start the transaction",
"authorize",
"(",
"chargingStationId",
",",
"idTag",
".",
"getToken",
"(",
")",
",",
"futureEventCallback",
",",
"addOnIdentity",
")",
";",
"}"
] | Generates a transaction identifier and starts a transaction by dispatching a StartTransactionCommand.
@param chargingStationId identifier of the charging station.
@param evseId evse identifier on which the transaction is started.
@param idTag the identification which started the transaction.
@param futureEventCallback will be called once the authorize result event occurs.
@param addOnIdentity identity of the add on that calls this method. | [
"Generates",
"a",
"transaction",
"identifier",
"and",
"starts",
"a",
"transaction",
"by",
"dispatching",
"a",
"StartTransactionCommand",
"."
] | train | https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/ocpp/view-model/src/main/java/io/motown/ocpp/viewmodel/domain/DomainService.java#L216-L226 |
mapbox/mapbox-java | services-geojson/src/main/java/com/mapbox/geojson/utils/PolylineUtils.java | PolylineUtils.getSqDist | private static double getSqDist(Point p1, Point p2) {
"""
Square distance between 2 points.
@param p1 first {@link Point}
@param p2 second Point
@return square of the distance between two input points
"""
double dx = p1.longitude() - p2.longitude();
double dy = p1.latitude() - p2.latitude();
return dx * dx + dy * dy;
} | java | private static double getSqDist(Point p1, Point p2) {
double dx = p1.longitude() - p2.longitude();
double dy = p1.latitude() - p2.latitude();
return dx * dx + dy * dy;
} | [
"private",
"static",
"double",
"getSqDist",
"(",
"Point",
"p1",
",",
"Point",
"p2",
")",
"{",
"double",
"dx",
"=",
"p1",
".",
"longitude",
"(",
")",
"-",
"p2",
".",
"longitude",
"(",
")",
";",
"double",
"dy",
"=",
"p1",
".",
"latitude",
"(",
")",
"-",
"p2",
".",
"latitude",
"(",
")",
";",
"return",
"dx",
"*",
"dx",
"+",
"dy",
"*",
"dy",
";",
"}"
] | Square distance between 2 points.
@param p1 first {@link Point}
@param p2 second Point
@return square of the distance between two input points | [
"Square",
"distance",
"between",
"2",
"points",
"."
] | train | https://github.com/mapbox/mapbox-java/blob/c0be138f462f91441388584c668f3760ba0e18e2/services-geojson/src/main/java/com/mapbox/geojson/utils/PolylineUtils.java#L209-L213 |
OpenTSDB/opentsdb | src/tools/Search.java | Search.runCommand | private static int runCommand(final TSDB tsdb,
final boolean use_data_table,
final String[] args) throws Exception {
"""
Determines the command requested of the user can calls the appropriate
method.
@param tsdb The TSDB to use for communication
@param use_data_table Whether or not lookups should be done on the full
data table
@param args Arguments to parse
@return An exit code
"""
final int nargs = args.length;
if (args[0].equals("lookup")) {
if (nargs < 2) { // need a query
usage(null, "Not enough arguments");
return 2;
}
return lookup(tsdb, use_data_table, args);
} else {
usage(null, "Unknown sub command: " + args[0]);
return 2;
}
} | java | private static int runCommand(final TSDB tsdb,
final boolean use_data_table,
final String[] args) throws Exception {
final int nargs = args.length;
if (args[0].equals("lookup")) {
if (nargs < 2) { // need a query
usage(null, "Not enough arguments");
return 2;
}
return lookup(tsdb, use_data_table, args);
} else {
usage(null, "Unknown sub command: " + args[0]);
return 2;
}
} | [
"private",
"static",
"int",
"runCommand",
"(",
"final",
"TSDB",
"tsdb",
",",
"final",
"boolean",
"use_data_table",
",",
"final",
"String",
"[",
"]",
"args",
")",
"throws",
"Exception",
"{",
"final",
"int",
"nargs",
"=",
"args",
".",
"length",
";",
"if",
"(",
"args",
"[",
"0",
"]",
".",
"equals",
"(",
"\"lookup\"",
")",
")",
"{",
"if",
"(",
"nargs",
"<",
"2",
")",
"{",
"// need a query",
"usage",
"(",
"null",
",",
"\"Not enough arguments\"",
")",
";",
"return",
"2",
";",
"}",
"return",
"lookup",
"(",
"tsdb",
",",
"use_data_table",
",",
"args",
")",
";",
"}",
"else",
"{",
"usage",
"(",
"null",
",",
"\"Unknown sub command: \"",
"+",
"args",
"[",
"0",
"]",
")",
";",
"return",
"2",
";",
"}",
"}"
] | Determines the command requested of the user can calls the appropriate
method.
@param tsdb The TSDB to use for communication
@param use_data_table Whether or not lookups should be done on the full
data table
@param args Arguments to parse
@return An exit code | [
"Determines",
"the",
"command",
"requested",
"of",
"the",
"user",
"can",
"calls",
"the",
"appropriate",
"method",
"."
] | train | https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/tools/Search.java#L97-L111 |
carewebframework/carewebframework-core | org.carewebframework.help-parent/org.carewebframework.help.core/src/main/java/org/carewebframework/help/HelpModule.java | HelpModule.getLocalizedId | public static String getLocalizedId(String id, Locale locale) {
"""
Adds locale information to a help module id.
@param id Help module id.
@param locale Locale (may be null).
@return The id with locale information appended.
"""
String locstr = locale == null ? "" : ("_" + locale.toString());
return id + locstr;
} | java | public static String getLocalizedId(String id, Locale locale) {
String locstr = locale == null ? "" : ("_" + locale.toString());
return id + locstr;
} | [
"public",
"static",
"String",
"getLocalizedId",
"(",
"String",
"id",
",",
"Locale",
"locale",
")",
"{",
"String",
"locstr",
"=",
"locale",
"==",
"null",
"?",
"\"\"",
":",
"(",
"\"_\"",
"+",
"locale",
".",
"toString",
"(",
")",
")",
";",
"return",
"id",
"+",
"locstr",
";",
"}"
] | Adds locale information to a help module id.
@param id Help module id.
@param locale Locale (may be null).
@return The id with locale information appended. | [
"Adds",
"locale",
"information",
"to",
"a",
"help",
"module",
"id",
"."
] | train | https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.help-parent/org.carewebframework.help.core/src/main/java/org/carewebframework/help/HelpModule.java#L68-L71 |
Stratio/bdt | src/main/java/com/stratio/qa/specs/ZookeeperSpec.java | ZookeeperSpec.createZNode | @When("^I create the zNode '(.+?)'( with content '(.+?)')? which (IS|IS NOT) ephemeral$")
public void createZNode(String path, String foo, String content, boolean ephemeral) throws Exception {
"""
Create zPath and domcument
@param path path at zookeeper
@param foo a dummy match group
@param content if it has content it should be defined
@param ephemeral if it's created as ephemeral or not
"""
if (content != null) {
commonspec.getZookeeperSecClient().zCreate(path, content, ephemeral);
} else {
commonspec.getZookeeperSecClient().zCreate(path, ephemeral);
}
} | java | @When("^I create the zNode '(.+?)'( with content '(.+?)')? which (IS|IS NOT) ephemeral$")
public void createZNode(String path, String foo, String content, boolean ephemeral) throws Exception {
if (content != null) {
commonspec.getZookeeperSecClient().zCreate(path, content, ephemeral);
} else {
commonspec.getZookeeperSecClient().zCreate(path, ephemeral);
}
} | [
"@",
"When",
"(",
"\"^I create the zNode '(.+?)'( with content '(.+?)')? which (IS|IS NOT) ephemeral$\"",
")",
"public",
"void",
"createZNode",
"(",
"String",
"path",
",",
"String",
"foo",
",",
"String",
"content",
",",
"boolean",
"ephemeral",
")",
"throws",
"Exception",
"{",
"if",
"(",
"content",
"!=",
"null",
")",
"{",
"commonspec",
".",
"getZookeeperSecClient",
"(",
")",
".",
"zCreate",
"(",
"path",
",",
"content",
",",
"ephemeral",
")",
";",
"}",
"else",
"{",
"commonspec",
".",
"getZookeeperSecClient",
"(",
")",
".",
"zCreate",
"(",
"path",
",",
"ephemeral",
")",
";",
"}",
"}"
] | Create zPath and domcument
@param path path at zookeeper
@param foo a dummy match group
@param content if it has content it should be defined
@param ephemeral if it's created as ephemeral or not | [
"Create",
"zPath",
"and",
"domcument"
] | train | https://github.com/Stratio/bdt/blob/55324d19e7497764ad3dd7139923e13eb9841d75/src/main/java/com/stratio/qa/specs/ZookeeperSpec.java#L78-L85 |
meltmedia/cadmium | core/src/main/java/com/meltmedia/cadmium/core/util/Jsr250Utils.java | Jsr250Utils.safeInvokeMethod | private static void safeInvokeMethod(Object obj, Method aMethod, Logger log)
throws Exception {
"""
Invokes a method safely on a Object regardless of accessibility (Unless not allowed with security settings).
@param obj
@param aMethod
@param log
@throws Exception
"""
boolean accessible = aMethod.isAccessible();
try {
if(!accessible) {
aMethod.setAccessible(true);
}
if(Modifier.isStatic(aMethod.getModifiers())) {
log.debug("Invoking static method: {}", aMethod);
aMethod.invoke(null);
} else {
log.debug("Invoking method {} on object instance {}", aMethod, obj);
aMethod.invoke(obj);
}
} finally {
if(!accessible) {
aMethod.setAccessible(accessible);
}
}
} | java | private static void safeInvokeMethod(Object obj, Method aMethod, Logger log)
throws Exception {
boolean accessible = aMethod.isAccessible();
try {
if(!accessible) {
aMethod.setAccessible(true);
}
if(Modifier.isStatic(aMethod.getModifiers())) {
log.debug("Invoking static method: {}", aMethod);
aMethod.invoke(null);
} else {
log.debug("Invoking method {} on object instance {}", aMethod, obj);
aMethod.invoke(obj);
}
} finally {
if(!accessible) {
aMethod.setAccessible(accessible);
}
}
} | [
"private",
"static",
"void",
"safeInvokeMethod",
"(",
"Object",
"obj",
",",
"Method",
"aMethod",
",",
"Logger",
"log",
")",
"throws",
"Exception",
"{",
"boolean",
"accessible",
"=",
"aMethod",
".",
"isAccessible",
"(",
")",
";",
"try",
"{",
"if",
"(",
"!",
"accessible",
")",
"{",
"aMethod",
".",
"setAccessible",
"(",
"true",
")",
";",
"}",
"if",
"(",
"Modifier",
".",
"isStatic",
"(",
"aMethod",
".",
"getModifiers",
"(",
")",
")",
")",
"{",
"log",
".",
"debug",
"(",
"\"Invoking static method: {}\"",
",",
"aMethod",
")",
";",
"aMethod",
".",
"invoke",
"(",
"null",
")",
";",
"}",
"else",
"{",
"log",
".",
"debug",
"(",
"\"Invoking method {} on object instance {}\"",
",",
"aMethod",
",",
"obj",
")",
";",
"aMethod",
".",
"invoke",
"(",
"obj",
")",
";",
"}",
"}",
"finally",
"{",
"if",
"(",
"!",
"accessible",
")",
"{",
"aMethod",
".",
"setAccessible",
"(",
"accessible",
")",
";",
"}",
"}",
"}"
] | Invokes a method safely on a Object regardless of accessibility (Unless not allowed with security settings).
@param obj
@param aMethod
@param log
@throws Exception | [
"Invokes",
"a",
"method",
"safely",
"on",
"a",
"Object",
"regardless",
"of",
"accessibility",
"(",
"Unless",
"not",
"allowed",
"with",
"security",
"settings",
")",
"."
] | train | https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/util/Jsr250Utils.java#L113-L132 |
hdbeukel/james-core | src/main/java/org/jamesframework/core/subset/neigh/SingleSwapNeighbourhood.java | SingleSwapNeighbourhood.getRandomMove | @Override
public SubsetMove getRandomMove(SubsetSolution solution, Random rnd) {
"""
Generates a random swap move for the given subset solution that removes a single ID from the set of currently selected IDs,
and replaces it with a random ID taken from the set of currently unselected IDs. Possible fixed IDs are not considered to be
swapped. If no swap move can be generated, <code>null</code> is returned.
@param solution solution for which a random swap move is generated
@param rnd source of randomness used to generate random move
@return random swap move, <code>null</code> if no swap move can be generated
"""
// get set of candidate IDs for removal and addition (possibly fixed IDs are discarded)
Set<Integer> removeCandidates = getRemoveCandidates(solution);
Set<Integer> addCandidates = getAddCandidates(solution);
// check if swap is possible
if(removeCandidates.isEmpty() || addCandidates.isEmpty()){
// impossible to perform a swap
return null;
}
// select random ID to remove from selection
int del = SetUtilities.getRandomElement(removeCandidates, rnd);
// select random ID to add to selection
int add = SetUtilities.getRandomElement(addCandidates, rnd);
// create and return swap move
return new SwapMove(add, del);
} | java | @Override
public SubsetMove getRandomMove(SubsetSolution solution, Random rnd) {
// get set of candidate IDs for removal and addition (possibly fixed IDs are discarded)
Set<Integer> removeCandidates = getRemoveCandidates(solution);
Set<Integer> addCandidates = getAddCandidates(solution);
// check if swap is possible
if(removeCandidates.isEmpty() || addCandidates.isEmpty()){
// impossible to perform a swap
return null;
}
// select random ID to remove from selection
int del = SetUtilities.getRandomElement(removeCandidates, rnd);
// select random ID to add to selection
int add = SetUtilities.getRandomElement(addCandidates, rnd);
// create and return swap move
return new SwapMove(add, del);
} | [
"@",
"Override",
"public",
"SubsetMove",
"getRandomMove",
"(",
"SubsetSolution",
"solution",
",",
"Random",
"rnd",
")",
"{",
"// get set of candidate IDs for removal and addition (possibly fixed IDs are discarded)",
"Set",
"<",
"Integer",
">",
"removeCandidates",
"=",
"getRemoveCandidates",
"(",
"solution",
")",
";",
"Set",
"<",
"Integer",
">",
"addCandidates",
"=",
"getAddCandidates",
"(",
"solution",
")",
";",
"// check if swap is possible",
"if",
"(",
"removeCandidates",
".",
"isEmpty",
"(",
")",
"||",
"addCandidates",
".",
"isEmpty",
"(",
")",
")",
"{",
"// impossible to perform a swap",
"return",
"null",
";",
"}",
"// select random ID to remove from selection",
"int",
"del",
"=",
"SetUtilities",
".",
"getRandomElement",
"(",
"removeCandidates",
",",
"rnd",
")",
";",
"// select random ID to add to selection",
"int",
"add",
"=",
"SetUtilities",
".",
"getRandomElement",
"(",
"addCandidates",
",",
"rnd",
")",
";",
"// create and return swap move",
"return",
"new",
"SwapMove",
"(",
"add",
",",
"del",
")",
";",
"}"
] | Generates a random swap move for the given subset solution that removes a single ID from the set of currently selected IDs,
and replaces it with a random ID taken from the set of currently unselected IDs. Possible fixed IDs are not considered to be
swapped. If no swap move can be generated, <code>null</code> is returned.
@param solution solution for which a random swap move is generated
@param rnd source of randomness used to generate random move
@return random swap move, <code>null</code> if no swap move can be generated | [
"Generates",
"a",
"random",
"swap",
"move",
"for",
"the",
"given",
"subset",
"solution",
"that",
"removes",
"a",
"single",
"ID",
"from",
"the",
"set",
"of",
"currently",
"selected",
"IDs",
"and",
"replaces",
"it",
"with",
"a",
"random",
"ID",
"taken",
"from",
"the",
"set",
"of",
"currently",
"unselected",
"IDs",
".",
"Possible",
"fixed",
"IDs",
"are",
"not",
"considered",
"to",
"be",
"swapped",
".",
"If",
"no",
"swap",
"move",
"can",
"be",
"generated",
"<code",
">",
"null<",
"/",
"code",
">",
"is",
"returned",
"."
] | train | https://github.com/hdbeukel/james-core/blob/4e85c20c142902373e5b5e8b5d12a2558650f66d/src/main/java/org/jamesframework/core/subset/neigh/SingleSwapNeighbourhood.java#L71-L87 |
apache/incubator-gobblin | gobblin-metrics-libs/gobblin-metrics/src/main/java/org/apache/gobblin/metrics/GobblinMetrics.java | GobblinMetrics.getHistogram | public Histogram getHistogram(String prefix, String... suffixes) {
"""
Get a {@link Histogram} with the given name prefix and suffixes.
@param prefix the given name prefix
@param suffixes the given name suffixes
@return a {@link Histogram} with the given name prefix and suffixes
"""
return this.metricContext.histogram(MetricRegistry.name(prefix, suffixes));
} | java | public Histogram getHistogram(String prefix, String... suffixes) {
return this.metricContext.histogram(MetricRegistry.name(prefix, suffixes));
} | [
"public",
"Histogram",
"getHistogram",
"(",
"String",
"prefix",
",",
"String",
"...",
"suffixes",
")",
"{",
"return",
"this",
".",
"metricContext",
".",
"histogram",
"(",
"MetricRegistry",
".",
"name",
"(",
"prefix",
",",
"suffixes",
")",
")",
";",
"}"
] | Get a {@link Histogram} with the given name prefix and suffixes.
@param prefix the given name prefix
@param suffixes the given name suffixes
@return a {@link Histogram} with the given name prefix and suffixes | [
"Get",
"a",
"{",
"@link",
"Histogram",
"}",
"with",
"the",
"given",
"name",
"prefix",
"and",
"suffixes",
"."
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-metrics-libs/gobblin-metrics/src/main/java/org/apache/gobblin/metrics/GobblinMetrics.java#L334-L336 |
geomajas/geomajas-project-server | impl/src/main/java/org/geomajas/internal/rendering/strategy/TiledFeatureService.java | TiledFeatureService.clipTile | public void clipTile(InternalTile tile, double scale, Coordinate panOrigin) throws GeomajasException {
"""
Apply clipping to the features in a tile. The tile and its features should already be in map space.
@param tile
tile to put features in
@param scale
scale
@param panOrigin
When panning on the client, only this parameter changes. So we need to be aware of it as we calculate
the maxScreenEnvelope.
@throws GeomajasException oops
"""
log.debug("clipTile before {}", tile);
List<InternalFeature> orgFeatures = tile.getFeatures();
tile.setFeatures(new ArrayList<InternalFeature>());
Geometry maxScreenBbox = null; // The tile's maximum bounds in screen space. Used for clipping.
for (InternalFeature feature : orgFeatures) {
// clip feature if necessary
if (exceedsScreenDimensions(feature, scale)) {
log.debug("feature {} exceeds screen dimensions", feature);
InternalFeatureImpl vectorFeature = (InternalFeatureImpl) feature.clone();
tile.setClipped(true);
vectorFeature.setClipped(true);
if (null == maxScreenBbox) {
maxScreenBbox = JTS.toGeometry(getMaxScreenEnvelope(tile, panOrigin));
}
Geometry clipped = maxScreenBbox.intersection(feature.getGeometry());
vectorFeature.setClippedGeometry(clipped);
tile.addFeature(vectorFeature);
} else {
tile.addFeature(feature);
}
}
log.debug("clipTile after {}", tile);
} | java | public void clipTile(InternalTile tile, double scale, Coordinate panOrigin) throws GeomajasException {
log.debug("clipTile before {}", tile);
List<InternalFeature> orgFeatures = tile.getFeatures();
tile.setFeatures(new ArrayList<InternalFeature>());
Geometry maxScreenBbox = null; // The tile's maximum bounds in screen space. Used for clipping.
for (InternalFeature feature : orgFeatures) {
// clip feature if necessary
if (exceedsScreenDimensions(feature, scale)) {
log.debug("feature {} exceeds screen dimensions", feature);
InternalFeatureImpl vectorFeature = (InternalFeatureImpl) feature.clone();
tile.setClipped(true);
vectorFeature.setClipped(true);
if (null == maxScreenBbox) {
maxScreenBbox = JTS.toGeometry(getMaxScreenEnvelope(tile, panOrigin));
}
Geometry clipped = maxScreenBbox.intersection(feature.getGeometry());
vectorFeature.setClippedGeometry(clipped);
tile.addFeature(vectorFeature);
} else {
tile.addFeature(feature);
}
}
log.debug("clipTile after {}", tile);
} | [
"public",
"void",
"clipTile",
"(",
"InternalTile",
"tile",
",",
"double",
"scale",
",",
"Coordinate",
"panOrigin",
")",
"throws",
"GeomajasException",
"{",
"log",
".",
"debug",
"(",
"\"clipTile before {}\"",
",",
"tile",
")",
";",
"List",
"<",
"InternalFeature",
">",
"orgFeatures",
"=",
"tile",
".",
"getFeatures",
"(",
")",
";",
"tile",
".",
"setFeatures",
"(",
"new",
"ArrayList",
"<",
"InternalFeature",
">",
"(",
")",
")",
";",
"Geometry",
"maxScreenBbox",
"=",
"null",
";",
"// The tile's maximum bounds in screen space. Used for clipping.",
"for",
"(",
"InternalFeature",
"feature",
":",
"orgFeatures",
")",
"{",
"// clip feature if necessary",
"if",
"(",
"exceedsScreenDimensions",
"(",
"feature",
",",
"scale",
")",
")",
"{",
"log",
".",
"debug",
"(",
"\"feature {} exceeds screen dimensions\"",
",",
"feature",
")",
";",
"InternalFeatureImpl",
"vectorFeature",
"=",
"(",
"InternalFeatureImpl",
")",
"feature",
".",
"clone",
"(",
")",
";",
"tile",
".",
"setClipped",
"(",
"true",
")",
";",
"vectorFeature",
".",
"setClipped",
"(",
"true",
")",
";",
"if",
"(",
"null",
"==",
"maxScreenBbox",
")",
"{",
"maxScreenBbox",
"=",
"JTS",
".",
"toGeometry",
"(",
"getMaxScreenEnvelope",
"(",
"tile",
",",
"panOrigin",
")",
")",
";",
"}",
"Geometry",
"clipped",
"=",
"maxScreenBbox",
".",
"intersection",
"(",
"feature",
".",
"getGeometry",
"(",
")",
")",
";",
"vectorFeature",
".",
"setClippedGeometry",
"(",
"clipped",
")",
";",
"tile",
".",
"addFeature",
"(",
"vectorFeature",
")",
";",
"}",
"else",
"{",
"tile",
".",
"addFeature",
"(",
"feature",
")",
";",
"}",
"}",
"log",
".",
"debug",
"(",
"\"clipTile after {}\"",
",",
"tile",
")",
";",
"}"
] | Apply clipping to the features in a tile. The tile and its features should already be in map space.
@param tile
tile to put features in
@param scale
scale
@param panOrigin
When panning on the client, only this parameter changes. So we need to be aware of it as we calculate
the maxScreenEnvelope.
@throws GeomajasException oops | [
"Apply",
"clipping",
"to",
"the",
"features",
"in",
"a",
"tile",
".",
"The",
"tile",
"and",
"its",
"features",
"should",
"already",
"be",
"in",
"map",
"space",
"."
] | train | https://github.com/geomajas/geomajas-project-server/blob/904b7d7deed1350d28955589098dd1e0a786d76e/impl/src/main/java/org/geomajas/internal/rendering/strategy/TiledFeatureService.java#L95-L118 |
duracloud/duracloud | retrievaltool/src/main/java/org/duracloud/retrieval/mgmt/RetrievalWorker.java | RetrievalWorker.checksumsMatch | protected boolean checksumsMatch(File localFile, String remoteChecksum)
throws IOException {
"""
/*
Checks to see if the checksums of the local file and remote file match
"""
if (remoteChecksum == null || "".equals(remoteChecksum)) {
if (contentStream != null) {
remoteChecksum = contentStream.getChecksum();
} else {
remoteChecksum = source.getSourceChecksum(contentItem);
}
}
String localChecksum = getChecksum(localFile);
return localChecksum.equals(remoteChecksum);
} | java | protected boolean checksumsMatch(File localFile, String remoteChecksum)
throws IOException {
if (remoteChecksum == null || "".equals(remoteChecksum)) {
if (contentStream != null) {
remoteChecksum = contentStream.getChecksum();
} else {
remoteChecksum = source.getSourceChecksum(contentItem);
}
}
String localChecksum = getChecksum(localFile);
return localChecksum.equals(remoteChecksum);
} | [
"protected",
"boolean",
"checksumsMatch",
"(",
"File",
"localFile",
",",
"String",
"remoteChecksum",
")",
"throws",
"IOException",
"{",
"if",
"(",
"remoteChecksum",
"==",
"null",
"||",
"\"\"",
".",
"equals",
"(",
"remoteChecksum",
")",
")",
"{",
"if",
"(",
"contentStream",
"!=",
"null",
")",
"{",
"remoteChecksum",
"=",
"contentStream",
".",
"getChecksum",
"(",
")",
";",
"}",
"else",
"{",
"remoteChecksum",
"=",
"source",
".",
"getSourceChecksum",
"(",
"contentItem",
")",
";",
"}",
"}",
"String",
"localChecksum",
"=",
"getChecksum",
"(",
"localFile",
")",
";",
"return",
"localChecksum",
".",
"equals",
"(",
"remoteChecksum",
")",
";",
"}"
] | /*
Checks to see if the checksums of the local file and remote file match | [
"/",
"*",
"Checks",
"to",
"see",
"if",
"the",
"checksums",
"of",
"the",
"local",
"file",
"and",
"remote",
"file",
"match"
] | train | https://github.com/duracloud/duracloud/blob/dc4f3a1716d43543cc3b2e1880605f9389849b66/retrievaltool/src/main/java/org/duracloud/retrieval/mgmt/RetrievalWorker.java#L169-L180 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/dataset/api/preprocessor/MultiNormalizerHybrid.java | MultiNormalizerHybrid.minMaxScaleOutput | public MultiNormalizerHybrid minMaxScaleOutput(int output, double rangeFrom, double rangeTo) {
"""
Apply min-max scaling to a specific output, overriding the global output strategy if any
@param output the index of the input
@param rangeFrom lower bound of the target range
@param rangeTo upper bound of the target range
@return the normalizer
"""
perOutputStrategies.put(output, new MinMaxStrategy(rangeFrom, rangeTo));
return this;
} | java | public MultiNormalizerHybrid minMaxScaleOutput(int output, double rangeFrom, double rangeTo) {
perOutputStrategies.put(output, new MinMaxStrategy(rangeFrom, rangeTo));
return this;
} | [
"public",
"MultiNormalizerHybrid",
"minMaxScaleOutput",
"(",
"int",
"output",
",",
"double",
"rangeFrom",
",",
"double",
"rangeTo",
")",
"{",
"perOutputStrategies",
".",
"put",
"(",
"output",
",",
"new",
"MinMaxStrategy",
"(",
"rangeFrom",
",",
"rangeTo",
")",
")",
";",
"return",
"this",
";",
"}"
] | Apply min-max scaling to a specific output, overriding the global output strategy if any
@param output the index of the input
@param rangeFrom lower bound of the target range
@param rangeTo upper bound of the target range
@return the normalizer | [
"Apply",
"min",
"-",
"max",
"scaling",
"to",
"a",
"specific",
"output",
"overriding",
"the",
"global",
"output",
"strategy",
"if",
"any"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/dataset/api/preprocessor/MultiNormalizerHybrid.java#L188-L191 |
joniles/mpxj | src/main/java/net/sf/mpxj/Duration.java | Duration.add | public static Duration add(Duration a, Duration b, ProjectProperties defaults) {
"""
If a and b are not null, returns a new duration of a + b.
If a is null and b is not null, returns b.
If a is not null and b is null, returns a.
If a and b are null, returns null.
If needed, b is converted to a's time unit using the project properties.
@param a first duration
@param b second duration
@param defaults project properties containing default values
@return a + b
"""
if (a == null && b == null)
{
return null;
}
if (a == null)
{
return b;
}
if (b == null)
{
return a;
}
TimeUnit unit = a.getUnits();
if (b.getUnits() != unit)
{
b = b.convertUnits(unit, defaults);
}
return Duration.getInstance(a.getDuration() + b.getDuration(), unit);
} | java | public static Duration add(Duration a, Duration b, ProjectProperties defaults)
{
if (a == null && b == null)
{
return null;
}
if (a == null)
{
return b;
}
if (b == null)
{
return a;
}
TimeUnit unit = a.getUnits();
if (b.getUnits() != unit)
{
b = b.convertUnits(unit, defaults);
}
return Duration.getInstance(a.getDuration() + b.getDuration(), unit);
} | [
"public",
"static",
"Duration",
"add",
"(",
"Duration",
"a",
",",
"Duration",
"b",
",",
"ProjectProperties",
"defaults",
")",
"{",
"if",
"(",
"a",
"==",
"null",
"&&",
"b",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"a",
"==",
"null",
")",
"{",
"return",
"b",
";",
"}",
"if",
"(",
"b",
"==",
"null",
")",
"{",
"return",
"a",
";",
"}",
"TimeUnit",
"unit",
"=",
"a",
".",
"getUnits",
"(",
")",
";",
"if",
"(",
"b",
".",
"getUnits",
"(",
")",
"!=",
"unit",
")",
"{",
"b",
"=",
"b",
".",
"convertUnits",
"(",
"unit",
",",
"defaults",
")",
";",
"}",
"return",
"Duration",
".",
"getInstance",
"(",
"a",
".",
"getDuration",
"(",
")",
"+",
"b",
".",
"getDuration",
"(",
")",
",",
"unit",
")",
";",
"}"
] | If a and b are not null, returns a new duration of a + b.
If a is null and b is not null, returns b.
If a is not null and b is null, returns a.
If a and b are null, returns null.
If needed, b is converted to a's time unit using the project properties.
@param a first duration
@param b second duration
@param defaults project properties containing default values
@return a + b | [
"If",
"a",
"and",
"b",
"are",
"not",
"null",
"returns",
"a",
"new",
"duration",
"of",
"a",
"+",
"b",
".",
"If",
"a",
"is",
"null",
"and",
"b",
"is",
"not",
"null",
"returns",
"b",
".",
"If",
"a",
"is",
"not",
"null",
"and",
"b",
"is",
"null",
"returns",
"a",
".",
"If",
"a",
"and",
"b",
"are",
"null",
"returns",
"null",
".",
"If",
"needed",
"b",
"is",
"converted",
"to",
"a",
"s",
"time",
"unit",
"using",
"the",
"project",
"properties",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/Duration.java#L405-L426 |
bazaarvoice/emodb | mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/LocationUtil.java | LocationUtil.getCuratorForLocation | public static Optional<CuratorFramework> getCuratorForLocation(URI location) {
"""
Returns a configured, started Curator for a given location, or absent if the location does not
use host discovery.
"""
final String defaultConnectionString;
final String namespace;
if (getLocationType(location) != LocationType.EMO_HOST_DISCOVERY) {
// Only host discovery may require ZooKeeper
return Optional.absent();
}
if (getHostOverride(location).isPresent()) {
// Fixed host discovery doesn't require ZooKeeper
return Optional.absent();
}
Matcher matcher = getLocatorMatcher(location);
checkArgument(matcher.matches(), "Invalid location: %s", location);
if (matcher.group("universe") != null) {
// Normal host discovery
String universe = matcher.group("universe");
Region region = getRegion(Objects.firstNonNull(matcher.group("region"), DEFAULT_REGION));
namespace = format("%s/%s", universe, region);
defaultConnectionString = DEFAULT_ZK_CONNECTION_STRING;
} else {
// Local host discovery; typically for developer testing
namespace = null;
defaultConnectionString = DEFAULT_LOCAL_ZK_CONNECTION_STRING;
}
String connectionString = getZkConnectionStringOverride(location).or(defaultConnectionString);
CuratorFramework curator = CuratorFrameworkFactory.builder()
.ensembleProvider(new ResolvingEnsembleProvider(connectionString))
.retryPolicy(new BoundedExponentialBackoffRetry(100, 1000, 10))
.threadFactory(new ThreadFactoryBuilder().setNameFormat("emo-zookeeper-%d").build())
.namespace(namespace)
.build();
curator.start();
return Optional.of(curator);
} | java | public static Optional<CuratorFramework> getCuratorForLocation(URI location) {
final String defaultConnectionString;
final String namespace;
if (getLocationType(location) != LocationType.EMO_HOST_DISCOVERY) {
// Only host discovery may require ZooKeeper
return Optional.absent();
}
if (getHostOverride(location).isPresent()) {
// Fixed host discovery doesn't require ZooKeeper
return Optional.absent();
}
Matcher matcher = getLocatorMatcher(location);
checkArgument(matcher.matches(), "Invalid location: %s", location);
if (matcher.group("universe") != null) {
// Normal host discovery
String universe = matcher.group("universe");
Region region = getRegion(Objects.firstNonNull(matcher.group("region"), DEFAULT_REGION));
namespace = format("%s/%s", universe, region);
defaultConnectionString = DEFAULT_ZK_CONNECTION_STRING;
} else {
// Local host discovery; typically for developer testing
namespace = null;
defaultConnectionString = DEFAULT_LOCAL_ZK_CONNECTION_STRING;
}
String connectionString = getZkConnectionStringOverride(location).or(defaultConnectionString);
CuratorFramework curator = CuratorFrameworkFactory.builder()
.ensembleProvider(new ResolvingEnsembleProvider(connectionString))
.retryPolicy(new BoundedExponentialBackoffRetry(100, 1000, 10))
.threadFactory(new ThreadFactoryBuilder().setNameFormat("emo-zookeeper-%d").build())
.namespace(namespace)
.build();
curator.start();
return Optional.of(curator);
} | [
"public",
"static",
"Optional",
"<",
"CuratorFramework",
">",
"getCuratorForLocation",
"(",
"URI",
"location",
")",
"{",
"final",
"String",
"defaultConnectionString",
";",
"final",
"String",
"namespace",
";",
"if",
"(",
"getLocationType",
"(",
"location",
")",
"!=",
"LocationType",
".",
"EMO_HOST_DISCOVERY",
")",
"{",
"// Only host discovery may require ZooKeeper",
"return",
"Optional",
".",
"absent",
"(",
")",
";",
"}",
"if",
"(",
"getHostOverride",
"(",
"location",
")",
".",
"isPresent",
"(",
")",
")",
"{",
"// Fixed host discovery doesn't require ZooKeeper",
"return",
"Optional",
".",
"absent",
"(",
")",
";",
"}",
"Matcher",
"matcher",
"=",
"getLocatorMatcher",
"(",
"location",
")",
";",
"checkArgument",
"(",
"matcher",
".",
"matches",
"(",
")",
",",
"\"Invalid location: %s\"",
",",
"location",
")",
";",
"if",
"(",
"matcher",
".",
"group",
"(",
"\"universe\"",
")",
"!=",
"null",
")",
"{",
"// Normal host discovery",
"String",
"universe",
"=",
"matcher",
".",
"group",
"(",
"\"universe\"",
")",
";",
"Region",
"region",
"=",
"getRegion",
"(",
"Objects",
".",
"firstNonNull",
"(",
"matcher",
".",
"group",
"(",
"\"region\"",
")",
",",
"DEFAULT_REGION",
")",
")",
";",
"namespace",
"=",
"format",
"(",
"\"%s/%s\"",
",",
"universe",
",",
"region",
")",
";",
"defaultConnectionString",
"=",
"DEFAULT_ZK_CONNECTION_STRING",
";",
"}",
"else",
"{",
"// Local host discovery; typically for developer testing",
"namespace",
"=",
"null",
";",
"defaultConnectionString",
"=",
"DEFAULT_LOCAL_ZK_CONNECTION_STRING",
";",
"}",
"String",
"connectionString",
"=",
"getZkConnectionStringOverride",
"(",
"location",
")",
".",
"or",
"(",
"defaultConnectionString",
")",
";",
"CuratorFramework",
"curator",
"=",
"CuratorFrameworkFactory",
".",
"builder",
"(",
")",
".",
"ensembleProvider",
"(",
"new",
"ResolvingEnsembleProvider",
"(",
"connectionString",
")",
")",
".",
"retryPolicy",
"(",
"new",
"BoundedExponentialBackoffRetry",
"(",
"100",
",",
"1000",
",",
"10",
")",
")",
".",
"threadFactory",
"(",
"new",
"ThreadFactoryBuilder",
"(",
")",
".",
"setNameFormat",
"(",
"\"emo-zookeeper-%d\"",
")",
".",
"build",
"(",
")",
")",
".",
"namespace",
"(",
"namespace",
")",
".",
"build",
"(",
")",
";",
"curator",
".",
"start",
"(",
")",
";",
"return",
"Optional",
".",
"of",
"(",
"curator",
")",
";",
"}"
] | Returns a configured, started Curator for a given location, or absent if the location does not
use host discovery. | [
"Returns",
"a",
"configured",
"started",
"Curator",
"for",
"a",
"given",
"location",
"or",
"absent",
"if",
"the",
"location",
"does",
"not",
"use",
"host",
"discovery",
"."
] | train | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/LocationUtil.java#L198-L239 |
knowm/Yank | src/main/java/org/knowm/yank/Yank.java | Yank.queryBeanListSQLKey | public static <T> List<T> queryBeanListSQLKey(String sqlKey, Class<T> beanType, Object[] params)
throws SQLStatementNotFoundException, YankSQLException {
"""
Return a List of Beans given a SQL Key using an SQL statement matching the sqlKey String in a
properties file loaded via Yank.addSQLStatements(...) using the default connection pool.
@param sqlKey The SQL Key found in a properties file corresponding to the desired SQL statement
value
@param beanType The Class of the desired return Objects matching the table
@param params The replacement parameters
@return The List of Objects
@throws SQLStatementNotFoundException if an SQL statement could not be found for the given
sqlKey String
"""
return queryBeanListSQLKey(YankPoolManager.DEFAULT_POOL_NAME, sqlKey, beanType, params);
} | java | public static <T> List<T> queryBeanListSQLKey(String sqlKey, Class<T> beanType, Object[] params)
throws SQLStatementNotFoundException, YankSQLException {
return queryBeanListSQLKey(YankPoolManager.DEFAULT_POOL_NAME, sqlKey, beanType, params);
} | [
"public",
"static",
"<",
"T",
">",
"List",
"<",
"T",
">",
"queryBeanListSQLKey",
"(",
"String",
"sqlKey",
",",
"Class",
"<",
"T",
">",
"beanType",
",",
"Object",
"[",
"]",
"params",
")",
"throws",
"SQLStatementNotFoundException",
",",
"YankSQLException",
"{",
"return",
"queryBeanListSQLKey",
"(",
"YankPoolManager",
".",
"DEFAULT_POOL_NAME",
",",
"sqlKey",
",",
"beanType",
",",
"params",
")",
";",
"}"
] | Return a List of Beans given a SQL Key using an SQL statement matching the sqlKey String in a
properties file loaded via Yank.addSQLStatements(...) using the default connection pool.
@param sqlKey The SQL Key found in a properties file corresponding to the desired SQL statement
value
@param beanType The Class of the desired return Objects matching the table
@param params The replacement parameters
@return The List of Objects
@throws SQLStatementNotFoundException if an SQL statement could not be found for the given
sqlKey String | [
"Return",
"a",
"List",
"of",
"Beans",
"given",
"a",
"SQL",
"Key",
"using",
"an",
"SQL",
"statement",
"matching",
"the",
"sqlKey",
"String",
"in",
"a",
"properties",
"file",
"loaded",
"via",
"Yank",
".",
"addSQLStatements",
"(",
"...",
")",
"using",
"the",
"default",
"connection",
"pool",
"."
] | train | https://github.com/knowm/Yank/blob/b2071dcd94da99db6904355f9557456b8b292a6b/src/main/java/org/knowm/yank/Yank.java#L431-L435 |
OpenLiberty/open-liberty | dev/wlp-generateRepositoryContent/src/com/ibm/ws/wlp/repository/esa/GenerateEsas.java | GenerateEsas.copy | private void copy(OutputStream out, File in) throws IOException {
"""
Copies the file to the output stream
@param out The stream to write to
@param in The file to write
@throws IOException If something goes wrong
"""
FileInputStream inStream = null;
try {
inStream = new FileInputStream(in);
byte[] buffer = new byte[4096];
int len;
while ((len = inStream.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
} finally {
if (inStream != null) {
inStream.close();
}
}
} | java | private void copy(OutputStream out, File in) throws IOException {
FileInputStream inStream = null;
try {
inStream = new FileInputStream(in);
byte[] buffer = new byte[4096];
int len;
while ((len = inStream.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
} finally {
if (inStream != null) {
inStream.close();
}
}
} | [
"private",
"void",
"copy",
"(",
"OutputStream",
"out",
",",
"File",
"in",
")",
"throws",
"IOException",
"{",
"FileInputStream",
"inStream",
"=",
"null",
";",
"try",
"{",
"inStream",
"=",
"new",
"FileInputStream",
"(",
"in",
")",
";",
"byte",
"[",
"]",
"buffer",
"=",
"new",
"byte",
"[",
"4096",
"]",
";",
"int",
"len",
";",
"while",
"(",
"(",
"len",
"=",
"inStream",
".",
"read",
"(",
"buffer",
")",
")",
"!=",
"-",
"1",
")",
"{",
"out",
".",
"write",
"(",
"buffer",
",",
"0",
",",
"len",
")",
";",
"}",
"}",
"finally",
"{",
"if",
"(",
"inStream",
"!=",
"null",
")",
"{",
"inStream",
".",
"close",
"(",
")",
";",
"}",
"}",
"}"
] | Copies the file to the output stream
@param out The stream to write to
@param in The file to write
@throws IOException If something goes wrong | [
"Copies",
"the",
"file",
"to",
"the",
"output",
"stream"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/wlp-generateRepositoryContent/src/com/ibm/ws/wlp/repository/esa/GenerateEsas.java#L733-L748 |
VoltDB/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/jdbc/JDBCResultSet.java | JDBCResultSet.updateString | public void updateString(int columnIndex, String x) throws SQLException {
"""
<!-- start generic documentation -->
Updates the designated column with a <code>String</code> value.
The updater methods are used to update column values in the
current row or the insert row. The updater methods do not
update the underlying database; instead the <code>updateRow</code> or
<code>insertRow</code> methods are called to update the database.
<!-- end generic documentation -->
<!-- start release-specific documentation -->
<div class="ReleaseSpecificDocumentation">
<h3>HSQLDB-Specific Information:</h3> <p>
HSQLDB supports this feature. <p>
</div>
<!-- end release-specific documentation -->
@param columnIndex the first column is 1, the second is 2, ...
@param x the new column value
@exception SQLException if a database access error occurs,
the result set concurrency is <code>CONCUR_READ_ONLY</code>
or this method is called on a closed result set
@exception SQLFeatureNotSupportedException if the JDBC driver does not support
this method
@since JDK 1.2 (JDK 1.1.x developers: read the overview for
JDBCResultSet)
"""
startUpdate(columnIndex);
preparedStatement.setParameter(columnIndex, x);
} | java | public void updateString(int columnIndex, String x) throws SQLException {
startUpdate(columnIndex);
preparedStatement.setParameter(columnIndex, x);
} | [
"public",
"void",
"updateString",
"(",
"int",
"columnIndex",
",",
"String",
"x",
")",
"throws",
"SQLException",
"{",
"startUpdate",
"(",
"columnIndex",
")",
";",
"preparedStatement",
".",
"setParameter",
"(",
"columnIndex",
",",
"x",
")",
";",
"}"
] | <!-- start generic documentation -->
Updates the designated column with a <code>String</code> value.
The updater methods are used to update column values in the
current row or the insert row. The updater methods do not
update the underlying database; instead the <code>updateRow</code> or
<code>insertRow</code> methods are called to update the database.
<!-- end generic documentation -->
<!-- start release-specific documentation -->
<div class="ReleaseSpecificDocumentation">
<h3>HSQLDB-Specific Information:</h3> <p>
HSQLDB supports this feature. <p>
</div>
<!-- end release-specific documentation -->
@param columnIndex the first column is 1, the second is 2, ...
@param x the new column value
@exception SQLException if a database access error occurs,
the result set concurrency is <code>CONCUR_READ_ONLY</code>
or this method is called on a closed result set
@exception SQLFeatureNotSupportedException if the JDBC driver does not support
this method
@since JDK 1.2 (JDK 1.1.x developers: read the overview for
JDBCResultSet) | [
"<!",
"--",
"start",
"generic",
"documentation",
"--",
">",
"Updates",
"the",
"designated",
"column",
"with",
"a",
"<code",
">",
"String<",
"/",
"code",
">",
"value",
".",
"The",
"updater",
"methods",
"are",
"used",
"to",
"update",
"column",
"values",
"in",
"the",
"current",
"row",
"or",
"the",
"insert",
"row",
".",
"The",
"updater",
"methods",
"do",
"not",
"update",
"the",
"underlying",
"database",
";",
"instead",
"the",
"<code",
">",
"updateRow<",
"/",
"code",
">",
"or",
"<code",
">",
"insertRow<",
"/",
"code",
">",
"methods",
"are",
"called",
"to",
"update",
"the",
"database",
".",
"<!",
"--",
"end",
"generic",
"documentation",
"--",
">"
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/jdbc/JDBCResultSet.java#L2917-L2920 |
liferay/com-liferay-commerce | commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDefinitionOptionValueRelPersistenceImpl.java | CPDefinitionOptionValueRelPersistenceImpl.countByC_K | @Override
public int countByC_K(long CPDefinitionOptionRelId, String key) {
"""
Returns the number of cp definition option value rels where CPDefinitionOptionRelId = ? and key = ?.
@param CPDefinitionOptionRelId the cp definition option rel ID
@param key the key
@return the number of matching cp definition option value rels
"""
FinderPath finderPath = FINDER_PATH_COUNT_BY_C_K;
Object[] finderArgs = new Object[] { CPDefinitionOptionRelId, key };
Long count = (Long)finderCache.getResult(finderPath, finderArgs, this);
if (count == null) {
StringBundler query = new StringBundler(3);
query.append(_SQL_COUNT_CPDEFINITIONOPTIONVALUEREL_WHERE);
query.append(_FINDER_COLUMN_C_K_CPDEFINITIONOPTIONRELID_2);
boolean bindKey = false;
if (key == null) {
query.append(_FINDER_COLUMN_C_K_KEY_1);
}
else if (key.equals("")) {
query.append(_FINDER_COLUMN_C_K_KEY_3);
}
else {
bindKey = true;
query.append(_FINDER_COLUMN_C_K_KEY_2);
}
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
qPos.add(CPDefinitionOptionRelId);
if (bindKey) {
qPos.add(key);
}
count = (Long)q.uniqueResult();
finderCache.putResult(finderPath, finderArgs, count);
}
catch (Exception e) {
finderCache.removeResult(finderPath, finderArgs);
throw processException(e);
}
finally {
closeSession(session);
}
}
return count.intValue();
} | java | @Override
public int countByC_K(long CPDefinitionOptionRelId, String key) {
FinderPath finderPath = FINDER_PATH_COUNT_BY_C_K;
Object[] finderArgs = new Object[] { CPDefinitionOptionRelId, key };
Long count = (Long)finderCache.getResult(finderPath, finderArgs, this);
if (count == null) {
StringBundler query = new StringBundler(3);
query.append(_SQL_COUNT_CPDEFINITIONOPTIONVALUEREL_WHERE);
query.append(_FINDER_COLUMN_C_K_CPDEFINITIONOPTIONRELID_2);
boolean bindKey = false;
if (key == null) {
query.append(_FINDER_COLUMN_C_K_KEY_1);
}
else if (key.equals("")) {
query.append(_FINDER_COLUMN_C_K_KEY_3);
}
else {
bindKey = true;
query.append(_FINDER_COLUMN_C_K_KEY_2);
}
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
qPos.add(CPDefinitionOptionRelId);
if (bindKey) {
qPos.add(key);
}
count = (Long)q.uniqueResult();
finderCache.putResult(finderPath, finderArgs, count);
}
catch (Exception e) {
finderCache.removeResult(finderPath, finderArgs);
throw processException(e);
}
finally {
closeSession(session);
}
}
return count.intValue();
} | [
"@",
"Override",
"public",
"int",
"countByC_K",
"(",
"long",
"CPDefinitionOptionRelId",
",",
"String",
"key",
")",
"{",
"FinderPath",
"finderPath",
"=",
"FINDER_PATH_COUNT_BY_C_K",
";",
"Object",
"[",
"]",
"finderArgs",
"=",
"new",
"Object",
"[",
"]",
"{",
"CPDefinitionOptionRelId",
",",
"key",
"}",
";",
"Long",
"count",
"=",
"(",
"Long",
")",
"finderCache",
".",
"getResult",
"(",
"finderPath",
",",
"finderArgs",
",",
"this",
")",
";",
"if",
"(",
"count",
"==",
"null",
")",
"{",
"StringBundler",
"query",
"=",
"new",
"StringBundler",
"(",
"3",
")",
";",
"query",
".",
"append",
"(",
"_SQL_COUNT_CPDEFINITIONOPTIONVALUEREL_WHERE",
")",
";",
"query",
".",
"append",
"(",
"_FINDER_COLUMN_C_K_CPDEFINITIONOPTIONRELID_2",
")",
";",
"boolean",
"bindKey",
"=",
"false",
";",
"if",
"(",
"key",
"==",
"null",
")",
"{",
"query",
".",
"append",
"(",
"_FINDER_COLUMN_C_K_KEY_1",
")",
";",
"}",
"else",
"if",
"(",
"key",
".",
"equals",
"(",
"\"\"",
")",
")",
"{",
"query",
".",
"append",
"(",
"_FINDER_COLUMN_C_K_KEY_3",
")",
";",
"}",
"else",
"{",
"bindKey",
"=",
"true",
";",
"query",
".",
"append",
"(",
"_FINDER_COLUMN_C_K_KEY_2",
")",
";",
"}",
"String",
"sql",
"=",
"query",
".",
"toString",
"(",
")",
";",
"Session",
"session",
"=",
"null",
";",
"try",
"{",
"session",
"=",
"openSession",
"(",
")",
";",
"Query",
"q",
"=",
"session",
".",
"createQuery",
"(",
"sql",
")",
";",
"QueryPos",
"qPos",
"=",
"QueryPos",
".",
"getInstance",
"(",
"q",
")",
";",
"qPos",
".",
"add",
"(",
"CPDefinitionOptionRelId",
")",
";",
"if",
"(",
"bindKey",
")",
"{",
"qPos",
".",
"add",
"(",
"key",
")",
";",
"}",
"count",
"=",
"(",
"Long",
")",
"q",
".",
"uniqueResult",
"(",
")",
";",
"finderCache",
".",
"putResult",
"(",
"finderPath",
",",
"finderArgs",
",",
"count",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"finderCache",
".",
"removeResult",
"(",
"finderPath",
",",
"finderArgs",
")",
";",
"throw",
"processException",
"(",
"e",
")",
";",
"}",
"finally",
"{",
"closeSession",
"(",
"session",
")",
";",
"}",
"}",
"return",
"count",
".",
"intValue",
"(",
")",
";",
"}"
] | Returns the number of cp definition option value rels where CPDefinitionOptionRelId = ? and key = ?.
@param CPDefinitionOptionRelId the cp definition option rel ID
@param key the key
@return the number of matching cp definition option value rels | [
"Returns",
"the",
"number",
"of",
"cp",
"definition",
"option",
"value",
"rels",
"where",
"CPDefinitionOptionRelId",
"=",
"?",
";",
"and",
"key",
"=",
"?",
";",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDefinitionOptionValueRelPersistenceImpl.java#L3808-L3869 |
Pi4J/pi4j | pi4j-core/src/main/java/com/pi4j/io/spi/SpiFactory.java | SpiFactory.getInstance | public static SpiDevice getInstance(SpiChannel channel, SpiMode mode) throws IOException {
"""
Create new SpiDevice instance
@param channel
spi channel to use
@param mode
spi mode (see http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus#Mode_numbers)
@return Return a new SpiDevice impl instance.
@throws java.io.IOException
"""
return new SpiDeviceImpl(channel, mode);
} | java | public static SpiDevice getInstance(SpiChannel channel, SpiMode mode) throws IOException {
return new SpiDeviceImpl(channel, mode);
} | [
"public",
"static",
"SpiDevice",
"getInstance",
"(",
"SpiChannel",
"channel",
",",
"SpiMode",
"mode",
")",
"throws",
"IOException",
"{",
"return",
"new",
"SpiDeviceImpl",
"(",
"channel",
",",
"mode",
")",
";",
"}"
] | Create new SpiDevice instance
@param channel
spi channel to use
@param mode
spi mode (see http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus#Mode_numbers)
@return Return a new SpiDevice impl instance.
@throws java.io.IOException | [
"Create",
"new",
"SpiDevice",
"instance"
] | train | https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/io/spi/SpiFactory.java#L75-L77 |
timols/java-gitlab-api | src/main/java/org/gitlab/api/GitlabAPI.java | GitlabAPI.createUserProject | public GitlabProject createUserProject(Integer userId, String name) throws IOException {
"""
Creates a Project for a specific User
@param userId The id of the user to create the project for
@param name The name of the project
@return The GitLab Project
@throws IOException on gitlab api call error
"""
return createUserProject(userId, name, null, null, null, null, null, null, null, null, null);
} | java | public GitlabProject createUserProject(Integer userId, String name) throws IOException {
return createUserProject(userId, name, null, null, null, null, null, null, null, null, null);
} | [
"public",
"GitlabProject",
"createUserProject",
"(",
"Integer",
"userId",
",",
"String",
"name",
")",
"throws",
"IOException",
"{",
"return",
"createUserProject",
"(",
"userId",
",",
"name",
",",
"null",
",",
"null",
",",
"null",
",",
"null",
",",
"null",
",",
"null",
",",
"null",
",",
"null",
",",
"null",
")",
";",
"}"
] | Creates a Project for a specific User
@param userId The id of the user to create the project for
@param name The name of the project
@return The GitLab Project
@throws IOException on gitlab api call error | [
"Creates",
"a",
"Project",
"for",
"a",
"specific",
"User"
] | train | https://github.com/timols/java-gitlab-api/blob/f03eedf952cfbb40306be3bf9234dcf78fab029e/src/main/java/org/gitlab/api/GitlabAPI.java#L1276-L1278 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/SubnetworkClient.java | SubnetworkClient.insertSubnetwork | @BetaApi
public final Operation insertSubnetwork(String region, Subnetwork subnetworkResource) {
"""
Creates a subnetwork in the specified project using the data included in the request.
<p>Sample code:
<pre><code>
try (SubnetworkClient subnetworkClient = SubnetworkClient.create()) {
ProjectRegionName region = ProjectRegionName.of("[PROJECT]", "[REGION]");
Subnetwork subnetworkResource = Subnetwork.newBuilder().build();
Operation response = subnetworkClient.insertSubnetwork(region.toString(), subnetworkResource);
}
</code></pre>
@param region Name of the region scoping this request.
@param subnetworkResource A Subnetwork resource. (== resource_for beta.subnetworks ==) (==
resource_for v1.subnetworks ==)
@throws com.google.api.gax.rpc.ApiException if the remote call fails
"""
InsertSubnetworkHttpRequest request =
InsertSubnetworkHttpRequest.newBuilder()
.setRegion(region)
.setSubnetworkResource(subnetworkResource)
.build();
return insertSubnetwork(request);
} | java | @BetaApi
public final Operation insertSubnetwork(String region, Subnetwork subnetworkResource) {
InsertSubnetworkHttpRequest request =
InsertSubnetworkHttpRequest.newBuilder()
.setRegion(region)
.setSubnetworkResource(subnetworkResource)
.build();
return insertSubnetwork(request);
} | [
"@",
"BetaApi",
"public",
"final",
"Operation",
"insertSubnetwork",
"(",
"String",
"region",
",",
"Subnetwork",
"subnetworkResource",
")",
"{",
"InsertSubnetworkHttpRequest",
"request",
"=",
"InsertSubnetworkHttpRequest",
".",
"newBuilder",
"(",
")",
".",
"setRegion",
"(",
"region",
")",
".",
"setSubnetworkResource",
"(",
"subnetworkResource",
")",
".",
"build",
"(",
")",
";",
"return",
"insertSubnetwork",
"(",
"request",
")",
";",
"}"
] | Creates a subnetwork in the specified project using the data included in the request.
<p>Sample code:
<pre><code>
try (SubnetworkClient subnetworkClient = SubnetworkClient.create()) {
ProjectRegionName region = ProjectRegionName.of("[PROJECT]", "[REGION]");
Subnetwork subnetworkResource = Subnetwork.newBuilder().build();
Operation response = subnetworkClient.insertSubnetwork(region.toString(), subnetworkResource);
}
</code></pre>
@param region Name of the region scoping this request.
@param subnetworkResource A Subnetwork resource. (== resource_for beta.subnetworks ==) (==
resource_for v1.subnetworks ==)
@throws com.google.api.gax.rpc.ApiException if the remote call fails | [
"Creates",
"a",
"subnetwork",
"in",
"the",
"specified",
"project",
"using",
"the",
"data",
"included",
"in",
"the",
"request",
"."
] | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/SubnetworkClient.java#L756-L765 |
openbaton/openbaton-client | sdk/src/main/java/org/openbaton/sdk/api/rest/NetworkServiceRecordAgent.java | NetworkServiceRecordAgent.restartVnfr | @Help(help = "Scales out/add a VNF to a running NetworkServiceRecord with specific id")
public void restartVnfr(final String idNsr, final String idVnfr, String imageName)
throws SDKException {
"""
Restarts a VNFR in a running NSR.
@param idNsr the ID of the NetworkServiceRecord
@param idVnfr the ID of the VNFR to restart
@param imageName rebuilding the VNFR with a different image if defined
@throws SDKException if the request fails
"""
HashMap<String, Serializable> jsonBody = new HashMap<>();
jsonBody.put("imageName", imageName);
String url = idNsr + "/vnfrecords" + "/" + idVnfr + "/restart";
requestPost(url, jsonBody);
} | java | @Help(help = "Scales out/add a VNF to a running NetworkServiceRecord with specific id")
public void restartVnfr(final String idNsr, final String idVnfr, String imageName)
throws SDKException {
HashMap<String, Serializable> jsonBody = new HashMap<>();
jsonBody.put("imageName", imageName);
String url = idNsr + "/vnfrecords" + "/" + idVnfr + "/restart";
requestPost(url, jsonBody);
} | [
"@",
"Help",
"(",
"help",
"=",
"\"Scales out/add a VNF to a running NetworkServiceRecord with specific id\"",
")",
"public",
"void",
"restartVnfr",
"(",
"final",
"String",
"idNsr",
",",
"final",
"String",
"idVnfr",
",",
"String",
"imageName",
")",
"throws",
"SDKException",
"{",
"HashMap",
"<",
"String",
",",
"Serializable",
">",
"jsonBody",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"jsonBody",
".",
"put",
"(",
"\"imageName\"",
",",
"imageName",
")",
";",
"String",
"url",
"=",
"idNsr",
"+",
"\"/vnfrecords\"",
"+",
"\"/\"",
"+",
"idVnfr",
"+",
"\"/restart\"",
";",
"requestPost",
"(",
"url",
",",
"jsonBody",
")",
";",
"}"
] | Restarts a VNFR in a running NSR.
@param idNsr the ID of the NetworkServiceRecord
@param idVnfr the ID of the VNFR to restart
@param imageName rebuilding the VNFR with a different image if defined
@throws SDKException if the request fails | [
"Restarts",
"a",
"VNFR",
"in",
"a",
"running",
"NSR",
"."
] | train | https://github.com/openbaton/openbaton-client/blob/6ca6dd6b62a23940d312213d6fa489d5b636061a/sdk/src/main/java/org/openbaton/sdk/api/rest/NetworkServiceRecordAgent.java#L674-L681 |
OpenLiberty/open-liberty | dev/com.ibm.ws.artifact.overlay/src/com/ibm/ws/artifact/overlay/internal/DirectoryBasedOverlayContainerImpl.java | DirectoryBasedOverlayContainerImpl.collectPaths | private void collectPaths(ArtifactContainer c, Set<String> s) {
"""
Little recursive routine to collect all the files present within a ArtifactContainer.<p>
@param c The ArtifactContainer to process
@param s The set to add paths to.
"""
if (!"/".equals(c.getPath())) {
s.add(c.getPath());
}
for (ArtifactEntry e : c) {
s.add(e.getPath());
ArtifactContainer n = e.convertToContainer();
if (n != null && !n.isRoot()) {
collectPaths(n, s);
}
}
} | java | private void collectPaths(ArtifactContainer c, Set<String> s) {
if (!"/".equals(c.getPath())) {
s.add(c.getPath());
}
for (ArtifactEntry e : c) {
s.add(e.getPath());
ArtifactContainer n = e.convertToContainer();
if (n != null && !n.isRoot()) {
collectPaths(n, s);
}
}
} | [
"private",
"void",
"collectPaths",
"(",
"ArtifactContainer",
"c",
",",
"Set",
"<",
"String",
">",
"s",
")",
"{",
"if",
"(",
"!",
"\"/\"",
".",
"equals",
"(",
"c",
".",
"getPath",
"(",
")",
")",
")",
"{",
"s",
".",
"add",
"(",
"c",
".",
"getPath",
"(",
")",
")",
";",
"}",
"for",
"(",
"ArtifactEntry",
"e",
":",
"c",
")",
"{",
"s",
".",
"add",
"(",
"e",
".",
"getPath",
"(",
")",
")",
";",
"ArtifactContainer",
"n",
"=",
"e",
".",
"convertToContainer",
"(",
")",
";",
"if",
"(",
"n",
"!=",
"null",
"&&",
"!",
"n",
".",
"isRoot",
"(",
")",
")",
"{",
"collectPaths",
"(",
"n",
",",
"s",
")",
";",
"}",
"}",
"}"
] | Little recursive routine to collect all the files present within a ArtifactContainer.<p>
@param c The ArtifactContainer to process
@param s The set to add paths to. | [
"Little",
"recursive",
"routine",
"to",
"collect",
"all",
"the",
"files",
"present",
"within",
"a",
"ArtifactContainer",
".",
"<p",
">"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.artifact.overlay/src/com/ibm/ws/artifact/overlay/internal/DirectoryBasedOverlayContainerImpl.java#L1153-L1164 |
OpenLiberty/open-liberty | dev/com.ibm.ws.transport.iiop/src/com/ibm/ws/transport/iiop/yoko/ORBConfigAdapter.java | ORBConfigAdapter.translateToClientProps | private Properties translateToClientProps(Map<String, Object> clientProps, Collection<SubsystemFactory> subsystemFactories) throws ConfigException {
"""
Translate client configuration into the
property bundle necessary to configure the
client ORB instance.
@param clientProps configuration properties
@param subsystemFactories configured subsystem factories
@return A property bundle that can be passed to ORB.init();
@exception ConfigException if configuration cannot be interpreted
"""
Properties result = createYokoORBProperties();
for (SubsystemFactory sf : subsystemFactories) {
addInitializerPropertyForSubsystem(result, sf, false);
sf.addClientORBInitProperties(result, clientProps);
}
return result;
} | java | private Properties translateToClientProps(Map<String, Object> clientProps, Collection<SubsystemFactory> subsystemFactories) throws ConfigException {
Properties result = createYokoORBProperties();
for (SubsystemFactory sf : subsystemFactories) {
addInitializerPropertyForSubsystem(result, sf, false);
sf.addClientORBInitProperties(result, clientProps);
}
return result;
} | [
"private",
"Properties",
"translateToClientProps",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"clientProps",
",",
"Collection",
"<",
"SubsystemFactory",
">",
"subsystemFactories",
")",
"throws",
"ConfigException",
"{",
"Properties",
"result",
"=",
"createYokoORBProperties",
"(",
")",
";",
"for",
"(",
"SubsystemFactory",
"sf",
":",
"subsystemFactories",
")",
"{",
"addInitializerPropertyForSubsystem",
"(",
"result",
",",
"sf",
",",
"false",
")",
";",
"sf",
".",
"addClientORBInitProperties",
"(",
"result",
",",
"clientProps",
")",
";",
"}",
"return",
"result",
";",
"}"
] | Translate client configuration into the
property bundle necessary to configure the
client ORB instance.
@param clientProps configuration properties
@param subsystemFactories configured subsystem factories
@return A property bundle that can be passed to ORB.init();
@exception ConfigException if configuration cannot be interpreted | [
"Translate",
"client",
"configuration",
"into",
"the",
"property",
"bundle",
"necessary",
"to",
"configure",
"the",
"client",
"ORB",
"instance",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.transport.iiop/src/com/ibm/ws/transport/iiop/yoko/ORBConfigAdapter.java#L179-L186 |
alkacon/opencms-core | src/org/opencms/ui/dialogs/CmsDeleteDialog.java | CmsDeleteDialog.getBrokenLinks | public static Multimap<CmsResource, CmsResource> getBrokenLinks(
CmsObject cms,
List<CmsResource> selectedResources,
boolean includeSiblings)
throws CmsException {
"""
Gets the broken links.<p>
@param cms the CMS context
@param selectedResources the selected resources
@param includeSiblings <code>true</code> if siblings would be deleted too
@return multimap of broken links, with sources as keys and targets as values
@throws CmsException if something goes wrong
"""
return getBrokenLinks(cms, selectedResources, includeSiblings, false);
} | java | public static Multimap<CmsResource, CmsResource> getBrokenLinks(
CmsObject cms,
List<CmsResource> selectedResources,
boolean includeSiblings)
throws CmsException {
return getBrokenLinks(cms, selectedResources, includeSiblings, false);
} | [
"public",
"static",
"Multimap",
"<",
"CmsResource",
",",
"CmsResource",
">",
"getBrokenLinks",
"(",
"CmsObject",
"cms",
",",
"List",
"<",
"CmsResource",
">",
"selectedResources",
",",
"boolean",
"includeSiblings",
")",
"throws",
"CmsException",
"{",
"return",
"getBrokenLinks",
"(",
"cms",
",",
"selectedResources",
",",
"includeSiblings",
",",
"false",
")",
";",
"}"
] | Gets the broken links.<p>
@param cms the CMS context
@param selectedResources the selected resources
@param includeSiblings <code>true</code> if siblings would be deleted too
@return multimap of broken links, with sources as keys and targets as values
@throws CmsException if something goes wrong | [
"Gets",
"the",
"broken",
"links",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/dialogs/CmsDeleteDialog.java#L191-L199 |
b3dgs/lionengine | lionengine-core/src/main/java/com/b3dgs/lionengine/Check.java | Check.inferiorStrict | public static void inferiorStrict(int a, int b) {
"""
Check if <code>a</code> is strictly inferior to <code>b</code>.
@param a The parameter to test.
@param b The parameter to compare to.
@throws LionEngineException If check failed.
"""
if (a >= b)
{
throw new LionEngineException(ERROR_ARGUMENT
+ String.valueOf(a)
+ ERROR_INFERIOR_STRICT
+ String.valueOf(b));
}
} | java | public static void inferiorStrict(int a, int b)
{
if (a >= b)
{
throw new LionEngineException(ERROR_ARGUMENT
+ String.valueOf(a)
+ ERROR_INFERIOR_STRICT
+ String.valueOf(b));
}
} | [
"public",
"static",
"void",
"inferiorStrict",
"(",
"int",
"a",
",",
"int",
"b",
")",
"{",
"if",
"(",
"a",
">=",
"b",
")",
"{",
"throw",
"new",
"LionEngineException",
"(",
"ERROR_ARGUMENT",
"+",
"String",
".",
"valueOf",
"(",
"a",
")",
"+",
"ERROR_INFERIOR_STRICT",
"+",
"String",
".",
"valueOf",
"(",
"b",
")",
")",
";",
"}",
"}"
] | Check if <code>a</code> is strictly inferior to <code>b</code>.
@param a The parameter to test.
@param b The parameter to compare to.
@throws LionEngineException If check failed. | [
"Check",
"if",
"<code",
">",
"a<",
"/",
"code",
">",
"is",
"strictly",
"inferior",
"to",
"<code",
">",
"b<",
"/",
"code",
">",
"."
] | train | https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-core/src/main/java/com/b3dgs/lionengine/Check.java#L148-L157 |
haraldk/TwelveMonkeys | imageio/imageio-core/src/main/java/com/twelvemonkeys/imageio/ImageReaderBase.java | ImageReaderBase.setInput | @Override
public void setInput(final Object input, final boolean seekForwardOnly, final boolean ignoreMetadata) {
"""
Overrides {@code setInput}, to allow easy access to the input, in case
it is an {@code ImageInputStream}.
@param input the {@code ImageInputStream} or other
{@code Object} to use for future decoding.
@param seekForwardOnly if {@code true}, images and metadata
may only be read in ascending order from this input source.
@param ignoreMetadata if {@code true}, metadata
may be ignored during reads.
@exception IllegalArgumentException if {@code input} is
not an instance of one of the classes returned by the
originating service provider's {@code getInputTypes}
method, or is not an {@code ImageInputStream}.
@see ImageInputStream
"""
resetMembers();
super.setInput(input, seekForwardOnly, ignoreMetadata);
if (input instanceof ImageInputStream) {
imageInput = (ImageInputStream) input;
}
else {
imageInput = null;
}
} | java | @Override
public void setInput(final Object input, final boolean seekForwardOnly, final boolean ignoreMetadata) {
resetMembers();
super.setInput(input, seekForwardOnly, ignoreMetadata);
if (input instanceof ImageInputStream) {
imageInput = (ImageInputStream) input;
}
else {
imageInput = null;
}
} | [
"@",
"Override",
"public",
"void",
"setInput",
"(",
"final",
"Object",
"input",
",",
"final",
"boolean",
"seekForwardOnly",
",",
"final",
"boolean",
"ignoreMetadata",
")",
"{",
"resetMembers",
"(",
")",
";",
"super",
".",
"setInput",
"(",
"input",
",",
"seekForwardOnly",
",",
"ignoreMetadata",
")",
";",
"if",
"(",
"input",
"instanceof",
"ImageInputStream",
")",
"{",
"imageInput",
"=",
"(",
"ImageInputStream",
")",
"input",
";",
"}",
"else",
"{",
"imageInput",
"=",
"null",
";",
"}",
"}"
] | Overrides {@code setInput}, to allow easy access to the input, in case
it is an {@code ImageInputStream}.
@param input the {@code ImageInputStream} or other
{@code Object} to use for future decoding.
@param seekForwardOnly if {@code true}, images and metadata
may only be read in ascending order from this input source.
@param ignoreMetadata if {@code true}, metadata
may be ignored during reads.
@exception IllegalArgumentException if {@code input} is
not an instance of one of the classes returned by the
originating service provider's {@code getInputTypes}
method, or is not an {@code ImageInputStream}.
@see ImageInputStream | [
"Overrides",
"{",
"@code",
"setInput",
"}",
"to",
"allow",
"easy",
"access",
"to",
"the",
"input",
"in",
"case",
"it",
"is",
"an",
"{",
"@code",
"ImageInputStream",
"}",
"."
] | train | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/imageio/imageio-core/src/main/java/com/twelvemonkeys/imageio/ImageReaderBase.java#L106-L117 |
pac4j/pac4j | pac4j-core/src/main/java/org/pac4j/core/util/CommonHelper.java | CommonHelper.urlEncode | public static String urlEncode(final String text) {
"""
URL encode a text using UTF-8.
@param text text to encode
@return the encoded text
"""
try {
return URLEncoder.encode(text, StandardCharsets.UTF_8.name());
} catch (final UnsupportedEncodingException e) {
final String message = "Unable to encode text : " + text;
throw new TechnicalException(message, e);
}
} | java | public static String urlEncode(final String text) {
try {
return URLEncoder.encode(text, StandardCharsets.UTF_8.name());
} catch (final UnsupportedEncodingException e) {
final String message = "Unable to encode text : " + text;
throw new TechnicalException(message, e);
}
} | [
"public",
"static",
"String",
"urlEncode",
"(",
"final",
"String",
"text",
")",
"{",
"try",
"{",
"return",
"URLEncoder",
".",
"encode",
"(",
"text",
",",
"StandardCharsets",
".",
"UTF_8",
".",
"name",
"(",
")",
")",
";",
"}",
"catch",
"(",
"final",
"UnsupportedEncodingException",
"e",
")",
"{",
"final",
"String",
"message",
"=",
"\"Unable to encode text : \"",
"+",
"text",
";",
"throw",
"new",
"TechnicalException",
"(",
"message",
",",
"e",
")",
";",
"}",
"}"
] | URL encode a text using UTF-8.
@param text text to encode
@return the encoded text | [
"URL",
"encode",
"a",
"text",
"using",
"UTF",
"-",
"8",
"."
] | train | https://github.com/pac4j/pac4j/blob/d9cd029f8783792b31dd48bf1e32f80628f2c4a3/pac4j-core/src/main/java/org/pac4j/core/util/CommonHelper.java#L192-L199 |
facebook/SoLoader | java/com/facebook/soloader/SoLoader.java | SoLoader.loadLibrary | public static boolean loadLibrary(String shortName, int loadFlags) throws UnsatisfiedLinkError {
"""
Load a shared library, initializing any JNI binding it contains.
@param shortName Name of library to find, without "lib" prefix or ".so" suffix
@param loadFlags Control flags for the loading behavior. See available flags under {@link
SoSource} (LOAD_FLAG_XXX).
@return Whether the library was loaded as a result of this call (true), or was already loaded
through a previous call to SoLoader (false).
"""
sSoSourcesLock.readLock().lock();
try {
if (sSoSources == null) {
// This should never happen during normal operation,
// but if we're running in a non-Android environment,
// fall back to System.loadLibrary.
if ("http://www.android.com/".equals(System.getProperty("java.vendor.url"))) {
// This will throw.
assertInitialized();
} else {
// Not on an Android system. Ask the JVM to load for us.
synchronized (SoLoader.class) {
boolean needsLoad = !sLoadedLibraries.contains(shortName);
if (needsLoad) {
if (sSystemLoadLibraryWrapper != null) {
sSystemLoadLibraryWrapper.loadLibrary(shortName);
} else {
System.loadLibrary(shortName);
}
}
return needsLoad;
}
}
}
} finally {
sSoSourcesLock.readLock().unlock();
}
String mergedLibName = MergedSoMapping.mapLibName(shortName);
String soName = mergedLibName != null ? mergedLibName : shortName;
return loadLibraryBySoName(
System.mapLibraryName(soName),
shortName,
mergedLibName,
loadFlags | SoSource.LOAD_FLAG_ALLOW_SOURCE_CHANGE,
null);
} | java | public static boolean loadLibrary(String shortName, int loadFlags) throws UnsatisfiedLinkError {
sSoSourcesLock.readLock().lock();
try {
if (sSoSources == null) {
// This should never happen during normal operation,
// but if we're running in a non-Android environment,
// fall back to System.loadLibrary.
if ("http://www.android.com/".equals(System.getProperty("java.vendor.url"))) {
// This will throw.
assertInitialized();
} else {
// Not on an Android system. Ask the JVM to load for us.
synchronized (SoLoader.class) {
boolean needsLoad = !sLoadedLibraries.contains(shortName);
if (needsLoad) {
if (sSystemLoadLibraryWrapper != null) {
sSystemLoadLibraryWrapper.loadLibrary(shortName);
} else {
System.loadLibrary(shortName);
}
}
return needsLoad;
}
}
}
} finally {
sSoSourcesLock.readLock().unlock();
}
String mergedLibName = MergedSoMapping.mapLibName(shortName);
String soName = mergedLibName != null ? mergedLibName : shortName;
return loadLibraryBySoName(
System.mapLibraryName(soName),
shortName,
mergedLibName,
loadFlags | SoSource.LOAD_FLAG_ALLOW_SOURCE_CHANGE,
null);
} | [
"public",
"static",
"boolean",
"loadLibrary",
"(",
"String",
"shortName",
",",
"int",
"loadFlags",
")",
"throws",
"UnsatisfiedLinkError",
"{",
"sSoSourcesLock",
".",
"readLock",
"(",
")",
".",
"lock",
"(",
")",
";",
"try",
"{",
"if",
"(",
"sSoSources",
"==",
"null",
")",
"{",
"// This should never happen during normal operation,",
"// but if we're running in a non-Android environment,",
"// fall back to System.loadLibrary.",
"if",
"(",
"\"http://www.android.com/\"",
".",
"equals",
"(",
"System",
".",
"getProperty",
"(",
"\"java.vendor.url\"",
")",
")",
")",
"{",
"// This will throw.",
"assertInitialized",
"(",
")",
";",
"}",
"else",
"{",
"// Not on an Android system. Ask the JVM to load for us.",
"synchronized",
"(",
"SoLoader",
".",
"class",
")",
"{",
"boolean",
"needsLoad",
"=",
"!",
"sLoadedLibraries",
".",
"contains",
"(",
"shortName",
")",
";",
"if",
"(",
"needsLoad",
")",
"{",
"if",
"(",
"sSystemLoadLibraryWrapper",
"!=",
"null",
")",
"{",
"sSystemLoadLibraryWrapper",
".",
"loadLibrary",
"(",
"shortName",
")",
";",
"}",
"else",
"{",
"System",
".",
"loadLibrary",
"(",
"shortName",
")",
";",
"}",
"}",
"return",
"needsLoad",
";",
"}",
"}",
"}",
"}",
"finally",
"{",
"sSoSourcesLock",
".",
"readLock",
"(",
")",
".",
"unlock",
"(",
")",
";",
"}",
"String",
"mergedLibName",
"=",
"MergedSoMapping",
".",
"mapLibName",
"(",
"shortName",
")",
";",
"String",
"soName",
"=",
"mergedLibName",
"!=",
"null",
"?",
"mergedLibName",
":",
"shortName",
";",
"return",
"loadLibraryBySoName",
"(",
"System",
".",
"mapLibraryName",
"(",
"soName",
")",
",",
"shortName",
",",
"mergedLibName",
",",
"loadFlags",
"|",
"SoSource",
".",
"LOAD_FLAG_ALLOW_SOURCE_CHANGE",
",",
"null",
")",
";",
"}"
] | Load a shared library, initializing any JNI binding it contains.
@param shortName Name of library to find, without "lib" prefix or ".so" suffix
@param loadFlags Control flags for the loading behavior. See available flags under {@link
SoSource} (LOAD_FLAG_XXX).
@return Whether the library was loaded as a result of this call (true), or was already loaded
through a previous call to SoLoader (false). | [
"Load",
"a",
"shared",
"library",
"initializing",
"any",
"JNI",
"binding",
"it",
"contains",
"."
] | train | https://github.com/facebook/SoLoader/blob/263af31d2960b2c0d0afe79d80197165a543be86/java/com/facebook/soloader/SoLoader.java#L519-L558 |
brettwooldridge/HikariCP | src/main/java/com/zaxxer/hikari/pool/PoolBase.java | PoolBase.setQueryTimeout | private void setQueryTimeout(final Statement statement, final int timeoutSec) {
"""
Set the query timeout, if it is supported by the driver.
@param statement a statement to set the query timeout on
@param timeoutSec the number of seconds before timeout
"""
if (isQueryTimeoutSupported != FALSE) {
try {
statement.setQueryTimeout(timeoutSec);
isQueryTimeoutSupported = TRUE;
}
catch (Exception e) {
if (isQueryTimeoutSupported == UNINITIALIZED) {
isQueryTimeoutSupported = FALSE;
logger.info("{} - Failed to set query timeout for statement. ({})", poolName, e.getMessage());
}
}
}
} | java | private void setQueryTimeout(final Statement statement, final int timeoutSec)
{
if (isQueryTimeoutSupported != FALSE) {
try {
statement.setQueryTimeout(timeoutSec);
isQueryTimeoutSupported = TRUE;
}
catch (Exception e) {
if (isQueryTimeoutSupported == UNINITIALIZED) {
isQueryTimeoutSupported = FALSE;
logger.info("{} - Failed to set query timeout for statement. ({})", poolName, e.getMessage());
}
}
}
} | [
"private",
"void",
"setQueryTimeout",
"(",
"final",
"Statement",
"statement",
",",
"final",
"int",
"timeoutSec",
")",
"{",
"if",
"(",
"isQueryTimeoutSupported",
"!=",
"FALSE",
")",
"{",
"try",
"{",
"statement",
".",
"setQueryTimeout",
"(",
"timeoutSec",
")",
";",
"isQueryTimeoutSupported",
"=",
"TRUE",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"if",
"(",
"isQueryTimeoutSupported",
"==",
"UNINITIALIZED",
")",
"{",
"isQueryTimeoutSupported",
"=",
"FALSE",
";",
"logger",
".",
"info",
"(",
"\"{} - Failed to set query timeout for statement. ({})\"",
",",
"poolName",
",",
"e",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"}",
"}",
"}"
] | Set the query timeout, if it is supported by the driver.
@param statement a statement to set the query timeout on
@param timeoutSec the number of seconds before timeout | [
"Set",
"the",
"query",
"timeout",
"if",
"it",
"is",
"supported",
"by",
"the",
"driver",
"."
] | train | https://github.com/brettwooldridge/HikariCP/blob/c509ec1a3f1e19769ee69323972f339cf098ff4b/src/main/java/com/zaxxer/hikari/pool/PoolBase.java#L490-L504 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/text/codepoint/CodepointHelper.java | CodepointHelper.setChar | public static void setChar (@Nonnull final CharSequence aSeq, final int nIndex, @Nonnull final Codepoint aCodepoint) {
"""
Set the character at a given location, automatically dealing with surrogate
pairs
@param aSeq
source sequence
@param nIndex
index
@param aCodepoint
codepoint to be set
"""
setChar (aSeq, nIndex, aCodepoint.getValue ());
} | java | public static void setChar (@Nonnull final CharSequence aSeq, final int nIndex, @Nonnull final Codepoint aCodepoint)
{
setChar (aSeq, nIndex, aCodepoint.getValue ());
} | [
"public",
"static",
"void",
"setChar",
"(",
"@",
"Nonnull",
"final",
"CharSequence",
"aSeq",
",",
"final",
"int",
"nIndex",
",",
"@",
"Nonnull",
"final",
"Codepoint",
"aCodepoint",
")",
"{",
"setChar",
"(",
"aSeq",
",",
"nIndex",
",",
"aCodepoint",
".",
"getValue",
"(",
")",
")",
";",
"}"
] | Set the character at a given location, automatically dealing with surrogate
pairs
@param aSeq
source sequence
@param nIndex
index
@param aCodepoint
codepoint to be set | [
"Set",
"the",
"character",
"at",
"a",
"given",
"location",
"automatically",
"dealing",
"with",
"surrogate",
"pairs"
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/text/codepoint/CodepointHelper.java#L220-L223 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.