repository_name stringlengths 7 58 | func_path_in_repository stringlengths 18 188 | func_name stringlengths 7 127 | whole_func_string stringlengths 77 3.91k | language stringclasses 1
value | func_code_string stringlengths 77 3.91k | func_code_tokens listlengths 20 745 | func_documentation_string stringlengths 61 1.98k | func_documentation_tokens listlengths 1 477 | split_name stringclasses 1
value | func_code_url stringlengths 111 288 |
|---|---|---|---|---|---|---|---|---|---|---|
ops4j/org.ops4j.pax.logging | pax-logging-api/src/main/java/org/jboss/logging/Logger.java | Logger.logv | public void logv(Level level, String format, Object... params) {
doLog(level, FQCN, format, params, null);
} | java | public void logv(Level level, String format, Object... params) {
doLog(level, FQCN, format, params, null);
} | [
"public",
"void",
"logv",
"(",
"Level",
"level",
",",
"String",
"format",
",",
"Object",
"...",
"params",
")",
"{",
"doLog",
"(",
"level",
",",
"FQCN",
",",
"format",
",",
"params",
",",
"null",
")",
";",
"}"
] | Issue a log message at the given log level using {@link java.text.MessageFormat}-style formatting.
@param level the level
@param format the message format string
@param params the parameters | [
"Issue",
"a",
"log",
"message",
"at",
"the",
"given",
"log",
"level",
"using",
"{",
"@link",
"java",
".",
"text",
".",
"MessageFormat",
"}",
"-",
"style",
"formatting",
"."
] | train | https://github.com/ops4j/org.ops4j.pax.logging/blob/493de4e1db4fe9f981f3dd78b8e40e5bf2b2e59d/pax-logging-api/src/main/java/org/jboss/logging/Logger.java#L2113-L2115 |
scottbw/spaws | src/main/java/uk/ac/bolton/spaws/ParadataManager.java | ParadataManager.getExternalStats | public List<ISubmission> getExternalStats(String resourceUrl) throws Exception{
return getExternalSubmissions(resourceUrl, IStats.VERB);
} | java | public List<ISubmission> getExternalStats(String resourceUrl) throws Exception{
return getExternalSubmissions(resourceUrl, IStats.VERB);
} | [
"public",
"List",
"<",
"ISubmission",
">",
"getExternalStats",
"(",
"String",
"resourceUrl",
")",
"throws",
"Exception",
"{",
"return",
"getExternalSubmissions",
"(",
"resourceUrl",
",",
"IStats",
".",
"VERB",
")",
";",
"}"
] | Return all stats from other submitters for the resource
@param resourceUrl
@return
@throws Exception | [
"Return",
"all",
"stats",
"from",
"other",
"submitters",
"for",
"the",
"resource"
] | train | https://github.com/scottbw/spaws/blob/9b1e07453091f6a8d60c6046d194b1a8f1236502/src/main/java/uk/ac/bolton/spaws/ParadataManager.java#L73-L75 |
orbisgis/h2gis | h2gis-utilities/src/main/java/org/h2gis/utilities/SFSUtilities.java | SFSUtilities.getResultSetEnvelope | public static Envelope getResultSetEnvelope(ResultSet resultSet) throws SQLException {
List<String> geometryFields = getGeometryFields(resultSet);
if (geometryFields.isEmpty()) {
throw new SQLException("This ResultSet doesn't contain any geometry field.");
} else {
return getResultSetEnvelope(resultSet, geometryFields.get(0));
}
} | java | public static Envelope getResultSetEnvelope(ResultSet resultSet) throws SQLException {
List<String> geometryFields = getGeometryFields(resultSet);
if (geometryFields.isEmpty()) {
throw new SQLException("This ResultSet doesn't contain any geometry field.");
} else {
return getResultSetEnvelope(resultSet, geometryFields.get(0));
}
} | [
"public",
"static",
"Envelope",
"getResultSetEnvelope",
"(",
"ResultSet",
"resultSet",
")",
"throws",
"SQLException",
"{",
"List",
"<",
"String",
">",
"geometryFields",
"=",
"getGeometryFields",
"(",
"resultSet",
")",
";",
"if",
"(",
"geometryFields",
".",
"isEmpt... | Compute the full extend of a ResultSet using the first geometry field. If
the ResultSet does not contain any geometry field throw an exception
@param resultSet ResultSet to analyse
@return The full envelope of the ResultSet
@throws SQLException | [
"Compute",
"the",
"full",
"extend",
"of",
"a",
"ResultSet",
"using",
"the",
"first",
"geometry",
"field",
".",
"If",
"the",
"ResultSet",
"does",
"not",
"contain",
"any",
"geometry",
"field",
"throw",
"an",
"exception"
] | train | https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-utilities/src/main/java/org/h2gis/utilities/SFSUtilities.java#L448-L455 |
Azure/azure-sdk-for-java | batch/data-plane/src/main/java/com/microsoft/azure/batch/PoolOperations.java | PoolOperations.stopResizePool | public void stopResizePool(String poolId, Iterable<BatchClientBehavior> additionalBehaviors)
throws BatchErrorException, IOException {
PoolStopResizeOptions options = new PoolStopResizeOptions();
BehaviorManager bhMgr = new BehaviorManager(this.customBehaviors(), additionalBehaviors);
bhMgr.applyRequestBehaviors(options);
this.parentBatchClient.protocolLayer().pools().stopResize(poolId, options);
} | java | public void stopResizePool(String poolId, Iterable<BatchClientBehavior> additionalBehaviors)
throws BatchErrorException, IOException {
PoolStopResizeOptions options = new PoolStopResizeOptions();
BehaviorManager bhMgr = new BehaviorManager(this.customBehaviors(), additionalBehaviors);
bhMgr.applyRequestBehaviors(options);
this.parentBatchClient.protocolLayer().pools().stopResize(poolId, options);
} | [
"public",
"void",
"stopResizePool",
"(",
"String",
"poolId",
",",
"Iterable",
"<",
"BatchClientBehavior",
">",
"additionalBehaviors",
")",
"throws",
"BatchErrorException",
",",
"IOException",
"{",
"PoolStopResizeOptions",
"options",
"=",
"new",
"PoolStopResizeOptions",
... | Stops a pool resize operation.
@param poolId
The ID of the pool.
@param additionalBehaviors
A collection of {@link BatchClientBehavior} instances that are
applied to the Batch service request.
@throws BatchErrorException
Exception thrown when an error response is received from the
Batch service.
@throws IOException
Exception thrown when there is an error in
serialization/deserialization of data sent to/received from the
Batch service. | [
"Stops",
"a",
"pool",
"resize",
"operation",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/PoolOperations.java#L649-L656 |
EvidentSolutions/dalesbred | dalesbred/src/main/java/org/dalesbred/Database.java | Database.findUnique | public <T> T findUnique(@NotNull Class<T> cl, @NotNull SqlQuery query) {
return executeQuery(rowMapperForClass(cl).unique(), query);
} | java | public <T> T findUnique(@NotNull Class<T> cl, @NotNull SqlQuery query) {
return executeQuery(rowMapperForClass(cl).unique(), query);
} | [
"public",
"<",
"T",
">",
"T",
"findUnique",
"(",
"@",
"NotNull",
"Class",
"<",
"T",
">",
"cl",
",",
"@",
"NotNull",
"SqlQuery",
"query",
")",
"{",
"return",
"executeQuery",
"(",
"rowMapperForClass",
"(",
"cl",
")",
".",
"unique",
"(",
")",
",",
"quer... | Finds a unique result from database, converting the database row to given class using default mechanisms.
@throws NonUniqueResultException if there is more then one row
@throws EmptyResultException if there are no rows | [
"Finds",
"a",
"unique",
"result",
"from",
"database",
"converting",
"the",
"database",
"row",
"to",
"given",
"class",
"using",
"default",
"mechanisms",
"."
] | train | https://github.com/EvidentSolutions/dalesbred/blob/713f5b6e152d97e1672ca68b9ff9c7c6c288ceb1/dalesbred/src/main/java/org/dalesbred/Database.java#L352-L354 |
arquillian/arquillian-recorder | arquillian-recorder/arquillian-recorder-api/src/main/java/org/arquillian/extension/recorder/Configuration.java | Configuration.getProperty | public String getProperty(String name, String defaultValue) throws IllegalStateException {
Validate.notNullOrEmpty(name, "Unable to get the configuration value of null or empty configuration key");
Validate.notNull(defaultValue, "Unable to set configuration value of " + name + " to null object.");
String found = getConfiguration().get(name);
if (found == null || found.isEmpty()) {
return defaultValue;
} else {
return found;
}
} | java | public String getProperty(String name, String defaultValue) throws IllegalStateException {
Validate.notNullOrEmpty(name, "Unable to get the configuration value of null or empty configuration key");
Validate.notNull(defaultValue, "Unable to set configuration value of " + name + " to null object.");
String found = getConfiguration().get(name);
if (found == null || found.isEmpty()) {
return defaultValue;
} else {
return found;
}
} | [
"public",
"String",
"getProperty",
"(",
"String",
"name",
",",
"String",
"defaultValue",
")",
"throws",
"IllegalStateException",
"{",
"Validate",
".",
"notNullOrEmpty",
"(",
"name",
",",
"\"Unable to get the configuration value of null or empty configuration key\"",
")",
";... | Gets value of {@code name} property. In case a value for such name does not exist or is a null object or an empty string,
{@code defaultValue} is returned.
@param name name of a property you want to get the value of
@param defaultValue value returned in case {@code name} is a null string or it is empty
@return value of a {@code name} property of {@code defaultValue} when {@code name} is null or empty string
@throws IllegalArgumentException if {@code name} is a null object or an empty string or if {@code defaultValue} is a null
object | [
"Gets",
"value",
"of",
"{",
"@code",
"name",
"}",
"property",
".",
"In",
"case",
"a",
"value",
"for",
"such",
"name",
"does",
"not",
"exist",
"or",
"is",
"a",
"null",
"object",
"or",
"an",
"empty",
"string",
"{",
"@code",
"defaultValue",
"}",
"is",
"... | train | https://github.com/arquillian/arquillian-recorder/blob/e3417111deb03a2e2d9b96d38b986db17e2c1d19/arquillian-recorder/arquillian-recorder-api/src/main/java/org/arquillian/extension/recorder/Configuration.java#L65-L75 |
Netflix/denominator | route53/src/main/java/denominator/route53/Route53AllProfileResourceRecordSetApi.java | Route53AllProfileResourceRecordSetApi.iterateByName | @Override
public Iterator<ResourceRecordSet<?>> iterateByName(String name) {
Filter<ResourceRecordSet<?>> filter = andNotAlias(nameEqualTo(name));
return lazyIterateRRSets(api.listResourceRecordSets(zoneId, name), filter);
} | java | @Override
public Iterator<ResourceRecordSet<?>> iterateByName(String name) {
Filter<ResourceRecordSet<?>> filter = andNotAlias(nameEqualTo(name));
return lazyIterateRRSets(api.listResourceRecordSets(zoneId, name), filter);
} | [
"@",
"Override",
"public",
"Iterator",
"<",
"ResourceRecordSet",
"<",
"?",
">",
">",
"iterateByName",
"(",
"String",
"name",
")",
"{",
"Filter",
"<",
"ResourceRecordSet",
"<",
"?",
">",
">",
"filter",
"=",
"andNotAlias",
"(",
"nameEqualTo",
"(",
"name",
")... | lists and lazily transforms all record sets for a name which are not aliases into denominator
format. | [
"lists",
"and",
"lazily",
"transforms",
"all",
"record",
"sets",
"for",
"a",
"name",
"which",
"are",
"not",
"aliases",
"into",
"denominator",
"format",
"."
] | train | https://github.com/Netflix/denominator/blob/c565e3b8c6043051252e0947029511f9ac5d306f/route53/src/main/java/denominator/route53/Route53AllProfileResourceRecordSetApi.java#L58-L62 |
mcxiaoke/Android-Next | core/src/main/java/com/mcxiaoke/next/utils/IOUtils.java | IOUtils.writeStream | public static boolean writeStream(String filePath, InputStream stream, boolean append) throws IOException {
return writeStream(filePath != null ? new File(filePath) : null, stream, append);
} | java | public static boolean writeStream(String filePath, InputStream stream, boolean append) throws IOException {
return writeStream(filePath != null ? new File(filePath) : null, stream, append);
} | [
"public",
"static",
"boolean",
"writeStream",
"(",
"String",
"filePath",
",",
"InputStream",
"stream",
",",
"boolean",
"append",
")",
"throws",
"IOException",
"{",
"return",
"writeStream",
"(",
"filePath",
"!=",
"null",
"?",
"new",
"File",
"(",
"filePath",
")"... | write file
@param filePath the file to be opened for writing.
@param stream the input stream
@param append if <code>true</code>, then bytes will be written to the end of the file rather than the beginning
@return return true
@throws IOException if an error occurs while operator FileOutputStream | [
"write",
"file"
] | train | https://github.com/mcxiaoke/Android-Next/blob/1bfdf99d0b81a849aa0fa6697c53ed673151ca39/core/src/main/java/com/mcxiaoke/next/utils/IOUtils.java#L1199-L1201 |
lievendoclo/Valkyrie-RCP | valkyrie-rcp-core/src/main/java/org/valkyriercp/form/binding/swing/SwingBinderSelectionStrategy.java | SwingBinderSelectionStrategy.getIdBoundBinder | public Binder getIdBoundBinder(String id)
{
Binder binder = idBoundBinders.get(id);
if (binder == null) // try to locate the binder bean
{
Object binderBean = getApplicationContext().getBean(id);
if (binderBean instanceof Binder)
{
if (binderBean != null)
{
idBoundBinders.put(id, (Binder) binderBean);
binder = (Binder) binderBean;
}
}
else
{
throw new IllegalArgumentException("Bean '" + id + "' was found, but was not a binder");
}
}
return binder;
} | java | public Binder getIdBoundBinder(String id)
{
Binder binder = idBoundBinders.get(id);
if (binder == null) // try to locate the binder bean
{
Object binderBean = getApplicationContext().getBean(id);
if (binderBean instanceof Binder)
{
if (binderBean != null)
{
idBoundBinders.put(id, (Binder) binderBean);
binder = (Binder) binderBean;
}
}
else
{
throw new IllegalArgumentException("Bean '" + id + "' was found, but was not a binder");
}
}
return binder;
} | [
"public",
"Binder",
"getIdBoundBinder",
"(",
"String",
"id",
")",
"{",
"Binder",
"binder",
"=",
"idBoundBinders",
".",
"get",
"(",
"id",
")",
";",
"if",
"(",
"binder",
"==",
"null",
")",
"// try to locate the binder bean",
"{",
"Object",
"binderBean",
"=",
... | Try to find a binder with a specified id. If no binder is found, try
to locate it into the application context, check whether it's a binder and
add it to the id bound binder map.
@param id Id of the binder
@return Binder or <code>null</code> if not found. | [
"Try",
"to",
"find",
"a",
"binder",
"with",
"a",
"specified",
"id",
".",
"If",
"no",
"binder",
"is",
"found",
"try",
"to",
"locate",
"it",
"into",
"the",
"application",
"context",
"check",
"whether",
"it",
"s",
"a",
"binder",
"and",
"add",
"it",
"to",
... | train | https://github.com/lievendoclo/Valkyrie-RCP/blob/6aad6e640b348cda8f3b0841f6e42025233f1eb8/valkyrie-rcp-core/src/main/java/org/valkyriercp/form/binding/swing/SwingBinderSelectionStrategy.java#L69-L89 |
kuali/ojb-1.0.4 | src/java/org/apache/ojb/odmg/locking/LockManagerDefaultImpl.java | LockManagerDefaultImpl.checkWrite | public synchronized boolean checkWrite(TransactionImpl tx, Object obj)
{
if (log.isDebugEnabled()) log.debug("LM.checkWrite(tx-" + tx.getGUID() + ", " + new Identity(obj, tx.getBroker()).toString() + ")");
LockStrategy lockStrategy = LockStrategyFactory.getStrategyFor(obj);
return lockStrategy.checkWrite(tx, obj);
} | java | public synchronized boolean checkWrite(TransactionImpl tx, Object obj)
{
if (log.isDebugEnabled()) log.debug("LM.checkWrite(tx-" + tx.getGUID() + ", " + new Identity(obj, tx.getBroker()).toString() + ")");
LockStrategy lockStrategy = LockStrategyFactory.getStrategyFor(obj);
return lockStrategy.checkWrite(tx, obj);
} | [
"public",
"synchronized",
"boolean",
"checkWrite",
"(",
"TransactionImpl",
"tx",
",",
"Object",
"obj",
")",
"{",
"if",
"(",
"log",
".",
"isDebugEnabled",
"(",
")",
")",
"log",
".",
"debug",
"(",
"\"LM.checkWrite(tx-\"",
"+",
"tx",
".",
"getGUID",
"(",
")",... | checks if there is a writelock for transaction tx on object obj.
Returns true if so, else false. | [
"checks",
"if",
"there",
"is",
"a",
"writelock",
"for",
"transaction",
"tx",
"on",
"object",
"obj",
".",
"Returns",
"true",
"if",
"so",
"else",
"false",
"."
] | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/odmg/locking/LockManagerDefaultImpl.java#L142-L147 |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/BoundsOnBinomialProportions.java | BoundsOnBinomialProportions.approximateLowerBoundOnP | public static double approximateLowerBoundOnP(final long n, final long k, final double numStdDevs) {
checkInputs(n, k);
if (n == 0) { return 0.0; } // the coin was never flipped, so we know nothing
else if (k == 0) { return 0.0; }
else if (k == 1) { return (exactLowerBoundOnPForKequalsOne(n, deltaOfNumStdevs(numStdDevs))); }
else if (k == n) { return (exactLowerBoundOnPForKequalsN(n, deltaOfNumStdevs(numStdDevs))); }
else {
final double x = abramowitzStegunFormula26p5p22((n - k) + 1, k, (-1.0 * numStdDevs));
return (1.0 - x); // which is p
}
} | java | public static double approximateLowerBoundOnP(final long n, final long k, final double numStdDevs) {
checkInputs(n, k);
if (n == 0) { return 0.0; } // the coin was never flipped, so we know nothing
else if (k == 0) { return 0.0; }
else if (k == 1) { return (exactLowerBoundOnPForKequalsOne(n, deltaOfNumStdevs(numStdDevs))); }
else if (k == n) { return (exactLowerBoundOnPForKequalsN(n, deltaOfNumStdevs(numStdDevs))); }
else {
final double x = abramowitzStegunFormula26p5p22((n - k) + 1, k, (-1.0 * numStdDevs));
return (1.0 - x); // which is p
}
} | [
"public",
"static",
"double",
"approximateLowerBoundOnP",
"(",
"final",
"long",
"n",
",",
"final",
"long",
"k",
",",
"final",
"double",
"numStdDevs",
")",
"{",
"checkInputs",
"(",
"n",
",",
"k",
")",
";",
"if",
"(",
"n",
"==",
"0",
")",
"{",
"return",
... | Computes lower bound of approximate Clopper-Pearson confidence interval for a binomial
proportion.
<p>Implementation Notes:<br>
The approximateLowerBoundOnP is defined with respect to the right tail of the binomial
distribution.</p>
<ul>
<li>We want to solve for the <i>p</i> for which sum<sub><i>j,k,n</i></sub>bino(<i>j;n,p</i>)
= delta.</li>
<li>We now restate that in terms of the left tail.</li>
<li>We want to solve for the p for which sum<sub><i>j,0,(k-1)</i></sub>bino(<i>j;n,p</i>)
= 1 - delta.</li>
<li>Define <i>x</i> = 1-<i>p</i>.</li>
<li>We want to solve for the <i>x</i> for which I<sub><i>x(n-k+1,k)</i></sub> = 1 - delta.</li>
<li>We specify 1-delta via numStdDevs through the right tail of the standard normal
distribution.</li>
<li>Smaller values of numStdDevs correspond to bigger values of 1-delta and hence to smaller
values of delta. In fact, usefully small values of delta correspond to negative values of
numStdDevs.</li>
<li>return <i>p</i> = 1-<i>x</i>.</li>
</ul>
@param n is the number of trials. Must be non-negative.
@param k is the number of successes. Must be non-negative, and cannot exceed n.
@param numStdDevs the number of standard deviations defining the confidence interval
@return the lower bound of the approximate Clopper-Pearson confidence interval for the
unknown success probability. | [
"Computes",
"lower",
"bound",
"of",
"approximate",
"Clopper",
"-",
"Pearson",
"confidence",
"interval",
"for",
"a",
"binomial",
"proportion",
"."
] | train | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/BoundsOnBinomialProportions.java#L93-L103 |
kefirfromperm/kefirbb | src/org/kefirsf/bb/DomConfigurationFactory.java | DomConfigurationFactory.parseConstant | private Constant parseConstant(Node el, boolean ignoreCase) {
return new Constant(
nodeAttribute(el, TAG_CONSTANT_ATTR_VALUE),
nodeAttribute(el, TAG_CONSTANT_ATTR_IGNORE_CASE, ignoreCase),
nodeAttribute(el, TAG_ATTR_GHOST, PatternElement.DEFAULT_GHOST_VALUE)
);
} | java | private Constant parseConstant(Node el, boolean ignoreCase) {
return new Constant(
nodeAttribute(el, TAG_CONSTANT_ATTR_VALUE),
nodeAttribute(el, TAG_CONSTANT_ATTR_IGNORE_CASE, ignoreCase),
nodeAttribute(el, TAG_ATTR_GHOST, PatternElement.DEFAULT_GHOST_VALUE)
);
} | [
"private",
"Constant",
"parseConstant",
"(",
"Node",
"el",
",",
"boolean",
"ignoreCase",
")",
"{",
"return",
"new",
"Constant",
"(",
"nodeAttribute",
"(",
"el",
",",
"TAG_CONSTANT_ATTR_VALUE",
")",
",",
"nodeAttribute",
"(",
"el",
",",
"TAG_CONSTANT_ATTR_IGNORE_CA... | Parse constant pattern element
@param el DOM element
@param ignoreCase if true the constant must ignore case
@return constant definition | [
"Parse",
"constant",
"pattern",
"element"
] | train | https://github.com/kefirfromperm/kefirbb/blob/8c36fc3d3dc27459b0cdc179b87582df30420856/src/org/kefirsf/bb/DomConfigurationFactory.java#L454-L460 |
sebastiangraf/treetank | interfacemodules/xml/src/main/java/org/treetank/service/xml/xpath/PipelineBuilder.java | PipelineBuilder.addPredicate | public void addPredicate(final INodeReadTrx mTransaction) {
assert getPipeStack().size() >= 2;
final AbsAxis mPredicate = getPipeStack().pop().getExpr();
if (mPredicate instanceof LiteralExpr) {
mPredicate.hasNext();
// if is numeric literal -> abbrev for position()
final int type = mTransaction.getNode().getTypeKey();
if (type == NamePageHash.generateHashForString("xs:integer")
|| type == NamePageHash.generateHashForString("xs:double")
|| type == NamePageHash.generateHashForString("xs:float")
|| type == NamePageHash.generateHashForString("xs:decimal")) {
throw new IllegalStateException("function fn:position() is not implemented yet.");
// getExpression().add(
// new PosFilter(transaction, (int)
// Double.parseDouble(transaction
// .getValue())));
// return; // TODO: YES! it is dirty!
// AtomicValue pos =
// new AtomicValue(mTransaction.getNode().getRawValue(),
// mTransaction
// .keyForName("xs:integer"));
// long position = mTransaction.getItemList().addItem(pos);
// mPredicate.reset(mTransaction.getNode().getNodeKey());
// IAxis function =
// new FNPosition(mTransaction, new ArrayList<IAxis>(),
// FuncDef.POS.getMin(), FuncDef.POS
// .getMax(),
// mTransaction.keyForName(FuncDef.POS.getReturnType()));
// IAxis expectedPos = new LiteralExpr(mTransaction, position);
//
// mPredicate = new ValueComp(mTransaction, function,
// expectedPos, CompKind.EQ);
}
}
getExpression().add(new PredicateFilterAxis(mTransaction, mPredicate));
} | java | public void addPredicate(final INodeReadTrx mTransaction) {
assert getPipeStack().size() >= 2;
final AbsAxis mPredicate = getPipeStack().pop().getExpr();
if (mPredicate instanceof LiteralExpr) {
mPredicate.hasNext();
// if is numeric literal -> abbrev for position()
final int type = mTransaction.getNode().getTypeKey();
if (type == NamePageHash.generateHashForString("xs:integer")
|| type == NamePageHash.generateHashForString("xs:double")
|| type == NamePageHash.generateHashForString("xs:float")
|| type == NamePageHash.generateHashForString("xs:decimal")) {
throw new IllegalStateException("function fn:position() is not implemented yet.");
// getExpression().add(
// new PosFilter(transaction, (int)
// Double.parseDouble(transaction
// .getValue())));
// return; // TODO: YES! it is dirty!
// AtomicValue pos =
// new AtomicValue(mTransaction.getNode().getRawValue(),
// mTransaction
// .keyForName("xs:integer"));
// long position = mTransaction.getItemList().addItem(pos);
// mPredicate.reset(mTransaction.getNode().getNodeKey());
// IAxis function =
// new FNPosition(mTransaction, new ArrayList<IAxis>(),
// FuncDef.POS.getMin(), FuncDef.POS
// .getMax(),
// mTransaction.keyForName(FuncDef.POS.getReturnType()));
// IAxis expectedPos = new LiteralExpr(mTransaction, position);
//
// mPredicate = new ValueComp(mTransaction, function,
// expectedPos, CompKind.EQ);
}
}
getExpression().add(new PredicateFilterAxis(mTransaction, mPredicate));
} | [
"public",
"void",
"addPredicate",
"(",
"final",
"INodeReadTrx",
"mTransaction",
")",
"{",
"assert",
"getPipeStack",
"(",
")",
".",
"size",
"(",
")",
">=",
"2",
";",
"final",
"AbsAxis",
"mPredicate",
"=",
"getPipeStack",
"(",
")",
".",
"pop",
"(",
")",
".... | Adds a predicate to the pipeline.
@param mTransaction
Transaction to operate with. | [
"Adds",
"a",
"predicate",
"to",
"the",
"pipeline",
"."
] | train | https://github.com/sebastiangraf/treetank/blob/9b96d631b6c2a8502a0cc958dcb02bd6a6fd8b60/interfacemodules/xml/src/main/java/org/treetank/service/xml/xpath/PipelineBuilder.java#L537-L582 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/VirtualNetworkGatewaysInner.java | VirtualNetworkGatewaysInner.beginGetBgpPeerStatusAsync | public Observable<BgpPeerStatusListResultInner> beginGetBgpPeerStatusAsync(String resourceGroupName, String virtualNetworkGatewayName, String peer) {
return beginGetBgpPeerStatusWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayName, peer).map(new Func1<ServiceResponse<BgpPeerStatusListResultInner>, BgpPeerStatusListResultInner>() {
@Override
public BgpPeerStatusListResultInner call(ServiceResponse<BgpPeerStatusListResultInner> response) {
return response.body();
}
});
} | java | public Observable<BgpPeerStatusListResultInner> beginGetBgpPeerStatusAsync(String resourceGroupName, String virtualNetworkGatewayName, String peer) {
return beginGetBgpPeerStatusWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayName, peer).map(new Func1<ServiceResponse<BgpPeerStatusListResultInner>, BgpPeerStatusListResultInner>() {
@Override
public BgpPeerStatusListResultInner call(ServiceResponse<BgpPeerStatusListResultInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"BgpPeerStatusListResultInner",
">",
"beginGetBgpPeerStatusAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"virtualNetworkGatewayName",
",",
"String",
"peer",
")",
"{",
"return",
"beginGetBgpPeerStatusWithServiceResponseAsync",
"(",
"re... | The GetBgpPeerStatus operation retrieves the status of all BGP peers.
@param resourceGroupName The name of the resource group.
@param virtualNetworkGatewayName The name of the virtual network gateway.
@param peer The IP address of the peer to retrieve the status of.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the BgpPeerStatusListResultInner object | [
"The",
"GetBgpPeerStatus",
"operation",
"retrieves",
"the",
"status",
"of",
"all",
"BGP",
"peers",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/VirtualNetworkGatewaysInner.java#L2195-L2202 |
NoraUi/NoraUi | src/main/java/com/github/noraui/application/steps/CommonSteps.java | CommonSteps.clickOnXpathByJs | @Conditioned
@Quand("Je clique via js sur xpath '(.*)' de '(.*)' page[\\.|\\?]")
@When("I click by js on xpath '(.*)' from '(.*)' page[\\.|\\?]")
public void clickOnXpathByJs(String xpath, String page, List<GherkinStepCondition> conditions) throws TechnicalException, FailureException {
logger.debug("clickOnByJs with xpath {} on {} page", xpath, page);
clickOnByJs(Page.getInstance(page), xpath);
} | java | @Conditioned
@Quand("Je clique via js sur xpath '(.*)' de '(.*)' page[\\.|\\?]")
@When("I click by js on xpath '(.*)' from '(.*)' page[\\.|\\?]")
public void clickOnXpathByJs(String xpath, String page, List<GherkinStepCondition> conditions) throws TechnicalException, FailureException {
logger.debug("clickOnByJs with xpath {} on {} page", xpath, page);
clickOnByJs(Page.getInstance(page), xpath);
} | [
"@",
"Conditioned",
"@",
"Quand",
"(",
"\"Je clique via js sur xpath '(.*)' de '(.*)' page[\\\\.|\\\\?]\"",
")",
"@",
"When",
"(",
"\"I click by js on xpath '(.*)' from '(.*)' page[\\\\.|\\\\?]\"",
")",
"public",
"void",
"clickOnXpathByJs",
"(",
"String",
"xpath",
",",
"String"... | Click on html element using Javascript if all 'expected' parameters equals 'actual' parameters in conditions.
@param xpath
xpath of html element
@param page
The concerned page of toClick
@param conditions
list of 'expected' values condition and 'actual' values ({@link com.github.noraui.gherkin.GherkinStepCondition}).
@throws TechnicalException
is thrown if you have a technical error (format, configuration, datas, ...) in NoraUi.
Exception with {@value com.github.noraui.utils.Messages#FAIL_MESSAGE_UNABLE_TO_OPEN_ON_CLICK} message (with screenshot, with exception)
@throws FailureException
if the scenario encounters a functional error | [
"Click",
"on",
"html",
"element",
"using",
"Javascript",
"if",
"all",
"expected",
"parameters",
"equals",
"actual",
"parameters",
"in",
"conditions",
"."
] | train | https://github.com/NoraUi/NoraUi/blob/5f491a3339c7d3c20d7207760bdaf2acdb8f260c/src/main/java/com/github/noraui/application/steps/CommonSteps.java#L430-L436 |
krummas/DrizzleJDBC | src/main/java/org/drizzle/jdbc/DrizzleBlob.java | DrizzleBlob.setBytes | public int setBytes(final long pos, final byte[] bytes) throws SQLException {
final int arrayPos = (int) pos - 1;
final int bytesWritten;
if (blobContent == null) {
this.blobContent = new byte[arrayPos + bytes.length];
bytesWritten = blobContent.length;
this.actualSize = bytesWritten;
} else if (blobContent.length > arrayPos + bytes.length) {
bytesWritten = bytes.length;
} else {
blobContent = Utils.copyWithLength(blobContent, arrayPos + bytes.length);
actualSize = blobContent.length;
bytesWritten = bytes.length;
}
System.arraycopy(bytes, 0, this.blobContent, arrayPos, bytes.length);
return bytesWritten;
} | java | public int setBytes(final long pos, final byte[] bytes) throws SQLException {
final int arrayPos = (int) pos - 1;
final int bytesWritten;
if (blobContent == null) {
this.blobContent = new byte[arrayPos + bytes.length];
bytesWritten = blobContent.length;
this.actualSize = bytesWritten;
} else if (blobContent.length > arrayPos + bytes.length) {
bytesWritten = bytes.length;
} else {
blobContent = Utils.copyWithLength(blobContent, arrayPos + bytes.length);
actualSize = blobContent.length;
bytesWritten = bytes.length;
}
System.arraycopy(bytes, 0, this.blobContent, arrayPos, bytes.length);
return bytesWritten;
} | [
"public",
"int",
"setBytes",
"(",
"final",
"long",
"pos",
",",
"final",
"byte",
"[",
"]",
"bytes",
")",
"throws",
"SQLException",
"{",
"final",
"int",
"arrayPos",
"=",
"(",
"int",
")",
"pos",
"-",
"1",
";",
"final",
"int",
"bytesWritten",
";",
"if",
... | Writes the given array of bytes to the <code>BLOB</code> value that this <code>Blob</code> object represents,
starting at position <code>pos</code>, and returns the number of bytes written. The array of bytes will overwrite
the existing bytes in the <code>Blob</code> object starting at the position <code>pos</code>. If the end of the
<code>Blob</code> value is reached while writing the array of bytes, then the length of the <code>Blob</code>
value will be increased to accomodate the extra bytes.
<p/>
<b>Note:</b> If the value specified for <code>pos</code> is greater then the length+1 of the <code>BLOB</code>
value then the behavior is undefined. Some JDBC drivers may throw a <code>SQLException</code> while other drivers
may support this operation.
@param pos the position in the <code>BLOB</code> object at which to start writing; the first position is 1
@param bytes the array of bytes to be written to the <code>BLOB</code> value that this <code>Blob</code> object
represents
@return the number of bytes written
@see #getBytes
@since 1.4 | [
"Writes",
"the",
"given",
"array",
"of",
"bytes",
"to",
"the",
"<code",
">",
"BLOB<",
"/",
"code",
">",
"value",
"that",
"this",
"<code",
">",
"Blob<",
"/",
"code",
">",
"object",
"represents",
"starting",
"at",
"position",
"<code",
">",
"pos<",
"/",
"... | train | https://github.com/krummas/DrizzleJDBC/blob/716f31fd71f3cc289edf69844d8117deb86d98d6/src/main/java/org/drizzle/jdbc/DrizzleBlob.java#L207-L226 |
apache/flink | flink-runtime/src/main/java/org/apache/flink/runtime/executiongraph/Execution.java | Execution.notifyCheckpointComplete | public void notifyCheckpointComplete(long checkpointId, long timestamp) {
final LogicalSlot slot = assignedResource;
if (slot != null) {
final TaskManagerGateway taskManagerGateway = slot.getTaskManagerGateway();
taskManagerGateway.notifyCheckpointComplete(attemptId, getVertex().getJobId(), checkpointId, timestamp);
} else {
LOG.debug("The execution has no slot assigned. This indicates that the execution is " +
"no longer running.");
}
} | java | public void notifyCheckpointComplete(long checkpointId, long timestamp) {
final LogicalSlot slot = assignedResource;
if (slot != null) {
final TaskManagerGateway taskManagerGateway = slot.getTaskManagerGateway();
taskManagerGateway.notifyCheckpointComplete(attemptId, getVertex().getJobId(), checkpointId, timestamp);
} else {
LOG.debug("The execution has no slot assigned. This indicates that the execution is " +
"no longer running.");
}
} | [
"public",
"void",
"notifyCheckpointComplete",
"(",
"long",
"checkpointId",
",",
"long",
"timestamp",
")",
"{",
"final",
"LogicalSlot",
"slot",
"=",
"assignedResource",
";",
"if",
"(",
"slot",
"!=",
"null",
")",
"{",
"final",
"TaskManagerGateway",
"taskManagerGatew... | Notify the task of this execution about a completed checkpoint.
@param checkpointId of the completed checkpoint
@param timestamp of the completed checkpoint | [
"Notify",
"the",
"task",
"of",
"this",
"execution",
"about",
"a",
"completed",
"checkpoint",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/executiongraph/Execution.java#L848-L859 |
liferay/com-liferay-commerce | commerce-tax-service/src/main/java/com/liferay/commerce/tax/service/persistence/impl/CommerceTaxMethodPersistenceImpl.java | CommerceTaxMethodPersistenceImpl.removeByG_A | @Override
public void removeByG_A(long groupId, boolean active) {
for (CommerceTaxMethod commerceTaxMethod : findByG_A(groupId, active,
QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
remove(commerceTaxMethod);
}
} | java | @Override
public void removeByG_A(long groupId, boolean active) {
for (CommerceTaxMethod commerceTaxMethod : findByG_A(groupId, active,
QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
remove(commerceTaxMethod);
}
} | [
"@",
"Override",
"public",
"void",
"removeByG_A",
"(",
"long",
"groupId",
",",
"boolean",
"active",
")",
"{",
"for",
"(",
"CommerceTaxMethod",
"commerceTaxMethod",
":",
"findByG_A",
"(",
"groupId",
",",
"active",
",",
"QueryUtil",
".",
"ALL_POS",
",",
"QueryUt... | Removes all the commerce tax methods where groupId = ? and active = ? from the database.
@param groupId the group ID
@param active the active | [
"Removes",
"all",
"the",
"commerce",
"tax",
"methods",
"where",
"groupId",
"=",
"?",
";",
"and",
"active",
"=",
"?",
";",
"from",
"the",
"database",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-tax-service/src/main/java/com/liferay/commerce/tax/service/persistence/impl/CommerceTaxMethodPersistenceImpl.java#L1332-L1338 |
Swagger2Markup/swagger2markup | src/main/java/io/github/swagger2markup/internal/component/PathOperationComponent.java | PathOperationComponent.buildDeprecatedSection | private void buildDeprecatedSection(MarkupDocBuilder markupDocBuilder, PathOperation operation) {
if (BooleanUtils.isTrue(operation.getOperation().isDeprecated())) {
markupDocBuilder.block(DEPRECATED_OPERATION, MarkupBlockStyle.EXAMPLE, null, MarkupAdmonition.CAUTION);
}
} | java | private void buildDeprecatedSection(MarkupDocBuilder markupDocBuilder, PathOperation operation) {
if (BooleanUtils.isTrue(operation.getOperation().isDeprecated())) {
markupDocBuilder.block(DEPRECATED_OPERATION, MarkupBlockStyle.EXAMPLE, null, MarkupAdmonition.CAUTION);
}
} | [
"private",
"void",
"buildDeprecatedSection",
"(",
"MarkupDocBuilder",
"markupDocBuilder",
",",
"PathOperation",
"operation",
")",
"{",
"if",
"(",
"BooleanUtils",
".",
"isTrue",
"(",
"operation",
".",
"getOperation",
"(",
")",
".",
"isDeprecated",
"(",
")",
")",
... | Builds a warning if method is deprecated.
@param operation the Swagger Operation | [
"Builds",
"a",
"warning",
"if",
"method",
"is",
"deprecated",
"."
] | train | https://github.com/Swagger2Markup/swagger2markup/blob/da83465f19a2f8a0f1fba873b5762bca8587896b/src/main/java/io/github/swagger2markup/internal/component/PathOperationComponent.java#L161-L165 |
alkacon/opencms-core | src-gwt/org/opencms/ade/containerpage/client/CmsContainerpageHandler.java | CmsContainerpageHandler.insertContextMenu | public void insertContextMenu(List<CmsContextMenuEntryBean> menuBeans, CmsUUID structureId) {
List<I_CmsContextMenuEntry> menuEntries = transformEntries(menuBeans, structureId);
m_editor.getContext().showMenu(menuEntries);
} | java | public void insertContextMenu(List<CmsContextMenuEntryBean> menuBeans, CmsUUID structureId) {
List<I_CmsContextMenuEntry> menuEntries = transformEntries(menuBeans, structureId);
m_editor.getContext().showMenu(menuEntries);
} | [
"public",
"void",
"insertContextMenu",
"(",
"List",
"<",
"CmsContextMenuEntryBean",
">",
"menuBeans",
",",
"CmsUUID",
"structureId",
")",
"{",
"List",
"<",
"I_CmsContextMenuEntry",
">",
"menuEntries",
"=",
"transformEntries",
"(",
"menuBeans",
",",
"structureId",
")... | Inserts the context menu.<p>
@param menuBeans the menu beans from the server
@param structureId the structure id of the resource for which the context menu entries should be generated | [
"Inserts",
"the",
"context",
"menu",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/containerpage/client/CmsContainerpageHandler.java#L578-L582 |
Carbonado/Carbonado | src/main/java/com/amazon/carbonado/repo/jdbc/JDBCStorableGenerator.java | JDBCStorableGenerator.closeResultSet | private void closeResultSet
(CodeBuilder b, LocalVariable rsVar, Label tryAfterRs)
{
Label contLabel = b.createLabel();
Label endFinallyLabel = b.createLabel().setLocation();
b.loadLocal(rsVar);
b.invokeInterface(TypeDesc.forClass(ResultSet.class), "close", null, null);
b.branch(contLabel);
b.exceptionHandler(tryAfterRs, endFinallyLabel, null);
b.loadLocal(rsVar);
b.invokeInterface(TypeDesc.forClass(ResultSet.class), "close", null, null);
b.throwObject();
contLabel.setLocation();
} | java | private void closeResultSet
(CodeBuilder b, LocalVariable rsVar, Label tryAfterRs)
{
Label contLabel = b.createLabel();
Label endFinallyLabel = b.createLabel().setLocation();
b.loadLocal(rsVar);
b.invokeInterface(TypeDesc.forClass(ResultSet.class), "close", null, null);
b.branch(contLabel);
b.exceptionHandler(tryAfterRs, endFinallyLabel, null);
b.loadLocal(rsVar);
b.invokeInterface(TypeDesc.forClass(ResultSet.class), "close", null, null);
b.throwObject();
contLabel.setLocation();
} | [
"private",
"void",
"closeResultSet",
"(",
"CodeBuilder",
"b",
",",
"LocalVariable",
"rsVar",
",",
"Label",
"tryAfterRs",
")",
"{",
"Label",
"contLabel",
"=",
"b",
".",
"createLabel",
"(",
")",
";",
"Label",
"endFinallyLabel",
"=",
"b",
".",
"createLabel",
"(... | Generates code which emulates this:
...
} finally {
rs.close();
}
@param rsVar ResultSet variable
@param tryAfterRs label right after ResultSet acquisition | [
"Generates",
"code",
"which",
"emulates",
"this",
":"
] | train | https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/repo/jdbc/JDBCStorableGenerator.java#L1915-L1931 |
powermock/powermock | powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java | PowerMock.mockStaticNice | public static synchronized void mockStaticNice(Class<?> type, Method... methods) {
doMock(type, true, new NiceMockStrategy(), null, methods);
} | java | public static synchronized void mockStaticNice(Class<?> type, Method... methods) {
doMock(type, true, new NiceMockStrategy(), null, methods);
} | [
"public",
"static",
"synchronized",
"void",
"mockStaticNice",
"(",
"Class",
"<",
"?",
">",
"type",
",",
"Method",
"...",
"methods",
")",
"{",
"doMock",
"(",
"type",
",",
"true",
",",
"new",
"NiceMockStrategy",
"(",
")",
",",
"null",
",",
"methods",
")",
... | Enable nice static mocking for a class.
@param type the class to enable static mocking
@param methods optionally what methods to mock | [
"Enable",
"nice",
"static",
"mocking",
"for",
"a",
"class",
"."
] | train | https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java#L287-L289 |
threerings/nenya | core/src/main/java/com/threerings/media/animation/ScaleAnimation.java | ScaleAnimation.getBounds | public static Rectangle getBounds (float scale, Point center, Mirage image)
{
Point size = getSize(scale, image);
Point corner = getCorner(center, size);
return new Rectangle(corner.x, corner.y, size.x, size.y);
} | java | public static Rectangle getBounds (float scale, Point center, Mirage image)
{
Point size = getSize(scale, image);
Point corner = getCorner(center, size);
return new Rectangle(corner.x, corner.y, size.x, size.y);
} | [
"public",
"static",
"Rectangle",
"getBounds",
"(",
"float",
"scale",
",",
"Point",
"center",
",",
"Mirage",
"image",
")",
"{",
"Point",
"size",
"=",
"getSize",
"(",
"scale",
",",
"image",
")",
";",
"Point",
"corner",
"=",
"getCorner",
"(",
"center",
",",... | Java wants the first call in a constructor to be super() if it exists at all, so we have to
trick it with this function.
Oh, and this function computes how big the bounding box needs to be to bound the inputted
image scaled to the inputted size centered around the inputted center point. | [
"Java",
"wants",
"the",
"first",
"call",
"in",
"a",
"constructor",
"to",
"be",
"super",
"()",
"if",
"it",
"exists",
"at",
"all",
"so",
"we",
"have",
"to",
"trick",
"it",
"with",
"this",
"function",
"."
] | train | https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/media/animation/ScaleAnimation.java#L80-L85 |
geomajas/geomajas-project-server | api/src/main/java/org/geomajas/layer/feature/attribute/ManyToOneAttribute.java | ManyToOneAttribute.setUrlAttribute | public void setUrlAttribute(String name, String value) {
ensureValue();
Attribute attribute = new UrlAttribute(value);
attribute.setEditable(isEditable(name));
getValue().getAllAttributes().put(name, attribute);
} | java | public void setUrlAttribute(String name, String value) {
ensureValue();
Attribute attribute = new UrlAttribute(value);
attribute.setEditable(isEditable(name));
getValue().getAllAttributes().put(name, attribute);
} | [
"public",
"void",
"setUrlAttribute",
"(",
"String",
"name",
",",
"String",
"value",
")",
"{",
"ensureValue",
"(",
")",
";",
"Attribute",
"attribute",
"=",
"new",
"UrlAttribute",
"(",
"value",
")",
";",
"attribute",
".",
"setEditable",
"(",
"isEditable",
"(",... | Sets the specified URL attribute to the specified value.
@param name name of the attribute
@param value value of the attribute
@since 1.9.0 | [
"Sets",
"the",
"specified",
"URL",
"attribute",
"to",
"the",
"specified",
"value",
"."
] | train | https://github.com/geomajas/geomajas-project-server/blob/904b7d7deed1350d28955589098dd1e0a786d76e/api/src/main/java/org/geomajas/layer/feature/attribute/ManyToOneAttribute.java#L258-L263 |
Stratio/stratio-cassandra | src/java/com/stratio/cassandra/index/schema/mapping/Mapping.java | Mapping.addFields | public void addFields(Document document, Columns columns) {
for (Column column : columns) {
String name = column.getName();
ColumnMapper columnMapper = getMapper(name);
if (columnMapper != null) {
for (IndexableField field : columnMapper.fields(column)) {
document.add(field);
}
}
}
} | java | public void addFields(Document document, Columns columns) {
for (Column column : columns) {
String name = column.getName();
ColumnMapper columnMapper = getMapper(name);
if (columnMapper != null) {
for (IndexableField field : columnMapper.fields(column)) {
document.add(field);
}
}
}
} | [
"public",
"void",
"addFields",
"(",
"Document",
"document",
",",
"Columns",
"columns",
")",
"{",
"for",
"(",
"Column",
"column",
":",
"columns",
")",
"{",
"String",
"name",
"=",
"column",
".",
"getName",
"(",
")",
";",
"ColumnMapper",
"columnMapper",
"=",
... | Adds to the specified {@link org.apache.lucene.document.Document} the Lucene fields representing the specified
{@link com.stratio.cassandra.index.schema.Columns}.
@param document The Lucene {@link org.apache.lucene.document.Document} where the fields are going to be added.
@param columns The {@link com.stratio.cassandra.index.schema.Columns} to be added. | [
"Adds",
"to",
"the",
"specified",
"{",
"@link",
"org",
".",
"apache",
".",
"lucene",
".",
"document",
".",
"Document",
"}",
"the",
"Lucene",
"fields",
"representing",
"the",
"specified",
"{",
"@link",
"com",
".",
"stratio",
".",
"cassandra",
".",
"index",
... | train | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/com/stratio/cassandra/index/schema/mapping/Mapping.java#L80-L90 |
awslabs/jsii | packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiEngine.java | JsiiEngine.invokeMethod | private Object invokeMethod(final Object obj, final Method method, final Object... args) {
// turn method to accessible. otherwise, we won't be able to callback to methods
// on non-public classes.
boolean accessibility = method.isAccessible();
method.setAccessible(true);
try {
try {
return method.invoke(obj, args);
} catch (Exception e) {
this.log("Error while invoking %s with %s: %s", method, Arrays.toString(args), Throwables.getStackTraceAsString(e));
throw e;
}
} catch (InvocationTargetException e) {
throw new JsiiException(e.getTargetException());
} catch (IllegalAccessException e) {
throw new JsiiException(e);
} finally {
// revert accessibility.
method.setAccessible(accessibility);
}
} | java | private Object invokeMethod(final Object obj, final Method method, final Object... args) {
// turn method to accessible. otherwise, we won't be able to callback to methods
// on non-public classes.
boolean accessibility = method.isAccessible();
method.setAccessible(true);
try {
try {
return method.invoke(obj, args);
} catch (Exception e) {
this.log("Error while invoking %s with %s: %s", method, Arrays.toString(args), Throwables.getStackTraceAsString(e));
throw e;
}
} catch (InvocationTargetException e) {
throw new JsiiException(e.getTargetException());
} catch (IllegalAccessException e) {
throw new JsiiException(e);
} finally {
// revert accessibility.
method.setAccessible(accessibility);
}
} | [
"private",
"Object",
"invokeMethod",
"(",
"final",
"Object",
"obj",
",",
"final",
"Method",
"method",
",",
"final",
"Object",
"...",
"args",
")",
"{",
"// turn method to accessible. otherwise, we won't be able to callback to methods",
"// on non-public classes.",
"boolean",
... | Invokes a Java method, even if the method is protected.
@param obj The object
@param method The method
@param args Method arguments
@return The return value | [
"Invokes",
"a",
"Java",
"method",
"even",
"if",
"the",
"method",
"is",
"protected",
"."
] | train | https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiEngine.java#L381-L402 |
RestComm/sip-servlets | sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/session/SipSessionImpl.java | SipSessionImpl.setAckReceived | public void setAckReceived(long cSeq, boolean ackReceived) {
if(logger.isDebugEnabled()) {
logger.debug("setting AckReceived to : " + ackReceived + " for CSeq " + cSeq);
}
acksReceived.put(cSeq, ackReceived);
if(ackReceived) {
cleanupAcksReceived(cSeq);
}
} | java | public void setAckReceived(long cSeq, boolean ackReceived) {
if(logger.isDebugEnabled()) {
logger.debug("setting AckReceived to : " + ackReceived + " for CSeq " + cSeq);
}
acksReceived.put(cSeq, ackReceived);
if(ackReceived) {
cleanupAcksReceived(cSeq);
}
} | [
"public",
"void",
"setAckReceived",
"(",
"long",
"cSeq",
",",
"boolean",
"ackReceived",
")",
"{",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"\"setting AckReceived to : \"",
"+",
"ackReceived",
"+",
"\" for CSe... | Setting ackReceived for CSeq to specified value in second param.
if the second param is true it will try to cleanup earlier cseq as well to save on memory
@param cSeq cseq to set the ackReceived
@param ackReceived whether or not the ack has been received for this cseq | [
"Setting",
"ackReceived",
"for",
"CSeq",
"to",
"specified",
"value",
"in",
"second",
"param",
".",
"if",
"the",
"second",
"param",
"is",
"true",
"it",
"will",
"try",
"to",
"cleanup",
"earlier",
"cseq",
"as",
"well",
"to",
"save",
"on",
"memory"
] | train | https://github.com/RestComm/sip-servlets/blob/fd7011d2803ab1d205b140768a760c8c69e0c997/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/session/SipSessionImpl.java#L2547-L2555 |
alkacon/opencms-core | src/org/opencms/db/CmsSecurityManager.java | CmsSecurityManager.writeProject | public void writeProject(CmsRequestContext context, CmsProject project)
throws CmsRoleViolationException, CmsException {
CmsDbContext dbc = m_dbContextFactory.getDbContext(context);
try {
checkManagerOfProjectRole(dbc, project);
m_driverManager.writeProject(dbc, project);
} catch (Exception e) {
dbc.report(null, Messages.get().container(Messages.ERR_WRITE_PROJECT_1, project.getName()), e);
} finally {
dbc.clear();
}
} | java | public void writeProject(CmsRequestContext context, CmsProject project)
throws CmsRoleViolationException, CmsException {
CmsDbContext dbc = m_dbContextFactory.getDbContext(context);
try {
checkManagerOfProjectRole(dbc, project);
m_driverManager.writeProject(dbc, project);
} catch (Exception e) {
dbc.report(null, Messages.get().container(Messages.ERR_WRITE_PROJECT_1, project.getName()), e);
} finally {
dbc.clear();
}
} | [
"public",
"void",
"writeProject",
"(",
"CmsRequestContext",
"context",
",",
"CmsProject",
"project",
")",
"throws",
"CmsRoleViolationException",
",",
"CmsException",
"{",
"CmsDbContext",
"dbc",
"=",
"m_dbContextFactory",
".",
"getDbContext",
"(",
"context",
")",
";",
... | Writes an already existing project.<p>
The project id has to be a valid OpenCms project id.<br>
The project with the given id will be completely overridden
by the given data.<p>
@param project the project that should be written
@param context the current request context
@throws CmsRoleViolationException if the current user does not own the required permissions
@throws CmsException if operation was not successful | [
"Writes",
"an",
"already",
"existing",
"project",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsSecurityManager.java#L6775-L6787 |
jamesagnew/hapi-fhir | hapi-fhir-base/src/main/java/ca/uhn/fhir/util/ParametersUtil.java | ParametersUtil.addParameterToParameters | public static void addParameterToParameters(FhirContext theContext, IBaseParameters theParameters, String theName, Object theValue) {
RuntimeResourceDefinition def = theContext.getResourceDefinition(theParameters);
BaseRuntimeChildDefinition paramChild = def.getChildByName("parameter");
BaseRuntimeElementCompositeDefinition<?> paramChildElem = (BaseRuntimeElementCompositeDefinition<?>) paramChild.getChildByName("parameter");
addClientParameter(theContext, theValue, theParameters, paramChild, paramChildElem, theName);
} | java | public static void addParameterToParameters(FhirContext theContext, IBaseParameters theParameters, String theName, Object theValue) {
RuntimeResourceDefinition def = theContext.getResourceDefinition(theParameters);
BaseRuntimeChildDefinition paramChild = def.getChildByName("parameter");
BaseRuntimeElementCompositeDefinition<?> paramChildElem = (BaseRuntimeElementCompositeDefinition<?>) paramChild.getChildByName("parameter");
addClientParameter(theContext, theValue, theParameters, paramChild, paramChildElem, theName);
} | [
"public",
"static",
"void",
"addParameterToParameters",
"(",
"FhirContext",
"theContext",
",",
"IBaseParameters",
"theParameters",
",",
"String",
"theName",
",",
"Object",
"theValue",
")",
"{",
"RuntimeResourceDefinition",
"def",
"=",
"theContext",
".",
"getResourceDefi... | Add a paratemer value to a Parameters resource
@param theContext The FhirContext
@param theParameters The Parameters resource
@param theName The parametr name
@param theValue The parameter value (can be a {@link IBaseResource resource} or a {@link IBaseDatatype datatype}) | [
"Add",
"a",
"paratemer",
"value",
"to",
"a",
"Parameters",
"resource"
] | train | https://github.com/jamesagnew/hapi-fhir/blob/150a84d52fe691b7f48fcb28247c4bddb7aec352/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/ParametersUtil.java#L99-L105 |
ops4j/org.ops4j.pax.logging | pax-logging-service/src/main/java/org/apache/log4j/config/PaxPropertySetter.java | PaxPropertySetter.setProperties | public
static
void setProperties(Object obj, Properties properties, String prefix) {
new PaxPropertySetter(obj).setProperties(properties, prefix);
} | java | public
static
void setProperties(Object obj, Properties properties, String prefix) {
new PaxPropertySetter(obj).setProperties(properties, prefix);
} | [
"public",
"static",
"void",
"setProperties",
"(",
"Object",
"obj",
",",
"Properties",
"properties",
",",
"String",
"prefix",
")",
"{",
"new",
"PaxPropertySetter",
"(",
"obj",
")",
".",
"setProperties",
"(",
"properties",
",",
"prefix",
")",
";",
"}"
] | Set the properties of an object passed as a parameter in one
go. The <code>properties</code> are parsed relative to a
<code>prefix</code>.
@param obj The object to configure.
@param properties A java.util.Properties containing keys and values.
@param prefix Only keys having the specified prefix will be set. | [
"Set",
"the",
"properties",
"of",
"an",
"object",
"passed",
"as",
"a",
"parameter",
"in",
"one",
"go",
".",
"The",
"<code",
">",
"properties<",
"/",
"code",
">",
"are",
"parsed",
"relative",
"to",
"a",
"<code",
">",
"prefix<",
"/",
"code",
">",
"."
] | train | https://github.com/ops4j/org.ops4j.pax.logging/blob/493de4e1db4fe9f981f3dd78b8e40e5bf2b2e59d/pax-logging-service/src/main/java/org/apache/log4j/config/PaxPropertySetter.java#L105-L109 |
carewebframework/carewebframework-vista | org.carewebframework.vista.mbroker/src/main/java/org/carewebframework/vista/mbroker/ConnectionParams.java | ConnectionParams.addPiece | private void addPiece(String pc, String prefix, StringBuilder sb) {
if (!pc.isEmpty()) {
if (sb.length() > 0) {
sb.append(prefix);
}
sb.append(pc);
}
} | java | private void addPiece(String pc, String prefix, StringBuilder sb) {
if (!pc.isEmpty()) {
if (sb.length() > 0) {
sb.append(prefix);
}
sb.append(pc);
}
} | [
"private",
"void",
"addPiece",
"(",
"String",
"pc",
",",
"String",
"prefix",
",",
"StringBuilder",
"sb",
")",
"{",
"if",
"(",
"!",
"pc",
".",
"isEmpty",
"(",
")",
")",
"{",
"if",
"(",
"sb",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"sb",
"."... | Used to build a connection string for display.
@param pc A connection string field.
@param prefix The prefix to include if the field is not empty.
@param sb String builder instance. | [
"Used",
"to",
"build",
"a",
"connection",
"string",
"for",
"display",
"."
] | train | https://github.com/carewebframework/carewebframework-vista/blob/883b2cbe395d9e8a21cd19db820f0876bda6b1c6/org.carewebframework.vista.mbroker/src/main/java/org/carewebframework/vista/mbroker/ConnectionParams.java#L153-L161 |
apache/flink | flink-core/src/main/java/org/apache/flink/util/ExceptionUtils.java | ExceptionUtils.rethrowException | public static void rethrowException(Throwable t, String parentMessage) throws Exception {
if (t instanceof Error) {
throw (Error) t;
}
else if (t instanceof Exception) {
throw (Exception) t;
}
else {
throw new Exception(parentMessage, t);
}
} | java | public static void rethrowException(Throwable t, String parentMessage) throws Exception {
if (t instanceof Error) {
throw (Error) t;
}
else if (t instanceof Exception) {
throw (Exception) t;
}
else {
throw new Exception(parentMessage, t);
}
} | [
"public",
"static",
"void",
"rethrowException",
"(",
"Throwable",
"t",
",",
"String",
"parentMessage",
")",
"throws",
"Exception",
"{",
"if",
"(",
"t",
"instanceof",
"Error",
")",
"{",
"throw",
"(",
"Error",
")",
"t",
";",
"}",
"else",
"if",
"(",
"t",
... | Throws the given {@code Throwable} in scenarios where the signatures do allow to
throw a Exception. Errors and Exceptions are thrown directly, other "exotic"
subclasses of Throwable are wrapped in an Exception.
@param t The throwable to be thrown.
@param parentMessage The message for the parent Exception, if one is needed. | [
"Throws",
"the",
"given",
"{",
"@code",
"Throwable",
"}",
"in",
"scenarios",
"where",
"the",
"signatures",
"do",
"allow",
"to",
"throw",
"a",
"Exception",
".",
"Errors",
"and",
"Exceptions",
"are",
"thrown",
"directly",
"other",
"exotic",
"subclasses",
"of",
... | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/util/ExceptionUtils.java#L231-L241 |
sirthias/parboiled | parboiled-core/src/main/java/org/parboiled/support/Checks.java | Checks.ensure | public static void ensure(boolean condition, String errorMessageFormat, Object... errorMessageArgs) {
if (!condition) {
throw new GrammarException(errorMessageFormat, errorMessageArgs);
}
} | java | public static void ensure(boolean condition, String errorMessageFormat, Object... errorMessageArgs) {
if (!condition) {
throw new GrammarException(errorMessageFormat, errorMessageArgs);
}
} | [
"public",
"static",
"void",
"ensure",
"(",
"boolean",
"condition",
",",
"String",
"errorMessageFormat",
",",
"Object",
"...",
"errorMessageArgs",
")",
"{",
"if",
"(",
"!",
"condition",
")",
"{",
"throw",
"new",
"GrammarException",
"(",
"errorMessageFormat",
",",... | Throws a GrammarException if the given condition is not met.
@param condition the condition
@param errorMessageFormat the error message format
@param errorMessageArgs the error message arguments | [
"Throws",
"a",
"GrammarException",
"if",
"the",
"given",
"condition",
"is",
"not",
"met",
"."
] | train | https://github.com/sirthias/parboiled/blob/84f3ed43e3e171b4c6ab5e6ca6297d264a9d686a/parboiled-core/src/main/java/org/parboiled/support/Checks.java#L35-L39 |
apache/reef | lang/java/reef-common/src/main/java/org/apache/reef/runtime/common/driver/resourcemanager/ResourceManagerStatus.java | ResourceManagerStatus.getIdleStatus | @Override
public synchronized IdleMessage getIdleStatus() {
if (this.isIdle()) {
return IDLE_MESSAGE;
}
final String message = String.format(
"There are %d outstanding container requests and %d allocated containers",
this.outstandingContainerRequests, this.containerAllocationCount);
return new IdleMessage(COMPONENT_NAME, message, false);
} | java | @Override
public synchronized IdleMessage getIdleStatus() {
if (this.isIdle()) {
return IDLE_MESSAGE;
}
final String message = String.format(
"There are %d outstanding container requests and %d allocated containers",
this.outstandingContainerRequests, this.containerAllocationCount);
return new IdleMessage(COMPONENT_NAME, message, false);
} | [
"@",
"Override",
"public",
"synchronized",
"IdleMessage",
"getIdleStatus",
"(",
")",
"{",
"if",
"(",
"this",
".",
"isIdle",
"(",
")",
")",
"{",
"return",
"IDLE_MESSAGE",
";",
"}",
"final",
"String",
"message",
"=",
"String",
".",
"format",
"(",
"\"There ar... | Driver is idle if, regardless of status, it has no evaluators allocated
and no pending container requests. This method is used in the DriverIdleManager.
If all DriverIdlenessSource components are idle, DriverIdleManager will initiate Driver shutdown.
@return idle, if there are no outstanding requests or allocations. Not idle otherwise. | [
"Driver",
"is",
"idle",
"if",
"regardless",
"of",
"status",
"it",
"has",
"no",
"evaluators",
"allocated",
"and",
"no",
"pending",
"container",
"requests",
".",
"This",
"method",
"is",
"used",
"in",
"the",
"DriverIdleManager",
".",
"If",
"all",
"DriverIdlenessS... | train | https://github.com/apache/reef/blob/e2c47121cde21108a602c560cf76565a40d0e916/lang/java/reef-common/src/main/java/org/apache/reef/runtime/common/driver/resourcemanager/ResourceManagerStatus.java#L127-L139 |
cdk/cdk | tool/formula/src/main/java/org/openscience/cdk/tools/manipulator/MolecularFormulaManipulator.java | MolecularFormulaManipulator.getMass | public static double getMass(IMolecularFormula mf, int flav) {
final Isotopes isofact;
try {
isofact = Isotopes.getInstance();
} catch (IOException e) {
throw new IllegalStateException("Could not load Isotopes!");
}
double mass = 0;
switch (flav & 0xf) {
case MolWeight:
for (IIsotope iso : mf.isotopes()) {
mass += mf.getIsotopeCount(iso) *
getMassOrAvg(isofact, iso);
}
break;
case MolWeightIgnoreSpecified:
for (IIsotope iso : mf.isotopes()) {
mass += mf.getIsotopeCount(iso) *
isofact.getNaturalMass(iso.getAtomicNumber());
}
break;
case MonoIsotopic:
for (IIsotope iso : mf.isotopes()) {
mass += mf.getIsotopeCount(iso) *
getExactMass(isofact, iso);
}
break;
case MostAbundant:
IMolecularFormula mamf = getMostAbundant(mf);
if (mamf != null)
mass = getMass(mamf, MonoIsotopic);
break;
}
return mass;
} | java | public static double getMass(IMolecularFormula mf, int flav) {
final Isotopes isofact;
try {
isofact = Isotopes.getInstance();
} catch (IOException e) {
throw new IllegalStateException("Could not load Isotopes!");
}
double mass = 0;
switch (flav & 0xf) {
case MolWeight:
for (IIsotope iso : mf.isotopes()) {
mass += mf.getIsotopeCount(iso) *
getMassOrAvg(isofact, iso);
}
break;
case MolWeightIgnoreSpecified:
for (IIsotope iso : mf.isotopes()) {
mass += mf.getIsotopeCount(iso) *
isofact.getNaturalMass(iso.getAtomicNumber());
}
break;
case MonoIsotopic:
for (IIsotope iso : mf.isotopes()) {
mass += mf.getIsotopeCount(iso) *
getExactMass(isofact, iso);
}
break;
case MostAbundant:
IMolecularFormula mamf = getMostAbundant(mf);
if (mamf != null)
mass = getMass(mamf, MonoIsotopic);
break;
}
return mass;
} | [
"public",
"static",
"double",
"getMass",
"(",
"IMolecularFormula",
"mf",
",",
"int",
"flav",
")",
"{",
"final",
"Isotopes",
"isofact",
";",
"try",
"{",
"isofact",
"=",
"Isotopes",
".",
"getInstance",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
... | Calculate the mass of a formula, this function takes an optional
'mass flavour' that switches the computation type. The key distinction
is how specified/unspecified isotopes are handled. A specified isotope
is an atom that has either {@link IAtom#setMassNumber(Integer)}
or {@link IAtom#setExactMass(Double)} set to non-null and non-zero.
<br>
The flavours are:
<br>
<ul>
<li>{@link #MolWeight} (default) - uses the exact mass of each
atom when an isotope is specified, if not specified the average mass
of the element is used.</li>
<li>{@link #MolWeightIgnoreSpecified} - uses the average mass of each
element, ignoring any isotopic/exact mass specification</li>
<li>{@link #MonoIsotopic} - uses the exact mass of each
atom when an isotope is specified, if not specified the major isotope
mass for that element is used.</li>
<li>{@link #MostAbundant} - uses the exact mass of each atom when
specified, if not specified a distribution is calculated and the
most abundant isotope pattern is used.</li>
</ul>
@param mf molecular formula
@param flav flavor
@return the mass of the molecule
@see #getMass(IMolecularFormula, int)
@see #MolWeight
@see #MolWeightIgnoreSpecified
@see #MonoIsotopic
@see #MostAbundant | [
"Calculate",
"the",
"mass",
"of",
"a",
"formula",
"this",
"function",
"takes",
"an",
"optional",
"mass",
"flavour",
"that",
"switches",
"the",
"computation",
"type",
".",
"The",
"key",
"distinction",
"is",
"how",
"specified",
"/",
"unspecified",
"isotopes",
"a... | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/tool/formula/src/main/java/org/openscience/cdk/tools/manipulator/MolecularFormulaManipulator.java#L907-L942 |
alipay/sofa-hessian | src/main/java/com/caucho/hessian/server/HessianServlet.java | HessianServlet.service | public void service(ServletRequest request, ServletResponse response)
throws IOException, ServletException
{
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
if (!req.getMethod().equals("POST")) {
res.setStatus(500); // , "Hessian Requires POST");
PrintWriter out = res.getWriter();
res.setContentType("text/html");
out.println("<h1>Hessian Requires POST</h1>");
return;
}
String serviceId = req.getPathInfo();
String objectId = req.getParameter("id");
if (objectId == null)
objectId = req.getParameter("ejbid");
ServiceContext.begin(req, res, serviceId, objectId);
try {
InputStream is = request.getInputStream();
OutputStream os = response.getOutputStream();
response.setContentType("x-application/hessian");
SerializerFactory serializerFactory = getSerializerFactory();
invoke(is, os, objectId, serializerFactory);
} catch (RuntimeException e) {
throw e;
} catch (ServletException e) {
throw e;
} catch (Throwable e) {
throw new ServletException(e);
} finally {
ServiceContext.end();
}
} | java | public void service(ServletRequest request, ServletResponse response)
throws IOException, ServletException
{
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
if (!req.getMethod().equals("POST")) {
res.setStatus(500); // , "Hessian Requires POST");
PrintWriter out = res.getWriter();
res.setContentType("text/html");
out.println("<h1>Hessian Requires POST</h1>");
return;
}
String serviceId = req.getPathInfo();
String objectId = req.getParameter("id");
if (objectId == null)
objectId = req.getParameter("ejbid");
ServiceContext.begin(req, res, serviceId, objectId);
try {
InputStream is = request.getInputStream();
OutputStream os = response.getOutputStream();
response.setContentType("x-application/hessian");
SerializerFactory serializerFactory = getSerializerFactory();
invoke(is, os, objectId, serializerFactory);
} catch (RuntimeException e) {
throw e;
} catch (ServletException e) {
throw e;
} catch (Throwable e) {
throw new ServletException(e);
} finally {
ServiceContext.end();
}
} | [
"public",
"void",
"service",
"(",
"ServletRequest",
"request",
",",
"ServletResponse",
"response",
")",
"throws",
"IOException",
",",
"ServletException",
"{",
"HttpServletRequest",
"req",
"=",
"(",
"HttpServletRequest",
")",
"request",
";",
"HttpServletResponse",
"res... | Execute a request. The path-info of the request selects the bean.
Once the bean's selected, it will be applied. | [
"Execute",
"a",
"request",
".",
"The",
"path",
"-",
"info",
"of",
"the",
"request",
"selects",
"the",
"bean",
".",
"Once",
"the",
"bean",
"s",
"selected",
"it",
"will",
"be",
"applied",
"."
] | train | https://github.com/alipay/sofa-hessian/blob/89e4f5af28602101dab7b498995018871616357b/src/main/java/com/caucho/hessian/server/HessianServlet.java#L372-L413 |
apache/groovy | subprojects/groovy-sql/src/main/java/groovy/sql/Sql.java | Sql.executeInsert | public List<GroovyRowResult> executeInsert(String sql, String[] keyColumnNames) throws SQLException {
Connection connection = createConnection();
Statement statement = null;
try {
statement = getStatement(connection, sql);
this.updateCount = statement.executeUpdate(sql, keyColumnNames);
ResultSet keys = statement.getGeneratedKeys();
return asList(sql, keys);
} catch (SQLException e) {
LOG.warning("Failed to execute: " + sql + " because: " + e.getMessage());
throw e;
} finally {
closeResources(connection, statement);
}
} | java | public List<GroovyRowResult> executeInsert(String sql, String[] keyColumnNames) throws SQLException {
Connection connection = createConnection();
Statement statement = null;
try {
statement = getStatement(connection, sql);
this.updateCount = statement.executeUpdate(sql, keyColumnNames);
ResultSet keys = statement.getGeneratedKeys();
return asList(sql, keys);
} catch (SQLException e) {
LOG.warning("Failed to execute: " + sql + " because: " + e.getMessage());
throw e;
} finally {
closeResources(connection, statement);
}
} | [
"public",
"List",
"<",
"GroovyRowResult",
">",
"executeInsert",
"(",
"String",
"sql",
",",
"String",
"[",
"]",
"keyColumnNames",
")",
"throws",
"SQLException",
"{",
"Connection",
"connection",
"=",
"createConnection",
"(",
")",
";",
"Statement",
"statement",
"="... | Executes the given SQL statement (typically an INSERT statement).
This variant allows you to receive the values of any auto-generated columns,
such as an autoincrement ID field (or fields) when you know the column name(s) of the ID field(s).
<p>
This method supports named and named ordinal parameters by supplying such
parameters in the <code>params</code> array. See the class Javadoc for more details.
@param sql The SQL statement to execute
@param keyColumnNames an array of column names indicating the columns that should be returned from the
inserted row or rows (some drivers may be case sensitive, e.g. may require uppercase names)
@return A list of the auto-generated row results for each inserted row (typically auto-generated keys)
@throws SQLException if a database access error occurs
@since 2.3.2 | [
"Executes",
"the",
"given",
"SQL",
"statement",
"(",
"typically",
"an",
"INSERT",
"statement",
")",
".",
"This",
"variant",
"allows",
"you",
"to",
"receive",
"the",
"values",
"of",
"any",
"auto",
"-",
"generated",
"columns",
"such",
"as",
"an",
"autoincremen... | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-sql/src/main/java/groovy/sql/Sql.java#L2774-L2788 |
astrapi69/jaulp-wicket | jaulp-wicket-components/src/main/java/de/alpharogroup/wicket/components/sign/in/form/SigninFormPanel.java | SigninFormPanel.newButton | protected Button newButton(final String id)
{
return new AjaxButton(id)
{
/**
* The serialVersionUID.
*/
private static final long serialVersionUID = 1L;
/**
* Listener method invoked on form submit with errors
*
* @param target
* @param form
*/
@Override
protected void onError(final AjaxRequestTarget target, final Form<?> form)
{
SigninFormPanel.this.onSignin(target, SigninFormPanel.this.form);
}
/**
* {@inheritDoc}
*/
@Override
public void onSubmit(final AjaxRequestTarget target, final Form<?> form)
{
SigninFormPanel.this.onSignin(target, SigninFormPanel.this.form);
}
};
} | java | protected Button newButton(final String id)
{
return new AjaxButton(id)
{
/**
* The serialVersionUID.
*/
private static final long serialVersionUID = 1L;
/**
* Listener method invoked on form submit with errors
*
* @param target
* @param form
*/
@Override
protected void onError(final AjaxRequestTarget target, final Form<?> form)
{
SigninFormPanel.this.onSignin(target, SigninFormPanel.this.form);
}
/**
* {@inheritDoc}
*/
@Override
public void onSubmit(final AjaxRequestTarget target, final Form<?> form)
{
SigninFormPanel.this.onSignin(target, SigninFormPanel.this.form);
}
};
} | [
"protected",
"Button",
"newButton",
"(",
"final",
"String",
"id",
")",
"{",
"return",
"new",
"AjaxButton",
"(",
"id",
")",
"{",
"/**\n\t\t\t * The serialVersionUID.\n\t\t\t */",
"private",
"static",
"final",
"long",
"serialVersionUID",
"=",
"1L",
";",
"/**\n\t\t\t *... | Factory method for creating the new {@link Button}. This method is invoked in the constructor
from the derived classes and can be overridden so users can provide their own version of a
new {@link Button}.
@param id
the id
@return the new {@link Button} | [
"Factory",
"method",
"for",
"creating",
"the",
"new",
"{",
"@link",
"Button",
"}",
".",
"This",
"method",
"is",
"invoked",
"in",
"the",
"constructor",
"from",
"the",
"derived",
"classes",
"and",
"can",
"be",
"overridden",
"so",
"users",
"can",
"provide",
"... | train | https://github.com/astrapi69/jaulp-wicket/blob/85d74368d00abd9bb97659b5794e38c0f8a013d4/jaulp-wicket-components/src/main/java/de/alpharogroup/wicket/components/sign/in/form/SigninFormPanel.java#L90-L121 |
NessComputing/components-ness-amqp | src/main/java/com/nesscomputing/amqp/AmqpRunnableFactory.java | AmqpRunnableFactory.createExchangeListener | public ExchangeConsumer createExchangeListener(final String name, final ConsumerCallback messageCallback)
{
Preconditions.checkState(connectionFactory != null, "connection factory was never injected!");
return new ExchangeConsumer(connectionFactory, amqpConfig, name, messageCallback);
} | java | public ExchangeConsumer createExchangeListener(final String name, final ConsumerCallback messageCallback)
{
Preconditions.checkState(connectionFactory != null, "connection factory was never injected!");
return new ExchangeConsumer(connectionFactory, amqpConfig, name, messageCallback);
} | [
"public",
"ExchangeConsumer",
"createExchangeListener",
"(",
"final",
"String",
"name",
",",
"final",
"ConsumerCallback",
"messageCallback",
")",
"{",
"Preconditions",
".",
"checkState",
"(",
"connectionFactory",
"!=",
"null",
",",
"\"connection factory was never injected!\... | Creates a new {@link ExchangeConsumer}. For every message received (or when the timeout waiting for messages is hit), the callback
is invoked with the message received. | [
"Creates",
"a",
"new",
"{"
] | train | https://github.com/NessComputing/components-ness-amqp/blob/3d36b0b71d975f943efb3c181a16c72d46892922/src/main/java/com/nesscomputing/amqp/AmqpRunnableFactory.java#L129-L133 |
pietermartin/sqlg | sqlg-core/src/main/java/org/umlg/sqlg/structure/topology/Schema.java | Schema.createPublicSchema | static Schema createPublicSchema(SqlgGraph sqlgGraph, Topology topology, String publicSchemaName) {
Schema schema = new Schema(topology, publicSchemaName);
if (!existPublicSchema(sqlgGraph)) {
schema.createSchemaOnDb();
}
schema.committed = false;
return schema;
} | java | static Schema createPublicSchema(SqlgGraph sqlgGraph, Topology topology, String publicSchemaName) {
Schema schema = new Schema(topology, publicSchemaName);
if (!existPublicSchema(sqlgGraph)) {
schema.createSchemaOnDb();
}
schema.committed = false;
return schema;
} | [
"static",
"Schema",
"createPublicSchema",
"(",
"SqlgGraph",
"sqlgGraph",
",",
"Topology",
"topology",
",",
"String",
"publicSchemaName",
")",
"{",
"Schema",
"schema",
"=",
"new",
"Schema",
"(",
"topology",
",",
"publicSchemaName",
")",
";",
"if",
"(",
"!",
"ex... | Creates the 'public' schema that always already exist and is pre-loaded in {@link Topology()} @see {@link Topology#cacheTopology()}
@param publicSchemaName The 'public' schema's name. Sometimes its upper case (Hsqldb) sometimes lower (Postgresql)
@param topology The {@link Topology} that contains the public schema.
@return The Schema that represents 'public' | [
"Creates",
"the",
"public",
"schema",
"that",
"always",
"already",
"exist",
"and",
"is",
"pre",
"-",
"loaded",
"in",
"{",
"@link",
"Topology",
"()",
"}",
"@see",
"{",
"@link",
"Topology#cacheTopology",
"()",
"}"
] | train | https://github.com/pietermartin/sqlg/blob/c1845a1b31328a5ffda646873b0369ee72af56a7/sqlg-core/src/main/java/org/umlg/sqlg/structure/topology/Schema.java#L73-L80 |
Azure/azure-sdk-for-java | recoveryservices/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/recoveryservices/v2016_06_01/implementation/VaultsInner.java | VaultsInner.updateAsync | public Observable<VaultInner> updateAsync(String resourceGroupName, String vaultName, PatchVault vault) {
return updateWithServiceResponseAsync(resourceGroupName, vaultName, vault).map(new Func1<ServiceResponse<VaultInner>, VaultInner>() {
@Override
public VaultInner call(ServiceResponse<VaultInner> response) {
return response.body();
}
});
} | java | public Observable<VaultInner> updateAsync(String resourceGroupName, String vaultName, PatchVault vault) {
return updateWithServiceResponseAsync(resourceGroupName, vaultName, vault).map(new Func1<ServiceResponse<VaultInner>, VaultInner>() {
@Override
public VaultInner call(ServiceResponse<VaultInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"VaultInner",
">",
"updateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"vaultName",
",",
"PatchVault",
"vault",
")",
"{",
"return",
"updateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"vaultName",
",",
"vault",
... | Updates the vault.
@param resourceGroupName The name of the resource group where the recovery services vault is present.
@param vaultName The name of the recovery services vault.
@param vault Recovery Services Vault to be created.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the VaultInner object | [
"Updates",
"the",
"vault",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/recoveryservices/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/recoveryservices/v2016_06_01/implementation/VaultsInner.java#L629-L636 |
aol/cyclops | cyclops/src/main/java/cyclops/companion/Streams.java | Streams.scheduleFixedDelay | public static <T> Connectable<T> scheduleFixedDelay(final Stream<T> stream, final long delay, final ScheduledExecutorService ex) {
return new NonPausableConnectable<>(
stream).scheduleFixedDelay(delay, ex);
} | java | public static <T> Connectable<T> scheduleFixedDelay(final Stream<T> stream, final long delay, final ScheduledExecutorService ex) {
return new NonPausableConnectable<>(
stream).scheduleFixedDelay(delay, ex);
} | [
"public",
"static",
"<",
"T",
">",
"Connectable",
"<",
"T",
">",
"scheduleFixedDelay",
"(",
"final",
"Stream",
"<",
"T",
">",
"stream",
",",
"final",
"long",
"delay",
",",
"final",
"ScheduledExecutorService",
"ex",
")",
"{",
"return",
"new",
"NonPausableConn... | Execute this Stream on a schedule
<pre>
{@code
//run every 60 seconds after last job completes
Streams.scheduleFixedDelay(Stream.generate(()->"next job:"+formatDate(new Date()))
.map(this::processJob)
,60_000,Executors.newScheduledThreadPool(1)));
}
</pre>
Connect to the Scheduled Stream
<pre>
{@code
Connectable<Data> dataStream = Streams.scheduleFixedDelay(Stream.generate(()->"next job:"+formatDate(new Date()))
.map(this::processJob)
,60_000,Executors.newScheduledThreadPool(1)));
data.connect().forEach(this::logToDB);
}
</pre>
@param stream the stream to schedule element processing on
@param delay Between last element completes passing through the Stream until the next one starts
@param ex ScheduledExecutorService
@return Connectable Connectable of emitted from scheduled Stream | [
"Execute",
"this",
"Stream",
"on",
"a",
"schedule"
] | train | https://github.com/aol/cyclops/blob/59a9fde30190a4d1faeb9f6d9851d209d82b81dd/cyclops/src/main/java/cyclops/companion/Streams.java#L777-L780 |
google/jimfs | jimfs/src/main/java/com/google/common/jimfs/JimfsPath.java | JimfsPath.startsWith | private static boolean startsWith(List<?> list, List<?> other) {
return list.size() >= other.size() && list.subList(0, other.size()).equals(other);
} | java | private static boolean startsWith(List<?> list, List<?> other) {
return list.size() >= other.size() && list.subList(0, other.size()).equals(other);
} | [
"private",
"static",
"boolean",
"startsWith",
"(",
"List",
"<",
"?",
">",
"list",
",",
"List",
"<",
"?",
">",
"other",
")",
"{",
"return",
"list",
".",
"size",
"(",
")",
">=",
"other",
".",
"size",
"(",
")",
"&&",
"list",
".",
"subList",
"(",
"0"... | Returns true if list starts with all elements of other in the same order. | [
"Returns",
"true",
"if",
"list",
"starts",
"with",
"all",
"elements",
"of",
"other",
"in",
"the",
"same",
"order",
"."
] | train | https://github.com/google/jimfs/blob/3eadff747a3afa7b498030f420d2d04ce700534a/jimfs/src/main/java/com/google/common/jimfs/JimfsPath.java#L163-L165 |
Whiley/WhileyCompiler | src/main/java/wyc/io/WhileyFileParser.java | WhileyFileParser.parseHeadlessStatement | private Stmt parseHeadlessStatement(EnclosingScope scope) {
int start = index;
// See if it is a named block
Identifier blockName = parseOptionalIdentifier(scope);
if (blockName != null) {
if (tryAndMatch(true, Colon) != null && isAtEOL()) {
int end = index;
matchEndLine();
scope = scope.newEnclosingScope();
scope.declareLifetime(blockName);
Stmt.Block body = parseBlock(scope, false);
return annotateSourceLocation(new Stmt.NamedBlock(blockName, body), start);
} else {
index = start; // backtrack
}
}
// assignment : Identifier | LeftBrace | Star
// variable decl: Identifier | LeftBrace | LeftCurly | Ampersand
// invoke : Identifier | LeftBrace | Star
if (tryAndMatch(false, Final) != null || (skipType(scope) && tryAndMatch(false, Identifier) != null)) {
// Must be a variable declaration as this is the only situation in which a type
// can be followed by an identifier.
index = start; // backtrack
//
return parseVariableDeclaration(scope);
}
// Must be an assignment or invocation
index = start; // backtrack
//
Expr e = parseExpression(scope, false);
//
if (e instanceof Expr.Invoke || e instanceof Expr.IndirectInvoke) {
// Must be an invocation since these are neither valid
// lvals (i.e. they cannot be assigned) nor types.
matchEndLine();
return e;
} else {
// At this point, the only remaining option is an assignment statement.
// Therefore, it must be that.
index = start; // backtrack
//
return parseAssignmentStatement(scope);
}
} | java | private Stmt parseHeadlessStatement(EnclosingScope scope) {
int start = index;
// See if it is a named block
Identifier blockName = parseOptionalIdentifier(scope);
if (blockName != null) {
if (tryAndMatch(true, Colon) != null && isAtEOL()) {
int end = index;
matchEndLine();
scope = scope.newEnclosingScope();
scope.declareLifetime(blockName);
Stmt.Block body = parseBlock(scope, false);
return annotateSourceLocation(new Stmt.NamedBlock(blockName, body), start);
} else {
index = start; // backtrack
}
}
// assignment : Identifier | LeftBrace | Star
// variable decl: Identifier | LeftBrace | LeftCurly | Ampersand
// invoke : Identifier | LeftBrace | Star
if (tryAndMatch(false, Final) != null || (skipType(scope) && tryAndMatch(false, Identifier) != null)) {
// Must be a variable declaration as this is the only situation in which a type
// can be followed by an identifier.
index = start; // backtrack
//
return parseVariableDeclaration(scope);
}
// Must be an assignment or invocation
index = start; // backtrack
//
Expr e = parseExpression(scope, false);
//
if (e instanceof Expr.Invoke || e instanceof Expr.IndirectInvoke) {
// Must be an invocation since these are neither valid
// lvals (i.e. they cannot be assigned) nor types.
matchEndLine();
return e;
} else {
// At this point, the only remaining option is an assignment statement.
// Therefore, it must be that.
index = start; // backtrack
//
return parseAssignmentStatement(scope);
}
} | [
"private",
"Stmt",
"parseHeadlessStatement",
"(",
"EnclosingScope",
"scope",
")",
"{",
"int",
"start",
"=",
"index",
";",
"// See if it is a named block",
"Identifier",
"blockName",
"=",
"parseOptionalIdentifier",
"(",
"scope",
")",
";",
"if",
"(",
"blockName",
"!="... | A headless statement is one which has no identifying keyword. The set of
headless statements include assignments, invocations, variable
declarations and named blocks.
@param scope
The enclosing scope for this statement, which determines the
set of visible (i.e. declared) variables and also the current
indentation level.
@return | [
"A",
"headless",
"statement",
"is",
"one",
"which",
"has",
"no",
"identifying",
"keyword",
".",
"The",
"set",
"of",
"headless",
"statements",
"include",
"assignments",
"invocations",
"variable",
"declarations",
"and",
"named",
"blocks",
"."
] | train | https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyc/io/WhileyFileParser.java#L756-L800 |
hazelcast/hazelcast | hazelcast/src/main/java/com/hazelcast/map/impl/querycache/subscriber/DefaultQueryCache.java | DefaultQueryCache.isTryRecoverSucceeded | private boolean isTryRecoverSucceeded(ConcurrentMap<Integer, Long> brokenSequences) {
int numberOfBrokenSequences = brokenSequences.size();
InvokerWrapper invokerWrapper = context.getInvokerWrapper();
SubscriberContext subscriberContext = context.getSubscriberContext();
SubscriberContextSupport subscriberContextSupport = subscriberContext.getSubscriberContextSupport();
List<Future<Object>> futures = new ArrayList<>(numberOfBrokenSequences);
for (Map.Entry<Integer, Long> entry : brokenSequences.entrySet()) {
Integer partitionId = entry.getKey();
Long sequence = entry.getValue();
Object recoveryOperation
= subscriberContextSupport.createRecoveryOperation(mapName, cacheId, sequence, partitionId);
Future<Object> future
= (Future<Object>)
invokerWrapper.invokeOnPartitionOwner(recoveryOperation, partitionId);
futures.add(future);
}
Collection<Object> results = FutureUtil.returnWithDeadline(futures, 1, MINUTES);
int successCount = 0;
for (Object object : results) {
Boolean resolvedResponse = subscriberContextSupport.resolveResponseForRecoveryOperation(object);
if (TRUE.equals(resolvedResponse)) {
successCount++;
}
}
return successCount == numberOfBrokenSequences;
} | java | private boolean isTryRecoverSucceeded(ConcurrentMap<Integer, Long> brokenSequences) {
int numberOfBrokenSequences = brokenSequences.size();
InvokerWrapper invokerWrapper = context.getInvokerWrapper();
SubscriberContext subscriberContext = context.getSubscriberContext();
SubscriberContextSupport subscriberContextSupport = subscriberContext.getSubscriberContextSupport();
List<Future<Object>> futures = new ArrayList<>(numberOfBrokenSequences);
for (Map.Entry<Integer, Long> entry : brokenSequences.entrySet()) {
Integer partitionId = entry.getKey();
Long sequence = entry.getValue();
Object recoveryOperation
= subscriberContextSupport.createRecoveryOperation(mapName, cacheId, sequence, partitionId);
Future<Object> future
= (Future<Object>)
invokerWrapper.invokeOnPartitionOwner(recoveryOperation, partitionId);
futures.add(future);
}
Collection<Object> results = FutureUtil.returnWithDeadline(futures, 1, MINUTES);
int successCount = 0;
for (Object object : results) {
Boolean resolvedResponse = subscriberContextSupport.resolveResponseForRecoveryOperation(object);
if (TRUE.equals(resolvedResponse)) {
successCount++;
}
}
return successCount == numberOfBrokenSequences;
} | [
"private",
"boolean",
"isTryRecoverSucceeded",
"(",
"ConcurrentMap",
"<",
"Integer",
",",
"Long",
">",
"brokenSequences",
")",
"{",
"int",
"numberOfBrokenSequences",
"=",
"brokenSequences",
".",
"size",
"(",
")",
";",
"InvokerWrapper",
"invokerWrapper",
"=",
"contex... | This tries to reset cursor position of the accumulator to the supplied sequence,
if that sequence is still there, it will be succeeded, otherwise query cache content stays inconsistent. | [
"This",
"tries",
"to",
"reset",
"cursor",
"position",
"of",
"the",
"accumulator",
"to",
"the",
"supplied",
"sequence",
"if",
"that",
"sequence",
"is",
"still",
"there",
"it",
"will",
"be",
"succeeded",
"otherwise",
"query",
"cache",
"content",
"stays",
"incons... | train | https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/map/impl/querycache/subscriber/DefaultQueryCache.java#L146-L173 |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/env/DefaultCoreEnvironment.java | DefaultCoreEnvironment.wrapShutdown | private Observable<ShutdownStatus> wrapShutdown(Observable<Boolean> source, final String target) {
return source.
reduce(true, new Func2<Boolean, Boolean, Boolean>() {
@Override
public Boolean call(Boolean previousStatus, Boolean currentStatus) {
return previousStatus && currentStatus;
}
})
.map(new Func1<Boolean, ShutdownStatus>() {
@Override
public ShutdownStatus call(Boolean status) {
return new ShutdownStatus(target, status, null);
}
})
.onErrorReturn(new Func1<Throwable, ShutdownStatus>() {
@Override
public ShutdownStatus call(Throwable throwable) {
return new ShutdownStatus(target, false, throwable);
}
})
.doOnNext(new Action1<ShutdownStatus>() {
@Override
public void call(ShutdownStatus shutdownStatus) {
LOGGER.info(shutdownStatus.toString());
}
});
} | java | private Observable<ShutdownStatus> wrapShutdown(Observable<Boolean> source, final String target) {
return source.
reduce(true, new Func2<Boolean, Boolean, Boolean>() {
@Override
public Boolean call(Boolean previousStatus, Boolean currentStatus) {
return previousStatus && currentStatus;
}
})
.map(new Func1<Boolean, ShutdownStatus>() {
@Override
public ShutdownStatus call(Boolean status) {
return new ShutdownStatus(target, status, null);
}
})
.onErrorReturn(new Func1<Throwable, ShutdownStatus>() {
@Override
public ShutdownStatus call(Throwable throwable) {
return new ShutdownStatus(target, false, throwable);
}
})
.doOnNext(new Action1<ShutdownStatus>() {
@Override
public void call(ShutdownStatus shutdownStatus) {
LOGGER.info(shutdownStatus.toString());
}
});
} | [
"private",
"Observable",
"<",
"ShutdownStatus",
">",
"wrapShutdown",
"(",
"Observable",
"<",
"Boolean",
">",
"source",
",",
"final",
"String",
"target",
")",
"{",
"return",
"source",
".",
"reduce",
"(",
"true",
",",
"new",
"Func2",
"<",
"Boolean",
",",
"Bo... | This method wraps an Observable of Boolean (for shutdown hook) into an Observable of ShutdownStatus.
It will log each status with a short message indicating which target has been shut down, and the result of
the call. | [
"This",
"method",
"wraps",
"an",
"Observable",
"of",
"Boolean",
"(",
"for",
"shutdown",
"hook",
")",
"into",
"an",
"Observable",
"of",
"ShutdownStatus",
".",
"It",
"will",
"log",
"each",
"status",
"with",
"a",
"short",
"message",
"indicating",
"which",
"targ... | train | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/env/DefaultCoreEnvironment.java#L719-L745 |
dmerkushov/log-helper | src/main/java/ru/dmerkushov/loghelper/configure/loggerwrapper/LoggerWrapperConfigurator.java | LoggerWrapperConfigurator.getConfigurationOptionValue | public String getConfigurationOptionValue (String optionName, String defaultValue) {
String optionValue;
Node configurationOption = this.getConfigurationOption (optionName);
if (configurationOption != null) {
optionValue = configurationOption.getTextContent ();
} else {
optionValue = defaultValue;
}
return optionValue;
} | java | public String getConfigurationOptionValue (String optionName, String defaultValue) {
String optionValue;
Node configurationOption = this.getConfigurationOption (optionName);
if (configurationOption != null) {
optionValue = configurationOption.getTextContent ();
} else {
optionValue = defaultValue;
}
return optionValue;
} | [
"public",
"String",
"getConfigurationOptionValue",
"(",
"String",
"optionName",
",",
"String",
"defaultValue",
")",
"{",
"String",
"optionValue",
";",
"Node",
"configurationOption",
"=",
"this",
".",
"getConfigurationOption",
"(",
"optionName",
")",
";",
"if",
"(",
... | Get a configuration option value as String.
@param optionName
@param defaultValue
@return The configuration option node value, or <code>defaultValue</code> if it does not exist | [
"Get",
"a",
"configuration",
"option",
"value",
"as",
"String",
"."
] | train | https://github.com/dmerkushov/log-helper/blob/3b7d3d30faa7f1437b27cd07c10fa579a995de23/src/main/java/ru/dmerkushov/loghelper/configure/loggerwrapper/LoggerWrapperConfigurator.java#L100-L109 |
google/error-prone | check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java | ASTHelpers.containsComments | public static boolean containsComments(Tree tree, VisitorState state) {
return ErrorProneTokens.getTokens(state.getSourceForNode(tree), state.context).stream()
.anyMatch(t -> !t.comments().isEmpty());
} | java | public static boolean containsComments(Tree tree, VisitorState state) {
return ErrorProneTokens.getTokens(state.getSourceForNode(tree), state.context).stream()
.anyMatch(t -> !t.comments().isEmpty());
} | [
"public",
"static",
"boolean",
"containsComments",
"(",
"Tree",
"tree",
",",
"VisitorState",
"state",
")",
"{",
"return",
"ErrorProneTokens",
".",
"getTokens",
"(",
"state",
".",
"getSourceForNode",
"(",
"tree",
")",
",",
"state",
".",
"context",
")",
".",
"... | Returns whether the given {@code tree} contains any comments in its source. | [
"Returns",
"whether",
"the",
"given",
"{"
] | train | https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java#L1646-L1649 |
kuali/ojb-1.0.4 | src/java/org/apache/ojb/broker/metadata/DescriptorRepository.java | DescriptorRepository.addExtent | void addExtent(String classname, ClassDescriptor cld)
{
synchronized (extentTable)
{
extentTable.put(classname, cld);
}
} | java | void addExtent(String classname, ClassDescriptor cld)
{
synchronized (extentTable)
{
extentTable.put(classname, cld);
}
} | [
"void",
"addExtent",
"(",
"String",
"classname",
",",
"ClassDescriptor",
"cld",
")",
"{",
"synchronized",
"(",
"extentTable",
")",
"{",
"extentTable",
".",
"put",
"(",
"classname",
",",
"cld",
")",
";",
"}",
"}"
] | Add a pair of extent/classdescriptor to the extentTable to gain speed
while retrieval of extents.
@param classname the name of the extent itself
@param cld the class descriptor, where it belongs to | [
"Add",
"a",
"pair",
"of",
"extent",
"/",
"classdescriptor",
"to",
"the",
"extentTable",
"to",
"gain",
"speed",
"while",
"retrieval",
"of",
"extents",
"."
] | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/metadata/DescriptorRepository.java#L98-L104 |
raydac/java-binary-block-parser | jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPTextWriter.java | JBBPTextWriter.Byte | public JBBPTextWriter Byte(final byte[] array, int off, int len) throws IOException {
ensureValueMode();
while (len-- > 0) {
Byte(array[off++]);
}
return this;
} | java | public JBBPTextWriter Byte(final byte[] array, int off, int len) throws IOException {
ensureValueMode();
while (len-- > 0) {
Byte(array[off++]);
}
return this;
} | [
"public",
"JBBPTextWriter",
"Byte",
"(",
"final",
"byte",
"[",
"]",
"array",
",",
"int",
"off",
",",
"int",
"len",
")",
"throws",
"IOException",
"{",
"ensureValueMode",
"(",
")",
";",
"while",
"(",
"len",
"--",
">",
"0",
")",
"{",
"Byte",
"(",
"array... | Print values from byte array.
@param array source byte array, must not be null
@param off the offset of the first element in array
@param len number of bytes to be printed
@return the context
@throws IOException it will be thrown for transport errors | [
"Print",
"values",
"from",
"byte",
"array",
"."
] | train | https://github.com/raydac/java-binary-block-parser/blob/6d98abcab01e0c72d525ebcc9e7b694f9ce49f5b/jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPTextWriter.java#L624-L631 |
eurekaclinical/protempa | protempa-ksb-protege/src/main/java/org/protempa/backend/ksb/protege/ConnectionManager.java | ConnectionManager.getFromProtege | private <S, T> S getFromProtege(T obj, ProtegeCommand<S, T> getter)
throws KnowledgeSourceReadException {
if (protegeKnowledgeBase != null && getter != null) {
int tries = TRIES;
Exception lastException = null;
do {
try {
return getter.getHelper(obj);
} catch (Exception e) {
lastException = e;
Util.logger().log(
Level.WARNING,
"Exception attempting to "
+ getter.getWhat() + " " + obj, e);
tries--;
}
close();
try {
init();
} catch (KnowledgeSourceBackendInitializationException e) {
throw new KnowledgeSourceReadException(
"Exception attempting to "
+ getter.getWhat() + " " + obj, e);
}
} while (tries > 0);
throw new KnowledgeSourceReadException(
"Failed to " + getter.getWhat() + " "
+ obj + " after "
+ TRIES + " tries", lastException);
}
return null;
} | java | private <S, T> S getFromProtege(T obj, ProtegeCommand<S, T> getter)
throws KnowledgeSourceReadException {
if (protegeKnowledgeBase != null && getter != null) {
int tries = TRIES;
Exception lastException = null;
do {
try {
return getter.getHelper(obj);
} catch (Exception e) {
lastException = e;
Util.logger().log(
Level.WARNING,
"Exception attempting to "
+ getter.getWhat() + " " + obj, e);
tries--;
}
close();
try {
init();
} catch (KnowledgeSourceBackendInitializationException e) {
throw new KnowledgeSourceReadException(
"Exception attempting to "
+ getter.getWhat() + " " + obj, e);
}
} while (tries > 0);
throw new KnowledgeSourceReadException(
"Failed to " + getter.getWhat() + " "
+ obj + " after "
+ TRIES + " tries", lastException);
}
return null;
} | [
"private",
"<",
"S",
",",
"T",
">",
"S",
"getFromProtege",
"(",
"T",
"obj",
",",
"ProtegeCommand",
"<",
"S",
",",
"T",
">",
"getter",
")",
"throws",
"KnowledgeSourceReadException",
"{",
"if",
"(",
"protegeKnowledgeBase",
"!=",
"null",
"&&",
"getter",
"!=",... | Executes a command upon the Protege knowledge base, retrying if needed.
@param <S> The type of what is returned by the getter.
@param <T> The type of what is passed to protege as a parameter.
@param obj What is passed to Protege as a parameter.
@param getter the <code>ProtegeCommand</code>.
@return what is returned from the Protege command. | [
"Executes",
"a",
"command",
"upon",
"the",
"Protege",
"knowledge",
"base",
"retrying",
"if",
"needed",
"."
] | train | https://github.com/eurekaclinical/protempa/blob/5a620d1a407c7a5426d1cf17d47b97717cf71634/protempa-ksb-protege/src/main/java/org/protempa/backend/ksb/protege/ConnectionManager.java#L233-L264 |
katharsis-project/katharsis-framework | katharsis-core/src/main/java/io/katharsis/legacy/queryParams/QueryParamsBuilder.java | QueryParamsBuilder.buildQueryParams | public QueryParams buildQueryParams(Map<String, Set<String>> queryParams) {
return buildQueryParams(new SimpleQueryParamsParserContext(queryParams));
} | java | public QueryParams buildQueryParams(Map<String, Set<String>> queryParams) {
return buildQueryParams(new SimpleQueryParamsParserContext(queryParams));
} | [
"public",
"QueryParams",
"buildQueryParams",
"(",
"Map",
"<",
"String",
",",
"Set",
"<",
"String",
">",
">",
"queryParams",
")",
"{",
"return",
"buildQueryParams",
"(",
"new",
"SimpleQueryParamsParserContext",
"(",
"queryParams",
")",
")",
";",
"}"
] | Decodes passed query parameters using the given raw map. Mainly intended to be used for testing purposes.
For most cases, use {@link #buildQueryParams(QueryParamsParserContext context) instead.}
@param queryParams Map of provided query params
@return QueryParams containing filtered query params grouped by JSON:API standard
@throws ParametersDeserializationException thrown when unsupported input format is detected | [
"Decodes",
"passed",
"query",
"parameters",
"using",
"the",
"given",
"raw",
"map",
".",
"Mainly",
"intended",
"to",
"be",
"used",
"for",
"testing",
"purposes",
".",
"For",
"most",
"cases",
"use",
"{",
"@link",
"#buildQueryParams",
"(",
"QueryParamsParserContext"... | train | https://github.com/katharsis-project/katharsis-framework/blob/73d1a8763c49c5cf4643d43e2dbfedb647630c46/katharsis-core/src/main/java/io/katharsis/legacy/queryParams/QueryParamsBuilder.java#L44-L46 |
Azure/azure-sdk-for-java | keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java | KeyVaultClientBaseImpl.purgeDeletedStorageAccountAsync | public Observable<Void> purgeDeletedStorageAccountAsync(String vaultBaseUrl, String storageAccountName) {
return purgeDeletedStorageAccountWithServiceResponseAsync(vaultBaseUrl, storageAccountName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | java | public Observable<Void> purgeDeletedStorageAccountAsync(String vaultBaseUrl, String storageAccountName) {
return purgeDeletedStorageAccountWithServiceResponseAsync(vaultBaseUrl, storageAccountName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Void",
">",
"purgeDeletedStorageAccountAsync",
"(",
"String",
"vaultBaseUrl",
",",
"String",
"storageAccountName",
")",
"{",
"return",
"purgeDeletedStorageAccountWithServiceResponseAsync",
"(",
"vaultBaseUrl",
",",
"storageAccountName",
")",
".... | Permanently deletes the specified storage account.
The purge deleted storage account operation removes the secret permanently, without the possibility of recovery. This operation can only be performed on a soft-delete enabled vault. This operation requires the storage/purge permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param storageAccountName The name of the storage account.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceResponse} object if successful. | [
"Permanently",
"deletes",
"the",
"specified",
"storage",
"account",
".",
"The",
"purge",
"deleted",
"storage",
"account",
"operation",
"removes",
"the",
"secret",
"permanently",
"without",
"the",
"possibility",
"of",
"recovery",
".",
"This",
"operation",
"can",
"o... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L9371-L9378 |
alkacon/opencms-core | src/org/opencms/loader/CmsDefaultFileNameGenerator.java | CmsDefaultFileNameGenerator.getNewFileName | public String getNewFileName(CmsObject cms, String namePattern, int defaultDigits, boolean explorerMode)
throws CmsException {
String checkPattern = cms.getRequestContext().removeSiteRoot(namePattern);
String folderName = CmsResource.getFolderPath(checkPattern);
// must check ALL resources in folder because name doesn't care for type
List<CmsResource> resources = cms.readResources(folderName, CmsResourceFilter.ALL, false);
// now create a list of all the file names
List<String> fileNames = new ArrayList<String>(resources.size());
for (CmsResource res : resources) {
fileNames.add(cms.getSitePath(res));
}
return getNewFileNameFromList(fileNames, checkPattern, defaultDigits, explorerMode);
} | java | public String getNewFileName(CmsObject cms, String namePattern, int defaultDigits, boolean explorerMode)
throws CmsException {
String checkPattern = cms.getRequestContext().removeSiteRoot(namePattern);
String folderName = CmsResource.getFolderPath(checkPattern);
// must check ALL resources in folder because name doesn't care for type
List<CmsResource> resources = cms.readResources(folderName, CmsResourceFilter.ALL, false);
// now create a list of all the file names
List<String> fileNames = new ArrayList<String>(resources.size());
for (CmsResource res : resources) {
fileNames.add(cms.getSitePath(res));
}
return getNewFileNameFromList(fileNames, checkPattern, defaultDigits, explorerMode);
} | [
"public",
"String",
"getNewFileName",
"(",
"CmsObject",
"cms",
",",
"String",
"namePattern",
",",
"int",
"defaultDigits",
",",
"boolean",
"explorerMode",
")",
"throws",
"CmsException",
"{",
"String",
"checkPattern",
"=",
"cms",
".",
"getRequestContext",
"(",
")",
... | Returns a new resource name based on the provided OpenCms user context and name pattern.<p>
The pattern in this default implementation must be a path which may contain the macro <code>%(number)</code>.
This will be replaced by the first "n" digit sequence for which the resulting file name is not already
used. For example the pattern <code>"/file_%(number).xml"</code> would result in something like <code>"/file_00003.xml"</code>.<p>
Alternatively, the macro can have the form <code>%(number:n)</code> with <code>n = {1...9}</code>, for example <code>%(number:6)</code>.
In this case the default digits will be ignored and instead the digits provided as "n" will be used.<p>
@param cms the current OpenCms user context
@param namePattern the pattern to be used when generating the new resource name
@param defaultDigits the default number of digits to use for numbering the created file names
@param explorerMode if true, the file name is first tried without a numeric macro, also underscores are inserted automatically before the number macro and don't need to be part of the name pattern
@return a new resource name based on the provided OpenCms user context and name pattern
@throws CmsException in case something goes wrong | [
"Returns",
"a",
"new",
"resource",
"name",
"based",
"on",
"the",
"provided",
"OpenCms",
"user",
"context",
"and",
"name",
"pattern",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/loader/CmsDefaultFileNameGenerator.java#L210-L226 |
lessthanoptimal/ejml | main/ejml-zdense/src/org/ejml/dense/row/CommonOps_ZDRM.java | CommonOps_ZDRM.multAddTransB | public static void multAddTransB(double realAlpha , double imagAlpha , ZMatrixRMaj a , ZMatrixRMaj b , ZMatrixRMaj c )
{
// TODO add a matrix vectory multiply here
MatrixMatrixMult_ZDRM.multAddTransB(realAlpha,imagAlpha,a,b,c);
} | java | public static void multAddTransB(double realAlpha , double imagAlpha , ZMatrixRMaj a , ZMatrixRMaj b , ZMatrixRMaj c )
{
// TODO add a matrix vectory multiply here
MatrixMatrixMult_ZDRM.multAddTransB(realAlpha,imagAlpha,a,b,c);
} | [
"public",
"static",
"void",
"multAddTransB",
"(",
"double",
"realAlpha",
",",
"double",
"imagAlpha",
",",
"ZMatrixRMaj",
"a",
",",
"ZMatrixRMaj",
"b",
",",
"ZMatrixRMaj",
"c",
")",
"{",
"// TODO add a matrix vectory multiply here",
"MatrixMatrixMult_ZDRM",
".",
"multA... | <p>
Performs the following operation:<br>
<br>
c = c + α * a * b<sup>H</sup><br>
c<sub>ij</sub> = c<sub>ij</sub> + α * ∑<sub>k=1:n</sub> { a<sub>ik</sub> * b<sub>jk</sub>}
</p>
@param realAlpha Real component of scaling factor.
@param imagAlpha Imaginary component of scaling factor.
@param a The left matrix in the multiplication operation. Not modified.
@param b The right matrix in the multiplication operation. Not modified.
@param c Where the results of the operation are stored. Modified. | [
"<p",
">",
"Performs",
"the",
"following",
"operation",
":",
"<br",
">",
"<br",
">",
"c",
"=",
"c",
"+",
"&alpha",
";",
"*",
"a",
"*",
"b<sup",
">",
"H<",
"/",
"sup",
">",
"<br",
">",
"c<sub",
">",
"ij<",
"/",
"sub",
">",
"=",
"c<sub",
">",
"... | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-zdense/src/org/ejml/dense/row/CommonOps_ZDRM.java#L650-L654 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/HashMap.java | HashMap.putMapEntries | final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
int s = m.size();
if (s > 0) {
if (table == null) { // pre-size
float ft = ((float)s / loadFactor) + 1.0F;
int t = ((ft < (float)MAXIMUM_CAPACITY) ?
(int)ft : MAXIMUM_CAPACITY);
if (t > threshold)
threshold = tableSizeFor(t);
}
else if (s > threshold)
resize();
for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
K key = e.getKey();
V value = e.getValue();
putVal(hash(key), key, value, false, evict);
}
}
} | java | final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
int s = m.size();
if (s > 0) {
if (table == null) { // pre-size
float ft = ((float)s / loadFactor) + 1.0F;
int t = ((ft < (float)MAXIMUM_CAPACITY) ?
(int)ft : MAXIMUM_CAPACITY);
if (t > threshold)
threshold = tableSizeFor(t);
}
else if (s > threshold)
resize();
for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
K key = e.getKey();
V value = e.getValue();
putVal(hash(key), key, value, false, evict);
}
}
} | [
"final",
"void",
"putMapEntries",
"(",
"Map",
"<",
"?",
"extends",
"K",
",",
"?",
"extends",
"V",
">",
"m",
",",
"boolean",
"evict",
")",
"{",
"int",
"s",
"=",
"m",
".",
"size",
"(",
")",
";",
"if",
"(",
"s",
">",
"0",
")",
"{",
"if",
"(",
... | Implements Map.putAll and Map constructor
@param m the map
@param evict false when initially constructing this map, else
true (relayed to method afterNodeInsertion). | [
"Implements",
"Map",
".",
"putAll",
"and",
"Map",
"constructor"
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/HashMap.java#L505-L523 |
xcesco/kripton | kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/BindM2MBuilder.java | BindM2MBuilder.generateDaoPart | private void generateDaoPart(M2MEntity entity) {
String daoClassName = entity.daoName.simpleName();
String daoPackageName = entity.daoName.packageName();
String entityPackageName = entity.getPackageName();
String generatedDaoClassName = "Generated" + daoClassName;
AnnotationProcessorUtilis.infoOnGeneratedClasses(BindDaoMany2Many.class, daoPackageName, generatedDaoClassName);
// @formatter:off
classBuilder = TypeSpec.interfaceBuilder(generatedDaoClassName).addModifiers(Modifier.PUBLIC)
.addAnnotation(AnnotationSpec.builder(BindDao.class)
.addMember("value", "$T.class", TypeUtility.className(entityPackageName, entity.name)).build())
.addAnnotation(AnnotationSpec.builder(BindGeneratedDao.class)
.addMember("dao", "$T.class", entity.daoName).build())
.addAnnotation(AnnotationSpec.builder(BindDaoMany2Many.class)
.addMember("entity1", "$T.class", entity.entity1Name)
.addMember("entity2", "$T.class", entity.entity2Name).build())
.addSuperinterface(entity.daoName);
// @formatter:on
JavadocUtility.generateJavadocGeneratedBy(classBuilder);
if (entity.generateMethods) {
generateSelects(entity, entityPackageName);
generateDeletes(entity, entityPackageName);
generateInsert(entity, entityPackageName);
}
TypeSpec typeSpec = classBuilder.build();
try {
JavaWriterHelper.writeJava2File(filer, daoPackageName, typeSpec);
} catch (IOException e) {
throw new KriptonRuntimeException(e);
}
GeneratedTypeElement daoPartElement = new GeneratedTypeElement(daoPackageName, classBuilder.build(), null,
null);
daoResult.add(daoPartElement);
} | java | private void generateDaoPart(M2MEntity entity) {
String daoClassName = entity.daoName.simpleName();
String daoPackageName = entity.daoName.packageName();
String entityPackageName = entity.getPackageName();
String generatedDaoClassName = "Generated" + daoClassName;
AnnotationProcessorUtilis.infoOnGeneratedClasses(BindDaoMany2Many.class, daoPackageName, generatedDaoClassName);
// @formatter:off
classBuilder = TypeSpec.interfaceBuilder(generatedDaoClassName).addModifiers(Modifier.PUBLIC)
.addAnnotation(AnnotationSpec.builder(BindDao.class)
.addMember("value", "$T.class", TypeUtility.className(entityPackageName, entity.name)).build())
.addAnnotation(AnnotationSpec.builder(BindGeneratedDao.class)
.addMember("dao", "$T.class", entity.daoName).build())
.addAnnotation(AnnotationSpec.builder(BindDaoMany2Many.class)
.addMember("entity1", "$T.class", entity.entity1Name)
.addMember("entity2", "$T.class", entity.entity2Name).build())
.addSuperinterface(entity.daoName);
// @formatter:on
JavadocUtility.generateJavadocGeneratedBy(classBuilder);
if (entity.generateMethods) {
generateSelects(entity, entityPackageName);
generateDeletes(entity, entityPackageName);
generateInsert(entity, entityPackageName);
}
TypeSpec typeSpec = classBuilder.build();
try {
JavaWriterHelper.writeJava2File(filer, daoPackageName, typeSpec);
} catch (IOException e) {
throw new KriptonRuntimeException(e);
}
GeneratedTypeElement daoPartElement = new GeneratedTypeElement(daoPackageName, classBuilder.build(), null,
null);
daoResult.add(daoPartElement);
} | [
"private",
"void",
"generateDaoPart",
"(",
"M2MEntity",
"entity",
")",
"{",
"String",
"daoClassName",
"=",
"entity",
".",
"daoName",
".",
"simpleName",
"(",
")",
";",
"String",
"daoPackageName",
"=",
"entity",
".",
"daoName",
".",
"packageName",
"(",
")",
";... | Generate dao part.
@param entity
the entity
@throws IOException
Signals that an I/O exception has occurred. | [
"Generate",
"dao",
"part",
"."
] | train | https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/BindM2MBuilder.java#L183-L222 |
BigBadaboom/androidsvg | androidsvg/src/main/java/com/caverock/androidsvg/SVG.java | SVG.renderToCanvas | @SuppressWarnings({"WeakerAccess", "unused"})
public void renderToCanvas(Canvas canvas, RenderOptions renderOptions)
{
if (renderOptions == null)
renderOptions = new RenderOptions();
if (!renderOptions.hasViewPort()) {
renderOptions.viewPort(0f, 0f, (float) canvas.getWidth(), (float) canvas.getHeight());
}
SVGAndroidRenderer renderer = new SVGAndroidRenderer(canvas, this.renderDPI);
renderer.renderDocument(this, renderOptions);
} | java | @SuppressWarnings({"WeakerAccess", "unused"})
public void renderToCanvas(Canvas canvas, RenderOptions renderOptions)
{
if (renderOptions == null)
renderOptions = new RenderOptions();
if (!renderOptions.hasViewPort()) {
renderOptions.viewPort(0f, 0f, (float) canvas.getWidth(), (float) canvas.getHeight());
}
SVGAndroidRenderer renderer = new SVGAndroidRenderer(canvas, this.renderDPI);
renderer.renderDocument(this, renderOptions);
} | [
"@",
"SuppressWarnings",
"(",
"{",
"\"WeakerAccess\"",
",",
"\"unused\"",
"}",
")",
"public",
"void",
"renderToCanvas",
"(",
"Canvas",
"canvas",
",",
"RenderOptions",
"renderOptions",
")",
"{",
"if",
"(",
"renderOptions",
"==",
"null",
")",
"renderOptions",
"=",... | Renders this SVG document to a Canvas object.
@param canvas the canvas to which the document should be rendered.
@param renderOptions options that describe how to render this SVG on the Canvas.
@since 1.3 | [
"Renders",
"this",
"SVG",
"document",
"to",
"a",
"Canvas",
"object",
"."
] | train | https://github.com/BigBadaboom/androidsvg/blob/0d1614dd1a4da10ea4afe3b0cea1361a4ac6b45a/androidsvg/src/main/java/com/caverock/androidsvg/SVG.java#L528-L541 |
Axway/Grapes | server/src/main/java/org/axway/grapes/server/core/DependencyHandler.java | DependencyHandler.getDependencyReport | public DependencyReport getDependencyReport(final String moduleId, final FiltersHolder filters) {
final DbModule module = moduleHandler.getModule(moduleId);
final DbOrganization organization = moduleHandler.getOrganization(module);
filters.setCorporateFilter(new CorporateFilter(organization));
final DependencyReport report = new DependencyReport(moduleId);
final List<String> done = new ArrayList<String>();
for(final DbModule submodule: DataUtils.getAllSubmodules(module)){
done.add(submodule.getId());
}
addModuleToReport(report, module, filters, done, 1);
return report;
} | java | public DependencyReport getDependencyReport(final String moduleId, final FiltersHolder filters) {
final DbModule module = moduleHandler.getModule(moduleId);
final DbOrganization organization = moduleHandler.getOrganization(module);
filters.setCorporateFilter(new CorporateFilter(organization));
final DependencyReport report = new DependencyReport(moduleId);
final List<String> done = new ArrayList<String>();
for(final DbModule submodule: DataUtils.getAllSubmodules(module)){
done.add(submodule.getId());
}
addModuleToReport(report, module, filters, done, 1);
return report;
} | [
"public",
"DependencyReport",
"getDependencyReport",
"(",
"final",
"String",
"moduleId",
",",
"final",
"FiltersHolder",
"filters",
")",
"{",
"final",
"DbModule",
"module",
"=",
"moduleHandler",
".",
"getModule",
"(",
"moduleId",
")",
";",
"final",
"DbOrganization",
... | Generate a report about the targeted module dependencies
@param moduleId String
@param filters FiltersHolder
@return DependencyReport | [
"Generate",
"a",
"report",
"about",
"the",
"targeted",
"module",
"dependencies"
] | train | https://github.com/Axway/Grapes/blob/ce9cc73d85f83eaa5fbc991abb593915a8c8374e/server/src/main/java/org/axway/grapes/server/core/DependencyHandler.java#L92-L106 |
code4everything/util | src/main/java/com/zhazhapan/util/Checker.java | Checker.isIn | public static <T> boolean isIn(T t, T... ts) {
if (isNotNull(t) && isNotNull(ts)) {
for (Object object : ts) {
if (t.equals(object)) {
return true;
}
}
}
return false;
} | java | public static <T> boolean isIn(T t, T... ts) {
if (isNotNull(t) && isNotNull(ts)) {
for (Object object : ts) {
if (t.equals(object)) {
return true;
}
}
}
return false;
} | [
"public",
"static",
"<",
"T",
">",
"boolean",
"isIn",
"(",
"T",
"t",
",",
"T",
"...",
"ts",
")",
"{",
"if",
"(",
"isNotNull",
"(",
"t",
")",
"&&",
"isNotNull",
"(",
"ts",
")",
")",
"{",
"for",
"(",
"Object",
"object",
":",
"ts",
")",
"{",
"if... | 检查对象是否在集合中
@param <T> 类型
@param t 对象
@param ts 集合
@return 是否存在
@since 1.0.8 | [
"检查对象是否在集合中"
] | train | https://github.com/code4everything/util/blob/1fc9f0ead1108f4d7208ba7c000df4244f708418/src/main/java/com/zhazhapan/util/Checker.java#L656-L665 |
lonnyj/liquibase-spatial | src/main/java/liquibase/ext/spatial/preconditions/SpatialIndexExistsPrecondition.java | SpatialIndexExistsPrecondition.getIndexExample | protected Index getIndexExample(final Database database, final Schema schema,
final String tableName) {
final Index example = new Index();
if (tableName != null) {
example.setTable((Table) new Table().setName(
database.correctObjectName(getTableName(), Table.class)).setSchema(schema));
}
example.setName(database.correctObjectName(getIndexName(), Index.class));
if (StringUtils.trimToNull(getColumnNames()) != null) {
for (final String columnName : getColumnNames().split("\\s*,\\s*")) {
final Column column = new Column(database.correctObjectName(columnName, Column.class));
example.getColumns().add(column);
}
}
return example;
} | java | protected Index getIndexExample(final Database database, final Schema schema,
final String tableName) {
final Index example = new Index();
if (tableName != null) {
example.setTable((Table) new Table().setName(
database.correctObjectName(getTableName(), Table.class)).setSchema(schema));
}
example.setName(database.correctObjectName(getIndexName(), Index.class));
if (StringUtils.trimToNull(getColumnNames()) != null) {
for (final String columnName : getColumnNames().split("\\s*,\\s*")) {
final Column column = new Column(database.correctObjectName(columnName, Column.class));
example.getColumns().add(column);
}
}
return example;
} | [
"protected",
"Index",
"getIndexExample",
"(",
"final",
"Database",
"database",
",",
"final",
"Schema",
"schema",
",",
"final",
"String",
"tableName",
")",
"{",
"final",
"Index",
"example",
"=",
"new",
"Index",
"(",
")",
";",
"if",
"(",
"tableName",
"!=",
"... | Generates the {@link Index} example (taken from {@link IndexExistsPrecondition}).
@param database
the database instance.
@param schema
the schema instance.
@param tableName
the table name of the index.
@return the index example. | [
"Generates",
"the",
"{",
"@link",
"Index",
"}",
"example",
"(",
"taken",
"from",
"{",
"@link",
"IndexExistsPrecondition",
"}",
")",
"."
] | train | https://github.com/lonnyj/liquibase-spatial/blob/36ae41b0d3d08bb00a22c856e51ffeed08891c0e/src/main/java/liquibase/ext/spatial/preconditions/SpatialIndexExistsPrecondition.java#L187-L202 |
citrusframework/citrus | modules/citrus-java-dsl/src/main/java/com/consol/citrus/dsl/builder/HttpServerRequestActionBuilder.java | HttpServerRequestActionBuilder.queryParam | public HttpServerRequestActionBuilder queryParam(String name, String value) {
httpMessage.queryParam(name, value);
return this;
} | java | public HttpServerRequestActionBuilder queryParam(String name, String value) {
httpMessage.queryParam(name, value);
return this;
} | [
"public",
"HttpServerRequestActionBuilder",
"queryParam",
"(",
"String",
"name",
",",
"String",
"value",
")",
"{",
"httpMessage",
".",
"queryParam",
"(",
"name",
",",
"value",
")",
";",
"return",
"this",
";",
"}"
] | Adds a query param to the request uri.
@param name
@param value
@return | [
"Adds",
"a",
"query",
"param",
"to",
"the",
"request",
"uri",
"."
] | train | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-java-dsl/src/main/java/com/consol/citrus/dsl/builder/HttpServerRequestActionBuilder.java#L111-L114 |
zaproxy/zaproxy | src/org/zaproxy/zap/extension/api/API.java | API.getLongLivedNonce | public String getLongLivedNonce(String apiUrl) {
String nonce = Long.toHexString(random.nextLong());
this.nonces.put(nonce, new Nonce(nonce, apiUrl, false));
return nonce;
} | java | public String getLongLivedNonce(String apiUrl) {
String nonce = Long.toHexString(random.nextLong());
this.nonces.put(nonce, new Nonce(nonce, apiUrl, false));
return nonce;
} | [
"public",
"String",
"getLongLivedNonce",
"(",
"String",
"apiUrl",
")",
"{",
"String",
"nonce",
"=",
"Long",
".",
"toHexString",
"(",
"random",
".",
"nextLong",
"(",
")",
")",
";",
"this",
".",
"nonces",
".",
"put",
"(",
"nonce",
",",
"new",
"Nonce",
"(... | Returns a nonce that will be valid for the lifetime of the ZAP process to used with the API call specified by the URL
@param apiUrl the API URL
@return a nonce that will be valid for the lifetime of the ZAP process
@since 2.6.0 | [
"Returns",
"a",
"nonce",
"that",
"will",
"be",
"valid",
"for",
"the",
"lifetime",
"of",
"the",
"ZAP",
"process",
"to",
"used",
"with",
"the",
"API",
"call",
"specified",
"by",
"the",
"URL"
] | train | https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/extension/api/API.java#L841-L845 |
roboconf/roboconf-platform | core/roboconf-target-iaas-openstack/src/main/java/net/roboconf/target/openstack/internal/OpenstackIaasHandler.java | OpenstackIaasHandler.swiftApi | static SwiftApi swiftApi( Map<String,String> targetProperties ) throws TargetException {
validate( targetProperties );
return ContextBuilder
.newBuilder( PROVIDER_SWIFT )
.endpoint( targetProperties.get( API_URL ))
.credentials( identity( targetProperties ), targetProperties.get( PASSWORD ))
.buildApi( SwiftApi.class );
} | java | static SwiftApi swiftApi( Map<String,String> targetProperties ) throws TargetException {
validate( targetProperties );
return ContextBuilder
.newBuilder( PROVIDER_SWIFT )
.endpoint( targetProperties.get( API_URL ))
.credentials( identity( targetProperties ), targetProperties.get( PASSWORD ))
.buildApi( SwiftApi.class );
} | [
"static",
"SwiftApi",
"swiftApi",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"targetProperties",
")",
"throws",
"TargetException",
"{",
"validate",
"(",
"targetProperties",
")",
";",
"return",
"ContextBuilder",
".",
"newBuilder",
"(",
"PROVIDER_SWIFT",
")",
... | Creates a JCloud context for Swift.
@param targetProperties the target properties
@return a non-null object
@throws TargetException if the target properties are invalid | [
"Creates",
"a",
"JCloud",
"context",
"for",
"Swift",
"."
] | train | https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-target-iaas-openstack/src/main/java/net/roboconf/target/openstack/internal/OpenstackIaasHandler.java#L374-L382 |
SeaCloudsEU/SeaCloudsPlatform | sla/sla-core/sla-service/src/main/java/eu/atos/sla/service/rest/TemplateRestEntity.java | TemplateRestEntity.getTemplates | @GET
public List<ITemplate> getTemplates(@QueryParam("providerId") String providerId, @QueryParam("serviceIds") String serviceIds) {
logger.debug("StartOf getTemplates - REQUEST for /templates");
TemplateHelperE templateRestHelper = getTemplateHelper();
// we remove the blank spaces just in case somebody is adding them
String serviceIdsSplitted[] = null;
if (serviceIds!=null){
String serviceIdsSplittedTmp[] = serviceIds.split(",");
serviceIdsSplitted = new String[serviceIdsSplittedTmp.length];
String tmp = "";
for (int i=0; i<serviceIdsSplittedTmp.length;i++){
serviceIdsSplitted[i] = serviceIdsSplittedTmp[i].trim();
tmp+= " "+serviceIdsSplitted[i];
}
logger.debug("getTemplates will search for service ids:"+tmp);
}
List<ITemplate> templates = templateRestHelper.getTemplates(providerId, serviceIdsSplitted);
logger.debug("EndOf getTemplates");
return templates;
} | java | @GET
public List<ITemplate> getTemplates(@QueryParam("providerId") String providerId, @QueryParam("serviceIds") String serviceIds) {
logger.debug("StartOf getTemplates - REQUEST for /templates");
TemplateHelperE templateRestHelper = getTemplateHelper();
// we remove the blank spaces just in case somebody is adding them
String serviceIdsSplitted[] = null;
if (serviceIds!=null){
String serviceIdsSplittedTmp[] = serviceIds.split(",");
serviceIdsSplitted = new String[serviceIdsSplittedTmp.length];
String tmp = "";
for (int i=0; i<serviceIdsSplittedTmp.length;i++){
serviceIdsSplitted[i] = serviceIdsSplittedTmp[i].trim();
tmp+= " "+serviceIdsSplitted[i];
}
logger.debug("getTemplates will search for service ids:"+tmp);
}
List<ITemplate> templates = templateRestHelper.getTemplates(providerId, serviceIdsSplitted);
logger.debug("EndOf getTemplates");
return templates;
} | [
"@",
"GET",
"public",
"List",
"<",
"ITemplate",
">",
"getTemplates",
"(",
"@",
"QueryParam",
"(",
"\"providerId\"",
")",
"String",
"providerId",
",",
"@",
"QueryParam",
"(",
"\"serviceIds\"",
")",
"String",
"serviceIds",
")",
"{",
"logger",
".",
"debug",
"("... | Gets a the list of available templates from where we can get metrics,
host information, etc.
<pre>
GET /templates
Request:
GET /templates{?serviceId} HTTP/1.1
Response:
HTTP/1.1 200 Ok
{@code
<?xml version="1.0" encoding="UTF-8"?>
<collection href="/templates">
<items offset="0" total="1">
<wsag:Template>...</wsag:Template>
...
</items>
</collection>
}
</pre>
Example: <li>curl http://localhost:8080/sla-service/templates</li>
<li>curl http://localhost:8080/sla-service/templates?serviceIds=service02</li>
<li>curl http://localhost:8080/sla-service/templates?serviceIds=service02,service03</li>
@return XML information with the different details and urls of the
templates | [
"Gets",
"a",
"the",
"list",
"of",
"available",
"templates",
"from",
"where",
"we",
"can",
"get",
"metrics",
"host",
"information",
"etc",
"."
] | train | https://github.com/SeaCloudsEU/SeaCloudsPlatform/blob/b199fe6de2c63b808cb248d3aca947d802375df8/sla/sla-core/sla-service/src/main/java/eu/atos/sla/service/rest/TemplateRestEntity.java#L155-L174 |
drinkjava2/jBeanBox | jbeanbox/src/main/java/com/github/drinkjava2/asm5_0_3/tree/analysis/Frame.java | Frame.setLocal | public void setLocal(final int i, final V value)
throws IndexOutOfBoundsException {
if (i >= locals) {
throw new IndexOutOfBoundsException(
"Trying to access an inexistant local variable " + i);
}
values[i] = value;
} | java | public void setLocal(final int i, final V value)
throws IndexOutOfBoundsException {
if (i >= locals) {
throw new IndexOutOfBoundsException(
"Trying to access an inexistant local variable " + i);
}
values[i] = value;
} | [
"public",
"void",
"setLocal",
"(",
"final",
"int",
"i",
",",
"final",
"V",
"value",
")",
"throws",
"IndexOutOfBoundsException",
"{",
"if",
"(",
"i",
">=",
"locals",
")",
"{",
"throw",
"new",
"IndexOutOfBoundsException",
"(",
"\"Trying to access an inexistant local... | Sets the value of the given local variable.
@param i
a local variable index.
@param value
the new value of this local variable.
@throws IndexOutOfBoundsException
if the variable does not exist. | [
"Sets",
"the",
"value",
"of",
"the",
"given",
"local",
"variable",
"."
] | train | https://github.com/drinkjava2/jBeanBox/blob/01c216599ffa2e5f2d9c01df2adaad0f45567c04/jbeanbox/src/main/java/com/github/drinkjava2/asm5_0_3/tree/analysis/Frame.java#L173-L180 |
jboss/jboss-jsf-api_spec | src/main/java/javax/faces/application/StateManager.java | StateManager.writeState | public void writeState(FacesContext context, Object state)
throws IOException {
if (null != state && state.getClass().isArray() &&
state.getClass().getComponentType().equals(Object.class)) {
Object stateArray[] = (Object[]) state;
if (2 == stateArray.length) {
SerializedView view = new SerializedView(stateArray[0],
stateArray[1]);
writeState(context, view);
}
}
} | java | public void writeState(FacesContext context, Object state)
throws IOException {
if (null != state && state.getClass().isArray() &&
state.getClass().getComponentType().equals(Object.class)) {
Object stateArray[] = (Object[]) state;
if (2 == stateArray.length) {
SerializedView view = new SerializedView(stateArray[0],
stateArray[1]);
writeState(context, view);
}
}
} | [
"public",
"void",
"writeState",
"(",
"FacesContext",
"context",
",",
"Object",
"state",
")",
"throws",
"IOException",
"{",
"if",
"(",
"null",
"!=",
"state",
"&&",
"state",
".",
"getClass",
"(",
")",
".",
"isArray",
"(",
")",
"&&",
"state",
".",
"getClass... | <p>Save the state represented in the specified state
<code>Object</code> instance, in an implementation dependent
manner.</p>
<p/>
<p>This method will typically simply delegate the actual
writing to the <code>writeState()</code> method of the
{@link ResponseStateManager} instance provided by the
{@link RenderKit} being used to render this view. This
method assumes that the caller has positioned the
{@link ResponseWriter} at the correct position for the
saved state to be written.</p>
<p/>
<p>For backwards compatability with existing
<code>StateManager</code> implementations, the default
implementation of this method checks if the argument is an
instance of <code>Object []</code> of length greater than or
equal to two. If so, it creates a <code>SerializedView</code>
instance with the tree structure coming from element zero and
the component state coming from element one and calls through to
{@link
#writeState(javax.faces.context.FacesContext,javax.faces.application.StateManager.SerializedView)}.
If not, does nothing.</p>
@param context {@link FacesContext} for the current request
@param state the Serializable state to be written,
as returned by {@link #saveSerializedView}
@since 1.2 | [
"<p",
">",
"Save",
"the",
"state",
"represented",
"in",
"the",
"specified",
"state",
"<code",
">",
"Object<",
"/",
"code",
">",
"instance",
"in",
"an",
"implementation",
"dependent",
"manner",
".",
"<",
"/",
"p",
">",
"<p",
"/",
">",
"<p",
">",
"This",... | train | https://github.com/jboss/jboss-jsf-api_spec/blob/cb33d215acbab847f2db5cdf2c6fe4d99c0a01c3/src/main/java/javax/faces/application/StateManager.java#L377-L388 |
prometheus/client_java | simpleclient_caffeine/src/main/java/io/prometheus/client/cache/caffeine/CacheMetricsCollector.java | CacheMetricsCollector.addCache | public void addCache(String cacheName, AsyncLoadingCache cache) {
children.put(cacheName, cache.synchronous());
} | java | public void addCache(String cacheName, AsyncLoadingCache cache) {
children.put(cacheName, cache.synchronous());
} | [
"public",
"void",
"addCache",
"(",
"String",
"cacheName",
",",
"AsyncLoadingCache",
"cache",
")",
"{",
"children",
".",
"put",
"(",
"cacheName",
",",
"cache",
".",
"synchronous",
"(",
")",
")",
";",
"}"
] | Add or replace the cache with the given name.
<p>
Any references any previous cache with this name is invalidated.
@param cacheName The name of the cache, will be the metrics label value
@param cache The cache being monitored | [
"Add",
"or",
"replace",
"the",
"cache",
"with",
"the",
"given",
"name",
".",
"<p",
">",
"Any",
"references",
"any",
"previous",
"cache",
"with",
"this",
"name",
"is",
"invalidated",
"."
] | train | https://github.com/prometheus/client_java/blob/4e0e7527b048f1ffd0382dcb74c0b9dab23b4d9f/simpleclient_caffeine/src/main/java/io/prometheus/client/cache/caffeine/CacheMetricsCollector.java#L75-L77 |
frostwire/frostwire-jlibtorrent | src/main/java/com/frostwire/jlibtorrent/SessionHandle.java | SessionHandle.dhtGetItem | public void dhtGetItem(byte[] key, byte[] salt) {
s.dht_get_item(Vectors.bytes2byte_vector(key), Vectors.bytes2byte_vector(salt));
} | java | public void dhtGetItem(byte[] key, byte[] salt) {
s.dht_get_item(Vectors.bytes2byte_vector(key), Vectors.bytes2byte_vector(salt));
} | [
"public",
"void",
"dhtGetItem",
"(",
"byte",
"[",
"]",
"key",
",",
"byte",
"[",
"]",
"salt",
")",
"{",
"s",
".",
"dht_get_item",
"(",
"Vectors",
".",
"bytes2byte_vector",
"(",
"key",
")",
",",
"Vectors",
".",
"bytes2byte_vector",
"(",
"salt",
")",
")",... | Query the DHT for a mutable item under the public key {@code key}.
this is an ed25519 key. The {@code salt} argument is optional and may be left
as an empty string if no salt is to be used.
<p>
if the item is found in the DHT, a {@link DhtMutableItemAlert} is
posted.
@param key
@param salt | [
"Query",
"the",
"DHT",
"for",
"a",
"mutable",
"item",
"under",
"the",
"public",
"key",
"{",
"@code",
"key",
"}",
".",
"this",
"is",
"an",
"ed25519",
"key",
".",
"The",
"{",
"@code",
"salt",
"}",
"argument",
"is",
"optional",
"and",
"may",
"be",
"left... | train | https://github.com/frostwire/frostwire-jlibtorrent/blob/a29249a940d34aba8c4677d238b472ef01833506/src/main/java/com/frostwire/jlibtorrent/SessionHandle.java#L481-L483 |
looly/hutool | hutool-db/src/main/java/cn/hutool/db/AbstractDb.java | AbstractDb.pageForEntityList | public List<Entity> pageForEntityList(Entity where, int page, int numPerPage) throws SQLException {
return pageForEntityList(where, new Page(page, numPerPage));
} | java | public List<Entity> pageForEntityList(Entity where, int page, int numPerPage) throws SQLException {
return pageForEntityList(where, new Page(page, numPerPage));
} | [
"public",
"List",
"<",
"Entity",
">",
"pageForEntityList",
"(",
"Entity",
"where",
",",
"int",
"page",
",",
"int",
"numPerPage",
")",
"throws",
"SQLException",
"{",
"return",
"pageForEntityList",
"(",
"where",
",",
"new",
"Page",
"(",
"page",
",",
"numPerPag... | 分页查询,结果为Entity列表,不计算总数<br>
查询条件为多个key value对表示,默认key = value,如果使用其它条件可以使用:where.put("key", " > 1"),value也可以传Condition对象,key被忽略
@param where 条件实体类(包含表名)
@param page 页码
@param numPerPage 每页条目数
@return 结果对象
@throws SQLException SQL执行异常
@since 3.2.2 | [
"分页查询,结果为Entity列表,不计算总数<br",
">",
"查询条件为多个key",
"value对表示,默认key",
"=",
"value,如果使用其它条件可以使用:where",
".",
"put",
"(",
"key",
">",
";",
"1",
")",
",value也可以传Condition对象,key被忽略"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-db/src/main/java/cn/hutool/db/AbstractDb.java#L659-L661 |
elki-project/elki | elki-outlier/src/main/java/de/lmu/ifi/dbs/elki/algorithm/outlier/lof/FlexibleLOF.java | FlexibleLOF.computeLOFs | protected void computeLOFs(KNNQuery<O> knnq, DBIDs ids, DoubleDataStore lrds, WritableDoubleDataStore lofs, DoubleMinMax lofminmax) {
FiniteProgress progressLOFs = LOG.isVerbose() ? new FiniteProgress("LOF_SCORE for objects", ids.size(), LOG) : null;
for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) {
final double lof;
final double lrdp = lrds.doubleValue(iter);
final KNNList neighbors = knnq.getKNNForDBID(iter, krefer);
if(!Double.isInfinite(lrdp)) {
double sum = 0.;
int count = 0;
for(DBIDIter neighbor = neighbors.iter(); neighbor.valid(); neighbor.advance()) {
// skip the point itself
if(DBIDUtil.equal(neighbor, iter)) {
continue;
}
final double val = lrds.doubleValue(neighbor);
sum += val;
count++;
if(Double.isInfinite(val)) {
break;
}
}
lof = sum / (lrdp * count);
}
else {
lof = 1.0;
}
lofs.putDouble(iter, lof);
// update minimum and maximum
lofminmax.put(lof);
LOG.incrementProcessed(progressLOFs);
}
LOG.ensureCompleted(progressLOFs);
} | java | protected void computeLOFs(KNNQuery<O> knnq, DBIDs ids, DoubleDataStore lrds, WritableDoubleDataStore lofs, DoubleMinMax lofminmax) {
FiniteProgress progressLOFs = LOG.isVerbose() ? new FiniteProgress("LOF_SCORE for objects", ids.size(), LOG) : null;
for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) {
final double lof;
final double lrdp = lrds.doubleValue(iter);
final KNNList neighbors = knnq.getKNNForDBID(iter, krefer);
if(!Double.isInfinite(lrdp)) {
double sum = 0.;
int count = 0;
for(DBIDIter neighbor = neighbors.iter(); neighbor.valid(); neighbor.advance()) {
// skip the point itself
if(DBIDUtil.equal(neighbor, iter)) {
continue;
}
final double val = lrds.doubleValue(neighbor);
sum += val;
count++;
if(Double.isInfinite(val)) {
break;
}
}
lof = sum / (lrdp * count);
}
else {
lof = 1.0;
}
lofs.putDouble(iter, lof);
// update minimum and maximum
lofminmax.put(lof);
LOG.incrementProcessed(progressLOFs);
}
LOG.ensureCompleted(progressLOFs);
} | [
"protected",
"void",
"computeLOFs",
"(",
"KNNQuery",
"<",
"O",
">",
"knnq",
",",
"DBIDs",
"ids",
",",
"DoubleDataStore",
"lrds",
",",
"WritableDoubleDataStore",
"lofs",
",",
"DoubleMinMax",
"lofminmax",
")",
"{",
"FiniteProgress",
"progressLOFs",
"=",
"LOG",
"."... | Computes the Local outlier factor (LOF) of the specified objects.
@param knnq the precomputed neighborhood of the objects w.r.t. the
reference distance
@param ids IDs to process
@param lrds Local reachability distances
@param lofs Local outlier factor storage
@param lofminmax Score minimum/maximum tracker | [
"Computes",
"the",
"Local",
"outlier",
"factor",
"(",
"LOF",
")",
"of",
"the",
"specified",
"objects",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-outlier/src/main/java/de/lmu/ifi/dbs/elki/algorithm/outlier/lof/FlexibleLOF.java#L282-L315 |
pgjdbc/pgjdbc | pgjdbc/src/main/java/org/postgresql/jdbc/EscapedFunctions2.java | EscapedFunctions2.sqlchar | public static void sqlchar(StringBuilder buf, List<? extends CharSequence> parsedArgs) throws SQLException {
singleArgumentFunctionCall(buf, "chr(", "char", parsedArgs);
} | java | public static void sqlchar(StringBuilder buf, List<? extends CharSequence> parsedArgs) throws SQLException {
singleArgumentFunctionCall(buf, "chr(", "char", parsedArgs);
} | [
"public",
"static",
"void",
"sqlchar",
"(",
"StringBuilder",
"buf",
",",
"List",
"<",
"?",
"extends",
"CharSequence",
">",
"parsedArgs",
")",
"throws",
"SQLException",
"{",
"singleArgumentFunctionCall",
"(",
"buf",
",",
"\"chr(\"",
",",
"\"char\"",
",",
"parsedA... | char to chr translation
@param buf The buffer to append into
@param parsedArgs arguments
@throws SQLException if something wrong happens | [
"char",
"to",
"chr",
"translation"
] | train | https://github.com/pgjdbc/pgjdbc/blob/95ba7b261e39754674c5817695ae5ebf9a341fae/pgjdbc/src/main/java/org/postgresql/jdbc/EscapedFunctions2.java#L144-L146 |
actorapp/actor-platform | actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/Messenger.java | Messenger.requestUploadState | @ObjectiveCName("requestUploadStateWithRid:withCallback:")
public void requestUploadState(long rid, UploadFileCallback callback) {
modules.getFilesModule().requestUploadState(rid, callback);
} | java | @ObjectiveCName("requestUploadStateWithRid:withCallback:")
public void requestUploadState(long rid, UploadFileCallback callback) {
modules.getFilesModule().requestUploadState(rid, callback);
} | [
"@",
"ObjectiveCName",
"(",
"\"requestUploadStateWithRid:withCallback:\"",
")",
"public",
"void",
"requestUploadState",
"(",
"long",
"rid",
",",
"UploadFileCallback",
"callback",
")",
"{",
"modules",
".",
"getFilesModule",
"(",
")",
".",
"requestUploadState",
"(",
"ri... | Request upload file state
@param rid file's random id
@param callback file state callback | [
"Request",
"upload",
"file",
"state"
] | train | https://github.com/actorapp/actor-platform/blob/5123c1584757c6eeea0ed2a0e7e043629871a0c6/actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/Messenger.java#L1986-L1989 |
msteiger/jxmapviewer2 | jxmapviewer2/src/main/java/org/jxmapviewer/viewer/wms/WMSService.java | WMSService.toWMSURL | public String toWMSURL(int x, int y, int zoom, int tileSize)
{
String format = "image/jpeg";
String styles = "";
String srs = "EPSG:4326";
int ts = tileSize;
int circumference = widthOfWorldInPixels(zoom, tileSize);
double radius = circumference / (2 * Math.PI);
double ulx = MercatorUtils.xToLong(x * ts, radius);
double uly = MercatorUtils.yToLat(y * ts, radius);
double lrx = MercatorUtils.xToLong((x + 1) * ts, radius);
double lry = MercatorUtils.yToLat((y + 1) * ts, radius);
String bbox = ulx + "," + uly + "," + lrx + "," + lry;
String url = getBaseUrl() + "version=1.1.1&request=" + "GetMap&Layers=" + layer + "&format=" + format
+ "&BBOX=" + bbox + "&width=" + ts + "&height=" + ts + "&SRS=" + srs + "&Styles=" + styles +
// "&transparent=TRUE"+
"";
return url;
} | java | public String toWMSURL(int x, int y, int zoom, int tileSize)
{
String format = "image/jpeg";
String styles = "";
String srs = "EPSG:4326";
int ts = tileSize;
int circumference = widthOfWorldInPixels(zoom, tileSize);
double radius = circumference / (2 * Math.PI);
double ulx = MercatorUtils.xToLong(x * ts, radius);
double uly = MercatorUtils.yToLat(y * ts, radius);
double lrx = MercatorUtils.xToLong((x + 1) * ts, radius);
double lry = MercatorUtils.yToLat((y + 1) * ts, radius);
String bbox = ulx + "," + uly + "," + lrx + "," + lry;
String url = getBaseUrl() + "version=1.1.1&request=" + "GetMap&Layers=" + layer + "&format=" + format
+ "&BBOX=" + bbox + "&width=" + ts + "&height=" + ts + "&SRS=" + srs + "&Styles=" + styles +
// "&transparent=TRUE"+
"";
return url;
} | [
"public",
"String",
"toWMSURL",
"(",
"int",
"x",
",",
"int",
"y",
",",
"int",
"zoom",
",",
"int",
"tileSize",
")",
"{",
"String",
"format",
"=",
"\"image/jpeg\"",
";",
"String",
"styles",
"=",
"\"\"",
";",
"String",
"srs",
"=",
"\"EPSG:4326\"",
";",
"i... | Convertes to a WMS URL
@param x the x coordinate
@param y the y coordinate
@param zoom the zomm factor
@param tileSize the tile size
@return a URL request string | [
"Convertes",
"to",
"a",
"WMS",
"URL"
] | train | https://github.com/msteiger/jxmapviewer2/blob/82639273b0aac983b6026fb90aa925c0cf596410/jxmapviewer2/src/main/java/org/jxmapviewer/viewer/wms/WMSService.java#L53-L71 |
zaproxy/zaproxy | src/org/parosproxy/paros/core/proxy/ProxyThread.java | ProxyThread.notifyPersistentConnectionListener | private boolean notifyPersistentConnectionListener(HttpMessage httpMessage, Socket inSocket, ZapGetMethod method) {
boolean keepSocketOpen = false;
PersistentConnectionListener listener = null;
List<PersistentConnectionListener> listenerList = parentServer.getPersistentConnectionListenerList();
for (int i=0; i<listenerList.size(); i++) {
listener = listenerList.get(i);
try {
if (listener.onHandshakeResponse(httpMessage, inSocket, method)) {
// inform as long as one listener wishes to overtake the connection
keepSocketOpen = true;
break;
}
} catch (Exception e) {
log.error("An error occurred while notifying listener:", e);
}
}
return keepSocketOpen;
} | java | private boolean notifyPersistentConnectionListener(HttpMessage httpMessage, Socket inSocket, ZapGetMethod method) {
boolean keepSocketOpen = false;
PersistentConnectionListener listener = null;
List<PersistentConnectionListener> listenerList = parentServer.getPersistentConnectionListenerList();
for (int i=0; i<listenerList.size(); i++) {
listener = listenerList.get(i);
try {
if (listener.onHandshakeResponse(httpMessage, inSocket, method)) {
// inform as long as one listener wishes to overtake the connection
keepSocketOpen = true;
break;
}
} catch (Exception e) {
log.error("An error occurred while notifying listener:", e);
}
}
return keepSocketOpen;
} | [
"private",
"boolean",
"notifyPersistentConnectionListener",
"(",
"HttpMessage",
"httpMessage",
",",
"Socket",
"inSocket",
",",
"ZapGetMethod",
"method",
")",
"{",
"boolean",
"keepSocketOpen",
"=",
"false",
";",
"PersistentConnectionListener",
"listener",
"=",
"null",
";... | Go thru each listener and offer him to take over the connection. The
first observer that returns true gets exclusive rights.
@param httpMessage Contains HTTP request & response.
@param inSocket Encapsulates the TCP connection to the browser.
@param method Provides more power to process response.
@return Boolean to indicate if socket should be kept open. | [
"Go",
"thru",
"each",
"listener",
"and",
"offer",
"him",
"to",
"take",
"over",
"the",
"connection",
".",
"The",
"first",
"observer",
"that",
"returns",
"true",
"gets",
"exclusive",
"rights",
"."
] | train | https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/parosproxy/paros/core/proxy/ProxyThread.java#L754-L771 |
jcuda/jcudnn | JCudnnJava/src/main/java/jcuda/jcudnn/JCudnn.java | JCudnn.cudnnGetReductionIndicesSize | public static int cudnnGetReductionIndicesSize(
cudnnHandle handle,
cudnnReduceTensorDescriptor reduceTensorDesc,
cudnnTensorDescriptor aDesc,
cudnnTensorDescriptor cDesc,
long[] sizeInBytes)
{
return checkResult(cudnnGetReductionIndicesSizeNative(handle, reduceTensorDesc, aDesc, cDesc, sizeInBytes));
} | java | public static int cudnnGetReductionIndicesSize(
cudnnHandle handle,
cudnnReduceTensorDescriptor reduceTensorDesc,
cudnnTensorDescriptor aDesc,
cudnnTensorDescriptor cDesc,
long[] sizeInBytes)
{
return checkResult(cudnnGetReductionIndicesSizeNative(handle, reduceTensorDesc, aDesc, cDesc, sizeInBytes));
} | [
"public",
"static",
"int",
"cudnnGetReductionIndicesSize",
"(",
"cudnnHandle",
"handle",
",",
"cudnnReduceTensorDescriptor",
"reduceTensorDesc",
",",
"cudnnTensorDescriptor",
"aDesc",
",",
"cudnnTensorDescriptor",
"cDesc",
",",
"long",
"[",
"]",
"sizeInBytes",
")",
"{",
... | Helper function to return the minimum size of the index space to be passed to the reduction given the input and
output tensors | [
"Helper",
"function",
"to",
"return",
"the",
"minimum",
"size",
"of",
"the",
"index",
"space",
"to",
"be",
"passed",
"to",
"the",
"reduction",
"given",
"the",
"input",
"and",
"output",
"tensors"
] | train | https://github.com/jcuda/jcudnn/blob/ce71f2fc02817cecace51a80e6db5f0c7f10cffc/JCudnnJava/src/main/java/jcuda/jcudnn/JCudnn.java#L619-L627 |
chen0040/java-genetic-programming | src/main/java/com/github/chen0040/gp/lgp/gp/Replacement.java | Replacement.compete | public static Program compete(List<Program> programs, Program current, Program candidate, LGP manager, RandEngine randEngine) {
if(manager.getReplacementStrategy() == LGPReplacementStrategy.DirectCompetition) {
if (CollectionUtils.isBetterThan(candidate, current)) {
int index = programs.indexOf(current);
programs.set(index, candidate);
return current;
}
else {
return candidate;
}
} else {
if(randEngine.uniform() <= manager.getReplacementProbability()){
int index = programs.indexOf(current);
programs.set(index, candidate);
return current;
} else {
return candidate;
}
}
} | java | public static Program compete(List<Program> programs, Program current, Program candidate, LGP manager, RandEngine randEngine) {
if(manager.getReplacementStrategy() == LGPReplacementStrategy.DirectCompetition) {
if (CollectionUtils.isBetterThan(candidate, current)) {
int index = programs.indexOf(current);
programs.set(index, candidate);
return current;
}
else {
return candidate;
}
} else {
if(randEngine.uniform() <= manager.getReplacementProbability()){
int index = programs.indexOf(current);
programs.set(index, candidate);
return current;
} else {
return candidate;
}
}
} | [
"public",
"static",
"Program",
"compete",
"(",
"List",
"<",
"Program",
">",
"programs",
",",
"Program",
"current",
",",
"Program",
"candidate",
",",
"LGP",
"manager",
",",
"RandEngine",
"randEngine",
")",
"{",
"if",
"(",
"manager",
".",
"getReplacementStrategy... | this method returns the pointer to the loser in the competition for survival; | [
"this",
"method",
"returns",
"the",
"pointer",
"to",
"the",
"loser",
"in",
"the",
"competition",
"for",
"survival",
";"
] | train | https://github.com/chen0040/java-genetic-programming/blob/498fc8f4407ea9d45f2e0ac797a8948da337c74f/src/main/java/com/github/chen0040/gp/lgp/gp/Replacement.java#L19-L38 |
alibaba/jstorm | jstorm-core/src/main/java/backtype/storm/utils/ShellUtils.java | ShellUtils.execCommand | public static String execCommand(Map<String,String> env, String ... cmd)
throws IOException {
return execCommand(env, cmd, 0L);
} | java | public static String execCommand(Map<String,String> env, String ... cmd)
throws IOException {
return execCommand(env, cmd, 0L);
} | [
"public",
"static",
"String",
"execCommand",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"env",
",",
"String",
"...",
"cmd",
")",
"throws",
"IOException",
"{",
"return",
"execCommand",
"(",
"env",
",",
"cmd",
",",
"0L",
")",
";",
"}"
] | Static method to execute a shell command. Covers most of the simple cases without requiring the user to implement the <code>Shell</code> interface.
@param env the map of environment key=value
@param cmd shell command to execute.
@return the output of the executed command. | [
"Static",
"method",
"to",
"execute",
"a",
"shell",
"command",
".",
"Covers",
"most",
"of",
"the",
"simple",
"cases",
"without",
"requiring",
"the",
"user",
"to",
"implement",
"the",
"<code",
">",
"Shell<",
"/",
"code",
">",
"interface",
"."
] | train | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/utils/ShellUtils.java#L454-L457 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDNN.java | SDNN.layerNorm | public SDVariable layerNorm(SDVariable input, SDVariable gain, SDVariable bias, int... dimensions) {
return layerNorm(null, input, gain, bias, dimensions);
} | java | public SDVariable layerNorm(SDVariable input, SDVariable gain, SDVariable bias, int... dimensions) {
return layerNorm(null, input, gain, bias, dimensions);
} | [
"public",
"SDVariable",
"layerNorm",
"(",
"SDVariable",
"input",
",",
"SDVariable",
"gain",
",",
"SDVariable",
"bias",
",",
"int",
"...",
"dimensions",
")",
"{",
"return",
"layerNorm",
"(",
"null",
",",
"input",
",",
"gain",
",",
"bias",
",",
"dimensions",
... | Apply Layer Normalization
y = gain * standardize(x) + bias
@return Output variable | [
"Apply",
"Layer",
"Normalization"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDNN.java#L701-L703 |
ironjacamar/ironjacamar | web/src/main/java/org/ironjacamar/web/SecurityActions.java | SecurityActions.createWebAppClassLoader | static WebAppClassLoader createWebAppClassLoader(final ClassLoader cl, final WebAppContext wac)
{
return AccessController.doPrivileged(new PrivilegedAction<WebAppClassLoader>()
{
public WebAppClassLoader run()
{
try
{
return new WebAppClassLoader(cl, wac);
}
catch (IOException ioe)
{
return null;
}
}
});
} | java | static WebAppClassLoader createWebAppClassLoader(final ClassLoader cl, final WebAppContext wac)
{
return AccessController.doPrivileged(new PrivilegedAction<WebAppClassLoader>()
{
public WebAppClassLoader run()
{
try
{
return new WebAppClassLoader(cl, wac);
}
catch (IOException ioe)
{
return null;
}
}
});
} | [
"static",
"WebAppClassLoader",
"createWebAppClassLoader",
"(",
"final",
"ClassLoader",
"cl",
",",
"final",
"WebAppContext",
"wac",
")",
"{",
"return",
"AccessController",
".",
"doPrivileged",
"(",
"new",
"PrivilegedAction",
"<",
"WebAppClassLoader",
">",
"(",
")",
"... | Create a WebClassLoader
@param cl The classloader
@param wac The web app context
@return The class loader | [
"Create",
"a",
"WebClassLoader"
] | train | https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/web/src/main/java/org/ironjacamar/web/SecurityActions.java#L152-L168 |
FINRAOS/DataGenerator | dg-example-hadoop/src/main/java/org/finra/datagenerator/samples/manager/JettyManager.java | JettyManager.makeReport | public String makeReport(String name, String report) {
long increment = Long.valueOf(report);
long currentLineCount = globalLineCounter.addAndGet(increment);
if (currentLineCount >= maxScenarios) {
return "exit";
} else {
return "ok";
}
} | java | public String makeReport(String name, String report) {
long increment = Long.valueOf(report);
long currentLineCount = globalLineCounter.addAndGet(increment);
if (currentLineCount >= maxScenarios) {
return "exit";
} else {
return "ok";
}
} | [
"public",
"String",
"makeReport",
"(",
"String",
"name",
",",
"String",
"report",
")",
"{",
"long",
"increment",
"=",
"Long",
".",
"valueOf",
"(",
"report",
")",
";",
"long",
"currentLineCount",
"=",
"globalLineCounter",
".",
"addAndGet",
"(",
"increment",
"... | Handles reports by consumers
@param name the name of the reporting consumer
@param report the number of lines the consumer has written since last report
@return "exit" if maxScenarios has been reached, "ok" otherwise | [
"Handles",
"reports",
"by",
"consumers"
] | train | https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-example-hadoop/src/main/java/org/finra/datagenerator/samples/manager/JettyManager.java#L101-L110 |
Azure/azure-sdk-for-java | sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/JobExecutionsInner.java | JobExecutionsInner.listByJobWithServiceResponseAsync | public Observable<ServiceResponse<Page<JobExecutionInner>>> listByJobWithServiceResponseAsync(final String resourceGroupName, final String serverName, final String jobAgentName, final String jobName) {
return listByJobSinglePageAsync(resourceGroupName, serverName, jobAgentName, jobName)
.concatMap(new Func1<ServiceResponse<Page<JobExecutionInner>>, Observable<ServiceResponse<Page<JobExecutionInner>>>>() {
@Override
public Observable<ServiceResponse<Page<JobExecutionInner>>> call(ServiceResponse<Page<JobExecutionInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listByJobNextWithServiceResponseAsync(nextPageLink));
}
});
} | java | public Observable<ServiceResponse<Page<JobExecutionInner>>> listByJobWithServiceResponseAsync(final String resourceGroupName, final String serverName, final String jobAgentName, final String jobName) {
return listByJobSinglePageAsync(resourceGroupName, serverName, jobAgentName, jobName)
.concatMap(new Func1<ServiceResponse<Page<JobExecutionInner>>, Observable<ServiceResponse<Page<JobExecutionInner>>>>() {
@Override
public Observable<ServiceResponse<Page<JobExecutionInner>>> call(ServiceResponse<Page<JobExecutionInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listByJobNextWithServiceResponseAsync(nextPageLink));
}
});
} | [
"public",
"Observable",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"JobExecutionInner",
">",
">",
">",
"listByJobWithServiceResponseAsync",
"(",
"final",
"String",
"resourceGroupName",
",",
"final",
"String",
"serverName",
",",
"final",
"String",
"jobAgentName",
",",
... | Lists a job's executions.
@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 jobAgentName The name of the job agent.
@param jobName The name of the job to get.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<JobExecutionInner> object | [
"Lists",
"a",
"job",
"s",
"executions",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/JobExecutionsInner.java#L768-L780 |
leancloud/java-sdk-all | realtime/src/main/java/cn/leancloud/im/v2/AVIMClient.java | AVIMClient.getConversation | public AVIMConversation getConversation(String conversationId, int convType) {
AVIMConversation result = null;
switch (convType) {
case Conversation.CONV_TYPE_SYSTEM:
result = getServiceConversation(conversationId);
break;
case Conversation.CONV_TYPE_TEMPORARY:
result = getTemporaryConversation(conversationId);
break;
case Conversation.CONV_TYPE_TRANSIENT:
result = getChatRoom(conversationId);
break;
default:
result = getConversation(conversationId);
break;
}
return result;
} | java | public AVIMConversation getConversation(String conversationId, int convType) {
AVIMConversation result = null;
switch (convType) {
case Conversation.CONV_TYPE_SYSTEM:
result = getServiceConversation(conversationId);
break;
case Conversation.CONV_TYPE_TEMPORARY:
result = getTemporaryConversation(conversationId);
break;
case Conversation.CONV_TYPE_TRANSIENT:
result = getChatRoom(conversationId);
break;
default:
result = getConversation(conversationId);
break;
}
return result;
} | [
"public",
"AVIMConversation",
"getConversation",
"(",
"String",
"conversationId",
",",
"int",
"convType",
")",
"{",
"AVIMConversation",
"result",
"=",
"null",
";",
"switch",
"(",
"convType",
")",
"{",
"case",
"Conversation",
".",
"CONV_TYPE_SYSTEM",
":",
"result",... | get conversation by id and type
@param conversationId
@param convType
@return | [
"get",
"conversation",
"by",
"id",
"and",
"type"
] | train | https://github.com/leancloud/java-sdk-all/blob/323f8e7ee38051b1350790e5192304768c5c9f5f/realtime/src/main/java/cn/leancloud/im/v2/AVIMClient.java#L402-L419 |
moparisthebest/beehive | beehive-netui-core/src/main/java/org/apache/beehive/netui/script/common/ImplicitObjectUtil.java | ImplicitObjectUtil.loadFacesBackingBean | public static void loadFacesBackingBean(ServletRequest request, FacesBackingBean facesBackingBean) {
if(facesBackingBean != null)
request.setAttribute(BACKING_IMPLICIT_OBJECT_KEY, facesBackingBean);
} | java | public static void loadFacesBackingBean(ServletRequest request, FacesBackingBean facesBackingBean) {
if(facesBackingBean != null)
request.setAttribute(BACKING_IMPLICIT_OBJECT_KEY, facesBackingBean);
} | [
"public",
"static",
"void",
"loadFacesBackingBean",
"(",
"ServletRequest",
"request",
",",
"FacesBackingBean",
"facesBackingBean",
")",
"{",
"if",
"(",
"facesBackingBean",
"!=",
"null",
")",
"request",
".",
"setAttribute",
"(",
"BACKING_IMPLICIT_OBJECT_KEY",
",",
"fac... | Load the JSF backing bean into the request.
@param request the request
@param facesBackingBean the JSF backing bean | [
"Load",
"the",
"JSF",
"backing",
"bean",
"into",
"the",
"request",
"."
] | train | https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/script/common/ImplicitObjectUtil.java#L118-L121 |
Headline/CleverBotAPI-Java | src/main/java/com/michaelwflaherty/cleverbotapi/CleverBotQuery.java | CleverBotQuery.sendRequest | public void sendRequest() throws IOException
{
/* Create & Format URL */
URL url = new URL(CleverBotQuery.formatRequest(CleverBotQuery.URL_STRING, this.key, this.phrase, this.conversationID));
/* Open Connection */
URLConnection urlConnection = url.openConnection();
/* Read input */
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String inputLine = in.readLine();
/* Create JSON Object */
JsonObject jsonObject = new JsonParser().parse(inputLine).getAsJsonObject(); // convert to JSON
/* Get params */
this.setConversationID(jsonObject.get("cs").getAsString()); // update conversation ID
this.setResponse(jsonObject.get("output").getAsString()); // get output
this.setRandomNumber(Integer.parseInt(jsonObject.get("random_number").getAsString())); // get output
in.close(); // close!
} | java | public void sendRequest() throws IOException
{
/* Create & Format URL */
URL url = new URL(CleverBotQuery.formatRequest(CleverBotQuery.URL_STRING, this.key, this.phrase, this.conversationID));
/* Open Connection */
URLConnection urlConnection = url.openConnection();
/* Read input */
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String inputLine = in.readLine();
/* Create JSON Object */
JsonObject jsonObject = new JsonParser().parse(inputLine).getAsJsonObject(); // convert to JSON
/* Get params */
this.setConversationID(jsonObject.get("cs").getAsString()); // update conversation ID
this.setResponse(jsonObject.get("output").getAsString()); // get output
this.setRandomNumber(Integer.parseInt(jsonObject.get("random_number").getAsString())); // get output
in.close(); // close!
} | [
"public",
"void",
"sendRequest",
"(",
")",
"throws",
"IOException",
"{",
"/* Create & Format URL */",
"URL",
"url",
"=",
"new",
"URL",
"(",
"CleverBotQuery",
".",
"formatRequest",
"(",
"CleverBotQuery",
".",
"URL_STRING",
",",
"this",
".",
"key",
",",
"this",
... | Sends request to CleverBot servers. API key and phrase should be set prior to this call
@throws IOException exception upon query failure | [
"Sends",
"request",
"to",
"CleverBot",
"servers",
".",
"API",
"key",
"and",
"phrase",
"should",
"be",
"set",
"prior",
"to",
"this",
"call"
] | train | https://github.com/Headline/CleverBotAPI-Java/blob/fe6818362eec687cdfeb7ee8deb4d2ee19611676/src/main/java/com/michaelwflaherty/cleverbotapi/CleverBotQuery.java#L174-L194 |
apache/incubator-gobblin | gobblin-utility/src/main/java/org/apache/gobblin/util/HadoopUtils.java | HadoopUtils.deserializeWriterDirPermissions | public static FsPermission deserializeWriterDirPermissions(State state, int numBranches, int branchId) {
return new FsPermission(state.getPropAsShortWithRadix(
ForkOperatorUtils.getPropertyNameForBranch(ConfigurationKeys.WRITER_DIR_PERMISSIONS, numBranches, branchId),
FsPermission.getDefault().toShort(), ConfigurationKeys.PERMISSION_PARSING_RADIX));
} | java | public static FsPermission deserializeWriterDirPermissions(State state, int numBranches, int branchId) {
return new FsPermission(state.getPropAsShortWithRadix(
ForkOperatorUtils.getPropertyNameForBranch(ConfigurationKeys.WRITER_DIR_PERMISSIONS, numBranches, branchId),
FsPermission.getDefault().toShort(), ConfigurationKeys.PERMISSION_PARSING_RADIX));
} | [
"public",
"static",
"FsPermission",
"deserializeWriterDirPermissions",
"(",
"State",
"state",
",",
"int",
"numBranches",
",",
"int",
"branchId",
")",
"{",
"return",
"new",
"FsPermission",
"(",
"state",
".",
"getPropAsShortWithRadix",
"(",
"ForkOperatorUtils",
".",
"... | Deserializes a {@link FsPermission}s object that should be used when a {@link DataWriter} is creating directories. | [
"Deserializes",
"a",
"{"
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/HadoopUtils.java#L894-L898 |
salesforce/Argus | ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/resources/ManagementResources.java | ManagementResources.updateWardenSuspensionLevelsAndDurations | @PUT
@Path("/wardensuspensionlevelsanddurations")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Description("Updates warden infraction level counts and suspension durations.")
public Response updateWardenSuspensionLevelsAndDurations(@Context HttpServletRequest req, Map<Integer, Long> infractionCounts) {
if (infractionCounts == null || infractionCounts.isEmpty()) {
throw new IllegalArgumentException("Infraction counts cannot be null or empty.");
}
validatePrivilegedUser(req);
managementService.updateWardenSuspensionLevelsAndDurations(infractionCounts);
return Response.status(Status.OK).build();
} | java | @PUT
@Path("/wardensuspensionlevelsanddurations")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Description("Updates warden infraction level counts and suspension durations.")
public Response updateWardenSuspensionLevelsAndDurations(@Context HttpServletRequest req, Map<Integer, Long> infractionCounts) {
if (infractionCounts == null || infractionCounts.isEmpty()) {
throw new IllegalArgumentException("Infraction counts cannot be null or empty.");
}
validatePrivilegedUser(req);
managementService.updateWardenSuspensionLevelsAndDurations(infractionCounts);
return Response.status(Status.OK).build();
} | [
"@",
"PUT",
"@",
"Path",
"(",
"\"/wardensuspensionlevelsanddurations\"",
")",
"@",
"Consumes",
"(",
"MediaType",
".",
"APPLICATION_JSON",
")",
"@",
"Produces",
"(",
"MediaType",
".",
"APPLICATION_JSON",
")",
"@",
"Description",
"(",
"\"Updates warden infraction level ... | Updates warden suspension levels.
@param req The HTTP request.
@param infractionCounts Warden suspension levels.
@return Response object indicating whether the operation was successful or not.
@throws IllegalArgumentException WebApplicationException. | [
"Updates",
"warden",
"suspension",
"levels",
"."
] | train | https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/resources/ManagementResources.java#L189-L201 |
ManfredTremmel/gwt-commons-lang3 | src/main/java/org/apache/commons/lang3/concurrent/ConcurrentUtils.java | ConcurrentUtils.putIfAbsent | public static <K, V> V putIfAbsent(final ConcurrentMap<K, V> map, final K key, final V value) {
if (map == null) {
return null;
}
final V result = map.putIfAbsent(key, value);
return result != null ? result : value;
} | java | public static <K, V> V putIfAbsent(final ConcurrentMap<K, V> map, final K key, final V value) {
if (map == null) {
return null;
}
final V result = map.putIfAbsent(key, value);
return result != null ? result : value;
} | [
"public",
"static",
"<",
"K",
",",
"V",
">",
"V",
"putIfAbsent",
"(",
"final",
"ConcurrentMap",
"<",
"K",
",",
"V",
">",
"map",
",",
"final",
"K",
"key",
",",
"final",
"V",
"value",
")",
"{",
"if",
"(",
"map",
"==",
"null",
")",
"{",
"return",
... | <p>
Puts a value in the specified {@code ConcurrentMap} if the key is not yet
present. This method works similar to the {@code putIfAbsent()} method of
the {@code ConcurrentMap} interface, but the value returned is different.
Basically, this method is equivalent to the following code fragment:
</p>
<pre>
if (!map.containsKey(key)) {
map.put(key, value);
return value;
} else {
return map.get(key);
}
</pre>
<p>
except that the action is performed atomically. So this method always
returns the value which is stored in the map.
</p>
<p>
This method is <b>null</b>-safe: It accepts a <b>null</b> map as input
without throwing an exception. In this case the return value is
<b>null</b>, too.
</p>
@param <K> the type of the keys of the map
@param <V> the type of the values of the map
@param map the map to be modified
@param key the key of the value to be added
@param value the value to be added
@return the value stored in the map after this operation | [
"<p",
">",
"Puts",
"a",
"value",
"in",
"the",
"specified",
"{",
"@code",
"ConcurrentMap",
"}",
"if",
"the",
"key",
"is",
"not",
"yet",
"present",
".",
"This",
"method",
"works",
"similar",
"to",
"the",
"{",
"@code",
"putIfAbsent",
"()",
"}",
"method",
... | train | https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/concurrent/ConcurrentUtils.java#L245-L252 |
calrissian/mango | mango-json/src/main/java/org/calrissian/mango/json/mappings/ObjectJsonNode.java | ObjectJsonNode.visit | @Override
public void visit(String[] keys, int level, Map<Integer, Integer> levelToIdx, ValueJsonNode valueJsonNode) {
if(level == keys.length-1)
children.put(keys[level], valueJsonNode);
else {
JsonTreeNode child = children.get(keys[level]);
// look toJson see if next item exists, otherwise, create it, add it toJson children, and visit it.
String nextKey = keys[level+1];
if(child == null) {
if (nextKey.equals("[]"))
child = new ArrayJsonNode();
else
child = new ObjectJsonNode();
children.put(keys[level], child);
}
child.visit(keys, level+1, levelToIdx, valueJsonNode);
}
} | java | @Override
public void visit(String[] keys, int level, Map<Integer, Integer> levelToIdx, ValueJsonNode valueJsonNode) {
if(level == keys.length-1)
children.put(keys[level], valueJsonNode);
else {
JsonTreeNode child = children.get(keys[level]);
// look toJson see if next item exists, otherwise, create it, add it toJson children, and visit it.
String nextKey = keys[level+1];
if(child == null) {
if (nextKey.equals("[]"))
child = new ArrayJsonNode();
else
child = new ObjectJsonNode();
children.put(keys[level], child);
}
child.visit(keys, level+1, levelToIdx, valueJsonNode);
}
} | [
"@",
"Override",
"public",
"void",
"visit",
"(",
"String",
"[",
"]",
"keys",
",",
"int",
"level",
",",
"Map",
"<",
"Integer",
",",
"Integer",
">",
"levelToIdx",
",",
"ValueJsonNode",
"valueJsonNode",
")",
"{",
"if",
"(",
"level",
"==",
"keys",
".",
"le... | Sets state on current instance based on the flattened tree representation from the input.
This will also determine the next child, if necessary, and propagate the next level of
the tree (down to the child).
@param keys
@param level
@param levelToIdx
@param valueJsonNode | [
"Sets",
"state",
"on",
"current",
"instance",
"based",
"on",
"the",
"flattened",
"tree",
"representation",
"from",
"the",
"input",
".",
"This",
"will",
"also",
"determine",
"the",
"next",
"child",
"if",
"necessary",
"and",
"propagate",
"the",
"next",
"level",
... | train | https://github.com/calrissian/mango/blob/a95aa5e77af9aa0e629787228d80806560023452/mango-json/src/main/java/org/calrissian/mango/json/mappings/ObjectJsonNode.java#L40-L63 |
grpc/grpc-java | core/src/main/java/io/grpc/internal/MessageFramer.java | MessageFramer.writeKnownLengthUncompressed | private int writeKnownLengthUncompressed(InputStream message, int messageLength)
throws IOException {
if (maxOutboundMessageSize >= 0 && messageLength > maxOutboundMessageSize) {
throw Status.RESOURCE_EXHAUSTED
.withDescription(
String.format("message too large %d > %d", messageLength , maxOutboundMessageSize))
.asRuntimeException();
}
ByteBuffer header = ByteBuffer.wrap(headerScratch);
header.put(UNCOMPRESSED);
header.putInt(messageLength);
// Allocate the initial buffer chunk based on frame header + payload length.
// Note that the allocator may allocate a buffer larger or smaller than this length
if (buffer == null) {
buffer = bufferAllocator.allocate(header.position() + messageLength);
}
writeRaw(headerScratch, 0, header.position());
return writeToOutputStream(message, outputStreamAdapter);
} | java | private int writeKnownLengthUncompressed(InputStream message, int messageLength)
throws IOException {
if (maxOutboundMessageSize >= 0 && messageLength > maxOutboundMessageSize) {
throw Status.RESOURCE_EXHAUSTED
.withDescription(
String.format("message too large %d > %d", messageLength , maxOutboundMessageSize))
.asRuntimeException();
}
ByteBuffer header = ByteBuffer.wrap(headerScratch);
header.put(UNCOMPRESSED);
header.putInt(messageLength);
// Allocate the initial buffer chunk based on frame header + payload length.
// Note that the allocator may allocate a buffer larger or smaller than this length
if (buffer == null) {
buffer = bufferAllocator.allocate(header.position() + messageLength);
}
writeRaw(headerScratch, 0, header.position());
return writeToOutputStream(message, outputStreamAdapter);
} | [
"private",
"int",
"writeKnownLengthUncompressed",
"(",
"InputStream",
"message",
",",
"int",
"messageLength",
")",
"throws",
"IOException",
"{",
"if",
"(",
"maxOutboundMessageSize",
">=",
"0",
"&&",
"messageLength",
">",
"maxOutboundMessageSize",
")",
"{",
"throw",
... | Write an unserialized message with a known length, uncompressed. | [
"Write",
"an",
"unserialized",
"message",
"with",
"a",
"known",
"length",
"uncompressed",
"."
] | train | https://github.com/grpc/grpc-java/blob/973885457f9609de232d2553b82c67f6c3ff57bf/core/src/main/java/io/grpc/internal/MessageFramer.java#L212-L230 |
gmessner/gitlab4j-api | src/main/java/org/gitlab4j/api/GitLabApi.java | GitLabApi.oauth2Login | public static GitLabApi oauth2Login(String url, String username, CharSequence password) throws GitLabApiException {
return (GitLabApi.oauth2Login(ApiVersion.V4, url, username, password, null, null, false));
} | java | public static GitLabApi oauth2Login(String url, String username, CharSequence password) throws GitLabApiException {
return (GitLabApi.oauth2Login(ApiVersion.V4, url, username, password, null, null, false));
} | [
"public",
"static",
"GitLabApi",
"oauth2Login",
"(",
"String",
"url",
",",
"String",
"username",
",",
"CharSequence",
"password",
")",
"throws",
"GitLabApiException",
"{",
"return",
"(",
"GitLabApi",
".",
"oauth2Login",
"(",
"ApiVersion",
".",
"V4",
",",
"url",
... | <p>Logs into GitLab using OAuth2 with the provided {@code username} and {@code password},
and creates a new {@code GitLabApi} instance using returned access token.</p>
@param url GitLab URL
@param username user name for which private token should be obtained
@param password a CharSequence containing the password for a given {@code username}
@return new {@code GitLabApi} instance configured for a user-specific token
@throws GitLabApiException GitLabApiException if any exception occurs during execution | [
"<p",
">",
"Logs",
"into",
"GitLab",
"using",
"OAuth2",
"with",
"the",
"provided",
"{",
"@code",
"username",
"}",
"and",
"{",
"@code",
"password",
"}",
"and",
"creates",
"a",
"new",
"{",
"@code",
"GitLabApi",
"}",
"instance",
"using",
"returned",
"access",... | train | https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/GitLabApi.java#L129-L131 |
zaproxy/zaproxy | src/org/apache/commons/httpclient/HttpConnection.java | HttpConnection.getRequestOutputStream | public OutputStream getRequestOutputStream()
throws IOException, IllegalStateException {
LOG.trace("enter HttpConnection.getRequestOutputStream()");
assertOpen();
OutputStream out = this.outputStream;
if (Wire.CONTENT_WIRE.enabled()) {
out = new WireLogOutputStream(out, Wire.CONTENT_WIRE);
}
return out;
} | java | public OutputStream getRequestOutputStream()
throws IOException, IllegalStateException {
LOG.trace("enter HttpConnection.getRequestOutputStream()");
assertOpen();
OutputStream out = this.outputStream;
if (Wire.CONTENT_WIRE.enabled()) {
out = new WireLogOutputStream(out, Wire.CONTENT_WIRE);
}
return out;
} | [
"public",
"OutputStream",
"getRequestOutputStream",
"(",
")",
"throws",
"IOException",
",",
"IllegalStateException",
"{",
"LOG",
".",
"trace",
"(",
"\"enter HttpConnection.getRequestOutputStream()\"",
")",
";",
"assertOpen",
"(",
")",
";",
"OutputStream",
"out",
"=",
... | Returns an {@link OutputStream} suitable for writing the request.
@throws IllegalStateException if the connection is not open
@throws IOException if an I/O problem occurs
@return a stream to write the request to | [
"Returns",
"an",
"{",
"@link",
"OutputStream",
"}",
"suitable",
"for",
"writing",
"the",
"request",
"."
] | train | https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/apache/commons/httpclient/HttpConnection.java#L870-L879 |
pravega/pravega | common/src/main/java/io/pravega/common/util/TypedProperties.java | TypedProperties.getEnum | public <T extends Enum<T>> T getEnum(Property<T> property, Class<T> enumClass) throws ConfigurationException {
return tryGet(property, s -> Enum.valueOf(enumClass, s));
} | java | public <T extends Enum<T>> T getEnum(Property<T> property, Class<T> enumClass) throws ConfigurationException {
return tryGet(property, s -> Enum.valueOf(enumClass, s));
} | [
"public",
"<",
"T",
"extends",
"Enum",
"<",
"T",
">",
">",
"T",
"getEnum",
"(",
"Property",
"<",
"T",
">",
"property",
",",
"Class",
"<",
"T",
">",
"enumClass",
")",
"throws",
"ConfigurationException",
"{",
"return",
"tryGet",
"(",
"property",
",",
"s"... | Gets the value of an Enumeration property.
@param property The Property to get.
@param enumClass Class defining return type.
@param <T> Type of Enumeration.
@return The property value or default value, if no such is defined in the base Properties.
@throws ConfigurationException When the given property name does not exist within the current component and the property
does not have a default value set, or when the property cannot be parsed as the given Enum. | [
"Gets",
"the",
"value",
"of",
"an",
"Enumeration",
"property",
"."
] | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/common/src/main/java/io/pravega/common/util/TypedProperties.java#L105-L107 |
netheosgithub/pcs_api | java/src/main/java/net/netheos/pcsapi/oauth/OAuth2SessionManager.java | OAuth2SessionManager.fetchUserCredentials | UserCredentials fetchUserCredentials( String code )
{
HttpPost post = new HttpPost( accessTokenUrl );
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add( new BasicNameValuePair( OAuth2.CLIENT_ID, appInfo.getAppId() ) );
parameters.add( new BasicNameValuePair( OAuth2.CLIENT_SECRET, appInfo.getAppSecret() ) );
parameters.add( new BasicNameValuePair( OAuth2.CODE, code ) );
parameters.add( new BasicNameValuePair( OAuth2.GRANT_TYPE, OAuth2.AUTHORIZATION_CODE ) );
if ( appInfo.getRedirectUrl() != null ) {
parameters.add( new BasicNameValuePair( OAuth2.REDIRECT_URI, appInfo.getRedirectUrl() ) );
}
try {
post.setEntity( new UrlEncodedFormEntity( parameters, PcsUtils.UTF8.name() ) );
} catch ( UnsupportedEncodingException ex ) {
throw new CStorageException( "Can't encode parameters", ex );
}
HttpResponse response;
try {
response = httpClient.execute( post );
} catch ( IOException e ) {
throw new CStorageException( "HTTP request while fetching token has failed", e );
}
// FIXME check status code here
final String json;
try {
json = EntityUtils.toString( response.getEntity(), PcsUtils.UTF8.name() );
} catch ( IOException e ) {
throw new CStorageException( "Can't retrieve json string in HTTP response entity", e );
}
LOGGER.debug( "fetchUserCredentials - json: {}", json );
Credentials credentials = Credentials.createFromJson( json );
userCredentials = new UserCredentials( appInfo,
null, // userId is unknown yet
credentials );
return userCredentials;
} | java | UserCredentials fetchUserCredentials( String code )
{
HttpPost post = new HttpPost( accessTokenUrl );
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add( new BasicNameValuePair( OAuth2.CLIENT_ID, appInfo.getAppId() ) );
parameters.add( new BasicNameValuePair( OAuth2.CLIENT_SECRET, appInfo.getAppSecret() ) );
parameters.add( new BasicNameValuePair( OAuth2.CODE, code ) );
parameters.add( new BasicNameValuePair( OAuth2.GRANT_TYPE, OAuth2.AUTHORIZATION_CODE ) );
if ( appInfo.getRedirectUrl() != null ) {
parameters.add( new BasicNameValuePair( OAuth2.REDIRECT_URI, appInfo.getRedirectUrl() ) );
}
try {
post.setEntity( new UrlEncodedFormEntity( parameters, PcsUtils.UTF8.name() ) );
} catch ( UnsupportedEncodingException ex ) {
throw new CStorageException( "Can't encode parameters", ex );
}
HttpResponse response;
try {
response = httpClient.execute( post );
} catch ( IOException e ) {
throw new CStorageException( "HTTP request while fetching token has failed", e );
}
// FIXME check status code here
final String json;
try {
json = EntityUtils.toString( response.getEntity(), PcsUtils.UTF8.name() );
} catch ( IOException e ) {
throw new CStorageException( "Can't retrieve json string in HTTP response entity", e );
}
LOGGER.debug( "fetchUserCredentials - json: {}", json );
Credentials credentials = Credentials.createFromJson( json );
userCredentials = new UserCredentials( appInfo,
null, // userId is unknown yet
credentials );
return userCredentials;
} | [
"UserCredentials",
"fetchUserCredentials",
"(",
"String",
"code",
")",
"{",
"HttpPost",
"post",
"=",
"new",
"HttpPost",
"(",
"accessTokenUrl",
")",
";",
"List",
"<",
"NameValuePair",
">",
"parameters",
"=",
"new",
"ArrayList",
"<",
"NameValuePair",
">",
"(",
"... | Fetches user credentials
@param code oauth2 OTP code
@return The user credentials (without userId) | [
"Fetches",
"user",
"credentials"
] | train | https://github.com/netheosgithub/pcs_api/blob/20691e52e144014f99ca75cb7dedc7ba0c18586c/java/src/main/java/net/netheos/pcsapi/oauth/OAuth2SessionManager.java#L198-L242 |
spotify/styx | styx-service-common/src/main/java/com/spotify/styx/util/ShardedCounter.java | ShardedCounter.updateLimit | public void updateLimit(StorageTransaction tx, String counterId, long limit) throws IOException {
tx.updateLimitForCounter(counterId, limit);
} | java | public void updateLimit(StorageTransaction tx, String counterId, long limit) throws IOException {
tx.updateLimitForCounter(counterId, limit);
} | [
"public",
"void",
"updateLimit",
"(",
"StorageTransaction",
"tx",
",",
"String",
"counterId",
",",
"long",
"limit",
")",
"throws",
"IOException",
"{",
"tx",
".",
"updateLimitForCounter",
"(",
"counterId",
",",
"limit",
")",
";",
"}"
] | Must be called within a TransactionCallable. (?)
<p>Augments the transaction with operations to persist the given limit in Datastore. So long as
there has been no preceding successful updateLimit operation, no limit is applied in
updateCounter operations on this counter. | [
"Must",
"be",
"called",
"within",
"a",
"TransactionCallable",
".",
"(",
"?",
")"
] | train | https://github.com/spotify/styx/blob/0d63999beeb93a17447e3bbccaa62175b74cf6e4/styx-service-common/src/main/java/com/spotify/styx/util/ShardedCounter.java#L229-L231 |
alkacon/opencms-core | src/org/opencms/importexport/CmsExport.java | CmsExport.exportUsers | protected void exportUsers(Element parent, CmsOrganizationalUnit orgunit)
throws CmsImportExportException, SAXException {
try {
I_CmsReport report = getReport();
List<CmsUser> allUsers = OpenCms.getOrgUnitManager().getUsers(getCms(), orgunit.getName(), false);
for (int i = 0, l = allUsers.size(); i < l; i++) {
CmsUser user = allUsers.get(i);
report.print(
org.opencms.report.Messages.get().container(
org.opencms.report.Messages.RPT_SUCCESSION_2,
String.valueOf(i + 1),
String.valueOf(l)),
I_CmsReport.FORMAT_NOTE);
report.print(Messages.get().container(Messages.RPT_EXPORT_USER_0), I_CmsReport.FORMAT_NOTE);
report.print(
org.opencms.report.Messages.get().container(
org.opencms.report.Messages.RPT_ARGUMENT_1,
user.getName()));
report.print(org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_DOTS_0));
exportUser(parent, user);
report.println(
org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_OK_0),
I_CmsReport.FORMAT_OK);
}
} catch (CmsImportExportException e) {
throw e;
} catch (CmsException e) {
if (LOG.isDebugEnabled()) {
LOG.debug(e.getLocalizedMessage(), e);
}
throw new CmsImportExportException(e.getMessageContainer(), e);
}
} | java | protected void exportUsers(Element parent, CmsOrganizationalUnit orgunit)
throws CmsImportExportException, SAXException {
try {
I_CmsReport report = getReport();
List<CmsUser> allUsers = OpenCms.getOrgUnitManager().getUsers(getCms(), orgunit.getName(), false);
for (int i = 0, l = allUsers.size(); i < l; i++) {
CmsUser user = allUsers.get(i);
report.print(
org.opencms.report.Messages.get().container(
org.opencms.report.Messages.RPT_SUCCESSION_2,
String.valueOf(i + 1),
String.valueOf(l)),
I_CmsReport.FORMAT_NOTE);
report.print(Messages.get().container(Messages.RPT_EXPORT_USER_0), I_CmsReport.FORMAT_NOTE);
report.print(
org.opencms.report.Messages.get().container(
org.opencms.report.Messages.RPT_ARGUMENT_1,
user.getName()));
report.print(org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_DOTS_0));
exportUser(parent, user);
report.println(
org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_OK_0),
I_CmsReport.FORMAT_OK);
}
} catch (CmsImportExportException e) {
throw e;
} catch (CmsException e) {
if (LOG.isDebugEnabled()) {
LOG.debug(e.getLocalizedMessage(), e);
}
throw new CmsImportExportException(e.getMessageContainer(), e);
}
} | [
"protected",
"void",
"exportUsers",
"(",
"Element",
"parent",
",",
"CmsOrganizationalUnit",
"orgunit",
")",
"throws",
"CmsImportExportException",
",",
"SAXException",
"{",
"try",
"{",
"I_CmsReport",
"report",
"=",
"getReport",
"(",
")",
";",
"List",
"<",
"CmsUser"... | Exports all users of the given organizational unit.<p>
@param parent the parent node to add the users to
@param orgunit the organizational unit to write the groups for
@throws CmsImportExportException if something goes wrong
@throws SAXException if something goes wrong processing the manifest.xml | [
"Exports",
"all",
"users",
"of",
"the",
"given",
"organizational",
"unit",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/importexport/CmsExport.java#L1321-L1354 |
moparisthebest/beehive | beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/SqlFragmentContainer.java | SqlFragmentContainer.getPreparedStatementText | String getPreparedStatementText(ControlBeanContext context, Method m, Object[] args) {
StringBuilder sb = new StringBuilder();
for (SqlFragment sf : _children) {
sb.append(sf.getPreparedStatementText(context, m, args));
}
return sb.toString();
} | java | String getPreparedStatementText(ControlBeanContext context, Method m, Object[] args) {
StringBuilder sb = new StringBuilder();
for (SqlFragment sf : _children) {
sb.append(sf.getPreparedStatementText(context, m, args));
}
return sb.toString();
} | [
"String",
"getPreparedStatementText",
"(",
"ControlBeanContext",
"context",
",",
"Method",
"m",
",",
"Object",
"[",
"]",
"args",
")",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"for",
"(",
"SqlFragment",
"sf",
":",
"_children",
"... | builds the text of the prepared statement
@param context A ControlBeanContext instance.
@param m The annotated method.
@param args The method's parameters.
@return The PreparedStatement text generated by this fragment and its children. | [
"builds",
"the",
"text",
"of",
"the",
"prepared",
"statement"
] | train | https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/SqlFragmentContainer.java#L92-L98 |
opsmatters/opsmatters-core | src/main/java/com/opsmatters/core/documents/XlsWorkbook.java | XlsWorkbook.createSheet | @Override
public XlsWorksheet createSheet(FileColumn[] columns, List<String[]> lines, String sheetName)
throws IOException
{
// Create the worksheet and add the cells
WritableSheet sheet = writableWorkbook.createSheet(sheetName, 9999); // Append sheet
try
{
appendRows(sheet, columns, lines, sheetName);
}
catch(WriteException e)
{
throw new IOException(e);
}
// Set the column to autosize
int numColumns = sheet.getColumns();
for(int i = 0; i < numColumns; i++)
{
CellView column = sheet.getColumnView(i);
column.setAutosize(true);
if(columns != null && i < columns.length)
{
CellFormat format = columns[i].getCellFormat();
if(format != null)
column.setFormat(format);
}
sheet.setColumnView(i, column);
}
return new XlsWorksheet(sheet);
} | java | @Override
public XlsWorksheet createSheet(FileColumn[] columns, List<String[]> lines, String sheetName)
throws IOException
{
// Create the worksheet and add the cells
WritableSheet sheet = writableWorkbook.createSheet(sheetName, 9999); // Append sheet
try
{
appendRows(sheet, columns, lines, sheetName);
}
catch(WriteException e)
{
throw new IOException(e);
}
// Set the column to autosize
int numColumns = sheet.getColumns();
for(int i = 0; i < numColumns; i++)
{
CellView column = sheet.getColumnView(i);
column.setAutosize(true);
if(columns != null && i < columns.length)
{
CellFormat format = columns[i].getCellFormat();
if(format != null)
column.setFormat(format);
}
sheet.setColumnView(i, column);
}
return new XlsWorksheet(sheet);
} | [
"@",
"Override",
"public",
"XlsWorksheet",
"createSheet",
"(",
"FileColumn",
"[",
"]",
"columns",
",",
"List",
"<",
"String",
"[",
"]",
">",
"lines",
",",
"String",
"sheetName",
")",
"throws",
"IOException",
"{",
"// Create the worksheet and add the cells",
"Writa... | Creates a sheet in the workbook with the given name and lines of data.
@param columns The column definitions for the worksheet
@param lines The list of lines to be added to the worksheet
@param sheetName The name of the worksheet to be added
@return The worksheet created
@throws IOException if the sheet cannot be created | [
"Creates",
"a",
"sheet",
"in",
"the",
"workbook",
"with",
"the",
"given",
"name",
"and",
"lines",
"of",
"data",
"."
] | train | https://github.com/opsmatters/opsmatters-core/blob/c48904f7e8d029fd45357811ec38a735e261e3fd/src/main/java/com/opsmatters/core/documents/XlsWorkbook.java#L238-L270 |
spring-projects/spring-session-data-mongodb | src/main/java/org/springframework/session/data/mongo/ReactiveMongoOperationsSessionRepository.java | ReactiveMongoOperationsSessionRepository.createSession | @Override
public Mono<MongoSession> createSession() {
return Mono.justOrEmpty(this.maxInactiveIntervalInSeconds) //
.map(MongoSession::new) //
.doOnNext(mongoSession -> publishEvent(new SessionCreatedEvent(this, mongoSession))) //
.switchIfEmpty(Mono.just(new MongoSession()));
} | java | @Override
public Mono<MongoSession> createSession() {
return Mono.justOrEmpty(this.maxInactiveIntervalInSeconds) //
.map(MongoSession::new) //
.doOnNext(mongoSession -> publishEvent(new SessionCreatedEvent(this, mongoSession))) //
.switchIfEmpty(Mono.just(new MongoSession()));
} | [
"@",
"Override",
"public",
"Mono",
"<",
"MongoSession",
">",
"createSession",
"(",
")",
"{",
"return",
"Mono",
".",
"justOrEmpty",
"(",
"this",
".",
"maxInactiveIntervalInSeconds",
")",
"//",
".",
"map",
"(",
"MongoSession",
"::",
"new",
")",
"//",
".",
"d... | Creates a new {@link MongoSession} that is capable of being persisted by this {@link ReactiveSessionRepository}.
<p>
This allows optimizations and customizations in how the {@link MongoSession} is persisted. For example, the
implementation returned might keep track of the changes ensuring that only the delta needs to be persisted on a
save.
</p>
@return a new {@link MongoSession} that is capable of being persisted by this {@link ReactiveSessionRepository} | [
"Creates",
"a",
"new",
"{",
"@link",
"MongoSession",
"}",
"that",
"is",
"capable",
"of",
"being",
"persisted",
"by",
"this",
"{",
"@link",
"ReactiveSessionRepository",
"}",
".",
"<p",
">",
"This",
"allows",
"optimizations",
"and",
"customizations",
"in",
"how"... | train | https://github.com/spring-projects/spring-session-data-mongodb/blob/c507bb2d2a9b52ea9846ffaf1ac7c71cb0e6690e/src/main/java/org/springframework/session/data/mongo/ReactiveMongoOperationsSessionRepository.java#L84-L91 |
moparisthebest/beehive | beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/PageFlowUtils.java | PageFlowUtils.getCurrentActionResolver | public static ActionResolver getCurrentActionResolver( HttpServletRequest request, ServletContext servletContext )
{
StorageHandler sh = Handlers.get( servletContext ).getStorageHandler();
HttpServletRequest unwrappedRequest = unwrapMultipart( request );
RequestContext rc = new RequestContext( unwrappedRequest, null );
//
// First see if the current page flow is a long-lived, which is stored in its own attribute.
//
String currentLongLivedAttrName =
ScopedServletUtils.getScopedSessionAttrName( CURRENT_LONGLIVED_ATTR, unwrappedRequest );
String currentLongLivedModulePath = ( String ) sh.getAttribute( rc, currentLongLivedAttrName );
if ( currentLongLivedModulePath != null )
{
return getLongLivedPageFlow( currentLongLivedModulePath, unwrappedRequest );
}
else
{
String currentJpfAttrName = ScopedServletUtils.getScopedSessionAttrName( CURRENT_JPF_ATTR, unwrappedRequest );
return ( ActionResolver ) sh.getAttribute( rc, currentJpfAttrName );
}
} | java | public static ActionResolver getCurrentActionResolver( HttpServletRequest request, ServletContext servletContext )
{
StorageHandler sh = Handlers.get( servletContext ).getStorageHandler();
HttpServletRequest unwrappedRequest = unwrapMultipart( request );
RequestContext rc = new RequestContext( unwrappedRequest, null );
//
// First see if the current page flow is a long-lived, which is stored in its own attribute.
//
String currentLongLivedAttrName =
ScopedServletUtils.getScopedSessionAttrName( CURRENT_LONGLIVED_ATTR, unwrappedRequest );
String currentLongLivedModulePath = ( String ) sh.getAttribute( rc, currentLongLivedAttrName );
if ( currentLongLivedModulePath != null )
{
return getLongLivedPageFlow( currentLongLivedModulePath, unwrappedRequest );
}
else
{
String currentJpfAttrName = ScopedServletUtils.getScopedSessionAttrName( CURRENT_JPF_ATTR, unwrappedRequest );
return ( ActionResolver ) sh.getAttribute( rc, currentJpfAttrName );
}
} | [
"public",
"static",
"ActionResolver",
"getCurrentActionResolver",
"(",
"HttpServletRequest",
"request",
",",
"ServletContext",
"servletContext",
")",
"{",
"StorageHandler",
"sh",
"=",
"Handlers",
".",
"get",
"(",
"servletContext",
")",
".",
"getStorageHandler",
"(",
"... | Get the current ActionResolver.
@deprecated Use {@link #getCurrentPageFlow(HttpServletRequest, ServletContext)} instead.
@param request the current HttpServletRequest.
@param servletContext the current ServletContext.
@return the current ActionResolver from the user session, or <code>null</code> if there is none. | [
"Get",
"the",
"current",
"ActionResolver",
".",
"@deprecated",
"Use",
"{",
"@link",
"#getCurrentPageFlow",
"(",
"HttpServletRequest",
"ServletContext",
")",
"}",
"instead",
"."
] | train | https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/PageFlowUtils.java#L300-L322 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.