repository_name stringlengths 7 54 | func_path_in_repository stringlengths 18 196 | func_name stringlengths 7 107 | whole_func_string stringlengths 76 3.82k | language stringclasses 1
value | func_code_string stringlengths 76 3.82k | func_code_tokens listlengths 22 717 | func_documentation_string stringlengths 61 1.98k | func_documentation_tokens listlengths 1 508 | split_name stringclasses 1
value | func_code_url stringlengths 111 310 |
|---|---|---|---|---|---|---|---|---|---|---|
apache/groovy | src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java | DefaultGroovyMethods.putAt | public static <T> void putAt(List<T> self, int idx, T value) {
int size = self.size();
idx = normaliseIndex(idx, size);
if (idx < size) {
self.set(idx, value);
} else {
while (size < idx) {
self.add(size++, null);
}
self.add(idx, value);
}
} | java | public static <T> void putAt(List<T> self, int idx, T value) {
int size = self.size();
idx = normaliseIndex(idx, size);
if (idx < size) {
self.set(idx, value);
} else {
while (size < idx) {
self.add(size++, null);
}
self.add(idx, value);
}
} | [
"public",
"static",
"<",
"T",
">",
"void",
"putAt",
"(",
"List",
"<",
"T",
">",
"self",
",",
"int",
"idx",
",",
"T",
"value",
")",
"{",
"int",
"size",
"=",
"self",
".",
"size",
"(",
")",
";",
"idx",
"=",
"normaliseIndex",
"(",
"idx",
",",
"size... | A helper method to allow lists to work with subscript operators.
<pre class="groovyTestCase">def list = [2, 3]
list[0] = 1
assert list == [1, 3]</pre>
@param self a List
@param idx an index
@param value the value to put at the given index
@since 1.0 | [
"A",
"helper",
"method",
"to",
"allow",
"lists",
"to",
"work",
"with",
"subscript",
"operators",
".",
"<pre",
"class",
"=",
"groovyTestCase",
">",
"def",
"list",
"=",
"[",
"2",
"3",
"]",
"list",
"[",
"0",
"]",
"=",
"1",
"assert",
"list",
"==",
"[",
... | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L7952-L7963 |
alkacon/opencms-core | src/org/opencms/flex/CmsFlexResponse.java | CmsFlexResponse.setHeaderList | private void setHeaderList(Map<String, List<String>> headers, String name, String value) {
List<String> values = new ArrayList<String>();
values.add(SET_HEADER + value);
headers.put(name, values);
} | java | private void setHeaderList(Map<String, List<String>> headers, String name, String value) {
List<String> values = new ArrayList<String>();
values.add(SET_HEADER + value);
headers.put(name, values);
} | [
"private",
"void",
"setHeaderList",
"(",
"Map",
"<",
"String",
",",
"List",
"<",
"String",
">",
">",
"headers",
",",
"String",
"name",
",",
"String",
"value",
")",
"{",
"List",
"<",
"String",
">",
"values",
"=",
"new",
"ArrayList",
"<",
"String",
">",
... | Helper method to set a value in the internal header list.
@param headers the headers to set the value in
@param name the name to set
@param value the value to set | [
"Helper",
"method",
"to",
"set",
"a",
"value",
"in",
"the",
"internal",
"header",
"list",
"."
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/flex/CmsFlexResponse.java#L1198-L1203 |
MorphiaOrg/morphia | morphia/src/main/java/dev/morphia/mapping/Mapper.java | Mapper.fromDBObject | @Deprecated
<T> T fromDBObject(final Datastore datastore, final DBObject dbObject) {
if (dbObject.containsField(opts.getDiscriminatorField())) {
T entity = opts.getObjectFactory().createInstance(null, dbObject);
entity = fromDb(datastore, dbObject, entity, createEntityCache());
return entity;
} else {
throw new MappingException(format("The DBObject does not contain a %s key. Determining entity type is impossible.",
opts.getDiscriminatorField()));
}
} | java | @Deprecated
<T> T fromDBObject(final Datastore datastore, final DBObject dbObject) {
if (dbObject.containsField(opts.getDiscriminatorField())) {
T entity = opts.getObjectFactory().createInstance(null, dbObject);
entity = fromDb(datastore, dbObject, entity, createEntityCache());
return entity;
} else {
throw new MappingException(format("The DBObject does not contain a %s key. Determining entity type is impossible.",
opts.getDiscriminatorField()));
}
} | [
"@",
"Deprecated",
"<",
"T",
">",
"T",
"fromDBObject",
"(",
"final",
"Datastore",
"datastore",
",",
"final",
"DBObject",
"dbObject",
")",
"{",
"if",
"(",
"dbObject",
".",
"containsField",
"(",
"opts",
".",
"getDiscriminatorField",
"(",
")",
")",
")",
"{",
... | Converts an entity (POJO) to a DBObject. A special field will be added to keep track of the class type.
@param datastore the Datastore to use when fetching this reference
@param dbObject the DBObject
@param <T> the type of the referenced entity
@return the entity
@morphia.internal
@deprecated no replacement is planned | [
"Converts",
"an",
"entity",
"(",
"POJO",
")",
"to",
"a",
"DBObject",
".",
"A",
"special",
"field",
"will",
"be",
"added",
"to",
"keep",
"track",
"of",
"the",
"class",
"type",
"."
] | train | https://github.com/MorphiaOrg/morphia/blob/667c30bdc7c6f1d9f2e2eb8774835d6137b52d12/morphia/src/main/java/dev/morphia/mapping/Mapper.java#L237-L248 |
ops4j/org.ops4j.base | ops4j-base-util/src/main/java/org/ops4j/util/i18n/ResourceManager.java | ResourceManager.getPackageResources | public static Resources getPackageResources( Class clazz, Locale locale )
{
return getBaseResources( getPackageResourcesBaseName( clazz ), locale, clazz.getClassLoader() );
} | java | public static Resources getPackageResources( Class clazz, Locale locale )
{
return getBaseResources( getPackageResourcesBaseName( clazz ), locale, clazz.getClassLoader() );
} | [
"public",
"static",
"Resources",
"getPackageResources",
"(",
"Class",
"clazz",
",",
"Locale",
"locale",
")",
"{",
"return",
"getBaseResources",
"(",
"getPackageResourcesBaseName",
"(",
"clazz",
")",
",",
"locale",
",",
"clazz",
".",
"getClassLoader",
"(",
")",
"... | Retrieve resource for specified Classes package.
The basename is determined by name of classes package
postfixed with ".Resources".
@param clazz the Class
@param locale the locale of the package resources requested.
@return the Resources | [
"Retrieve",
"resource",
"for",
"specified",
"Classes",
"package",
".",
"The",
"basename",
"is",
"determined",
"by",
"name",
"of",
"classes",
"package",
"postfixed",
"with",
".",
"Resources",
"."
] | train | https://github.com/ops4j/org.ops4j.base/blob/b0e742c0d9511f6b19ca64da2ebaf30b7a47256a/ops4j-base-util/src/main/java/org/ops4j/util/i18n/ResourceManager.java#L207-L210 |
nathanmarz/dfs-datastores | dfs-datastores-cascading/src/main/java/com/backtype/support/CascadingUtils.java | CascadingUtils.markSuccessfulOutputDir | public static void markSuccessfulOutputDir(Path path, JobConf conf) throws IOException {
FileSystem fs = FileSystem.get(conf);
// create a file in the folder to mark it
if (fs.exists(path)) {
Path filePath = new Path(path, VersionedStore.HADOOP_SUCCESS_FLAG);
fs.create(filePath).close();
}
} | java | public static void markSuccessfulOutputDir(Path path, JobConf conf) throws IOException {
FileSystem fs = FileSystem.get(conf);
// create a file in the folder to mark it
if (fs.exists(path)) {
Path filePath = new Path(path, VersionedStore.HADOOP_SUCCESS_FLAG);
fs.create(filePath).close();
}
} | [
"public",
"static",
"void",
"markSuccessfulOutputDir",
"(",
"Path",
"path",
",",
"JobConf",
"conf",
")",
"throws",
"IOException",
"{",
"FileSystem",
"fs",
"=",
"FileSystem",
".",
"get",
"(",
"conf",
")",
";",
"// create a file in the folder to mark it",
"if",
"(",... | Mark the output dir of the job for which the context is passed. | [
"Mark",
"the",
"output",
"dir",
"of",
"the",
"job",
"for",
"which",
"the",
"context",
"is",
"passed",
"."
] | train | https://github.com/nathanmarz/dfs-datastores/blob/ad2ce6d1ef748bab8444e81fa1617ab5e8b1a43e/dfs-datastores-cascading/src/main/java/com/backtype/support/CascadingUtils.java#L27-L34 |
pravega/pravega | client/src/main/java/io/pravega/client/stream/impl/ReaderGroupStateManager.java | ReaderGroupStateManager.handleEndOfSegment | boolean handleEndOfSegment(Segment segmentCompleted) throws ReaderNotInReaderGroupException {
final Map<Segment, List<Long>> segmentToPredecessor;
if (sync.getState().getEndSegments().containsKey(segmentCompleted)) {
segmentToPredecessor = Collections.emptyMap();
} else {
val successors = getAndHandleExceptions(controller.getSuccessors(segmentCompleted), RuntimeException::new);
segmentToPredecessor = successors.getSegmentToPredecessor();
}
AtomicBoolean reinitRequired = new AtomicBoolean(false);
boolean result = sync.updateState((state, updates) -> {
if (!state.isReaderOnline(readerId)) {
reinitRequired.set(true);
} else {
log.debug("Marking segment {} as completed in reader group. CurrentState is: {}", segmentCompleted, state);
reinitRequired.set(false);
//This check guards against another checkpoint having started.
if (state.getCheckpointForReader(readerId) == null) {
updates.add(new SegmentCompleted(readerId, segmentCompleted, segmentToPredecessor));
return true;
}
}
return false;
});
if (reinitRequired.get()) {
throw new ReaderNotInReaderGroupException(readerId);
}
acquireTimer.zero();
return result;
} | java | boolean handleEndOfSegment(Segment segmentCompleted) throws ReaderNotInReaderGroupException {
final Map<Segment, List<Long>> segmentToPredecessor;
if (sync.getState().getEndSegments().containsKey(segmentCompleted)) {
segmentToPredecessor = Collections.emptyMap();
} else {
val successors = getAndHandleExceptions(controller.getSuccessors(segmentCompleted), RuntimeException::new);
segmentToPredecessor = successors.getSegmentToPredecessor();
}
AtomicBoolean reinitRequired = new AtomicBoolean(false);
boolean result = sync.updateState((state, updates) -> {
if (!state.isReaderOnline(readerId)) {
reinitRequired.set(true);
} else {
log.debug("Marking segment {} as completed in reader group. CurrentState is: {}", segmentCompleted, state);
reinitRequired.set(false);
//This check guards against another checkpoint having started.
if (state.getCheckpointForReader(readerId) == null) {
updates.add(new SegmentCompleted(readerId, segmentCompleted, segmentToPredecessor));
return true;
}
}
return false;
});
if (reinitRequired.get()) {
throw new ReaderNotInReaderGroupException(readerId);
}
acquireTimer.zero();
return result;
} | [
"boolean",
"handleEndOfSegment",
"(",
"Segment",
"segmentCompleted",
")",
"throws",
"ReaderNotInReaderGroupException",
"{",
"final",
"Map",
"<",
"Segment",
",",
"List",
"<",
"Long",
">",
">",
"segmentToPredecessor",
";",
"if",
"(",
"sync",
".",
"getState",
"(",
... | Handles a segment being completed by calling the controller to gather all successors to the
completed segment. To ensure consistent checkpoints, a segment cannot be released while a
checkpoint for the reader is pending, so it may or may not succeed.
@return true if the completed segment was released successfully. | [
"Handles",
"a",
"segment",
"being",
"completed",
"by",
"calling",
"the",
"controller",
"to",
"gather",
"all",
"successors",
"to",
"the",
"completed",
"segment",
".",
"To",
"ensure",
"consistent",
"checkpoints",
"a",
"segment",
"cannot",
"be",
"released",
"while"... | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/client/src/main/java/io/pravega/client/stream/impl/ReaderGroupStateManager.java#L156-L185 |
ModeShape/modeshape | modeshape-jcr/src/main/java/org/modeshape/jcr/query/engine/process/CountableSequence.java | CountableSequence.loadAll | protected long loadAll( NodeSequence sequence,
QueueBuffer<BufferedRow> buffer,
AtomicLong batchSize ) {
return loadAll(sequence, buffer, batchSize, null, 0);
} | java | protected long loadAll( NodeSequence sequence,
QueueBuffer<BufferedRow> buffer,
AtomicLong batchSize ) {
return loadAll(sequence, buffer, batchSize, null, 0);
} | [
"protected",
"long",
"loadAll",
"(",
"NodeSequence",
"sequence",
",",
"QueueBuffer",
"<",
"BufferedRow",
">",
"buffer",
",",
"AtomicLong",
"batchSize",
")",
"{",
"return",
"loadAll",
"(",
"sequence",
",",
"buffer",
",",
"batchSize",
",",
"null",
",",
"0",
")... | Load all of the rows from the supplied sequence into the buffer.
@param sequence the node sequence; may not be null
@param buffer the buffer into which all rows should be loaded; may not be null
@param batchSize the atomic that should be set with the size of the first batch
@return the total number of rows | [
"Load",
"all",
"of",
"the",
"rows",
"from",
"the",
"supplied",
"sequence",
"into",
"the",
"buffer",
"."
] | train | https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-jcr/src/main/java/org/modeshape/jcr/query/engine/process/CountableSequence.java#L122-L126 |
NessComputing/components-ness-pg | src/main/java/com/nesscomputing/db/postgres/embedded/EmbeddedPostgreSQLController.java | EmbeddedPostgreSQLController.getCluster | private synchronized static Cluster getCluster(URI baseUrl, String[] personalities) throws IOException
{
final Entry<URI, Set<String>> key = Maps.immutableEntry(baseUrl, (Set<String>)ImmutableSet.copyOf(personalities));
Cluster result = CLUSTERS.get(key);
if (result != null) {
return result;
}
result = new Cluster(EmbeddedPostgreSQL.start());
final DBI dbi = new DBI(result.getPg().getTemplateDatabase());
final Migratory migratory = new Migratory(new MigratoryConfig() {}, dbi, dbi);
migratory.addLocator(new DatabasePreparerLocator(migratory, baseUrl));
final MigrationPlan plan = new MigrationPlan();
int priority = 100;
for (final String personality : personalities) {
plan.addMigration(personality, Integer.MAX_VALUE, priority--);
}
migratory.dbMigrate(plan);
result.start();
CLUSTERS.put(key, result);
return result;
} | java | private synchronized static Cluster getCluster(URI baseUrl, String[] personalities) throws IOException
{
final Entry<URI, Set<String>> key = Maps.immutableEntry(baseUrl, (Set<String>)ImmutableSet.copyOf(personalities));
Cluster result = CLUSTERS.get(key);
if (result != null) {
return result;
}
result = new Cluster(EmbeddedPostgreSQL.start());
final DBI dbi = new DBI(result.getPg().getTemplateDatabase());
final Migratory migratory = new Migratory(new MigratoryConfig() {}, dbi, dbi);
migratory.addLocator(new DatabasePreparerLocator(migratory, baseUrl));
final MigrationPlan plan = new MigrationPlan();
int priority = 100;
for (final String personality : personalities) {
plan.addMigration(personality, Integer.MAX_VALUE, priority--);
}
migratory.dbMigrate(plan);
result.start();
CLUSTERS.put(key, result);
return result;
} | [
"private",
"synchronized",
"static",
"Cluster",
"getCluster",
"(",
"URI",
"baseUrl",
",",
"String",
"[",
"]",
"personalities",
")",
"throws",
"IOException",
"{",
"final",
"Entry",
"<",
"URI",
",",
"Set",
"<",
"String",
">",
">",
"key",
"=",
"Maps",
".",
... | Each schema set has its own database cluster. The template1 database has the schema preloaded so that
each test case need only create a new database and not re-invoke Migratory. | [
"Each",
"schema",
"set",
"has",
"its",
"own",
"database",
"cluster",
".",
"The",
"template1",
"database",
"has",
"the",
"schema",
"preloaded",
"so",
"that",
"each",
"test",
"case",
"need",
"only",
"create",
"a",
"new",
"database",
"and",
"not",
"re",
"-",
... | train | https://github.com/NessComputing/components-ness-pg/blob/e983d6075645ea1bf51cc5fc16901e5aab0f5c70/src/main/java/com/nesscomputing/db/postgres/embedded/EmbeddedPostgreSQLController.java#L77-L105 |
PeterisP/LVTagger | src/main/java/edu/stanford/nlp/classify/LogConditionalObjectiveFunction.java | LogConditionalObjectiveFunction.calculateStochastic | @Override
public void calculateStochastic(double[] x, double[] v, int[] batch){
if(method.calculatesHessianVectorProduct() && v != null){
// This is used for Stochastic Methods that involve second order information (SMD for example)
if(method.equals(StochasticCalculateMethods.AlgorithmicDifferentiation)){
calculateStochasticAlgorithmicDifferentiation(x,v,batch);
}else if(method.equals(StochasticCalculateMethods.IncorporatedFiniteDifference)){
calculateStochasticFiniteDifference(x,v,finiteDifferenceStepSize,batch);
}
} else{
//This is used for Stochastic Methods that don't need anything but the gradient (SGD)
calculateStochasticGradientOnly(x,batch);
}
} | java | @Override
public void calculateStochastic(double[] x, double[] v, int[] batch){
if(method.calculatesHessianVectorProduct() && v != null){
// This is used for Stochastic Methods that involve second order information (SMD for example)
if(method.equals(StochasticCalculateMethods.AlgorithmicDifferentiation)){
calculateStochasticAlgorithmicDifferentiation(x,v,batch);
}else if(method.equals(StochasticCalculateMethods.IncorporatedFiniteDifference)){
calculateStochasticFiniteDifference(x,v,finiteDifferenceStepSize,batch);
}
} else{
//This is used for Stochastic Methods that don't need anything but the gradient (SGD)
calculateStochasticGradientOnly(x,batch);
}
} | [
"@",
"Override",
"public",
"void",
"calculateStochastic",
"(",
"double",
"[",
"]",
"x",
",",
"double",
"[",
"]",
"v",
",",
"int",
"[",
"]",
"batch",
")",
"{",
"if",
"(",
"method",
".",
"calculatesHessianVectorProduct",
"(",
")",
"&&",
"v",
"!=",
"null"... | /*
This function is used to comme up with an estimate of the value / gradient based on only a small
portion of the data (refered to as the batchSize for lack of a better term. In this case batch does
not mean All!! It should be thought of in the sense of "a small batch of the data". | [
"/",
"*",
"This",
"function",
"is",
"used",
"to",
"comme",
"up",
"with",
"an",
"estimate",
"of",
"the",
"value",
"/",
"gradient",
"based",
"on",
"only",
"a",
"small",
"portion",
"of",
"the",
"data",
"(",
"refered",
"to",
"as",
"the",
"batchSize",
"for"... | train | https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/classify/LogConditionalObjectiveFunction.java#L115-L130 |
ben-manes/caffeine | caffeine/src/main/java/com/github/benmanes/caffeine/base/UnsafeAccess.java | UnsafeAccess.objectFieldOffset | public static long objectFieldOffset(Class<?> clazz, String fieldName) {
try {
return UNSAFE.objectFieldOffset(clazz.getDeclaredField(fieldName));
} catch (NoSuchFieldException | SecurityException e) {
throw new Error(e);
}
} | java | public static long objectFieldOffset(Class<?> clazz, String fieldName) {
try {
return UNSAFE.objectFieldOffset(clazz.getDeclaredField(fieldName));
} catch (NoSuchFieldException | SecurityException e) {
throw new Error(e);
}
} | [
"public",
"static",
"long",
"objectFieldOffset",
"(",
"Class",
"<",
"?",
">",
"clazz",
",",
"String",
"fieldName",
")",
"{",
"try",
"{",
"return",
"UNSAFE",
".",
"objectFieldOffset",
"(",
"clazz",
".",
"getDeclaredField",
"(",
"fieldName",
")",
")",
";",
"... | Returns the location of a given static field.
@param clazz the class containing the field
@param fieldName the name of the field
@return the address offset of the field | [
"Returns",
"the",
"location",
"of",
"a",
"given",
"static",
"field",
"."
] | train | https://github.com/ben-manes/caffeine/blob/4cf6d6e6a18ea2e8088f166261e5949343b0f2eb/caffeine/src/main/java/com/github/benmanes/caffeine/base/UnsafeAccess.java#L55-L61 |
VoltDB/voltdb | src/frontend/org/voltdb/jdbc/JDBC4PreparedStatement.java | JDBC4PreparedStatement.setURL | @Override
public void setURL(int parameterIndex, URL x) throws SQLException
{
checkParameterBounds(parameterIndex);
this.parameters[parameterIndex-1] = x == null ? VoltType.NULL_STRING_OR_VARBINARY : x.toString();
} | java | @Override
public void setURL(int parameterIndex, URL x) throws SQLException
{
checkParameterBounds(parameterIndex);
this.parameters[parameterIndex-1] = x == null ? VoltType.NULL_STRING_OR_VARBINARY : x.toString();
} | [
"@",
"Override",
"public",
"void",
"setURL",
"(",
"int",
"parameterIndex",
",",
"URL",
"x",
")",
"throws",
"SQLException",
"{",
"checkParameterBounds",
"(",
"parameterIndex",
")",
";",
"this",
".",
"parameters",
"[",
"parameterIndex",
"-",
"1",
"]",
"=",
"x"... | Sets the designated parameter to the given java.net.URL value. | [
"Sets",
"the",
"designated",
"parameter",
"to",
"the",
"given",
"java",
".",
"net",
".",
"URL",
"value",
"."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/jdbc/JDBC4PreparedStatement.java#L599-L604 |
amaembo/streamex | src/main/java/one/util/streamex/StreamEx.java | StreamEx.zipWith | public <V, R> StreamEx<R> zipWith(Stream<V> other, BiFunction<? super T, ? super V, ? extends R> mapper) {
return zipWith((BaseStream<V, ?>) other, mapper);
} | java | public <V, R> StreamEx<R> zipWith(Stream<V> other, BiFunction<? super T, ? super V, ? extends R> mapper) {
return zipWith((BaseStream<V, ?>) other, mapper);
} | [
"public",
"<",
"V",
",",
"R",
">",
"StreamEx",
"<",
"R",
">",
"zipWith",
"(",
"Stream",
"<",
"V",
">",
"other",
",",
"BiFunction",
"<",
"?",
"super",
"T",
",",
"?",
"super",
"V",
",",
"?",
"extends",
"R",
">",
"mapper",
")",
"{",
"return",
"zip... | Creates a new {@link StreamEx} which is the result of applying of the
mapper {@code BiFunction} to the corresponding elements of this stream
and the supplied other stream. The resulting stream is ordered if both of
the input streams are ordered, and parallel if either of the input
streams is parallel. When the resulting stream is closed, the close
handlers for both input streams are invoked.
<p>
This is a <a href="package-summary.html#StreamOps">quasi-intermediate
operation</a>.
<p>
The resulting stream finishes when either of the input streams finish:
the rest of the longer stream is discarded. It's unspecified whether the
rest elements of the longer stream are actually consumed.
<p>
The stream created by this operation may have poor characteristics and
parallelize badly, so it should be used only when there's no other
choice. If both input streams are random-access lists or arrays, consider
using {@link #zip(List, List, BiFunction)} or
{@link #zip(Object[], Object[], BiFunction)} respectively. If you want to
zip the stream with the stream of indices, consider using
{@link EntryStream#of(List)} instead.
@param <V> the type of the other stream elements
@param <R> the type of the resulting stream elements
@param other the stream to zip this stream with
@param mapper a non-interfering, stateless function to apply to the
corresponding pairs of this stream and other stream elements
@return the new stream
@since 0.5.5
@see #zipWith(Stream) | [
"Creates",
"a",
"new",
"{",
"@link",
"StreamEx",
"}",
"which",
"is",
"the",
"result",
"of",
"applying",
"of",
"the",
"mapper",
"{",
"@code",
"BiFunction",
"}",
"to",
"the",
"corresponding",
"elements",
"of",
"this",
"stream",
"and",
"the",
"supplied",
"oth... | train | https://github.com/amaembo/streamex/blob/936bbd1b7dfbcf64a3b990682bfc848213441d14/src/main/java/one/util/streamex/StreamEx.java#L1838-L1840 |
lionsoul2014/jcseg | jcseg-core/src/main/java/org/lionsoul/jcseg/util/IIntFIFO.java | IIntFIFO.enQueue | public boolean enQueue( int data )
{
Entry o = new Entry(data, head.next);
head.next = o;
size++;
return true;
} | java | public boolean enQueue( int data )
{
Entry o = new Entry(data, head.next);
head.next = o;
size++;
return true;
} | [
"public",
"boolean",
"enQueue",
"(",
"int",
"data",
")",
"{",
"Entry",
"o",
"=",
"new",
"Entry",
"(",
"data",
",",
"head",
".",
"next",
")",
";",
"head",
".",
"next",
"=",
"o",
";",
"size",
"++",
";",
"return",
"true",
";",
"}"
] | add a new item to the queue
@param data
@return boolean | [
"add",
"a",
"new",
"item",
"to",
"the",
"queue"
] | train | https://github.com/lionsoul2014/jcseg/blob/7c8a912e3bbcaf4f8de701180b9c24e2e444a94b/jcseg-core/src/main/java/org/lionsoul/jcseg/util/IIntFIFO.java#L28-L35 |
Azure/azure-sdk-for-java | containerregistry/resource-manager/v2017_06_01_preview/src/main/java/com/microsoft/azure/management/containerregistry/v2017_06_01_preview/implementation/ReplicationsInner.java | ReplicationsInner.createAsync | public Observable<ReplicationInner> createAsync(String resourceGroupName, String registryName, String replicationName, ReplicationInner replication) {
return createWithServiceResponseAsync(resourceGroupName, registryName, replicationName, replication).map(new Func1<ServiceResponse<ReplicationInner>, ReplicationInner>() {
@Override
public ReplicationInner call(ServiceResponse<ReplicationInner> response) {
return response.body();
}
});
} | java | public Observable<ReplicationInner> createAsync(String resourceGroupName, String registryName, String replicationName, ReplicationInner replication) {
return createWithServiceResponseAsync(resourceGroupName, registryName, replicationName, replication).map(new Func1<ServiceResponse<ReplicationInner>, ReplicationInner>() {
@Override
public ReplicationInner call(ServiceResponse<ReplicationInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"ReplicationInner",
">",
"createAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"registryName",
",",
"String",
"replicationName",
",",
"ReplicationInner",
"replication",
")",
"{",
"return",
"createWithServiceResponseAsync",
"(",
"... | Creates a replication for a container registry with the specified parameters.
@param resourceGroupName The name of the resource group to which the container registry belongs.
@param registryName The name of the container registry.
@param replicationName The name of the replication.
@param replication The parameters for creating a replication.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request | [
"Creates",
"a",
"replication",
"for",
"a",
"container",
"registry",
"with",
"the",
"specified",
"parameters",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/containerregistry/resource-manager/v2017_06_01_preview/src/main/java/com/microsoft/azure/management/containerregistry/v2017_06_01_preview/implementation/ReplicationsInner.java#L239-L246 |
algolia/instantsearch-android | ui/src/main/java/com/algolia/instantsearch/ui/databinding/BindingHelper.java | BindingHelper.setVariantForView | @Nullable
public static String setVariantForView(@NonNull View view, @NonNull AttributeSet attrs) {
String previousVariant;
final TypedArray styledAttributes = view.getContext().getTheme()
.obtainStyledAttributes(attrs, R.styleable.View, 0, 0);
try {
previousVariant = setVariantForView(view, styledAttributes
.getString(R.styleable.View_variant));
} finally {
styledAttributes.recycle();
}
return previousVariant;
} | java | @Nullable
public static String setVariantForView(@NonNull View view, @NonNull AttributeSet attrs) {
String previousVariant;
final TypedArray styledAttributes = view.getContext().getTheme()
.obtainStyledAttributes(attrs, R.styleable.View, 0, 0);
try {
previousVariant = setVariantForView(view, styledAttributes
.getString(R.styleable.View_variant));
} finally {
styledAttributes.recycle();
}
return previousVariant;
} | [
"@",
"Nullable",
"public",
"static",
"String",
"setVariantForView",
"(",
"@",
"NonNull",
"View",
"view",
",",
"@",
"NonNull",
"AttributeSet",
"attrs",
")",
"{",
"String",
"previousVariant",
";",
"final",
"TypedArray",
"styledAttributes",
"=",
"view",
".",
"getCo... | Associates programmatically a view with its variant, taking it from its `variant` layout attribute.
@param view any existing view.
@param attrs the view's AttributeSet.
@return the previous variant for this view, if any. | [
"Associates",
"programmatically",
"a",
"view",
"with",
"its",
"variant",
"taking",
"it",
"from",
"its",
"variant",
"layout",
"attribute",
"."
] | train | https://github.com/algolia/instantsearch-android/blob/12092ec30140df9ffc2bf916339b433372034616/ui/src/main/java/com/algolia/instantsearch/ui/databinding/BindingHelper.java#L98-L111 |
sonyxperiadev/gerrit-events | src/main/java/com/sonymobile/tools/gerrit/gerritevents/GerritQueryHandler.java | GerritQueryHandler.queryJson | public List<String> queryJson(String queryString) throws SshException, IOException {
return queryJson(queryString, true, true, false, false);
} | java | public List<String> queryJson(String queryString) throws SshException, IOException {
return queryJson(queryString, true, true, false, false);
} | [
"public",
"List",
"<",
"String",
">",
"queryJson",
"(",
"String",
"queryString",
")",
"throws",
"SshException",
",",
"IOException",
"{",
"return",
"queryJson",
"(",
"queryString",
",",
"true",
",",
"true",
",",
"false",
",",
"false",
")",
";",
"}"
] | Runs the query and returns the result as a list of JSON formatted strings.
This is the equivalent of calling queryJava(queryString, true, true, false, false).
@param queryString the query.
@return a List of JSON formatted strings.
@throws SshException if there is an error in the SSH Connection.
@throws IOException for some other IO problem. | [
"Runs",
"the",
"query",
"and",
"returns",
"the",
"result",
"as",
"a",
"list",
"of",
"JSON",
"formatted",
"strings",
".",
"This",
"is",
"the",
"equivalent",
"of",
"calling",
"queryJava",
"(",
"queryString",
"true",
"true",
"false",
"false",
")",
"."
] | train | https://github.com/sonyxperiadev/gerrit-events/blob/9a443d13dded85cc4709136ac33989f2bbb34fe2/src/main/java/com/sonymobile/tools/gerrit/gerritevents/GerritQueryHandler.java#L271-L273 |
ineunetOS/knife-commons | knife-commons-utils/src/main/java/com/ineunet/knife/util/StringUtils.java | StringUtils.endsWithAny | public static boolean endsWithAny(String string, String[] searchStrings) {
if (isEmpty(string) || ArrayUtils.isEmpty(searchStrings)) {
return false;
}
for (int i = 0; i < searchStrings.length; i++) {
String searchString = searchStrings[i];
if (StringUtils.endsWith(string, searchString)) {
return true;
}
}
return false;
} | java | public static boolean endsWithAny(String string, String[] searchStrings) {
if (isEmpty(string) || ArrayUtils.isEmpty(searchStrings)) {
return false;
}
for (int i = 0; i < searchStrings.length; i++) {
String searchString = searchStrings[i];
if (StringUtils.endsWith(string, searchString)) {
return true;
}
}
return false;
} | [
"public",
"static",
"boolean",
"endsWithAny",
"(",
"String",
"string",
",",
"String",
"[",
"]",
"searchStrings",
")",
"{",
"if",
"(",
"isEmpty",
"(",
"string",
")",
"||",
"ArrayUtils",
".",
"isEmpty",
"(",
"searchStrings",
")",
")",
"{",
"return",
"false",... | <p>Check if a String ends with any of an array of specified strings.</p>
<pre>
StringUtils.endsWithAny(null, null) = false
StringUtils.endsWithAny(null, new String[] {"abc"}) = false
StringUtils.endsWithAny("abcxyz", null) = false
StringUtils.endsWithAny("abcxyz", new String[] {""}) = true
StringUtils.endsWithAny("abcxyz", new String[] {"xyz"}) = true
StringUtils.endsWithAny("abcxyz", new String[] {null, "xyz", "abc"}) = true
</pre>
@param string the String to check, may be null
@param searchStrings the Strings to find, may be null or empty
@return <code>true</code> if the String ends with any of the the prefixes, case insensitive, or
both <code>null</code>
@since 2.6 | [
"<p",
">",
"Check",
"if",
"a",
"String",
"ends",
"with",
"any",
"of",
"an",
"array",
"of",
"specified",
"strings",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/ineunetOS/knife-commons/blob/eae9e59afa020a00ae8977c10d43ac8ae46ae236/knife-commons-utils/src/main/java/com/ineunet/knife/util/StringUtils.java#L6442-L6453 |
OpenLiberty/open-liberty | dev/com.ibm.ws.logging.hpel/src/com/ibm/ws/logging/hpel/handlers/LogRepositoryConfiguration.java | LogRepositoryConfiguration.setTraceMemory | public void setTraceMemory(String dataDirectory, long memoryBufferSize) {
TraceState state = (TraceState)ivTrace.clone();
state.ivStorageType = MEMORYBUFFER_TYPE;
state.ivDataDirectory = dataDirectory;
state.ivMemoryBufferSize = memoryBufferSize;
updateTraceConfiguration(state);
state.copyTo(ivTrace);
} | java | public void setTraceMemory(String dataDirectory, long memoryBufferSize) {
TraceState state = (TraceState)ivTrace.clone();
state.ivStorageType = MEMORYBUFFER_TYPE;
state.ivDataDirectory = dataDirectory;
state.ivMemoryBufferSize = memoryBufferSize;
updateTraceConfiguration(state);
state.copyTo(ivTrace);
} | [
"public",
"void",
"setTraceMemory",
"(",
"String",
"dataDirectory",
",",
"long",
"memoryBufferSize",
")",
"{",
"TraceState",
"state",
"=",
"(",
"TraceState",
")",
"ivTrace",
".",
"clone",
"(",
")",
";",
"state",
".",
"ivStorageType",
"=",
"MEMORYBUFFER_TYPE",
... | Modify the trace to use a memory buffer
@param dataDirectory directory where buffer will be dumped if requested
@param memoryBufferSize amount of memory (in Mb) to be used for this circular buffer | [
"Modify",
"the",
"trace",
"to",
"use",
"a",
"memory",
"buffer"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.logging.hpel/src/com/ibm/ws/logging/hpel/handlers/LogRepositoryConfiguration.java#L436-L445 |
biojava/biojava | biojava-structure/src/main/java/org/biojava/nbio/structure/AtomPositionMap.java | AtomPositionMap.getLength | public int getLength(int positionA, int positionB, String startingChain) {
int positionStart, positionEnd;
if (positionA <= positionB) {
positionStart = positionA;
positionEnd = positionB;
} else {
positionStart = positionB;
positionEnd = positionA;
}
int count = 0;
// Inefficient search
for (Map.Entry<ResidueNumber, Integer> entry : treeMap.entrySet()) {
if (entry.getKey().getChainName().equals(startingChain)
&& positionStart <= entry.getValue()
&& entry.getValue() <= positionEnd)
{
count++;
}
}
return count;
} | java | public int getLength(int positionA, int positionB, String startingChain) {
int positionStart, positionEnd;
if (positionA <= positionB) {
positionStart = positionA;
positionEnd = positionB;
} else {
positionStart = positionB;
positionEnd = positionA;
}
int count = 0;
// Inefficient search
for (Map.Entry<ResidueNumber, Integer> entry : treeMap.entrySet()) {
if (entry.getKey().getChainName().equals(startingChain)
&& positionStart <= entry.getValue()
&& entry.getValue() <= positionEnd)
{
count++;
}
}
return count;
} | [
"public",
"int",
"getLength",
"(",
"int",
"positionA",
",",
"int",
"positionB",
",",
"String",
"startingChain",
")",
"{",
"int",
"positionStart",
",",
"positionEnd",
";",
"if",
"(",
"positionA",
"<=",
"positionB",
")",
"{",
"positionStart",
"=",
"positionA",
... | Calculates the number of residues of the specified chain in a given range, inclusive.
@param positionA index of the first atom to count
@param positionB index of the last atom to count
@param startingChain Case-sensitive chain
@return The number of atoms between A and B inclusive belonging to the given chain | [
"Calculates",
"the",
"number",
"of",
"residues",
"of",
"the",
"specified",
"chain",
"in",
"a",
"given",
"range",
"inclusive",
"."
] | train | https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/AtomPositionMap.java#L187-L209 |
lessthanoptimal/ejml | main/ejml-ddense/src/org/ejml/dense/fixed/CommonOps_DDF2.java | CommonOps_DDF2.multTransAB | public static void multTransAB( double alpha , DMatrix2x2 a , DMatrix2x2 b , DMatrix2x2 c) {
c.a11 = alpha*(a.a11*b.a11 + a.a21*b.a12);
c.a12 = alpha*(a.a11*b.a21 + a.a21*b.a22);
c.a21 = alpha*(a.a12*b.a11 + a.a22*b.a12);
c.a22 = alpha*(a.a12*b.a21 + a.a22*b.a22);
} | java | public static void multTransAB( double alpha , DMatrix2x2 a , DMatrix2x2 b , DMatrix2x2 c) {
c.a11 = alpha*(a.a11*b.a11 + a.a21*b.a12);
c.a12 = alpha*(a.a11*b.a21 + a.a21*b.a22);
c.a21 = alpha*(a.a12*b.a11 + a.a22*b.a12);
c.a22 = alpha*(a.a12*b.a21 + a.a22*b.a22);
} | [
"public",
"static",
"void",
"multTransAB",
"(",
"double",
"alpha",
",",
"DMatrix2x2",
"a",
",",
"DMatrix2x2",
"b",
",",
"DMatrix2x2",
"c",
")",
"{",
"c",
".",
"a11",
"=",
"alpha",
"*",
"(",
"a",
".",
"a11",
"*",
"b",
".",
"a11",
"+",
"a",
".",
"a... | <p>
Performs the following operation:<br>
<br>
c = α*a<sup>T</sup> * b<sup>T</sup><br>
c<sub>ij</sub> = α*∑<sub>k=1:n</sub> { a<sub>ki</sub> * b<sub>jk</sub>}
</p>
@param alpha 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",
"=",
"&alpha",
";",
"*",
"a<sup",
">",
"T<",
"/",
"sup",
">",
"*",
"b<sup",
">",
"T<",
"/",
"sup",
">",
"<br",
">",
"c<sub",
">",
"ij<",
"/",
"sub",
">",
... | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/fixed/CommonOps_DDF2.java#L325-L330 |
clanie/clanie-core | src/main/java/dk/clanie/collections/NumberMap.java | NumberMap.newIntegerMap | public static <K> NumberMap<K, Integer> newIntegerMap() {
return new NumberMap<K, Integer>() {
@Override
public void add(K key, Integer addend) {
put(key, containsKey(key) ? (get(key) + addend) : addend);
}
@Override
public void sub(K key, Integer subtrahend) {
put(key, (containsKey(key) ? get(key) : 0) - subtrahend);
}
};
} | java | public static <K> NumberMap<K, Integer> newIntegerMap() {
return new NumberMap<K, Integer>() {
@Override
public void add(K key, Integer addend) {
put(key, containsKey(key) ? (get(key) + addend) : addend);
}
@Override
public void sub(K key, Integer subtrahend) {
put(key, (containsKey(key) ? get(key) : 0) - subtrahend);
}
};
} | [
"public",
"static",
"<",
"K",
">",
"NumberMap",
"<",
"K",
",",
"Integer",
">",
"newIntegerMap",
"(",
")",
"{",
"return",
"new",
"NumberMap",
"<",
"K",
",",
"Integer",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"add",
"(",
"K",
"key",
",... | Creates a NumberMap for Integers.
@param <K>
@return NumberMap<K, Integer> | [
"Creates",
"a",
"NumberMap",
"for",
"Integers",
"."
] | train | https://github.com/clanie/clanie-core/blob/ac8a655b93127f0e281b741c4d53f429be2816ad/src/main/java/dk/clanie/collections/NumberMap.java#L172-L183 |
shrinkwrap/resolver | api/src/main/java/org/jboss/shrinkwrap/resolver/api/ResolverSystemFactory.java | ResolverSystemFactory.createFromUserView | static <RESOLVERSYSTEMTYPE extends ResolverSystem> RESOLVERSYSTEMTYPE createFromUserView(
final Class<RESOLVERSYSTEMTYPE> userViewClass) throws IllegalArgumentException {
return createFromUserView(userViewClass, SecurityActions.getThreadContextClassLoader());
} | java | static <RESOLVERSYSTEMTYPE extends ResolverSystem> RESOLVERSYSTEMTYPE createFromUserView(
final Class<RESOLVERSYSTEMTYPE> userViewClass) throws IllegalArgumentException {
return createFromUserView(userViewClass, SecurityActions.getThreadContextClassLoader());
} | [
"static",
"<",
"RESOLVERSYSTEMTYPE",
"extends",
"ResolverSystem",
">",
"RESOLVERSYSTEMTYPE",
"createFromUserView",
"(",
"final",
"Class",
"<",
"RESOLVERSYSTEMTYPE",
">",
"userViewClass",
")",
"throws",
"IllegalArgumentException",
"{",
"return",
"createFromUserView",
"(",
... | Creates a new {@link ResolverSystem} instance of the specified user view type using the {@link Thread} Context
{@link ClassLoader}. Will consult a configuration file visible to the {@link Thread} Context {@link ClassLoader} named
"META-INF/services/$fullyQualfiedClassName" which should contain a key=value format with the key
{@link ResolverSystemFactory#KEY_IMPL_CLASS_NAME}. The implementation class name must have a no-arg constructor.
@param userViewClass The user view type
@return The new {@link ResolverSystem} instance of the specified user view type created by using the {@link Thread}
Context {@link ClassLoader}.
@throws IllegalArgumentException
If the user view class was not specified | [
"Creates",
"a",
"new",
"{",
"@link",
"ResolverSystem",
"}",
"instance",
"of",
"the",
"specified",
"user",
"view",
"type",
"using",
"the",
"{",
"@link",
"Thread",
"}",
"Context",
"{",
"@link",
"ClassLoader",
"}",
".",
"Will",
"consult",
"a",
"configuration",
... | train | https://github.com/shrinkwrap/resolver/blob/e881a84b8cff5b0a014f2a5ebf612be3eb9db01f/api/src/main/java/org/jboss/shrinkwrap/resolver/api/ResolverSystemFactory.java#L52-L55 |
ngageoint/geopackage-android-map | geopackage-map/src/main/java/mil/nga/geopackage/map/features/FeatureInfoBuilder.java | FeatureInfoBuilder.buildTableDataAndClose | public FeatureTableData buildTableDataAndClose(FeatureIndexResults results, double tolerance, LatLng clickLocation) {
return buildTableDataAndClose(results, tolerance, clickLocation, null);
} | java | public FeatureTableData buildTableDataAndClose(FeatureIndexResults results, double tolerance, LatLng clickLocation) {
return buildTableDataAndClose(results, tolerance, clickLocation, null);
} | [
"public",
"FeatureTableData",
"buildTableDataAndClose",
"(",
"FeatureIndexResults",
"results",
",",
"double",
"tolerance",
",",
"LatLng",
"clickLocation",
")",
"{",
"return",
"buildTableDataAndClose",
"(",
"results",
",",
"tolerance",
",",
"clickLocation",
",",
"null",
... | Build a feature results information message
@param results feature index results
@param tolerance distance tolerance
@param clickLocation map click location
@return feature table data or null if not results | [
"Build",
"a",
"feature",
"results",
"information",
"message"
] | train | https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/features/FeatureInfoBuilder.java#L444-L446 |
SpartaTech/sparta-spring-web-utils | src/main/java/org/sparta/springwebutils/property/PropertiesLoaderBuilder.java | PropertiesLoaderBuilder.addProperty | public PropertiesLoaderBuilder addProperty(String name, String value) {
props.put(name, value);
return this;
} | java | public PropertiesLoaderBuilder addProperty(String name, String value) {
props.put(name, value);
return this;
} | [
"public",
"PropertiesLoaderBuilder",
"addProperty",
"(",
"String",
"name",
",",
"String",
"value",
")",
"{",
"props",
".",
"put",
"(",
"name",
",",
"value",
")",
";",
"return",
"this",
";",
"}"
] | Adds a new property. Giving both name and value.
This methods does not lookup in the Spring Context, it only adds property and value as given.
@param name to be added in the properties
@param value to be added in the properties
@return PropertyLoaderBuilder to continue the builder chain | [
"Adds",
"a",
"new",
"property",
".",
"Giving",
"both",
"name",
"and",
"value",
".",
"This",
"methods",
"does",
"not",
"lookup",
"in",
"the",
"Spring",
"Context",
"it",
"only",
"adds",
"property",
"and",
"value",
"as",
"given",
"."
] | train | https://github.com/SpartaTech/sparta-spring-web-utils/blob/f5382474d46a6048d58707fc64e7936277e8b2ce/src/main/java/org/sparta/springwebutils/property/PropertiesLoaderBuilder.java#L58-L61 |
aol/micro-server | micro-s3/src/main/java/com/oath/micro/server/s3/data/S3Utils.java | S3Utils.getInputStream | @Deprecated
public InputStream getInputStream(String bucketName, String key, Supplier<File> tempFileSupplier) throws AmazonServiceException, AmazonClientException, InterruptedException, IOException{
return readUtils.getInputStream(bucketName, key, tempFileSupplier);
} | java | @Deprecated
public InputStream getInputStream(String bucketName, String key, Supplier<File> tempFileSupplier) throws AmazonServiceException, AmazonClientException, InterruptedException, IOException{
return readUtils.getInputStream(bucketName, key, tempFileSupplier);
} | [
"@",
"Deprecated",
"public",
"InputStream",
"getInputStream",
"(",
"String",
"bucketName",
",",
"String",
"key",
",",
"Supplier",
"<",
"File",
">",
"tempFileSupplier",
")",
"throws",
"AmazonServiceException",
",",
"AmazonClientException",
",",
"InterruptedException",
... | Method returns InputStream from S3Object. Multi-part download is used to
get file. s3.tmp.dir property used to store temporary files. You can
specify temporary file name by using tempFileSupplier object.
@param bucketName
@param key
-
@param tempFileSupplier
- Supplier providing temporary filenames
@return InputStream of
@throws AmazonServiceException
@throws AmazonClientException
@throws InterruptedException
@throws IOException
@deprecated see ReadUtils | [
"Method",
"returns",
"InputStream",
"from",
"S3Object",
".",
"Multi",
"-",
"part",
"download",
"is",
"used",
"to",
"get",
"file",
".",
"s3",
".",
"tmp",
".",
"dir",
"property",
"used",
"to",
"store",
"temporary",
"files",
".",
"You",
"can",
"specify",
"t... | train | https://github.com/aol/micro-server/blob/5c7103c5b43d2f4d16350dbd2f9802af307c63f7/micro-s3/src/main/java/com/oath/micro/server/s3/data/S3Utils.java#L193-L196 |
operasoftware/operaprestodriver | src/com/opera/core/systems/internal/StackHashMap.java | StackHashMap.putIfAbsent | public V putIfAbsent(K k, V v) {
synchronized (map) {
if (!containsKey(k)) {
list.addFirst(k);
return map.put(k, v);
} else {
list.remove(k);
}
list.addFirst(k);
return null;
}
} | java | public V putIfAbsent(K k, V v) {
synchronized (map) {
if (!containsKey(k)) {
list.addFirst(k);
return map.put(k, v);
} else {
list.remove(k);
}
list.addFirst(k);
return null;
}
} | [
"public",
"V",
"putIfAbsent",
"(",
"K",
"k",
",",
"V",
"v",
")",
"{",
"synchronized",
"(",
"map",
")",
"{",
"if",
"(",
"!",
"containsKey",
"(",
"k",
")",
")",
"{",
"list",
".",
"addFirst",
"(",
"k",
")",
";",
"return",
"map",
".",
"put",
"(",
... | Puts a key to top of the map if absent if the key is present in stack it is removed
@return the value if it is not contained, null otherwise | [
"Puts",
"a",
"key",
"to",
"top",
"of",
"the",
"map",
"if",
"absent",
"if",
"the",
"key",
"is",
"present",
"in",
"stack",
"it",
"is",
"removed"
] | train | https://github.com/operasoftware/operaprestodriver/blob/1ccceda80f1c1a0489171d17dcaa6e7b18fb4c01/src/com/opera/core/systems/internal/StackHashMap.java#L168-L179 |
gallandarakhneorg/afc | advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/location/GeoLocationUtil.java | GeoLocationUtil.epsilonCompareToDistance | @Pure
public static int epsilonCompareToDistance(double distance1, double distance2) {
final double min = distance2 - distancePrecision;
final double max = distance2 + distancePrecision;
if (distance1 >= min && distance1 <= max) {
return 0;
}
if (distance1 < min) {
return -1;
}
return 1;
} | java | @Pure
public static int epsilonCompareToDistance(double distance1, double distance2) {
final double min = distance2 - distancePrecision;
final double max = distance2 + distancePrecision;
if (distance1 >= min && distance1 <= max) {
return 0;
}
if (distance1 < min) {
return -1;
}
return 1;
} | [
"@",
"Pure",
"public",
"static",
"int",
"epsilonCompareToDistance",
"(",
"double",
"distance1",
",",
"double",
"distance2",
")",
"{",
"final",
"double",
"min",
"=",
"distance2",
"-",
"distancePrecision",
";",
"final",
"double",
"max",
"=",
"distance2",
"+",
"d... | Replies if the specified distances are approximatively equal,
less or greater than.
@param distance1 the first distance.
@param distance2 the second distance.
@return a negative value if the parameter <var>distance1</var> is
lower than <var>distance2</var>, a positive if <var>distance1</var>
is greater than <var>distance2</var>, zero if the two parameters
are approximatively equal. | [
"Replies",
"if",
"the",
"specified",
"distances",
"are",
"approximatively",
"equal",
"less",
"or",
"greater",
"than",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/location/GeoLocationUtil.java#L177-L188 |
WhereIsMyTransport/TransportApiSdk.Java | transportapisdk/src/main/java/transportapisdk/TransportApiClient.java | TransportApiClient.getLinesNearby | public TransportApiResult<List<Line>> getLinesNearby(LineQueryOptions options, double latitude, double longitude, int radiusInMeters)
{
if (options == null)
{
options = LineQueryOptions.defaultQueryOptions();
}
if (radiusInMeters < 0)
{
throw new IllegalArgumentException("Invalid limit. Valid values are positive numbers only.");
}
return TransportApiClientCalls.getLines(tokenComponent, settings, options, new Point(longitude, latitude), radiusInMeters, null);
} | java | public TransportApiResult<List<Line>> getLinesNearby(LineQueryOptions options, double latitude, double longitude, int radiusInMeters)
{
if (options == null)
{
options = LineQueryOptions.defaultQueryOptions();
}
if (radiusInMeters < 0)
{
throw new IllegalArgumentException("Invalid limit. Valid values are positive numbers only.");
}
return TransportApiClientCalls.getLines(tokenComponent, settings, options, new Point(longitude, latitude), radiusInMeters, null);
} | [
"public",
"TransportApiResult",
"<",
"List",
"<",
"Line",
">",
">",
"getLinesNearby",
"(",
"LineQueryOptions",
"options",
",",
"double",
"latitude",
",",
"double",
"longitude",
",",
"int",
"radiusInMeters",
")",
"{",
"if",
"(",
"options",
"==",
"null",
")",
... | Gets a list of lines nearby ordered by distance from the point specified.
@param options Options to limit the results by. Default: LineQueryOptions.defaultQueryOptions()
@param latitude Latitude in decimal degrees.
@param longitude Longitude in decimal degrees.
@param radiusInMeters Radius in meters to filter results by.
@return A list of lines nearby the specified point. | [
"Gets",
"a",
"list",
"of",
"lines",
"nearby",
"ordered",
"by",
"distance",
"from",
"the",
"point",
"specified",
"."
] | train | https://github.com/WhereIsMyTransport/TransportApiSdk.Java/blob/f4ade7046c8dadfcb2976ee354f85f67a6e930a2/transportapisdk/src/main/java/transportapisdk/TransportApiClient.java#L193-L206 |
gallandarakhneorg/afc | core/text/src/main/java/org/arakhne/afc/text/TextUtil.java | TextUtil.mergeBrackets | @Pure
@Inline(value = "TextUtil.join('{', '}', $1)", imported = {TextUtil.class})
public static String mergeBrackets(Iterable<?> strs) {
return join('{', '}', strs);
} | java | @Pure
@Inline(value = "TextUtil.join('{', '}', $1)", imported = {TextUtil.class})
public static String mergeBrackets(Iterable<?> strs) {
return join('{', '}', strs);
} | [
"@",
"Pure",
"@",
"Inline",
"(",
"value",
"=",
"\"TextUtil.join('{', '}', $1)\"",
",",
"imported",
"=",
"{",
"TextUtil",
".",
"class",
"}",
")",
"public",
"static",
"String",
"mergeBrackets",
"(",
"Iterable",
"<",
"?",
">",
"strs",
")",
"{",
"return",
"joi... | Merge the given strings with to brackets.
The brackets are used to delimit the groups
of characters.
<p>Examples:
<ul>
<li><code>mergeBrackets("a","b","cd")</code> returns the string
<code>"{a}{b}{cd}"</code></li>
<li><code>mergeBrackets("a{bcd")</code> returns the string
<code>"{a{bcd}"</code></li>
</ul>
@param strs is the array of strings.
@return the string with bracketed strings.
@see #join(char, char, Iterable) | [
"Merge",
"the",
"given",
"strings",
"with",
"to",
"brackets",
".",
"The",
"brackets",
"are",
"used",
"to",
"delimit",
"the",
"groups",
"of",
"characters",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/text/src/main/java/org/arakhne/afc/text/TextUtil.java#L864-L868 |
facebookarchive/hadoop-20 | src/contrib/namespace-notifier/src/java/org/apache/hadoop/hdfs/notifier/server/ServerLogReaderTransactional.java | ServerLogReaderTransactional.updateState | private void updateState(FSEditLogOp op, boolean checkTxnId) throws IOException {
InjectionHandler.processEvent(InjectionEvent.SERVERLOGREADER_UPDATE, op);
if (checkTxnId) {
mostRecentlyReadTransactionTxId = ServerLogReaderUtil.checkTransactionId(
mostRecentlyReadTransactionTxId, op);
}
updateStreamPosition();
// read a valid operation
core.getMetrics().readOperations.inc();
mostRecentlyReadTransactionTime = now();
// current log segment ends normally
if (op.opCode == FSEditLogOpCodes.OP_END_LOG_SEGMENT) {
LOG.info("Segment - ending log segment start txid: " + currentSegmentTxId
+ ", end txid: " + op.getTransactionId());
// move forward with next segment
currentSegmentTxId = op.getTransactionId() + 1;
// set the stream to null so the next getNotification()
// will recreate it
currentEditLogInputStream = null;
// indicate that a new stream will be opened
currentEditLogInputStreamPosition = -1;
} else if (op.opCode == FSEditLogOpCodes.OP_START_LOG_SEGMENT) {
LOG.info("Segment - starting log segment start txid: "
+ currentSegmentTxId);
}
} | java | private void updateState(FSEditLogOp op, boolean checkTxnId) throws IOException {
InjectionHandler.processEvent(InjectionEvent.SERVERLOGREADER_UPDATE, op);
if (checkTxnId) {
mostRecentlyReadTransactionTxId = ServerLogReaderUtil.checkTransactionId(
mostRecentlyReadTransactionTxId, op);
}
updateStreamPosition();
// read a valid operation
core.getMetrics().readOperations.inc();
mostRecentlyReadTransactionTime = now();
// current log segment ends normally
if (op.opCode == FSEditLogOpCodes.OP_END_LOG_SEGMENT) {
LOG.info("Segment - ending log segment start txid: " + currentSegmentTxId
+ ", end txid: " + op.getTransactionId());
// move forward with next segment
currentSegmentTxId = op.getTransactionId() + 1;
// set the stream to null so the next getNotification()
// will recreate it
currentEditLogInputStream = null;
// indicate that a new stream will be opened
currentEditLogInputStreamPosition = -1;
} else if (op.opCode == FSEditLogOpCodes.OP_START_LOG_SEGMENT) {
LOG.info("Segment - starting log segment start txid: "
+ currentSegmentTxId);
}
} | [
"private",
"void",
"updateState",
"(",
"FSEditLogOp",
"op",
",",
"boolean",
"checkTxnId",
")",
"throws",
"IOException",
"{",
"InjectionHandler",
".",
"processEvent",
"(",
"InjectionEvent",
".",
"SERVERLOGREADER_UPDATE",
",",
"op",
")",
";",
"if",
"(",
"checkTxnId"... | For each operation read from the stream, check if this is a closing
transaction. If so, we are sure we need to move to the next segment.
We also mark that this is the most recent time, we read something valid
from the input. | [
"For",
"each",
"operation",
"read",
"from",
"the",
"stream",
"check",
"if",
"this",
"is",
"a",
"closing",
"transaction",
".",
"If",
"so",
"we",
"are",
"sure",
"we",
"need",
"to",
"move",
"to",
"the",
"next",
"segment",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/namespace-notifier/src/java/org/apache/hadoop/hdfs/notifier/server/ServerLogReaderTransactional.java#L253-L282 |
rhuss/jolokia | agent/core/src/main/java/org/jolokia/converter/json/ObjectToJsonConverter.java | ObjectToJsonConverter.setObjectValue | private Object setObjectValue(Object pInner, String pAttribute, Object pValue)
throws IllegalAccessException, InvocationTargetException {
// Call various handlers depending on the type of the inner object, as is extract Object
Class clazz = pInner.getClass();
if (clazz.isArray()) {
return arrayExtractor.setObjectValue(stringToObjectConverter,pInner,pAttribute,pValue);
}
Extractor handler = getExtractor(clazz);
if (handler != null) {
return handler.setObjectValue(stringToObjectConverter,pInner,pAttribute,pValue);
} else {
throw new IllegalStateException(
"Internal error: No handler found for class " + clazz + " for setting object value." +
" (object: " + pInner + ", attribute: " + pAttribute + ", value: " + pValue + ")");
}
} | java | private Object setObjectValue(Object pInner, String pAttribute, Object pValue)
throws IllegalAccessException, InvocationTargetException {
// Call various handlers depending on the type of the inner object, as is extract Object
Class clazz = pInner.getClass();
if (clazz.isArray()) {
return arrayExtractor.setObjectValue(stringToObjectConverter,pInner,pAttribute,pValue);
}
Extractor handler = getExtractor(clazz);
if (handler != null) {
return handler.setObjectValue(stringToObjectConverter,pInner,pAttribute,pValue);
} else {
throw new IllegalStateException(
"Internal error: No handler found for class " + clazz + " for setting object value." +
" (object: " + pInner + ", attribute: " + pAttribute + ", value: " + pValue + ")");
}
} | [
"private",
"Object",
"setObjectValue",
"(",
"Object",
"pInner",
",",
"String",
"pAttribute",
",",
"Object",
"pValue",
")",
"throws",
"IllegalAccessException",
",",
"InvocationTargetException",
"{",
"// Call various handlers depending on the type of the inner object, as is extract... | Set an value of an inner object
@param pInner the inner object
@param pAttribute the attribute to set
@param pValue the value to set
@return the old value
@throws IllegalAccessException if the reflection code fails during setting of the value
@throws InvocationTargetException reflection error | [
"Set",
"an",
"value",
"of",
"an",
"inner",
"object"
] | train | https://github.com/rhuss/jolokia/blob/dc95e7bef859b1829776c5a84c8f7738f5d7d9c3/agent/core/src/main/java/org/jolokia/converter/json/ObjectToJsonConverter.java#L226-L244 |
primefaces-extensions/core | src/main/java/org/primefaces/extensions/model/dynaform/DynaFormRow.java | DynaFormRow.addControl | public DynaFormControl addControl(final Object data, final int colspan, final int rowspan) {
return addControl(data, DynaFormControl.DEFAULT_TYPE, colspan, rowspan);
} | java | public DynaFormControl addControl(final Object data, final int colspan, final int rowspan) {
return addControl(data, DynaFormControl.DEFAULT_TYPE, colspan, rowspan);
} | [
"public",
"DynaFormControl",
"addControl",
"(",
"final",
"Object",
"data",
",",
"final",
"int",
"colspan",
",",
"final",
"int",
"rowspan",
")",
"{",
"return",
"addControl",
"(",
"data",
",",
"DynaFormControl",
".",
"DEFAULT_TYPE",
",",
"colspan",
",",
"rowspan... | Adds control with given data, default type, colspan and rowspan.
@param data data object
@param colspan colspan
@param rowspan rowspan
@return DynaFormControl added control | [
"Adds",
"control",
"with",
"given",
"data",
"default",
"type",
"colspan",
"and",
"rowspan",
"."
] | train | https://github.com/primefaces-extensions/core/blob/afdbca591f60f47898e3517e1e939bc2f63d5355/src/main/java/org/primefaces/extensions/model/dynaform/DynaFormRow.java#L82-L84 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/graph/ComputationGraph.java | ComputationGraph.feedForward | public Map<String, INDArray> feedForward(INDArray[] input, boolean train) {
return feedForward(input, train, true);
} | java | public Map<String, INDArray> feedForward(INDArray[] input, boolean train) {
return feedForward(input, train, true);
} | [
"public",
"Map",
"<",
"String",
",",
"INDArray",
">",
"feedForward",
"(",
"INDArray",
"[",
"]",
"input",
",",
"boolean",
"train",
")",
"{",
"return",
"feedForward",
"(",
"input",
",",
"train",
",",
"true",
")",
";",
"}"
] | Conduct forward pass using an array of inputs
@param input An array of ComputationGraph inputs
@param train If true: do forward pass at training time; false: do forward pass at test time
@return A map of activations for each layer (not each GraphVertex). Keys = layer name, values = layer activations | [
"Conduct",
"forward",
"pass",
"using",
"an",
"array",
"of",
"inputs"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/graph/ComputationGraph.java#L1530-L1532 |
samskivert/samskivert | src/main/java/com/samskivert/servlet/user/UserRepository.java | UserRepository.registerSession | public String registerSession (User user, int expireDays)
throws PersistenceException
{
// look for an existing session for this user
final String query = "select authcode from sessions where userId = " + user.userId;
String authcode = execute(new Operation<String>() {
public String invoke (Connection conn, DatabaseLiaison liaison)
throws PersistenceException, SQLException
{
Statement stmt = conn.createStatement();
try {
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
return rs.getString(1);
}
return null;
} finally {
JDBCUtil.close(stmt);
}
}
});
// figure out when to expire the session
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, expireDays);
Date expires = new Date(cal.getTime().getTime());
// if we found one, update its expires time and reuse it
if (authcode != null) {
update("update sessions set expires = '" + expires + "' where " +
"authcode = '" + authcode + "'");
} else {
// otherwise create a new one and insert it into the table
authcode = UserUtil.genAuthCode(user);
update("insert into sessions (authcode, userId, expires) values('" + authcode + "', " +
user.userId + ", '" + expires + "')");
}
return authcode;
} | java | public String registerSession (User user, int expireDays)
throws PersistenceException
{
// look for an existing session for this user
final String query = "select authcode from sessions where userId = " + user.userId;
String authcode = execute(new Operation<String>() {
public String invoke (Connection conn, DatabaseLiaison liaison)
throws PersistenceException, SQLException
{
Statement stmt = conn.createStatement();
try {
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
return rs.getString(1);
}
return null;
} finally {
JDBCUtil.close(stmt);
}
}
});
// figure out when to expire the session
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, expireDays);
Date expires = new Date(cal.getTime().getTime());
// if we found one, update its expires time and reuse it
if (authcode != null) {
update("update sessions set expires = '" + expires + "' where " +
"authcode = '" + authcode + "'");
} else {
// otherwise create a new one and insert it into the table
authcode = UserUtil.genAuthCode(user);
update("insert into sessions (authcode, userId, expires) values('" + authcode + "', " +
user.userId + ", '" + expires + "')");
}
return authcode;
} | [
"public",
"String",
"registerSession",
"(",
"User",
"user",
",",
"int",
"expireDays",
")",
"throws",
"PersistenceException",
"{",
"// look for an existing session for this user",
"final",
"String",
"query",
"=",
"\"select authcode from sessions where userId = \"",
"+",
"user"... | Creates a new session for the specified user and returns the randomly generated session
identifier for that session. If a session entry already exists for the specified user it
will be reused.
@param expireDays the number of days in which the session token should expire. | [
"Creates",
"a",
"new",
"session",
"for",
"the",
"specified",
"user",
"and",
"returns",
"the",
"randomly",
"generated",
"session",
"identifier",
"for",
"that",
"session",
".",
"If",
"a",
"session",
"entry",
"already",
"exists",
"for",
"the",
"specified",
"user"... | train | https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/servlet/user/UserRepository.java#L250-L289 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/CharsTrieBuilder.java | CharsTrieBuilder.write | @Deprecated
@Override
protected int write(int offset, int length) {
int newLength=charsLength+length;
ensureCapacity(newLength);
charsLength=newLength;
int charsOffset=chars.length-charsLength;
while(length>0) {
chars[charsOffset++]=strings.charAt(offset++);
--length;
}
return charsLength;
} | java | @Deprecated
@Override
protected int write(int offset, int length) {
int newLength=charsLength+length;
ensureCapacity(newLength);
charsLength=newLength;
int charsOffset=chars.length-charsLength;
while(length>0) {
chars[charsOffset++]=strings.charAt(offset++);
--length;
}
return charsLength;
} | [
"@",
"Deprecated",
"@",
"Override",
"protected",
"int",
"write",
"(",
"int",
"offset",
",",
"int",
"length",
")",
"{",
"int",
"newLength",
"=",
"charsLength",
"+",
"length",
";",
"ensureCapacity",
"(",
"newLength",
")",
";",
"charsLength",
"=",
"newLength",
... | {@inheritDoc}
@deprecated This API is ICU internal only.
@hide draft / provisional / internal are hidden on Android | [
"{"
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/CharsTrieBuilder.java#L166-L178 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/net/Inet6Address.java | Inet6Address.getByAddress | public static Inet6Address getByAddress(String host, byte[] addr, NetworkInterface nif)
throws UnknownHostException {
if (host != null && host.length() > 0 && host.charAt(0) == '[') {
if (host.charAt(host.length()-1) == ']') {
host = host.substring(1, host.length() -1);
}
}
if (addr != null) {
if (addr.length == Inet6Address.INADDRSZ) {
return new Inet6Address(host, addr, nif);
}
}
throw new UnknownHostException("addr is of illegal length");
} | java | public static Inet6Address getByAddress(String host, byte[] addr, NetworkInterface nif)
throws UnknownHostException {
if (host != null && host.length() > 0 && host.charAt(0) == '[') {
if (host.charAt(host.length()-1) == ']') {
host = host.substring(1, host.length() -1);
}
}
if (addr != null) {
if (addr.length == Inet6Address.INADDRSZ) {
return new Inet6Address(host, addr, nif);
}
}
throw new UnknownHostException("addr is of illegal length");
} | [
"public",
"static",
"Inet6Address",
"getByAddress",
"(",
"String",
"host",
",",
"byte",
"[",
"]",
"addr",
",",
"NetworkInterface",
"nif",
")",
"throws",
"UnknownHostException",
"{",
"if",
"(",
"host",
"!=",
"null",
"&&",
"host",
".",
"length",
"(",
")",
">... | Create an Inet6Address in the exact manner of {@link InetAddress#getByAddress(String,byte[])}
except that the IPv6 scope_id is set to the value corresponding to the given interface
for the address type specified in <code>addr</code>.
The call will fail with an UnknownHostException if the given interface does not have a numeric
scope_id assigned for the given address type (eg. link-local or site-local).
See <a href="Inet6Address.html#scoped">here</a> for a description of IPv6
scoped addresses.
@param host the specified host
@param addr the raw IP address in network byte order
@param nif an interface this address must be associated with.
@return an Inet6Address object created from the raw IP address.
@exception UnknownHostException if IP address is of illegal length, or if the interface
does not have a numeric scope_id assigned for the given address type.
@since 1.5 | [
"Create",
"an",
"Inet6Address",
"in",
"the",
"exact",
"manner",
"of",
"{",
"@link",
"InetAddress#getByAddress",
"(",
"String",
"byte",
"[]",
")",
"}",
"except",
"that",
"the",
"IPv6",
"scope_id",
"is",
"set",
"to",
"the",
"value",
"corresponding",
"to",
"the... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/net/Inet6Address.java#L289-L302 |
OpenLiberty/open-liberty | dev/com.ibm.ws.session.cache/src/com/ibm/ws/session/store/cache/TypeConversion.java | TypeConversion.bytesToLong | public static long bytesToLong(byte[] bytes, int offset) {
long result = 0x0;
for (int i = offset; i < offset + 8; ++i) {
result = result << 8;
result |= (bytes[i] & 0x00000000000000FFl);
}
return result;
} | java | public static long bytesToLong(byte[] bytes, int offset) {
long result = 0x0;
for (int i = offset; i < offset + 8; ++i) {
result = result << 8;
result |= (bytes[i] & 0x00000000000000FFl);
}
return result;
} | [
"public",
"static",
"long",
"bytesToLong",
"(",
"byte",
"[",
"]",
"bytes",
",",
"int",
"offset",
")",
"{",
"long",
"result",
"=",
"0x0",
";",
"for",
"(",
"int",
"i",
"=",
"offset",
";",
"i",
"<",
"offset",
"+",
"8",
";",
"++",
"i",
")",
"{",
"r... | A utility method to convert the long from the byte array to a long.
@param bytes
The byte array containing the long.
@param offset
The index at which the long is located.
@return The long value. | [
"A",
"utility",
"method",
"to",
"convert",
"the",
"long",
"from",
"the",
"byte",
"array",
"to",
"a",
"long",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.session.cache/src/com/ibm/ws/session/store/cache/TypeConversion.java#L65-L72 |
elastic/elasticsearch-hadoop | storm/src/main/java/org/elasticsearch/storm/security/AutoElasticsearch.java | AutoElasticsearch.populateCredentials | @Override
public void populateCredentials(Map<String, String> credentials, Map topologyConfiguration) {
populateCredentials(credentials, topologyConfiguration, null);
} | java | @Override
public void populateCredentials(Map<String, String> credentials, Map topologyConfiguration) {
populateCredentials(credentials, topologyConfiguration, null);
} | [
"@",
"Override",
"public",
"void",
"populateCredentials",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"credentials",
",",
"Map",
"topologyConfiguration",
")",
"{",
"populateCredentials",
"(",
"credentials",
",",
"topologyConfiguration",
",",
"null",
")",
";",
... | {@inheritDoc}
@deprecated This is available for any storm cluster that operates against the older method of obtaining credentials | [
"{"
] | train | https://github.com/elastic/elasticsearch-hadoop/blob/f3acaba268ff96efae8eb946088c748c777c22cc/storm/src/main/java/org/elasticsearch/storm/security/AutoElasticsearch.java#L98-L101 |
pravega/pravega | shared/protocol/src/main/java/io/pravega/shared/segment/StreamSegmentNameUtils.java | StreamSegmentNameUtils.getTransactionNameFromId | public static String getTransactionNameFromId(String parentStreamSegmentName, UUID transactionId) {
StringBuilder result = new StringBuilder();
result.append(parentStreamSegmentName);
result.append(TRANSACTION_DELIMITER);
result.append(String.format(FULL_HEX_FORMAT, transactionId.getMostSignificantBits()));
result.append(String.format(FULL_HEX_FORMAT, transactionId.getLeastSignificantBits()));
return result.toString();
} | java | public static String getTransactionNameFromId(String parentStreamSegmentName, UUID transactionId) {
StringBuilder result = new StringBuilder();
result.append(parentStreamSegmentName);
result.append(TRANSACTION_DELIMITER);
result.append(String.format(FULL_HEX_FORMAT, transactionId.getMostSignificantBits()));
result.append(String.format(FULL_HEX_FORMAT, transactionId.getLeastSignificantBits()));
return result.toString();
} | [
"public",
"static",
"String",
"getTransactionNameFromId",
"(",
"String",
"parentStreamSegmentName",
",",
"UUID",
"transactionId",
")",
"{",
"StringBuilder",
"result",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"result",
".",
"append",
"(",
"parentStreamSegmentName",
... | Returns the transaction name for a TransactionStreamSegment based on the name of the current Parent StreamSegment, and the transactionId.
@param parentStreamSegmentName The name of the Parent StreamSegment for this transaction.
@param transactionId The unique Id for the transaction.
@return The name of the Transaction StreamSegmentId. | [
"Returns",
"the",
"transaction",
"name",
"for",
"a",
"TransactionStreamSegment",
"based",
"on",
"the",
"name",
"of",
"the",
"current",
"Parent",
"StreamSegment",
"and",
"the",
"transactionId",
"."
] | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/shared/protocol/src/main/java/io/pravega/shared/segment/StreamSegmentNameUtils.java#L83-L90 |
puniverse/capsule | capsule-util/src/main/java/co/paralleluniverse/capsule/Jar.java | Jar.getAttribute | public String getAttribute(String section, String name) {
Attributes attr = getManifest().getAttributes(section);
return attr != null ? attr.getValue(name) : null;
} | java | public String getAttribute(String section, String name) {
Attributes attr = getManifest().getAttributes(section);
return attr != null ? attr.getValue(name) : null;
} | [
"public",
"String",
"getAttribute",
"(",
"String",
"section",
",",
"String",
"name",
")",
"{",
"Attributes",
"attr",
"=",
"getManifest",
"(",
")",
".",
"getAttributes",
"(",
"section",
")",
";",
"return",
"attr",
"!=",
"null",
"?",
"attr",
".",
"getValue",... | Returns an attribute's value from a non-main section of this JAR's manifest.
@param section the manifest's section
@param name the attribute's name | [
"Returns",
"an",
"attribute",
"s",
"value",
"from",
"a",
"non",
"-",
"main",
"section",
"of",
"this",
"JAR",
"s",
"manifest",
"."
] | train | https://github.com/puniverse/capsule/blob/291a54e501a32aaf0284707b8c1fbff6a566822b/capsule-util/src/main/java/co/paralleluniverse/capsule/Jar.java#L234-L237 |
astrapi69/jaulp-wicket | jaulp-wicket-components/src/main/java/de/alpharogroup/wicket/components/sign/up/SignupPanel.java | SignupPanel.newUsernameTextField | protected Component newUsernameTextField(final String id, final IModel<T> model)
{
final IModel<String> labelModel = ResourceModelFactory
.newResourceModel("global.username.label", this);
final IModel<String> placeholderModel = ResourceModelFactory
.newResourceModel("global.enter.your.username.label", this);
final LabeledTextFieldPanel<String, T> nameTextField = new LabeledTextFieldPanel<String, T>(
id, model, labelModel)
{
private static final long serialVersionUID = 1L;
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
protected TextField newTextField(final String id, final IModel<T> modelSuper)
{
final TextField<String> textField = new TextField<String>(id,
new PropertyModel<>(model, "username"));
textField.setOutputMarkupId(true);
textField.setRequired(true);
if (placeholderModel != null)
{
textField.add(new AttributeAppender("placeholder", placeholderModel));
}
return textField;
}
};
return nameTextField;
} | java | protected Component newUsernameTextField(final String id, final IModel<T> model)
{
final IModel<String> labelModel = ResourceModelFactory
.newResourceModel("global.username.label", this);
final IModel<String> placeholderModel = ResourceModelFactory
.newResourceModel("global.enter.your.username.label", this);
final LabeledTextFieldPanel<String, T> nameTextField = new LabeledTextFieldPanel<String, T>(
id, model, labelModel)
{
private static final long serialVersionUID = 1L;
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
protected TextField newTextField(final String id, final IModel<T> modelSuper)
{
final TextField<String> textField = new TextField<String>(id,
new PropertyModel<>(model, "username"));
textField.setOutputMarkupId(true);
textField.setRequired(true);
if (placeholderModel != null)
{
textField.add(new AttributeAppender("placeholder", placeholderModel));
}
return textField;
}
};
return nameTextField;
} | [
"protected",
"Component",
"newUsernameTextField",
"(",
"final",
"String",
"id",
",",
"final",
"IModel",
"<",
"T",
">",
"model",
")",
"{",
"final",
"IModel",
"<",
"String",
">",
"labelModel",
"=",
"ResourceModelFactory",
".",
"newResourceModel",
"(",
"\"global.us... | Factory method for creating the TextField for the username. This method is invoked in the
constructor from the derived classes and can be overridden so users can provide their own
version of a TextField for the username.
@param id
the id
@param model
the model
@return the text field | [
"Factory",
"method",
"for",
"creating",
"the",
"TextField",
"for",
"the",
"username",
".",
"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/up/SignupPanel.java#L140-L168 |
OpenLiberty/open-liberty | dev/com.ibm.ws.kernel.boot.core/src/com/ibm/ws/kernel/boot/BootstrapConfig.java | BootstrapConfig.getConfigFile | public File getConfigFile(String relativeServerPath) {
if (relativeServerPath == null)
return configDir;
else
return new File(configDir, relativeServerPath);
} | java | public File getConfigFile(String relativeServerPath) {
if (relativeServerPath == null)
return configDir;
else
return new File(configDir, relativeServerPath);
} | [
"public",
"File",
"getConfigFile",
"(",
"String",
"relativeServerPath",
")",
"{",
"if",
"(",
"relativeServerPath",
"==",
"null",
")",
"return",
"configDir",
";",
"else",
"return",
"new",
"File",
"(",
"configDir",
",",
"relativeServerPath",
")",
";",
"}"
] | Allocate a file in the server config directory, e.g.
usr/servers/serverName/relativeServerPath
@param relativeServerPath
relative path of file to create in the server directory
@return File object for relative path, or for the server directory itself
if the relative path argument is null | [
"Allocate",
"a",
"file",
"in",
"the",
"server",
"config",
"directory",
"e",
".",
"g",
".",
"usr",
"/",
"servers",
"/",
"serverName",
"/",
"relativeServerPath"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.kernel.boot.core/src/com/ibm/ws/kernel/boot/BootstrapConfig.java#L612-L617 |
dkmfbk/knowledgestore | ks-core/src/main/java/eu/fbk/knowledgestore/data/XPath.java | XPath.evalUnique | @Nullable
public final <T> T evalUnique(final Object object, final Class<T> resultClass)
throws IllegalArgumentException {
Preconditions.checkNotNull(object);
Preconditions.checkNotNull(resultClass);
try {
return toUnique(doEval(object), resultClass);
} catch (final Exception ex) {
if (isLenient()) {
return null;
}
throw new IllegalArgumentException("Evaluation of XPath failed: " + ex.getMessage()
+ "\nXPath is: " + this.support.string + "\nInput is: " + object
+ "\nExpected result is: " + resultClass.getSimpleName(), ex);
}
} | java | @Nullable
public final <T> T evalUnique(final Object object, final Class<T> resultClass)
throws IllegalArgumentException {
Preconditions.checkNotNull(object);
Preconditions.checkNotNull(resultClass);
try {
return toUnique(doEval(object), resultClass);
} catch (final Exception ex) {
if (isLenient()) {
return null;
}
throw new IllegalArgumentException("Evaluation of XPath failed: " + ex.getMessage()
+ "\nXPath is: " + this.support.string + "\nInput is: " + object
+ "\nExpected result is: " + resultClass.getSimpleName(), ex);
}
} | [
"@",
"Nullable",
"public",
"final",
"<",
"T",
">",
"T",
"evalUnique",
"(",
"final",
"Object",
"object",
",",
"final",
"Class",
"<",
"T",
">",
"resultClass",
")",
"throws",
"IllegalArgumentException",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"object",
... | Evaluates this {@code XPath} expression on the object supplied, producing as result a
unique object of the type {@code T} specified.
@param object
the object to evaluate this expression on
@param resultClass
the {@code Class} object for the result object
@param <T>
the type of result
@return on success, the unique object of the requested type resulting from the evaluation,
or null if evaluation produced no results; on failure, null is returned if this
{@code XPath} expression is lenient
@throws IllegalArgumentException
if this {@code XPath} expression is not lenient and evaluation fails for the
object supplied | [
"Evaluates",
"this",
"{",
"@code",
"XPath",
"}",
"expression",
"on",
"the",
"object",
"supplied",
"producing",
"as",
"result",
"a",
"unique",
"object",
"of",
"the",
"type",
"{",
"@code",
"T",
"}",
"specified",
"."
] | train | https://github.com/dkmfbk/knowledgestore/blob/a548101b1dd67fcf72a1ec6f838ea7539bdbbe7a/ks-core/src/main/java/eu/fbk/knowledgestore/data/XPath.java#L953-L971 |
ManfredTremmel/gwt-commons-lang3 | src/main/java/org/apache/commons/lang3/math/Fraction.java | Fraction.multiplyBy | public Fraction multiplyBy(final Fraction fraction) {
Validate.isTrue(fraction != null, "The fraction must not be null");
if (numerator == 0 || fraction.numerator == 0) {
return ZERO;
}
// knuth 4.5.1
// make sure we don't overflow unless the result *must* overflow.
final int d1 = greatestCommonDivisor(numerator, fraction.denominator);
final int d2 = greatestCommonDivisor(fraction.numerator, denominator);
return getReducedFraction(mulAndCheck(numerator / d1, fraction.numerator / d2),
mulPosAndCheck(denominator / d2, fraction.denominator / d1));
} | java | public Fraction multiplyBy(final Fraction fraction) {
Validate.isTrue(fraction != null, "The fraction must not be null");
if (numerator == 0 || fraction.numerator == 0) {
return ZERO;
}
// knuth 4.5.1
// make sure we don't overflow unless the result *must* overflow.
final int d1 = greatestCommonDivisor(numerator, fraction.denominator);
final int d2 = greatestCommonDivisor(fraction.numerator, denominator);
return getReducedFraction(mulAndCheck(numerator / d1, fraction.numerator / d2),
mulPosAndCheck(denominator / d2, fraction.denominator / d1));
} | [
"public",
"Fraction",
"multiplyBy",
"(",
"final",
"Fraction",
"fraction",
")",
"{",
"Validate",
".",
"isTrue",
"(",
"fraction",
"!=",
"null",
",",
"\"The fraction must not be null\"",
")",
";",
"if",
"(",
"numerator",
"==",
"0",
"||",
"fraction",
".",
"numerat... | <p>Multiplies the value of this fraction by another, returning the
result in reduced form.</p>
@param fraction the fraction to multiply by, must not be <code>null</code>
@return a <code>Fraction</code> instance with the resulting values
@throws IllegalArgumentException if the fraction is <code>null</code>
@throws ArithmeticException if the resulting numerator or denominator exceeds
<code>Integer.MAX_VALUE</code> | [
"<p",
">",
"Multiplies",
"the",
"value",
"of",
"this",
"fraction",
"by",
"another",
"returning",
"the",
"result",
"in",
"reduced",
"form",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/math/Fraction.java#L783-L794 |
salesforce/Argus | ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/dto/AuditDto.java | AuditDto.transformToDto | public static List<AuditDto> transformToDto(List<Audit> audits) {
if (audits == null) {
throw new WebApplicationException("Null entity object cannot be converted to Dto object.", Status.INTERNAL_SERVER_ERROR);
}
List<AuditDto> result = new ArrayList<AuditDto>();
for (Audit audit : audits) {
result.add(transformToDto(audit));
}
return result;
} | java | public static List<AuditDto> transformToDto(List<Audit> audits) {
if (audits == null) {
throw new WebApplicationException("Null entity object cannot be converted to Dto object.", Status.INTERNAL_SERVER_ERROR);
}
List<AuditDto> result = new ArrayList<AuditDto>();
for (Audit audit : audits) {
result.add(transformToDto(audit));
}
return result;
} | [
"public",
"static",
"List",
"<",
"AuditDto",
">",
"transformToDto",
"(",
"List",
"<",
"Audit",
">",
"audits",
")",
"{",
"if",
"(",
"audits",
"==",
"null",
")",
"{",
"throw",
"new",
"WebApplicationException",
"(",
"\"Null entity object cannot be converted to Dto ob... | Converts a list of audit entities to DTOs.
@param audits The list of audit entities to convert.
@return The list of DTO objects.
@throws WebApplicationException If an error occurs. | [
"Converts",
"a",
"list",
"of",
"audit",
"entities",
"to",
"DTOs",
"."
] | train | https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/dto/AuditDto.java#L102-L114 |
liferay/com-liferay-commerce | commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPFriendlyURLEntryPersistenceImpl.java | CPFriendlyURLEntryPersistenceImpl.removeByUUID_G | @Override
public CPFriendlyURLEntry removeByUUID_G(String uuid, long groupId)
throws NoSuchCPFriendlyURLEntryException {
CPFriendlyURLEntry cpFriendlyURLEntry = findByUUID_G(uuid, groupId);
return remove(cpFriendlyURLEntry);
} | java | @Override
public CPFriendlyURLEntry removeByUUID_G(String uuid, long groupId)
throws NoSuchCPFriendlyURLEntryException {
CPFriendlyURLEntry cpFriendlyURLEntry = findByUUID_G(uuid, groupId);
return remove(cpFriendlyURLEntry);
} | [
"@",
"Override",
"public",
"CPFriendlyURLEntry",
"removeByUUID_G",
"(",
"String",
"uuid",
",",
"long",
"groupId",
")",
"throws",
"NoSuchCPFriendlyURLEntryException",
"{",
"CPFriendlyURLEntry",
"cpFriendlyURLEntry",
"=",
"findByUUID_G",
"(",
"uuid",
",",
"groupId",
")",
... | Removes the cp friendly url entry where uuid = ? and groupId = ? from the database.
@param uuid the uuid
@param groupId the group ID
@return the cp friendly url entry that was removed | [
"Removes",
"the",
"cp",
"friendly",
"url",
"entry",
"where",
"uuid",
"=",
"?",
";",
"and",
"groupId",
"=",
"?",
";",
"from",
"the",
"database",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPFriendlyURLEntryPersistenceImpl.java#L817-L823 |
Graylog2/graylog2-server | graylog2-server/src/main/java/org/graylog2/search/SearchQueryParser.java | SearchQueryParser.createFieldValue | @VisibleForTesting
FieldValue createFieldValue(SearchQueryField field, String quotedStringValue, boolean negate) {
// Make sure there are no quotes in the value (e.g. `"foo"' --> `foo')
final String value = quotedStringValue.replaceAll(QUOTE_REPLACE_REGEX, "");
final SearchQueryField.Type fieldType = field.getFieldType();
final Pair<String, SearchQueryOperator> pair = extractOperator(value, fieldType == STRING ? DEFAULT_STRING_OPERATOR : DEFAULT_OPERATOR);
switch (fieldType) {
case DATE:
return new FieldValue(parseDate(pair.getLeft()), pair.getRight(), negate);
case STRING:
return new FieldValue(pair.getLeft(), pair.getRight(), negate);
case INT:
return new FieldValue(Integer.parseInt(pair.getLeft()), pair.getRight(), negate);
case LONG:
return new FieldValue(Long.parseLong(pair.getLeft()), pair.getRight(), negate);
default:
throw new IllegalArgumentException("Unhandled field type: " + fieldType.toString());
}
} | java | @VisibleForTesting
FieldValue createFieldValue(SearchQueryField field, String quotedStringValue, boolean negate) {
// Make sure there are no quotes in the value (e.g. `"foo"' --> `foo')
final String value = quotedStringValue.replaceAll(QUOTE_REPLACE_REGEX, "");
final SearchQueryField.Type fieldType = field.getFieldType();
final Pair<String, SearchQueryOperator> pair = extractOperator(value, fieldType == STRING ? DEFAULT_STRING_OPERATOR : DEFAULT_OPERATOR);
switch (fieldType) {
case DATE:
return new FieldValue(parseDate(pair.getLeft()), pair.getRight(), negate);
case STRING:
return new FieldValue(pair.getLeft(), pair.getRight(), negate);
case INT:
return new FieldValue(Integer.parseInt(pair.getLeft()), pair.getRight(), negate);
case LONG:
return new FieldValue(Long.parseLong(pair.getLeft()), pair.getRight(), negate);
default:
throw new IllegalArgumentException("Unhandled field type: " + fieldType.toString());
}
} | [
"@",
"VisibleForTesting",
"FieldValue",
"createFieldValue",
"(",
"SearchQueryField",
"field",
",",
"String",
"quotedStringValue",
",",
"boolean",
"negate",
")",
"{",
"// Make sure there are no quotes in the value (e.g. `\"foo\"' --> `foo')",
"final",
"String",
"value",
"=",
"... | /* Create a FieldValue for the query field from the string value.
We try to convert the value types according to the data type of the query field. | [
"/",
"*",
"Create",
"a",
"FieldValue",
"for",
"the",
"query",
"field",
"from",
"the",
"string",
"value",
".",
"We",
"try",
"to",
"convert",
"the",
"value",
"types",
"according",
"to",
"the",
"data",
"type",
"of",
"the",
"query",
"field",
"."
] | train | https://github.com/Graylog2/graylog2-server/blob/50b565dcead6e0a372236d5c2f8530dc5726fa9b/graylog2-server/src/main/java/org/graylog2/search/SearchQueryParser.java#L232-L251 |
cdk/cdk | base/isomorphism/src/main/java/org/openscience/cdk/isomorphism/CompatibilityMatrix.java | CompatibilityMatrix.resetRows | void resetRows(int i, int marking) {
for (int j = (i * mCols); j < data.length; j++)
if (data[j] == marking) data[j] = 1;
} | java | void resetRows(int i, int marking) {
for (int j = (i * mCols); j < data.length; j++)
if (data[j] == marking) data[j] = 1;
} | [
"void",
"resetRows",
"(",
"int",
"i",
",",
"int",
"marking",
")",
"{",
"for",
"(",
"int",
"j",
"=",
"(",
"i",
"*",
"mCols",
")",
";",
"j",
"<",
"data",
".",
"length",
";",
"j",
"++",
")",
"if",
"(",
"data",
"[",
"j",
"]",
"==",
"marking",
"... | Reset all values marked with (marking) from row i onwards.
@param i row index
@param marking the marking to reset (should be negative) | [
"Reset",
"all",
"values",
"marked",
"with",
"(",
"marking",
")",
"from",
"row",
"i",
"onwards",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/isomorphism/src/main/java/org/openscience/cdk/isomorphism/CompatibilityMatrix.java#L119-L122 |
lionsoul2014/jcseg | jcseg-server/src/main/java/org/lionsoul/jcseg/server/core/ContextRouter.java | ContextRouter.getPathEntry | private PathEntry getPathEntry(UriEntry uri)
{
PathEntry pathEntry = new PathEntry( ContextRouter.MAP_PATH_TYPE, "default");
int length = uri.getLength();
// like /a or /
if ( length < 2) return pathEntry;
String requestUri = uri.getRequestUri();
String last_str = uri.get( length - 1 );
if ( last_str.equals("*") || last_str.equals("") ) {
// StringBuffer buffer = new StringBuffer();
// buffer.append('/');
//
// for(int i = 0; i < length - 1; i++)
// {
// buffer.append(uri.get(i) + "/");
// }
// position of last / charactor
int lastPosition = requestUri.lastIndexOf('/');
pathEntry.type = ContextRouter.MATCH_PATH_TYPE;
pathEntry.key = requestUri.substring(0, lastPosition + 1);
// @TODO maybe we should get parameters to pathEntry
} else {
pathEntry.key = requestUri;
}
return pathEntry;
} | java | private PathEntry getPathEntry(UriEntry uri)
{
PathEntry pathEntry = new PathEntry( ContextRouter.MAP_PATH_TYPE, "default");
int length = uri.getLength();
// like /a or /
if ( length < 2) return pathEntry;
String requestUri = uri.getRequestUri();
String last_str = uri.get( length - 1 );
if ( last_str.equals("*") || last_str.equals("") ) {
// StringBuffer buffer = new StringBuffer();
// buffer.append('/');
//
// for(int i = 0; i < length - 1; i++)
// {
// buffer.append(uri.get(i) + "/");
// }
// position of last / charactor
int lastPosition = requestUri.lastIndexOf('/');
pathEntry.type = ContextRouter.MATCH_PATH_TYPE;
pathEntry.key = requestUri.substring(0, lastPosition + 1);
// @TODO maybe we should get parameters to pathEntry
} else {
pathEntry.key = requestUri;
}
return pathEntry;
} | [
"private",
"PathEntry",
"getPathEntry",
"(",
"UriEntry",
"uri",
")",
"{",
"PathEntry",
"pathEntry",
"=",
"new",
"PathEntry",
"(",
"ContextRouter",
".",
"MAP_PATH_TYPE",
",",
"\"default\"",
")",
";",
"int",
"length",
"=",
"uri",
".",
"getLength",
"(",
")",
";... | get the final key with specified path
paths : return:
/a/b : /a/b
/a/* : /a/
/a/b/c : /a/b/c
/a/b/* : /a/b/
/a/b/ : /a/b/ | [
"get",
"the",
"final",
"key",
"with",
"specified",
"path"
] | train | https://github.com/lionsoul2014/jcseg/blob/7c8a912e3bbcaf4f8de701180b9c24e2e444a94b/jcseg-server/src/main/java/org/lionsoul/jcseg/server/core/ContextRouter.java#L59-L93 |
OpenTSDB/opentsdb | src/tools/Fsck.java | Fsck.runFullTable | public void runFullTable() throws Exception {
LOG.info("Starting full table scan");
final long start_time = System.currentTimeMillis() / 1000;
final int workers = options.threads() > 0 ? options.threads() :
Runtime.getRuntime().availableProcessors() * 2;
final List<Scanner> scanners = CliUtils.getDataTableScanners(tsdb, workers);
LOG.info("Spooling up [" + scanners.size() + "] worker threads");
final List<Thread> threads = new ArrayList<Thread>(scanners.size());
int i = 0;
for (final Scanner scanner : scanners) {
final FsckWorker worker = new FsckWorker(scanner, i++, this.options);
worker.setName("Fsck #" + i);
worker.start();
threads.add(worker);
}
final Thread reporter = new ProgressReporter();
reporter.start();
for (final Thread thread : threads) {
thread.join();
LOG.info("Thread [" + thread + "] Finished");
}
reporter.interrupt();
logResults();
final long duration = (System.currentTimeMillis() / 1000) - start_time;
LOG.info("Completed fsck in [" + duration + "] seconds");
} | java | public void runFullTable() throws Exception {
LOG.info("Starting full table scan");
final long start_time = System.currentTimeMillis() / 1000;
final int workers = options.threads() > 0 ? options.threads() :
Runtime.getRuntime().availableProcessors() * 2;
final List<Scanner> scanners = CliUtils.getDataTableScanners(tsdb, workers);
LOG.info("Spooling up [" + scanners.size() + "] worker threads");
final List<Thread> threads = new ArrayList<Thread>(scanners.size());
int i = 0;
for (final Scanner scanner : scanners) {
final FsckWorker worker = new FsckWorker(scanner, i++, this.options);
worker.setName("Fsck #" + i);
worker.start();
threads.add(worker);
}
final Thread reporter = new ProgressReporter();
reporter.start();
for (final Thread thread : threads) {
thread.join();
LOG.info("Thread [" + thread + "] Finished");
}
reporter.interrupt();
logResults();
final long duration = (System.currentTimeMillis() / 1000) - start_time;
LOG.info("Completed fsck in [" + duration + "] seconds");
} | [
"public",
"void",
"runFullTable",
"(",
")",
"throws",
"Exception",
"{",
"LOG",
".",
"info",
"(",
"\"Starting full table scan\"",
")",
";",
"final",
"long",
"start_time",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
"/",
"1000",
";",
"final",
"int",
"wo... | Fetches the max metric ID and splits the data table up amongst threads on
a naive split. By default we execute cores * 2 threads but the user can
specify more or fewer.
@throws Exception If something goes pear shaped. | [
"Fetches",
"the",
"max",
"metric",
"ID",
"and",
"splits",
"the",
"data",
"table",
"up",
"amongst",
"threads",
"on",
"a",
"naive",
"split",
".",
"By",
"default",
"we",
"execute",
"cores",
"*",
"2",
"threads",
"but",
"the",
"user",
"can",
"specify",
"more"... | train | https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/tools/Fsck.java#L147-L175 |
alkacon/opencms-core | src/org/opencms/db/generic/CmsSqlManager.java | CmsSqlManager.readQuery | public String readQuery(CmsUUID projectId, String queryKey) {
String key;
if ((projectId != null) && !projectId.isNullUUID()) {
// id 0 is special, please see below
StringBuffer buffer = new StringBuffer(128);
buffer.append(queryKey);
if (projectId.equals(CmsProject.ONLINE_PROJECT_ID)) {
buffer.append("_ONLINE");
} else {
buffer.append("_OFFLINE");
}
key = buffer.toString();
} else {
key = queryKey;
}
// look up the query in the cache
String query = m_cachedQueries.get(key);
if (query == null) {
// the query has not been cached yet
// get the SQL statement from the properties hash
query = readQuery(queryKey);
if (query == null) {
throw new CmsRuntimeException(Messages.get().container(Messages.ERR_QUERY_NOT_FOUND_1, queryKey));
}
// replace control chars.
query = CmsStringUtil.substitute(query, "\t", " ");
query = CmsStringUtil.substitute(query, "\n", " ");
if ((projectId != null) && !projectId.isNullUUID()) {
// a project ID = 0 is an internal indicator that a project-independent
// query was requested - further regex operations are not required then
query = CmsSqlManager.replaceProjectPattern(projectId, query);
}
// to minimize costs, all statements with replaced expressions are cached in a map
m_cachedQueries.put(key, query);
}
return query;
} | java | public String readQuery(CmsUUID projectId, String queryKey) {
String key;
if ((projectId != null) && !projectId.isNullUUID()) {
// id 0 is special, please see below
StringBuffer buffer = new StringBuffer(128);
buffer.append(queryKey);
if (projectId.equals(CmsProject.ONLINE_PROJECT_ID)) {
buffer.append("_ONLINE");
} else {
buffer.append("_OFFLINE");
}
key = buffer.toString();
} else {
key = queryKey;
}
// look up the query in the cache
String query = m_cachedQueries.get(key);
if (query == null) {
// the query has not been cached yet
// get the SQL statement from the properties hash
query = readQuery(queryKey);
if (query == null) {
throw new CmsRuntimeException(Messages.get().container(Messages.ERR_QUERY_NOT_FOUND_1, queryKey));
}
// replace control chars.
query = CmsStringUtil.substitute(query, "\t", " ");
query = CmsStringUtil.substitute(query, "\n", " ");
if ((projectId != null) && !projectId.isNullUUID()) {
// a project ID = 0 is an internal indicator that a project-independent
// query was requested - further regex operations are not required then
query = CmsSqlManager.replaceProjectPattern(projectId, query);
}
// to minimize costs, all statements with replaced expressions are cached in a map
m_cachedQueries.put(key, query);
}
return query;
} | [
"public",
"String",
"readQuery",
"(",
"CmsUUID",
"projectId",
",",
"String",
"queryKey",
")",
"{",
"String",
"key",
";",
"if",
"(",
"(",
"projectId",
"!=",
"null",
")",
"&&",
"!",
"projectId",
".",
"isNullUUID",
"(",
")",
")",
"{",
"// id 0 is special, ple... | Searches for the SQL query with the specified key and project-ID.<p>
For projectIds ≠ 0, the pattern {@link #QUERY_PROJECT_SEARCH_PATTERN} in table names of queries is
replaced with "_ONLINE_" or "_OFFLINE_" to choose the right database
tables for SQL queries that are project dependent!
@param projectId the ID of the specified CmsProject
@param queryKey the key of the SQL query
@return the the SQL query in this property list with the specified key | [
"Searches",
"for",
"the",
"SQL",
"query",
"with",
"the",
"specified",
"key",
"and",
"project",
"-",
"ID",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/generic/CmsSqlManager.java#L329-L373 |
undertow-io/undertow | servlet/src/main/java/io/undertow/servlet/Servlets.java | Servlets.errorPage | public static ErrorPage errorPage(String location, Class<? extends Throwable> exceptionType) {
return new ErrorPage(location, exceptionType);
} | java | public static ErrorPage errorPage(String location, Class<? extends Throwable> exceptionType) {
return new ErrorPage(location, exceptionType);
} | [
"public",
"static",
"ErrorPage",
"errorPage",
"(",
"String",
"location",
",",
"Class",
"<",
"?",
"extends",
"Throwable",
">",
"exceptionType",
")",
"{",
"return",
"new",
"ErrorPage",
"(",
"location",
",",
"exceptionType",
")",
";",
"}"
] | Create an ErrorPage instance for a given exception type
@param location The location to redirect to
@param exceptionType The exception type
@return The error page definition | [
"Create",
"an",
"ErrorPage",
"instance",
"for",
"a",
"given",
"exception",
"type"
] | train | https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/servlet/src/main/java/io/undertow/servlet/Servlets.java#L204-L206 |
sebastiangraf/treetank | interfacemodules/xml/src/main/java/org/treetank/service/xml/xpath/parser/XPathParser.java | XPathParser.parseIfExpr | private void parseIfExpr() throws TTXPathException {
// parse if expression
consume("if", true);
consume(TokenType.OPEN_BR, true);
// parse test expression axis
parseExpression();
consume(TokenType.CLOSE_BR, true);
// parse then expression
consume("then", true);
parseExprSingle();
// parse else expression
consume("else", true);
parseExprSingle();
mPipeBuilder.addIfExpression(getTransaction());
} | java | private void parseIfExpr() throws TTXPathException {
// parse if expression
consume("if", true);
consume(TokenType.OPEN_BR, true);
// parse test expression axis
parseExpression();
consume(TokenType.CLOSE_BR, true);
// parse then expression
consume("then", true);
parseExprSingle();
// parse else expression
consume("else", true);
parseExprSingle();
mPipeBuilder.addIfExpression(getTransaction());
} | [
"private",
"void",
"parseIfExpr",
"(",
")",
"throws",
"TTXPathException",
"{",
"// parse if expression",
"consume",
"(",
"\"if\"",
",",
"true",
")",
";",
"consume",
"(",
"TokenType",
".",
"OPEN_BR",
",",
"true",
")",
";",
"// parse test expression axis",
"parseExp... | Parses the the rule IfExpr according to the following production rule:
<p>
[7] IfExpr ::= <"if" "("> Expr ")" "then" ExprSingle "else" ExprSingle.
</p>
@throws TTXPathException | [
"Parses",
"the",
"the",
"rule",
"IfExpr",
"according",
"to",
"the",
"following",
"production",
"rule",
":",
"<p",
">",
"[",
"7",
"]",
"IfExpr",
"::",
"=",
"<",
"if",
"(",
">",
"Expr",
")",
"then",
"ExprSingle",
"else",
"ExprSingle",
".",
"<",
"/",
"p... | train | https://github.com/sebastiangraf/treetank/blob/9b96d631b6c2a8502a0cc958dcb02bd6a6fd8b60/interfacemodules/xml/src/main/java/org/treetank/service/xml/xpath/parser/XPathParser.java#L290-L310 |
ggrandes/kvstore | src/main/java/org/javastack/kvstore/structures/hash/IntHashMap.java | IntHashMap.put | public V put(final int key, final V value) {
int index = (key & 0x7FFFFFFF) % elementData.length;
IntEntry<V> entry = elementData[index];
while (entry != null && key != entry.key) {
entry = entry.nextInSlot;
}
if (entry == null) {
if (++elementCount > threshold) {
rehash();
index = (key & 0x7FFFFFFF) % elementData.length;
}
entry = createHashedEntry(key, index);
}
V result = entry.value;
entry.value = value;
return result;
} | java | public V put(final int key, final V value) {
int index = (key & 0x7FFFFFFF) % elementData.length;
IntEntry<V> entry = elementData[index];
while (entry != null && key != entry.key) {
entry = entry.nextInSlot;
}
if (entry == null) {
if (++elementCount > threshold) {
rehash();
index = (key & 0x7FFFFFFF) % elementData.length;
}
entry = createHashedEntry(key, index);
}
V result = entry.value;
entry.value = value;
return result;
} | [
"public",
"V",
"put",
"(",
"final",
"int",
"key",
",",
"final",
"V",
"value",
")",
"{",
"int",
"index",
"=",
"(",
"key",
"&",
"0x7FFFFFFF",
")",
"%",
"elementData",
".",
"length",
";",
"IntEntry",
"<",
"V",
">",
"entry",
"=",
"elementData",
"[",
"i... | Maps the specified key to the specified value.
@param key the key.
@param value the value.
@return the value of any previous mapping with the specified key or {@code null} if there was no such
mapping. | [
"Maps",
"the",
"specified",
"key",
"to",
"the",
"specified",
"value",
"."
] | train | https://github.com/ggrandes/kvstore/blob/c79277f79f4604e0fec8349a98519838e3de38f0/src/main/java/org/javastack/kvstore/structures/hash/IntHashMap.java#L152-L171 |
liferay/com-liferay-commerce | commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceAvailabilityEstimatePersistenceImpl.java | CommerceAvailabilityEstimatePersistenceImpl.findAll | @Override
public List<CommerceAvailabilityEstimate> findAll() {
return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
} | java | @Override
public List<CommerceAvailabilityEstimate> findAll() {
return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
} | [
"@",
"Override",
"public",
"List",
"<",
"CommerceAvailabilityEstimate",
">",
"findAll",
"(",
")",
"{",
"return",
"findAll",
"(",
"QueryUtil",
".",
"ALL_POS",
",",
"QueryUtil",
".",
"ALL_POS",
",",
"null",
")",
";",
"}"
] | Returns all the commerce availability estimates.
@return the commerce availability estimates | [
"Returns",
"all",
"the",
"commerce",
"availability",
"estimates",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceAvailabilityEstimatePersistenceImpl.java#L2678-L2681 |
alkacon/opencms-core | src/org/opencms/jsp/search/result/CmsSearchStateParameters.java | CmsSearchStateParameters.paramMapToString | public static String paramMapToString(final Map<String, String[]> parameters) {
final StringBuffer result = new StringBuffer();
for (final String key : parameters.keySet()) {
String[] values = parameters.get(key);
if (null == values) {
result.append(key).append('&');
} else {
for (final String value : parameters.get(key)) {
result.append(key).append('=').append(CmsEncoder.encode(value)).append('&');
}
}
}
// remove last '&'
if (result.length() > 0) {
result.setLength(result.length() - 1);
}
return result.toString();
} | java | public static String paramMapToString(final Map<String, String[]> parameters) {
final StringBuffer result = new StringBuffer();
for (final String key : parameters.keySet()) {
String[] values = parameters.get(key);
if (null == values) {
result.append(key).append('&');
} else {
for (final String value : parameters.get(key)) {
result.append(key).append('=').append(CmsEncoder.encode(value)).append('&');
}
}
}
// remove last '&'
if (result.length() > 0) {
result.setLength(result.length() - 1);
}
return result.toString();
} | [
"public",
"static",
"String",
"paramMapToString",
"(",
"final",
"Map",
"<",
"String",
",",
"String",
"[",
"]",
">",
"parameters",
")",
"{",
"final",
"StringBuffer",
"result",
"=",
"new",
"StringBuffer",
"(",
")",
";",
"for",
"(",
"final",
"String",
"key",
... | Converts a parameter map to the parameter string.
@param parameters the parameter map.
@return the parameter string. | [
"Converts",
"a",
"parameter",
"map",
"to",
"the",
"parameter",
"string",
"."
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jsp/search/result/CmsSearchStateParameters.java#L91-L109 |
wildfly/wildfly-core | server/src/main/java/org/jboss/as/server/deployment/module/ManifestClassPathProcessor.java | ManifestClassPathProcessor.createResourceRoot | private synchronized ResourceRoot createResourceRoot(final VirtualFile file, final DeploymentUnit deploymentUnit, final VirtualFile deploymentRoot) throws DeploymentUnitProcessingException {
try {
Map<String, MountedDeploymentOverlay> overlays = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_OVERLAY_LOCATIONS);
String relativeName = file.getPathNameRelativeTo(deploymentRoot);
MountedDeploymentOverlay overlay = overlays.get(relativeName);
Closeable closable = null;
if(overlay != null) {
overlay.remountAsZip(false);
} else if(file.isFile()) {
closable = VFS.mountZip(file, file, TempFileProviderService.provider());
}
final MountHandle mountHandle = MountHandle.create(closable);
final ResourceRoot resourceRoot = new ResourceRoot(file, mountHandle);
ModuleRootMarker.mark(resourceRoot);
ResourceRootIndexer.indexResourceRoot(resourceRoot);
return resourceRoot;
} catch (IOException e) {
throw new RuntimeException(e);
}
} | java | private synchronized ResourceRoot createResourceRoot(final VirtualFile file, final DeploymentUnit deploymentUnit, final VirtualFile deploymentRoot) throws DeploymentUnitProcessingException {
try {
Map<String, MountedDeploymentOverlay> overlays = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_OVERLAY_LOCATIONS);
String relativeName = file.getPathNameRelativeTo(deploymentRoot);
MountedDeploymentOverlay overlay = overlays.get(relativeName);
Closeable closable = null;
if(overlay != null) {
overlay.remountAsZip(false);
} else if(file.isFile()) {
closable = VFS.mountZip(file, file, TempFileProviderService.provider());
}
final MountHandle mountHandle = MountHandle.create(closable);
final ResourceRoot resourceRoot = new ResourceRoot(file, mountHandle);
ModuleRootMarker.mark(resourceRoot);
ResourceRootIndexer.indexResourceRoot(resourceRoot);
return resourceRoot;
} catch (IOException e) {
throw new RuntimeException(e);
}
} | [
"private",
"synchronized",
"ResourceRoot",
"createResourceRoot",
"(",
"final",
"VirtualFile",
"file",
",",
"final",
"DeploymentUnit",
"deploymentUnit",
",",
"final",
"VirtualFile",
"deploymentRoot",
")",
"throws",
"DeploymentUnitProcessingException",
"{",
"try",
"{",
"Map... | Creates a {@link ResourceRoot} for the passed {@link VirtualFile file} and adds it to the list of {@link ResourceRoot}s
in the {@link DeploymentUnit deploymentUnit}
@param file The file for which the resource root will be created
@return Returns the created {@link ResourceRoot}
@throws java.io.IOException | [
"Creates",
"a",
"{",
"@link",
"ResourceRoot",
"}",
"for",
"the",
"passed",
"{",
"@link",
"VirtualFile",
"file",
"}",
"and",
"adds",
"it",
"to",
"the",
"list",
"of",
"{",
"@link",
"ResourceRoot",
"}",
"s",
"in",
"the",
"{",
"@link",
"DeploymentUnit",
"dep... | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/server/src/main/java/org/jboss/as/server/deployment/module/ManifestClassPathProcessor.java#L265-L285 |
elki-project/elki | addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/svg/SVGCheckbox.java | SVGCheckbox.renderCheckBox | public Element renderCheckBox(SVGPlot svgp, double x, double y, double size) {
// create check
final Element checkmark = SVGEffects.makeCheckmark(svgp);
checkmark.setAttribute(SVGConstants.SVG_TRANSFORM_ATTRIBUTE, "scale(" + (size / 12) + ") translate(" + x + " " + y + ")");
if(!checked) {
checkmark.setAttribute(SVGConstants.SVG_STYLE_ATTRIBUTE, SVGConstants.CSS_DISPLAY_PROPERTY + ":" + SVGConstants.CSS_NONE_VALUE);
}
// create box
Element checkbox_box = SVGUtil.svgRect(svgp.getDocument(), x, y, size, size);
checkbox_box.setAttribute(SVGConstants.SVG_FILL_ATTRIBUTE, "#d4e4f1");
checkbox_box.setAttribute(SVGConstants.SVG_STROKE_ATTRIBUTE, "#a0a0a0");
checkbox_box.setAttribute(SVGConstants.SVG_STROKE_WIDTH_ATTRIBUTE, "0.5");
// create checkbox
final Element checkbox = svgp.svgElement(SVGConstants.SVG_G_TAG);
checkbox.appendChild(checkbox_box);
checkbox.appendChild(checkmark);
// create Label
if(label != null) {
Element labele = svgp.svgText(x + 2 * size, y + size, label);
// TODO: font size!
checkbox.appendChild(labele);
}
// add click event listener
EventTarget targ = (EventTarget) checkbox;
targ.addEventListener(SVGConstants.SVG_CLICK_EVENT_TYPE, new EventListener() {
@Override
public void handleEvent(Event evt) {
if(checked ^= true) {
checkmark.removeAttribute(SVGConstants.SVG_STYLE_ATTRIBUTE);
}
else {
checkmark.setAttribute(SVGConstants.SVG_STYLE_ATTRIBUTE, SVGConstants.CSS_DISPLAY_PROPERTY + ":" + SVGConstants.CSS_NONE_VALUE);
}
fireSwitchEvent(new ChangeEvent(SVGCheckbox.this));
}
}, false);
return checkbox;
} | java | public Element renderCheckBox(SVGPlot svgp, double x, double y, double size) {
// create check
final Element checkmark = SVGEffects.makeCheckmark(svgp);
checkmark.setAttribute(SVGConstants.SVG_TRANSFORM_ATTRIBUTE, "scale(" + (size / 12) + ") translate(" + x + " " + y + ")");
if(!checked) {
checkmark.setAttribute(SVGConstants.SVG_STYLE_ATTRIBUTE, SVGConstants.CSS_DISPLAY_PROPERTY + ":" + SVGConstants.CSS_NONE_VALUE);
}
// create box
Element checkbox_box = SVGUtil.svgRect(svgp.getDocument(), x, y, size, size);
checkbox_box.setAttribute(SVGConstants.SVG_FILL_ATTRIBUTE, "#d4e4f1");
checkbox_box.setAttribute(SVGConstants.SVG_STROKE_ATTRIBUTE, "#a0a0a0");
checkbox_box.setAttribute(SVGConstants.SVG_STROKE_WIDTH_ATTRIBUTE, "0.5");
// create checkbox
final Element checkbox = svgp.svgElement(SVGConstants.SVG_G_TAG);
checkbox.appendChild(checkbox_box);
checkbox.appendChild(checkmark);
// create Label
if(label != null) {
Element labele = svgp.svgText(x + 2 * size, y + size, label);
// TODO: font size!
checkbox.appendChild(labele);
}
// add click event listener
EventTarget targ = (EventTarget) checkbox;
targ.addEventListener(SVGConstants.SVG_CLICK_EVENT_TYPE, new EventListener() {
@Override
public void handleEvent(Event evt) {
if(checked ^= true) {
checkmark.removeAttribute(SVGConstants.SVG_STYLE_ATTRIBUTE);
}
else {
checkmark.setAttribute(SVGConstants.SVG_STYLE_ATTRIBUTE, SVGConstants.CSS_DISPLAY_PROPERTY + ":" + SVGConstants.CSS_NONE_VALUE);
}
fireSwitchEvent(new ChangeEvent(SVGCheckbox.this));
}
}, false);
return checkbox;
} | [
"public",
"Element",
"renderCheckBox",
"(",
"SVGPlot",
"svgp",
",",
"double",
"x",
",",
"double",
"y",
",",
"double",
"size",
")",
"{",
"// create check",
"final",
"Element",
"checkmark",
"=",
"SVGEffects",
".",
"makeCheckmark",
"(",
"svgp",
")",
";",
"check... | Render the SVG checkbox to a plot
@param svgp Plot to draw to
@param x X offset
@param y Y offset
@param size Size factor
@return Container element | [
"Render",
"the",
"SVG",
"checkbox",
"to",
"a",
"plot"
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/svg/SVGCheckbox.java#L84-L125 |
percolate/caffeine | caffeine/src/main/java/com/percolate/caffeine/IntentUtils.java | IntentUtils.launchCameraIntent | public static void launchCameraIntent(final Activity context, final Uri outputDestination, final int requestCode){
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputDestination);
if (intent.resolveActivity(context.getPackageManager()) != null) {
grantUriPermissionsForIntent(context, outputDestination, intent);
context.startActivityForResult(intent, requestCode);
}
} | java | public static void launchCameraIntent(final Activity context, final Uri outputDestination, final int requestCode){
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputDestination);
if (intent.resolveActivity(context.getPackageManager()) != null) {
grantUriPermissionsForIntent(context, outputDestination, intent);
context.startActivityForResult(intent, requestCode);
}
} | [
"public",
"static",
"void",
"launchCameraIntent",
"(",
"final",
"Activity",
"context",
",",
"final",
"Uri",
"outputDestination",
",",
"final",
"int",
"requestCode",
")",
"{",
"final",
"Intent",
"intent",
"=",
"new",
"Intent",
"(",
"MediaStore",
".",
"ACTION_IMAG... | Launch camera on the device using android's ACTION_IMAGE_CAPTURE intent.
@param outputDestination Save image to this location. | [
"Launch",
"camera",
"on",
"the",
"device",
"using",
"android",
"s",
"ACTION_IMAGE_CAPTURE",
"intent",
"."
] | train | https://github.com/percolate/caffeine/blob/e2265cab474a6397f4d75b1ed928c356a7b9672e/caffeine/src/main/java/com/percolate/caffeine/IntentUtils.java#L67-L74 |
algolia/algoliasearch-client-java | src/main/java/com/algolia/search/saas/Index.java | Index.deleteObjects | public JSONObject deleteObjects(List<String> objects, RequestOptions requestOptions) throws AlgoliaException {
try {
JSONArray array = new JSONArray();
for (String id : objects) {
JSONObject obj = new JSONObject();
obj.put("objectID", id);
JSONObject action = new JSONObject();
action.put("action", "deleteObject");
action.put("body", obj);
array.put(action);
}
return batch(array, requestOptions);
} catch (JSONException e) {
throw new AlgoliaException(e.getMessage());
}
} | java | public JSONObject deleteObjects(List<String> objects, RequestOptions requestOptions) throws AlgoliaException {
try {
JSONArray array = new JSONArray();
for (String id : objects) {
JSONObject obj = new JSONObject();
obj.put("objectID", id);
JSONObject action = new JSONObject();
action.put("action", "deleteObject");
action.put("body", obj);
array.put(action);
}
return batch(array, requestOptions);
} catch (JSONException e) {
throw new AlgoliaException(e.getMessage());
}
} | [
"public",
"JSONObject",
"deleteObjects",
"(",
"List",
"<",
"String",
">",
"objects",
",",
"RequestOptions",
"requestOptions",
")",
"throws",
"AlgoliaException",
"{",
"try",
"{",
"JSONArray",
"array",
"=",
"new",
"JSONArray",
"(",
")",
";",
"for",
"(",
"String"... | Delete several objects
@param objects the array of objectIDs to delete
@param requestOptions Options to pass to this request | [
"Delete",
"several",
"objects"
] | train | https://github.com/algolia/algoliasearch-client-java/blob/a05da2f66c099fe6f77295c7b6a8a12c24e95f9b/src/main/java/com/algolia/search/saas/Index.java#L746-L761 |
wwadge/bonecp | bonecp/src/main/java/com/jolbox/bonecp/PoolWatchThread.java | PoolWatchThread.fillConnections | private void fillConnections(int connectionsToCreate) throws InterruptedException {
try {
for (int i=0; i < connectionsToCreate; i++){
// boolean dbDown = this.pool.getDbIsDown().get();
if (this.pool.poolShuttingDown){
break;
}
this.partition.addFreeConnection(new ConnectionHandle(null, this.partition, this.pool, false));
}
} catch (Exception e) {
logger.error("Error in trying to obtain a connection. Retrying in "+this.acquireRetryDelayInMs+"ms", e);
Thread.sleep(this.acquireRetryDelayInMs);
}
} | java | private void fillConnections(int connectionsToCreate) throws InterruptedException {
try {
for (int i=0; i < connectionsToCreate; i++){
// boolean dbDown = this.pool.getDbIsDown().get();
if (this.pool.poolShuttingDown){
break;
}
this.partition.addFreeConnection(new ConnectionHandle(null, this.partition, this.pool, false));
}
} catch (Exception e) {
logger.error("Error in trying to obtain a connection. Retrying in "+this.acquireRetryDelayInMs+"ms", e);
Thread.sleep(this.acquireRetryDelayInMs);
}
} | [
"private",
"void",
"fillConnections",
"(",
"int",
"connectionsToCreate",
")",
"throws",
"InterruptedException",
"{",
"try",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"connectionsToCreate",
";",
"i",
"++",
")",
"{",
"//\tboolean dbDown = this.pool.get... | Adds new connections to the partition.
@param connectionsToCreate number of connections to create
@throws InterruptedException | [
"Adds",
"new",
"connections",
"to",
"the",
"partition",
"."
] | train | https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/PoolWatchThread.java#L108-L122 |
jtablesaw/tablesaw | core/src/main/java/tech/tablesaw/table/TableSliceGroup.java | TableSliceGroup.aggregate | @SuppressWarnings({ "unchecked", "rawtypes" })
public Table aggregate(ListMultimap<String, AggregateFunction<?,?>> functions) {
Preconditions.checkArgument(!getSlices().isEmpty());
Table groupTable = summaryTableName(sourceTable);
StringColumn groupColumn = StringColumn.create("Group");
groupTable.addColumns(groupColumn);
for (Map.Entry<String, Collection<AggregateFunction<?,?>>> entry : functions.asMap().entrySet()) {
String columnName = entry.getKey();
int functionCount = 0;
for (AggregateFunction function : entry.getValue()) {
String colName = aggregateColumnName(columnName, function.functionName());
ColumnType type = function.returnType();
Column resultColumn = type.create(colName);
for (TableSlice subTable : getSlices()) {
Object result = function.summarize(subTable.column(columnName));
if (functionCount == 0) {
groupColumn.append(subTable.name());
}
if (result instanceof Number) {
Number number = (Number) result;
resultColumn.append(number.doubleValue());
} else {
resultColumn.append(result);
}
}
groupTable.addColumns(resultColumn);
functionCount++;
}
}
return splitGroupingColumn(groupTable);
} | java | @SuppressWarnings({ "unchecked", "rawtypes" })
public Table aggregate(ListMultimap<String, AggregateFunction<?,?>> functions) {
Preconditions.checkArgument(!getSlices().isEmpty());
Table groupTable = summaryTableName(sourceTable);
StringColumn groupColumn = StringColumn.create("Group");
groupTable.addColumns(groupColumn);
for (Map.Entry<String, Collection<AggregateFunction<?,?>>> entry : functions.asMap().entrySet()) {
String columnName = entry.getKey();
int functionCount = 0;
for (AggregateFunction function : entry.getValue()) {
String colName = aggregateColumnName(columnName, function.functionName());
ColumnType type = function.returnType();
Column resultColumn = type.create(colName);
for (TableSlice subTable : getSlices()) {
Object result = function.summarize(subTable.column(columnName));
if (functionCount == 0) {
groupColumn.append(subTable.name());
}
if (result instanceof Number) {
Number number = (Number) result;
resultColumn.append(number.doubleValue());
} else {
resultColumn.append(result);
}
}
groupTable.addColumns(resultColumn);
functionCount++;
}
}
return splitGroupingColumn(groupTable);
} | [
"@",
"SuppressWarnings",
"(",
"{",
"\"unchecked\"",
",",
"\"rawtypes\"",
"}",
")",
"public",
"Table",
"aggregate",
"(",
"ListMultimap",
"<",
"String",
",",
"AggregateFunction",
"<",
"?",
",",
"?",
">",
">",
"functions",
")",
"{",
"Preconditions",
".",
"check... | Applies the given aggregations to the given columns.
The apply and combine steps of a split-apply-combine.
@param functions map from column name to aggregation to apply on that function | [
"Applies",
"the",
"given",
"aggregations",
"to",
"the",
"given",
"columns",
".",
"The",
"apply",
"and",
"combine",
"steps",
"of",
"a",
"split",
"-",
"apply",
"-",
"combine",
"."
] | train | https://github.com/jtablesaw/tablesaw/blob/68a75b4098ac677e9486df5572cf13ec39f9f701/core/src/main/java/tech/tablesaw/table/TableSliceGroup.java#L150-L180 |
alkacon/opencms-core | src/org/opencms/cache/CmsVfsDiskCache.java | CmsVfsDiskCache.getCacheName | public String getCacheName(boolean online, String rootPath, String parameters) {
String rfsName = CmsFileUtil.getRepositoryName(m_rfsRepository, rootPath, online);
if (CmsStringUtil.isNotEmpty(parameters)) {
String extension = CmsFileUtil.getExtension(rfsName);
// build the RFS name for the VFS name with parameters
rfsName = CmsFileUtil.getRfsPath(rfsName, extension, parameters);
}
return rfsName;
} | java | public String getCacheName(boolean online, String rootPath, String parameters) {
String rfsName = CmsFileUtil.getRepositoryName(m_rfsRepository, rootPath, online);
if (CmsStringUtil.isNotEmpty(parameters)) {
String extension = CmsFileUtil.getExtension(rfsName);
// build the RFS name for the VFS name with parameters
rfsName = CmsFileUtil.getRfsPath(rfsName, extension, parameters);
}
return rfsName;
} | [
"public",
"String",
"getCacheName",
"(",
"boolean",
"online",
",",
"String",
"rootPath",
",",
"String",
"parameters",
")",
"{",
"String",
"rfsName",
"=",
"CmsFileUtil",
".",
"getRepositoryName",
"(",
"m_rfsRepository",
",",
"rootPath",
",",
"online",
")",
";",
... | Returns the RFS name to use for caching the given VFS resource with parameters in the disk cache.<p>
@param online if true, the online disk cache is used, the offline disk cache otherwise
@param rootPath the VFS resource root path to get the RFS cache name for
@param parameters the parameters of the request to the VFS resource
@return the RFS name to use for caching the given VFS resource with parameters | [
"Returns",
"the",
"RFS",
"name",
"to",
"use",
"for",
"caching",
"the",
"given",
"VFS",
"resource",
"with",
"parameters",
"in",
"the",
"disk",
"cache",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/cache/CmsVfsDiskCache.java#L124-L134 |
alkacon/opencms-core | src/org/opencms/security/CmsOrgUnitManager.java | CmsOrgUnitManager.writeOrganizationalUnit | public void writeOrganizationalUnit(CmsObject cms, CmsOrganizationalUnit organizationalUnit) throws CmsException {
m_securityManager.writeOrganizationalUnit(cms.getRequestContext(), organizationalUnit);
} | java | public void writeOrganizationalUnit(CmsObject cms, CmsOrganizationalUnit organizationalUnit) throws CmsException {
m_securityManager.writeOrganizationalUnit(cms.getRequestContext(), organizationalUnit);
} | [
"public",
"void",
"writeOrganizationalUnit",
"(",
"CmsObject",
"cms",
",",
"CmsOrganizationalUnit",
"organizationalUnit",
")",
"throws",
"CmsException",
"{",
"m_securityManager",
".",
"writeOrganizationalUnit",
"(",
"cms",
".",
"getRequestContext",
"(",
")",
",",
"organ... | Writes an already existing organizational unit.<p>
The organizational unit has to be a valid OpenCms organizational unit.<br>
The organizational unit will be completely overridden by the given data.<p>
@param cms the opencms context
@param organizationalUnit the organizational unit that should be written
@throws CmsException if operation was not successful | [
"Writes",
"an",
"already",
"existing",
"organizational",
"unit",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/security/CmsOrgUnitManager.java#L375-L378 |
pippo-java/pippo | pippo-server-parent/pippo-jetty/src/main/java/ro/pippo/jetty/JettyServer.java | JettyServer.asJettyFriendlyPath | private String asJettyFriendlyPath(String path, String name) {
try {
new URL(path);
log.debug("Defer interpretation of {} URL '{}' to Jetty", name, path);
return path;
} catch (MalformedURLException e) {
//Expected. We've got a path and not a URL
Path p = Paths.get(path);
if (Files.exists(Paths.get(path))) {
//Jetty knows how to find files on the file system
log.debug("Located {} '{}' on file system", name, path);
return path;
} else {
//Maybe it's a resource on the Classpath. Jetty needs that converted to a URL.
//(e.g. "jar:file:/path/to/my.jar!<path>")
URL url = JettyServer.class.getResource(path);
if (url != null) {
log.debug("Located {} '{}' on Classpath", name, path);
return url.toExternalForm();
} else {
throw new IllegalArgumentException(String.format("%s '%s' not found", name, path));
}
}
}
} | java | private String asJettyFriendlyPath(String path, String name) {
try {
new URL(path);
log.debug("Defer interpretation of {} URL '{}' to Jetty", name, path);
return path;
} catch (MalformedURLException e) {
//Expected. We've got a path and not a URL
Path p = Paths.get(path);
if (Files.exists(Paths.get(path))) {
//Jetty knows how to find files on the file system
log.debug("Located {} '{}' on file system", name, path);
return path;
} else {
//Maybe it's a resource on the Classpath. Jetty needs that converted to a URL.
//(e.g. "jar:file:/path/to/my.jar!<path>")
URL url = JettyServer.class.getResource(path);
if (url != null) {
log.debug("Located {} '{}' on Classpath", name, path);
return url.toExternalForm();
} else {
throw new IllegalArgumentException(String.format("%s '%s' not found", name, path));
}
}
}
} | [
"private",
"String",
"asJettyFriendlyPath",
"(",
"String",
"path",
",",
"String",
"name",
")",
"{",
"try",
"{",
"new",
"URL",
"(",
"path",
")",
";",
"log",
".",
"debug",
"(",
"\"Defer interpretation of {} URL '{}' to Jetty\"",
",",
"name",
",",
"path",
")",
... | Jetty treats non-URL paths are file paths interpreted in the current working directory.
Provide ability to accept paths to resources on the Classpath.
@param path
@param name Descriptive name of what is for. Used in logs, error messages
@return Path in a format Jetty will understand, even if it is a Classpath-relative path. | [
"Jetty",
"treats",
"non",
"-",
"URL",
"paths",
"are",
"file",
"paths",
"interpreted",
"in",
"the",
"current",
"working",
"directory",
".",
"Provide",
"ability",
"to",
"accept",
"paths",
"to",
"resources",
"on",
"the",
"Classpath",
"."
] | train | https://github.com/pippo-java/pippo/blob/cb5ccb453bffcc3cf386adc660674812d10b9726/pippo-server-parent/pippo-jetty/src/main/java/ro/pippo/jetty/JettyServer.java#L134-L158 |
jbundle/jbundle | thin/base/db/misc/src/main/java/org/jbundle/thin/base/db/client/memory/MemoryRemoteTable.java | MemoryRemoteTable.doRemoteAction | public Object doRemoteAction(String strCommand, Map<String, Object> properties) throws DBException, RemoteException
{
return null; // Not supported
} | java | public Object doRemoteAction(String strCommand, Map<String, Object> properties) throws DBException, RemoteException
{
return null; // Not supported
} | [
"public",
"Object",
"doRemoteAction",
"(",
"String",
"strCommand",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"properties",
")",
"throws",
"DBException",
",",
"RemoteException",
"{",
"return",
"null",
";",
"// Not supported",
"}"
] | Do a remote action.
Not implemented.
@param strCommand Command to perform remotely.
@param properties Properties for this command (optional).
@return boolean success. | [
"Do",
"a",
"remote",
"action",
".",
"Not",
"implemented",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/db/misc/src/main/java/org/jbundle/thin/base/db/client/memory/MemoryRemoteTable.java#L304-L307 |
haraldk/TwelveMonkeys | common/common-image/src/main/java/com/twelvemonkeys/image/IndexImage.java | IndexImage.applyAlpha | private static void applyAlpha(BufferedImage pImage, BufferedImage pAlpha) {
// Apply alpha as transparency, using threshold of 25%
for (int y = 0; y < pAlpha.getHeight(); y++) {
for (int x = 0; x < pAlpha.getWidth(); x++) {
// Get alpha component of pixel, if less than 25% opaque
// (0x40 = 64 => 25% of 256), the pixel will be transparent
if (((pAlpha.getRGB(x, y) >> 24) & 0xFF) < 0x40) {
pImage.setRGB(x, y, 0x00FFFFFF); // 100% transparent
}
}
}
} | java | private static void applyAlpha(BufferedImage pImage, BufferedImage pAlpha) {
// Apply alpha as transparency, using threshold of 25%
for (int y = 0; y < pAlpha.getHeight(); y++) {
for (int x = 0; x < pAlpha.getWidth(); x++) {
// Get alpha component of pixel, if less than 25% opaque
// (0x40 = 64 => 25% of 256), the pixel will be transparent
if (((pAlpha.getRGB(x, y) >> 24) & 0xFF) < 0x40) {
pImage.setRGB(x, y, 0x00FFFFFF); // 100% transparent
}
}
}
} | [
"private",
"static",
"void",
"applyAlpha",
"(",
"BufferedImage",
"pImage",
",",
"BufferedImage",
"pAlpha",
")",
"{",
"// Apply alpha as transparency, using threshold of 25%\r",
"for",
"(",
"int",
"y",
"=",
"0",
";",
"y",
"<",
"pAlpha",
".",
"getHeight",
"(",
")",
... | Applies the alpha-component of the alpha image to the given image.
The given image is modified in place.
@param pImage the image to apply alpha to
@param pAlpha the image containing the alpha | [
"Applies",
"the",
"alpha",
"-",
"component",
"of",
"the",
"alpha",
"image",
"to",
"the",
"given",
"image",
".",
"The",
"given",
"image",
"is",
"modified",
"in",
"place",
"."
] | train | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-image/src/main/java/com/twelvemonkeys/image/IndexImage.java#L1189-L1201 |
networknt/light-4j | http-url/src/main/java/com/networknt/url/HttpURL.java | HttpURL.toURI | public URI toURI() {
String url = toString();
try {
return new URI(url);
} catch (URISyntaxException e) {
throw new RuntimeException("Cannot convert to URI: " + url, e);
}
} | java | public URI toURI() {
String url = toString();
try {
return new URI(url);
} catch (URISyntaxException e) {
throw new RuntimeException("Cannot convert to URI: " + url, e);
}
} | [
"public",
"URI",
"toURI",
"(",
")",
"{",
"String",
"url",
"=",
"toString",
"(",
")",
";",
"try",
"{",
"return",
"new",
"URI",
"(",
"url",
")",
";",
"}",
"catch",
"(",
"URISyntaxException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Ca... | Converts this HttpURL to a {@link URI}, making sure
appropriate characters are escaped properly.
@return a URI
@since 1.7.0
@throws RuntimeException when URL is malformed | [
"Converts",
"this",
"HttpURL",
"to",
"a",
"{"
] | train | https://github.com/networknt/light-4j/blob/2a60257c60663684c8f6dc8b5ea3cf184e534db6/http-url/src/main/java/com/networknt/url/HttpURL.java#L299-L306 |
stephanenicolas/robospice | robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/request/RequestProgressManager.java | RequestProgressManager.dontNotifyRequestListenersForRequest | public void dontNotifyRequestListenersForRequest(final CachedSpiceRequest<?> request, final Collection<RequestListener<?>> listRequestListener) {
final Set<RequestListener<?>> setRequestListener = mapRequestToRequestListener.get(request);
requestListenerNotifier.clearNotificationsForRequest(request, setRequestListener);
if (setRequestListener != null && listRequestListener != null) {
Ln.d("Removing listeners of request : " + request.toString() + " : " + setRequestListener.size());
setRequestListener.removeAll(listRequestListener);
}
} | java | public void dontNotifyRequestListenersForRequest(final CachedSpiceRequest<?> request, final Collection<RequestListener<?>> listRequestListener) {
final Set<RequestListener<?>> setRequestListener = mapRequestToRequestListener.get(request);
requestListenerNotifier.clearNotificationsForRequest(request, setRequestListener);
if (setRequestListener != null && listRequestListener != null) {
Ln.d("Removing listeners of request : " + request.toString() + " : " + setRequestListener.size());
setRequestListener.removeAll(listRequestListener);
}
} | [
"public",
"void",
"dontNotifyRequestListenersForRequest",
"(",
"final",
"CachedSpiceRequest",
"<",
"?",
">",
"request",
",",
"final",
"Collection",
"<",
"RequestListener",
"<",
"?",
">",
">",
"listRequestListener",
")",
"{",
"final",
"Set",
"<",
"RequestListener",
... | Disable request listeners notifications for a specific request.<br/>
All listeners associated to this request won't be called when request
will finish.<br/>
@param request
Request on which you want to disable listeners
@param listRequestListener
the collection of listeners associated to request not to be
notified | [
"Disable",
"request",
"listeners",
"notifications",
"for",
"a",
"specific",
"request",
".",
"<br",
"/",
">",
"All",
"listeners",
"associated",
"to",
"this",
"request",
"won",
"t",
"be",
"called",
"when",
"request",
"will",
"finish",
".",
"<br",
"/",
">"
] | train | https://github.com/stephanenicolas/robospice/blob/8bffde88b3534a961a13cab72a8f07a755f0a0fe/robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/request/RequestProgressManager.java#L141-L150 |
OpenLiberty/open-liberty | dev/com.ibm.ws.ssl/src/com/ibm/ws/ssl/core/WSX509KeyManager.java | WSX509KeyManager.chooseEngineServerAlias | @Override
public String chooseEngineServerAlias(String keyType, Principal[] issuers, SSLEngine engine) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
Tr.entry(tc, "chooseEngineServerAlias", new Object[] { keyType, issuers, engine });
String rc = null;
if (null != customKM && customKM instanceof X509ExtendedKeyManager) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
Tr.debug(tc, "chooseEngineServerAlias, using customKM -> " + customKM.getClass().getName());
rc = ((X509ExtendedKeyManager) customKM).chooseEngineServerAlias(keyType, issuers, engine);
} else {
rc = chooseServerAlias(keyType, issuers);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
Tr.exit(tc, "chooseEngineServerAlias: " + rc);
return rc;
} | java | @Override
public String chooseEngineServerAlias(String keyType, Principal[] issuers, SSLEngine engine) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
Tr.entry(tc, "chooseEngineServerAlias", new Object[] { keyType, issuers, engine });
String rc = null;
if (null != customKM && customKM instanceof X509ExtendedKeyManager) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
Tr.debug(tc, "chooseEngineServerAlias, using customKM -> " + customKM.getClass().getName());
rc = ((X509ExtendedKeyManager) customKM).chooseEngineServerAlias(keyType, issuers, engine);
} else {
rc = chooseServerAlias(keyType, issuers);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
Tr.exit(tc, "chooseEngineServerAlias: " + rc);
return rc;
} | [
"@",
"Override",
"public",
"String",
"chooseEngineServerAlias",
"(",
"String",
"keyType",
",",
"Principal",
"[",
"]",
"issuers",
",",
"SSLEngine",
"engine",
")",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryE... | Handshakes that use the SSLEngine and not an SSLSocket require this method
from the extended X509KeyManager.
@see javax.net.ssl.X509ExtendedKeyManager#chooseEngineServerAlias(java.lang.String, java.security.Principal[], javax.net.ssl.SSLEngine) | [
"Handshakes",
"that",
"use",
"the",
"SSLEngine",
"and",
"not",
"an",
"SSLSocket",
"require",
"this",
"method",
"from",
"the",
"extended",
"X509KeyManager",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ssl/src/com/ibm/ws/ssl/core/WSX509KeyManager.java#L313-L329 |
bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/TransactionBroadcast.java | TransactionBroadcast.setProgressCallback | public void setProgressCallback(ProgressCallback callback, @Nullable Executor executor) {
boolean shouldInvoke;
int num;
boolean mined;
synchronized (this) {
this.callback = callback;
this.progressCallbackExecutor = executor;
num = this.numSeemPeers;
mined = this.mined;
shouldInvoke = numWaitingFor > 0;
}
if (shouldInvoke)
invokeProgressCallback(num, mined);
} | java | public void setProgressCallback(ProgressCallback callback, @Nullable Executor executor) {
boolean shouldInvoke;
int num;
boolean mined;
synchronized (this) {
this.callback = callback;
this.progressCallbackExecutor = executor;
num = this.numSeemPeers;
mined = this.mined;
shouldInvoke = numWaitingFor > 0;
}
if (shouldInvoke)
invokeProgressCallback(num, mined);
} | [
"public",
"void",
"setProgressCallback",
"(",
"ProgressCallback",
"callback",
",",
"@",
"Nullable",
"Executor",
"executor",
")",
"{",
"boolean",
"shouldInvoke",
";",
"int",
"num",
";",
"boolean",
"mined",
";",
"synchronized",
"(",
"this",
")",
"{",
"this",
"."... | Sets the given callback for receiving progress values, which will run on the given executor. If the executor
is null then the callback will run on a network thread and may be invoked multiple times in parallel. You
probably want to provide your UI thread or Threading.USER_THREAD for the second parameter. If the broadcast
has already started then the callback will be invoked immediately with the current progress. | [
"Sets",
"the",
"given",
"callback",
"for",
"receiving",
"progress",
"values",
"which",
"will",
"run",
"on",
"the",
"given",
"executor",
".",
"If",
"the",
"executor",
"is",
"null",
"then",
"the",
"callback",
"will",
"run",
"on",
"a",
"network",
"thread",
"a... | train | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/TransactionBroadcast.java#L279-L292 |
exoplatform/jcr | exo.jcr.component.webdav/src/main/java/org/exoplatform/services/jcr/webdav/lock/NullResourceLocksHolder.java | NullResourceLocksHolder.checkLock | public void checkLock(Session session, String path, List<String> tokens) throws LockException
{
String repoPath = session.getRepository().hashCode() + "/" + session.getWorkspace().getName() + "/" + path;
String currentToken = nullResourceLocks.get(repoPath);
if (currentToken == null)
{
return;
}
if (tokens != null)
{
for (String token : tokens)
{
if (token.equals(currentToken))
{
return;
}
}
}
throw new LockException("Resource already locked " + repoPath);
} | java | public void checkLock(Session session, String path, List<String> tokens) throws LockException
{
String repoPath = session.getRepository().hashCode() + "/" + session.getWorkspace().getName() + "/" + path;
String currentToken = nullResourceLocks.get(repoPath);
if (currentToken == null)
{
return;
}
if (tokens != null)
{
for (String token : tokens)
{
if (token.equals(currentToken))
{
return;
}
}
}
throw new LockException("Resource already locked " + repoPath);
} | [
"public",
"void",
"checkLock",
"(",
"Session",
"session",
",",
"String",
"path",
",",
"List",
"<",
"String",
">",
"tokens",
")",
"throws",
"LockException",
"{",
"String",
"repoPath",
"=",
"session",
".",
"getRepository",
"(",
")",
".",
"hashCode",
"(",
")"... | Checks if the node can be unlocked using current tokens.
@param session current session
@param path node path
@param tokens tokens
@throws LockException {@link LockException} | [
"Checks",
"if",
"the",
"node",
"can",
"be",
"unlocked",
"using",
"current",
"tokens",
"."
] | train | https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.webdav/src/main/java/org/exoplatform/services/jcr/webdav/lock/NullResourceLocksHolder.java#L123-L146 |
kiegroup/jbpm | jbpm-runtime-manager/src/main/java/org/jbpm/runtime/manager/impl/RuntimeEnvironmentBuilder.java | RuntimeEnvironmentBuilder.getDefault | public static RuntimeEnvironmentBuilder getDefault(String groupId, String artifactId, String version, String kbaseName, String ksessionName) {
KieServices ks = KieServices.Factory.get();
return getDefault(ks.newReleaseId(groupId, artifactId, version), kbaseName, ksessionName);
} | java | public static RuntimeEnvironmentBuilder getDefault(String groupId, String artifactId, String version, String kbaseName, String ksessionName) {
KieServices ks = KieServices.Factory.get();
return getDefault(ks.newReleaseId(groupId, artifactId, version), kbaseName, ksessionName);
} | [
"public",
"static",
"RuntimeEnvironmentBuilder",
"getDefault",
"(",
"String",
"groupId",
",",
"String",
"artifactId",
",",
"String",
"version",
",",
"String",
"kbaseName",
",",
"String",
"ksessionName",
")",
"{",
"KieServices",
"ks",
"=",
"KieServices",
".",
"Fact... | Provides default configuration of <code>RuntimeEnvironmentBuilder</code> that is based on:
<ul>
<li>DefaultRuntimeEnvironment</li>
</ul>
This one is tailored to works smoothly with kjars as the notion of kbase and ksessions
@param groupId group id of kjar
@param artifactId artifact id of kjar
@param version version number of kjar
@param kbaseName name of the kbase defined in kmodule.xml stored in kjar
@param ksessionName name of the ksession define in kmodule.xml stored in kjar
@return new instance of <code>RuntimeEnvironmentBuilder</code> that is already preconfigured with defaults
@see DefaultRuntimeEnvironment | [
"Provides",
"default",
"configuration",
"of",
"<code",
">",
"RuntimeEnvironmentBuilder<",
"/",
"code",
">",
"that",
"is",
"based",
"on",
":",
"<ul",
">",
"<li",
">",
"DefaultRuntimeEnvironment<",
"/",
"li",
">",
"<",
"/",
"ul",
">",
"This",
"one",
"is",
"t... | train | https://github.com/kiegroup/jbpm/blob/c3473c728aa382ebbea01e380c5e754a96647b82/jbpm-runtime-manager/src/main/java/org/jbpm/runtime/manager/impl/RuntimeEnvironmentBuilder.java#L163-L166 |
OpenLiberty/open-liberty | dev/com.ibm.ws.webcontainer.security/src/com/ibm/ws/webcontainer/security/ServletStartedListener.java | ServletStartedListener.updateSecurityMetadataWithRunAs | public void updateSecurityMetadataWithRunAs(SecurityMetadata securityMetadataFromDD, IServletConfig servletConfig) {
String runAs = servletConfig.getRunAsRole();
if (runAs != null) {
String servletName = servletConfig.getServletName();
//only add if there is no run-as entry in web.xml
Map<String, String> servletNameToRunAsRole = securityMetadataFromDD.getRunAsMap();
if (servletNameToRunAsRole.get(servletName) == null) {
servletNameToRunAsRole.put(servletName, runAs);
List<String> allRoles = securityMetadataFromDD.getRoles();
if (!allRoles.contains(runAs)) {
allRoles.add(runAs);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Added runAs role: " + runAs);
}
}
}
} | java | public void updateSecurityMetadataWithRunAs(SecurityMetadata securityMetadataFromDD, IServletConfig servletConfig) {
String runAs = servletConfig.getRunAsRole();
if (runAs != null) {
String servletName = servletConfig.getServletName();
//only add if there is no run-as entry in web.xml
Map<String, String> servletNameToRunAsRole = securityMetadataFromDD.getRunAsMap();
if (servletNameToRunAsRole.get(servletName) == null) {
servletNameToRunAsRole.put(servletName, runAs);
List<String> allRoles = securityMetadataFromDD.getRoles();
if (!allRoles.contains(runAs)) {
allRoles.add(runAs);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Added runAs role: " + runAs);
}
}
}
} | [
"public",
"void",
"updateSecurityMetadataWithRunAs",
"(",
"SecurityMetadata",
"securityMetadataFromDD",
",",
"IServletConfig",
"servletConfig",
")",
"{",
"String",
"runAs",
"=",
"servletConfig",
".",
"getRunAsRole",
"(",
")",
";",
"if",
"(",
"runAs",
"!=",
"null",
"... | Updates the security metadata object (which at this time only has the deployment descriptor info)
with the runAs roles defined in the servlet. The sources are the web.xml, static annotations,
and dynamic annotations.
@param securityMetadataFromDD the security metadata processed from the deployment descriptor
@param servletConfig the configuration of the servlet | [
"Updates",
"the",
"security",
"metadata",
"object",
"(",
"which",
"at",
"this",
"time",
"only",
"has",
"the",
"deployment",
"descriptor",
"info",
")",
"with",
"the",
"runAs",
"roles",
"defined",
"in",
"the",
"servlet",
".",
"The",
"sources",
"are",
"the",
... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.webcontainer.security/src/com/ibm/ws/webcontainer/security/ServletStartedListener.java#L230-L247 |
Erudika/para | para-core/src/main/java/com/erudika/para/utils/Utils.java | Utils.stripAndTrim | public static String stripAndTrim(String str, String replaceWith, boolean asciiOnly) {
if (StringUtils.isBlank(str)) {
return "";
}
String s = str;
if (asciiOnly) {
s = str.replaceAll("[^\\p{ASCII}]", "");
}
return s.replaceAll("[\\p{S}\\p{P}\\p{C}]", replaceWith).replaceAll("\\p{Z}+", " ").trim();
} | java | public static String stripAndTrim(String str, String replaceWith, boolean asciiOnly) {
if (StringUtils.isBlank(str)) {
return "";
}
String s = str;
if (asciiOnly) {
s = str.replaceAll("[^\\p{ASCII}]", "");
}
return s.replaceAll("[\\p{S}\\p{P}\\p{C}]", replaceWith).replaceAll("\\p{Z}+", " ").trim();
} | [
"public",
"static",
"String",
"stripAndTrim",
"(",
"String",
"str",
",",
"String",
"replaceWith",
",",
"boolean",
"asciiOnly",
")",
"{",
"if",
"(",
"StringUtils",
".",
"isBlank",
"(",
"str",
")",
")",
"{",
"return",
"\"\"",
";",
"}",
"String",
"s",
"=",
... | Strips all symbols, punctuation, whitespace and control chars from a string.
@param str a dirty string
@param replaceWith a string to replace spaces with
@param asciiOnly if true, all non-ASCII characters will be stripped
@return a clean string | [
"Strips",
"all",
"symbols",
"punctuation",
"whitespace",
"and",
"control",
"chars",
"from",
"a",
"string",
"."
] | train | https://github.com/Erudika/para/blob/5ba096c477042ea7b18e9a0e8b5b1ee0f5bd6ce9/para-core/src/main/java/com/erudika/para/utils/Utils.java#L347-L356 |
BorderTech/wcomponents | wcomponents-core/src/main/java/com/github/bordertech/wcomponents/AbstractInput.java | AbstractInput.showIndicatorsForComponent | protected void showIndicatorsForComponent(final List<Diagnostic> diags, final int severity) {
InputModel model = getOrCreateComponentModel();
if (severity == Diagnostic.ERROR) {
model.errorDiagnostics.clear();
} else {
model.warningDiagnostics.clear();
}
UIContext uic = UIContextHolder.getCurrent();
for (int i = 0; i < diags.size(); i++) {
Diagnostic diagnostic = diags.get(i);
// NOTE: double equals because they must be the same instance.
if (diagnostic.getSeverity() == severity && uic == diagnostic.getContext() && this == diagnostic.getComponent()) {
if (severity == Diagnostic.ERROR) {
model.errorDiagnostics.add(diagnostic);
} else {
model.warningDiagnostics.add(diagnostic);
}
}
}
} | java | protected void showIndicatorsForComponent(final List<Diagnostic> diags, final int severity) {
InputModel model = getOrCreateComponentModel();
if (severity == Diagnostic.ERROR) {
model.errorDiagnostics.clear();
} else {
model.warningDiagnostics.clear();
}
UIContext uic = UIContextHolder.getCurrent();
for (int i = 0; i < diags.size(); i++) {
Diagnostic diagnostic = diags.get(i);
// NOTE: double equals because they must be the same instance.
if (diagnostic.getSeverity() == severity && uic == diagnostic.getContext() && this == diagnostic.getComponent()) {
if (severity == Diagnostic.ERROR) {
model.errorDiagnostics.add(diagnostic);
} else {
model.warningDiagnostics.add(diagnostic);
}
}
}
} | [
"protected",
"void",
"showIndicatorsForComponent",
"(",
"final",
"List",
"<",
"Diagnostic",
">",
"diags",
",",
"final",
"int",
"severity",
")",
"{",
"InputModel",
"model",
"=",
"getOrCreateComponentModel",
"(",
")",
";",
"if",
"(",
"severity",
"==",
"Diagnostic"... | Iterates over the {@link Diagnostic}s and finds the diagnostics that related to the current component.
@param diags A List of Diagnostic objects.
@param severity A Diagnostic severity code. e.g. {@link Diagnostic#ERROR} | [
"Iterates",
"over",
"the",
"{",
"@link",
"Diagnostic",
"}",
"s",
"and",
"finds",
"the",
"diagnostics",
"that",
"related",
"to",
"the",
"current",
"component",
"."
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/AbstractInput.java#L431-L450 |
codescape/bitvunit | bitvunit-core/src/main/java/de/codescape/bitvunit/util/html/HtmlPageUtil.java | HtmlPageUtil.toHtmlPage | public static HtmlPage toHtmlPage(URL url) {
try {
return (HtmlPage) new WebClient().getPage(url);
} catch (IOException e) {
throw new RuntimeException("Error creating HtmlPage from URL.", e);
}
} | java | public static HtmlPage toHtmlPage(URL url) {
try {
return (HtmlPage) new WebClient().getPage(url);
} catch (IOException e) {
throw new RuntimeException("Error creating HtmlPage from URL.", e);
}
} | [
"public",
"static",
"HtmlPage",
"toHtmlPage",
"(",
"URL",
"url",
")",
"{",
"try",
"{",
"return",
"(",
"HtmlPage",
")",
"new",
"WebClient",
"(",
")",
".",
"getPage",
"(",
"url",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new"... | Creates a {@link HtmlPage} from a given {@link URL} that points to the HTML code for that page.
@param url {@link URL} that points to the HTML code
@return {@link HtmlPage} for this {@link URL} | [
"Creates",
"a",
"{",
"@link",
"HtmlPage",
"}",
"from",
"a",
"given",
"{",
"@link",
"URL",
"}",
"that",
"points",
"to",
"the",
"HTML",
"code",
"for",
"that",
"page",
"."
] | train | https://github.com/codescape/bitvunit/blob/cef6d9af60d684e41294981c10b6d92c8f063a4e/bitvunit-core/src/main/java/de/codescape/bitvunit/util/html/HtmlPageUtil.java#L75-L81 |
alkacon/opencms-core | src/org/opencms/search/CmsSearchIndex.java | CmsSearchIndex.isSortScoring | protected boolean isSortScoring(IndexSearcher searcher, Sort sort) {
boolean doScoring = false;
if (sort != null) {
if ((sort == CmsSearchParameters.SORT_DEFAULT) || (sort == CmsSearchParameters.SORT_TITLE)) {
// these default sorts do need score calculation
doScoring = true;
} else if ((sort == CmsSearchParameters.SORT_DATE_CREATED)
|| (sort == CmsSearchParameters.SORT_DATE_LASTMODIFIED)) {
// these default sorts don't need score calculation
doScoring = false;
} else {
// for all non-defaults: check if the score field is present, in that case we must calculate the score
SortField[] fields = sort.getSort();
for (SortField field : fields) {
if (field == SortField.FIELD_SCORE) {
doScoring = true;
break;
}
}
}
}
return doScoring;
} | java | protected boolean isSortScoring(IndexSearcher searcher, Sort sort) {
boolean doScoring = false;
if (sort != null) {
if ((sort == CmsSearchParameters.SORT_DEFAULT) || (sort == CmsSearchParameters.SORT_TITLE)) {
// these default sorts do need score calculation
doScoring = true;
} else if ((sort == CmsSearchParameters.SORT_DATE_CREATED)
|| (sort == CmsSearchParameters.SORT_DATE_LASTMODIFIED)) {
// these default sorts don't need score calculation
doScoring = false;
} else {
// for all non-defaults: check if the score field is present, in that case we must calculate the score
SortField[] fields = sort.getSort();
for (SortField field : fields) {
if (field == SortField.FIELD_SCORE) {
doScoring = true;
break;
}
}
}
}
return doScoring;
} | [
"protected",
"boolean",
"isSortScoring",
"(",
"IndexSearcher",
"searcher",
",",
"Sort",
"sort",
")",
"{",
"boolean",
"doScoring",
"=",
"false",
";",
"if",
"(",
"sort",
"!=",
"null",
")",
"{",
"if",
"(",
"(",
"sort",
"==",
"CmsSearchParameters",
".",
"SORT_... | Checks if the score for the results must be calculated based on the provided sort option.<p>
Since Lucene 3 apparently the score is no longer calculated by default, but only if the
searcher is explicitly told so. This methods checks if, based on the given sort,
the score must be calculated.<p>
@param searcher the index searcher to prepare
@param sort the sort option to use
@return true if the sort option should be used | [
"Checks",
"if",
"the",
"score",
"for",
"the",
"results",
"must",
"be",
"calculated",
"based",
"on",
"the",
"provided",
"sort",
"option",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/search/CmsSearchIndex.java#L1922-L1945 |
square/okhttp | okhttp/src/main/java/okhttp3/internal/http/HttpHeaders.java | HttpHeaders.skipUntil | public static int skipUntil(String input, int pos, String characters) {
for (; pos < input.length(); pos++) {
if (characters.indexOf(input.charAt(pos)) != -1) {
break;
}
}
return pos;
} | java | public static int skipUntil(String input, int pos, String characters) {
for (; pos < input.length(); pos++) {
if (characters.indexOf(input.charAt(pos)) != -1) {
break;
}
}
return pos;
} | [
"public",
"static",
"int",
"skipUntil",
"(",
"String",
"input",
",",
"int",
"pos",
",",
"String",
"characters",
")",
"{",
"for",
"(",
";",
"pos",
"<",
"input",
".",
"length",
"(",
")",
";",
"pos",
"++",
")",
"{",
"if",
"(",
"characters",
".",
"inde... | Returns the next index in {@code input} at or after {@code pos} that contains a character from
{@code characters}. Returns the input length if none of the requested characters can be found. | [
"Returns",
"the",
"next",
"index",
"in",
"{"
] | train | https://github.com/square/okhttp/blob/a8c65a822dd6cadd2de7d115bf94adf312e67868/okhttp/src/main/java/okhttp3/internal/http/HttpHeaders.java#L360-L367 |
jbundle/jbundle | base/base/src/main/java/org/jbundle/base/field/BaseField.java | BaseField.moveSQLToField | public void moveSQLToField(ResultSet resultset, int iColumn) throws SQLException
{
String strResult = resultset.getString(iColumn);
if (resultset.wasNull())
this.setString(Constants.BLANK, false, DBConstants.READ_MOVE); // Null value
else
this.setString(strResult, false, DBConstants.READ_MOVE);
} | java | public void moveSQLToField(ResultSet resultset, int iColumn) throws SQLException
{
String strResult = resultset.getString(iColumn);
if (resultset.wasNull())
this.setString(Constants.BLANK, false, DBConstants.READ_MOVE); // Null value
else
this.setString(strResult, false, DBConstants.READ_MOVE);
} | [
"public",
"void",
"moveSQLToField",
"(",
"ResultSet",
"resultset",
",",
"int",
"iColumn",
")",
"throws",
"SQLException",
"{",
"String",
"strResult",
"=",
"resultset",
".",
"getString",
"(",
"iColumn",
")",
";",
"if",
"(",
"resultset",
".",
"wasNull",
"(",
")... | Move the physical binary data to this SQL parameter row.
This is overidden to move the physical data type.
@param resultset The resultset to get the SQL data from.
@param iColumn the column in the resultset that has my data.
@exception SQLException From SQL calls. | [
"Move",
"the",
"physical",
"binary",
"data",
"to",
"this",
"SQL",
"parameter",
"row",
".",
"This",
"is",
"overidden",
"to",
"move",
"the",
"physical",
"data",
"type",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/field/BaseField.java#L836-L843 |
Appendium/flatpack | flatpack/src/main/java/net/sf/flatpack/ordering/OrderBy.java | OrderBy.compare | @Override
public int compare(final Row row0, final Row row1) {
int result = 0;
for (int i = 0; i < orderbys.size(); i++) {
final OrderColumn oc = orderbys.get(i);
// null indicates "detail" record which is what the parser assigns
// to <column> 's setup outside of <record> elements
final String mdkey0 = row0.getMdkey() == null ? FPConstants.DETAIL_ID : row0.getMdkey();
final String mdkey1 = row1.getMdkey() == null ? FPConstants.DETAIL_ID : row1.getMdkey();
// shift all non detail records to the bottom of the DataSet
if (!mdkey0.equals(FPConstants.DETAIL_ID) && !mdkey1.equals(FPConstants.DETAIL_ID)) {
// keep headers / trailers in the same order at the bottom of
// the DataSet
return 0;
} else if (!mdkey0.equals(FPConstants.DETAIL_ID) || !mdkey1.equals(FPConstants.DETAIL_ID)) {
return !mdkey0.equals(FPConstants.DETAIL_ID) ? 1 : 0;
}
result = compareCol(row0, row1, oc);
// if it is = 0 then the primary sort is done, and it can start the
// secondary sorts
if (result != 0) {
break;
}
}
return result;
} | java | @Override
public int compare(final Row row0, final Row row1) {
int result = 0;
for (int i = 0; i < orderbys.size(); i++) {
final OrderColumn oc = orderbys.get(i);
// null indicates "detail" record which is what the parser assigns
// to <column> 's setup outside of <record> elements
final String mdkey0 = row0.getMdkey() == null ? FPConstants.DETAIL_ID : row0.getMdkey();
final String mdkey1 = row1.getMdkey() == null ? FPConstants.DETAIL_ID : row1.getMdkey();
// shift all non detail records to the bottom of the DataSet
if (!mdkey0.equals(FPConstants.DETAIL_ID) && !mdkey1.equals(FPConstants.DETAIL_ID)) {
// keep headers / trailers in the same order at the bottom of
// the DataSet
return 0;
} else if (!mdkey0.equals(FPConstants.DETAIL_ID) || !mdkey1.equals(FPConstants.DETAIL_ID)) {
return !mdkey0.equals(FPConstants.DETAIL_ID) ? 1 : 0;
}
result = compareCol(row0, row1, oc);
// if it is = 0 then the primary sort is done, and it can start the
// secondary sorts
if (result != 0) {
break;
}
}
return result;
} | [
"@",
"Override",
"public",
"int",
"compare",
"(",
"final",
"Row",
"row0",
",",
"final",
"Row",
"row1",
")",
"{",
"int",
"result",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"orderbys",
".",
"size",
"(",
")",
";",
"i",
"++",... | overridden from the Comparator class.
Performs the sort
@return int | [
"overridden",
"from",
"the",
"Comparator",
"class",
"."
] | train | https://github.com/Appendium/flatpack/blob/5e09875d97db7038e3ba6af9468f5313d99b0082/flatpack/src/main/java/net/sf/flatpack/ordering/OrderBy.java#L84-L114 |
google/error-prone-javac | src/jdk.compiler/share/classes/com/sun/tools/javac/main/JavaCompiler.java | JavaCompiler.genCode | JavaFileObject genCode(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
try {
if (gen.genClass(env, cdef) && (errorCount() == 0))
return writer.writeClass(cdef.sym);
} catch (ClassWriter.PoolOverflow ex) {
log.error(cdef.pos(), "limit.pool");
} catch (ClassWriter.StringOverflow ex) {
log.error(cdef.pos(), "limit.string.overflow",
ex.value.substring(0, 20));
} catch (CompletionFailure ex) {
chk.completionError(cdef.pos(), ex);
}
return null;
} | java | JavaFileObject genCode(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
try {
if (gen.genClass(env, cdef) && (errorCount() == 0))
return writer.writeClass(cdef.sym);
} catch (ClassWriter.PoolOverflow ex) {
log.error(cdef.pos(), "limit.pool");
} catch (ClassWriter.StringOverflow ex) {
log.error(cdef.pos(), "limit.string.overflow",
ex.value.substring(0, 20));
} catch (CompletionFailure ex) {
chk.completionError(cdef.pos(), ex);
}
return null;
} | [
"JavaFileObject",
"genCode",
"(",
"Env",
"<",
"AttrContext",
">",
"env",
",",
"JCClassDecl",
"cdef",
")",
"throws",
"IOException",
"{",
"try",
"{",
"if",
"(",
"gen",
".",
"genClass",
"(",
"env",
",",
"cdef",
")",
"&&",
"(",
"errorCount",
"(",
")",
"=="... | Generate code and emit a class file for a given class
@param env The attribution environment of the outermost class
containing this class.
@param cdef The class definition from which code is generated. | [
"Generate",
"code",
"and",
"emit",
"a",
"class",
"file",
"for",
"a",
"given",
"class"
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/main/JavaCompiler.java#L740-L753 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/jar/Attributes.java | Attributes.putValue | public String putValue(String name, String value) {
return (String)put(new Name(name), value);
} | java | public String putValue(String name, String value) {
return (String)put(new Name(name), value);
} | [
"public",
"String",
"putValue",
"(",
"String",
"name",
",",
"String",
"value",
")",
"{",
"return",
"(",
"String",
")",
"put",
"(",
"new",
"Name",
"(",
"name",
")",
",",
"value",
")",
";",
"}"
] | Associates the specified value with the specified attribute name,
specified as a String. The attributes name is case-insensitive.
If the Map previously contained a mapping for the attribute name,
the old value is replaced.
<p>
This method is defined as:
<pre>
return (String)put(new Attributes.Name(name), value);
</pre>
@param name the attribute name as a string
@param value the attribute value
@return the previous value of the attribute, or null if none
@exception IllegalArgumentException if the attribute name is invalid | [
"Associates",
"the",
"specified",
"value",
"with",
"the",
"specified",
"attribute",
"name",
"specified",
"as",
"a",
"String",
".",
"The",
"attributes",
"name",
"is",
"case",
"-",
"insensitive",
".",
"If",
"the",
"Map",
"previously",
"contained",
"a",
"mapping"... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/jar/Attributes.java#L168-L170 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/utils/DOMHelper.java | DOMHelper.getNamespaceForPrefix | public String getNamespaceForPrefix(String prefix, Element namespaceContext)
{
int type;
Node parent = namespaceContext;
String namespace = null;
if (prefix.equals("xml"))
{
namespace = QName.S_XMLNAMESPACEURI; // Hardcoded, per Namespace spec
}
else if(prefix.equals("xmlns"))
{
// Hardcoded in the DOM spec, expected to be adopted by
// Namespace spec. NOTE: Namespace declarations _must_ use
// the xmlns: prefix; other prefixes declared as belonging
// to this namespace will not be recognized and should
// probably be rejected by parsers as erroneous declarations.
namespace = "http://www.w3.org/2000/xmlns/";
}
else
{
// Attribute name for this prefix's declaration
String declname=(prefix=="")
? "xmlns"
: "xmlns:"+prefix;
// Scan until we run out of Elements or have resolved the namespace
while ((null != parent) && (null == namespace)
&& (((type = parent.getNodeType()) == Node.ELEMENT_NODE)
|| (type == Node.ENTITY_REFERENCE_NODE)))
{
if (type == Node.ELEMENT_NODE)
{
// Look for the appropriate Namespace Declaration attribute,
// either "xmlns:prefix" or (if prefix is "") "xmlns".
// TODO: This does not handle "implicit declarations"
// which may be created when the DOM is edited. DOM Level
// 3 will define how those should be interpreted. But
// this issue won't arise in freshly-parsed DOMs.
// NOTE: declname is set earlier, outside the loop.
Attr attr=((Element)parent).getAttributeNode(declname);
if(attr!=null)
{
namespace = attr.getNodeValue();
break;
}
}
parent = getParentOfNode(parent);
}
}
return namespace;
} | java | public String getNamespaceForPrefix(String prefix, Element namespaceContext)
{
int type;
Node parent = namespaceContext;
String namespace = null;
if (prefix.equals("xml"))
{
namespace = QName.S_XMLNAMESPACEURI; // Hardcoded, per Namespace spec
}
else if(prefix.equals("xmlns"))
{
// Hardcoded in the DOM spec, expected to be adopted by
// Namespace spec. NOTE: Namespace declarations _must_ use
// the xmlns: prefix; other prefixes declared as belonging
// to this namespace will not be recognized and should
// probably be rejected by parsers as erroneous declarations.
namespace = "http://www.w3.org/2000/xmlns/";
}
else
{
// Attribute name for this prefix's declaration
String declname=(prefix=="")
? "xmlns"
: "xmlns:"+prefix;
// Scan until we run out of Elements or have resolved the namespace
while ((null != parent) && (null == namespace)
&& (((type = parent.getNodeType()) == Node.ELEMENT_NODE)
|| (type == Node.ENTITY_REFERENCE_NODE)))
{
if (type == Node.ELEMENT_NODE)
{
// Look for the appropriate Namespace Declaration attribute,
// either "xmlns:prefix" or (if prefix is "") "xmlns".
// TODO: This does not handle "implicit declarations"
// which may be created when the DOM is edited. DOM Level
// 3 will define how those should be interpreted. But
// this issue won't arise in freshly-parsed DOMs.
// NOTE: declname is set earlier, outside the loop.
Attr attr=((Element)parent).getAttributeNode(declname);
if(attr!=null)
{
namespace = attr.getNodeValue();
break;
}
}
parent = getParentOfNode(parent);
}
}
return namespace;
} | [
"public",
"String",
"getNamespaceForPrefix",
"(",
"String",
"prefix",
",",
"Element",
"namespaceContext",
")",
"{",
"int",
"type",
";",
"Node",
"parent",
"=",
"namespaceContext",
";",
"String",
"namespace",
"=",
"null",
";",
"if",
"(",
"prefix",
".",
"equals",... | Given an XML Namespace prefix and a context in which the prefix
is to be evaluated, return the Namespace Name this prefix was
bound to. Note that DOM Level 3 is expected to provide a version of
this which deals with the DOM's "early binding" behavior.
Default handling:
@param prefix String containing namespace prefix to be resolved,
without the ':' which separates it from the localname when used
in a Node Name. The empty sting signifies the default namespace
at this point in the document.
@param namespaceContext Element which provides context for resolution.
(We could extend this to work for other nodes by first seeking their
nearest Element ancestor.)
@return a String containing the Namespace URI which this prefix
represents in the specified context. | [
"Given",
"an",
"XML",
"Namespace",
"prefix",
"and",
"a",
"context",
"in",
"which",
"the",
"prefix",
"is",
"to",
"be",
"evaluated",
"return",
"the",
"Namespace",
"Name",
"this",
"prefix",
"was",
"bound",
"to",
".",
"Note",
"that",
"DOM",
"Level",
"3",
"is... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/utils/DOMHelper.java#L512-L568 |
micrometer-metrics/micrometer | micrometer-core/src/main/java/io/micrometer/core/instrument/binder/cache/HazelcastCacheMetrics.java | HazelcastCacheMetrics.monitor | public static <K, V, C extends IMap<K, V>> C monitor(MeterRegistry registry, C cache, Iterable<Tag> tags) {
new HazelcastCacheMetrics(cache, tags).bindTo(registry);
return cache;
} | java | public static <K, V, C extends IMap<K, V>> C monitor(MeterRegistry registry, C cache, Iterable<Tag> tags) {
new HazelcastCacheMetrics(cache, tags).bindTo(registry);
return cache;
} | [
"public",
"static",
"<",
"K",
",",
"V",
",",
"C",
"extends",
"IMap",
"<",
"K",
",",
"V",
">",
">",
"C",
"monitor",
"(",
"MeterRegistry",
"registry",
",",
"C",
"cache",
",",
"Iterable",
"<",
"Tag",
">",
"tags",
")",
"{",
"new",
"HazelcastCacheMetrics"... | Record metrics on a Hazelcast cache.
@param registry The registry to bind metrics to.
@param cache The cache to instrument.
@param tags Tags to apply to all recorded metrics.
@param <C> The cache type.
@param <K> The cache key type.
@param <V> The cache value type.
@return The instrumented cache, unchanged. The original cache is not wrapped or proxied in any way. | [
"Record",
"metrics",
"on",
"a",
"Hazelcast",
"cache",
"."
] | train | https://github.com/micrometer-metrics/micrometer/blob/127fa3265325cc894f368312ed8890b76a055d88/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/cache/HazelcastCacheMetrics.java#L62-L65 |
hsiafan/requests | src/main/java/net/dongliu/requests/utils/CookieDateUtil.java | CookieDateUtil.formatDate | public static String formatDate(Date date, String pattern) {
SimpleDateFormat formatter = new SimpleDateFormat(pattern, Locale.US);
formatter.setTimeZone(GMT);
return formatter.format(date);
} | java | public static String formatDate(Date date, String pattern) {
SimpleDateFormat formatter = new SimpleDateFormat(pattern, Locale.US);
formatter.setTimeZone(GMT);
return formatter.format(date);
} | [
"public",
"static",
"String",
"formatDate",
"(",
"Date",
"date",
",",
"String",
"pattern",
")",
"{",
"SimpleDateFormat",
"formatter",
"=",
"new",
"SimpleDateFormat",
"(",
"pattern",
",",
"Locale",
".",
"US",
")",
";",
"formatter",
".",
"setTimeZone",
"(",
"G... | Formats the given date according to the specified pattern. The pattern
must conform to that used by the {@link SimpleDateFormat simple date
format} class.
@param date The date to format.
@param pattern The pattern to use for formatting the date.
@return A formatted date string.
@throws IllegalArgumentException If the given date pattern is invalid.
@see SimpleDateFormat | [
"Formats",
"the",
"given",
"date",
"according",
"to",
"the",
"specified",
"pattern",
".",
"The",
"pattern",
"must",
"conform",
"to",
"that",
"used",
"by",
"the",
"{",
"@link",
"SimpleDateFormat",
"simple",
"date",
"format",
"}",
"class",
"."
] | train | https://github.com/hsiafan/requests/blob/a6cc6f8293e808cc937d3789aec2616a8383dee0/src/main/java/net/dongliu/requests/utils/CookieDateUtil.java#L137-L141 |
cdk/cdk | display/renderbasic/src/main/java/org/openscience/cdk/renderer/generators/BasicBondGenerator.java | BasicBondGenerator.generateInnerElement | public LineElement generateInnerElement(IBond bond, IRing ring, RendererModel model) {
Point2d center = GeometryUtil.get2DCenter(ring);
Point2d a = bond.getBegin().getPoint2d();
Point2d b = bond.getEnd().getPoint2d();
// the proportion to move in towards the ring center
double distanceFactor = model.getParameter(TowardsRingCenterProportion.class).getValue();
double ringDistance = distanceFactor * IDEAL_RINGSIZE / ring.getAtomCount();
if (ringDistance < distanceFactor / MIN_RINGSIZE_FACTOR) ringDistance = distanceFactor / MIN_RINGSIZE_FACTOR;
Point2d w = new Point2d();
w.interpolate(a, center, ringDistance);
Point2d u = new Point2d();
u.interpolate(b, center, ringDistance);
double alpha = 0.2;
Point2d ww = new Point2d();
ww.interpolate(w, u, alpha);
Point2d uu = new Point2d();
uu.interpolate(u, w, alpha);
double width = getWidthForBond(bond, model);
Color color = getColorForBond(bond, model);
return new LineElement(u.x, u.y, w.x, w.y, width, color);
} | java | public LineElement generateInnerElement(IBond bond, IRing ring, RendererModel model) {
Point2d center = GeometryUtil.get2DCenter(ring);
Point2d a = bond.getBegin().getPoint2d();
Point2d b = bond.getEnd().getPoint2d();
// the proportion to move in towards the ring center
double distanceFactor = model.getParameter(TowardsRingCenterProportion.class).getValue();
double ringDistance = distanceFactor * IDEAL_RINGSIZE / ring.getAtomCount();
if (ringDistance < distanceFactor / MIN_RINGSIZE_FACTOR) ringDistance = distanceFactor / MIN_RINGSIZE_FACTOR;
Point2d w = new Point2d();
w.interpolate(a, center, ringDistance);
Point2d u = new Point2d();
u.interpolate(b, center, ringDistance);
double alpha = 0.2;
Point2d ww = new Point2d();
ww.interpolate(w, u, alpha);
Point2d uu = new Point2d();
uu.interpolate(u, w, alpha);
double width = getWidthForBond(bond, model);
Color color = getColorForBond(bond, model);
return new LineElement(u.x, u.y, w.x, w.y, width, color);
} | [
"public",
"LineElement",
"generateInnerElement",
"(",
"IBond",
"bond",
",",
"IRing",
"ring",
",",
"RendererModel",
"model",
")",
"{",
"Point2d",
"center",
"=",
"GeometryUtil",
".",
"get2DCenter",
"(",
"ring",
")",
";",
"Point2d",
"a",
"=",
"bond",
".",
"getB... | Make the inner ring bond, which is slightly shorter than the outer bond.
@param bond the ring bond
@param ring the ring that the bond is in
@param model the renderer model
@return the line element | [
"Make",
"the",
"inner",
"ring",
"bond",
"which",
"is",
"slightly",
"shorter",
"than",
"the",
"outer",
"bond",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/display/renderbasic/src/main/java/org/openscience/cdk/renderer/generators/BasicBondGenerator.java#L399-L424 |
alkacon/opencms-core | src-gwt/org/opencms/ade/sitemap/client/CmsSitemapView.java | CmsSitemapView.addGalleryEntries | private void addGalleryEntries(CmsGalleryTreeItem parent, List<CmsGalleryFolderEntry> galleries) {
for (CmsGalleryFolderEntry galleryFolder : galleries) {
CmsGalleryTreeItem folderItem = createGalleryFolderItem(galleryFolder);
parent.addChild(folderItem);
m_galleryTreeItems.put(galleryFolder.getStructureId(), folderItem);
addGalleryEntries(folderItem, galleryFolder.getSubGalleries());
}
} | java | private void addGalleryEntries(CmsGalleryTreeItem parent, List<CmsGalleryFolderEntry> galleries) {
for (CmsGalleryFolderEntry galleryFolder : galleries) {
CmsGalleryTreeItem folderItem = createGalleryFolderItem(galleryFolder);
parent.addChild(folderItem);
m_galleryTreeItems.put(galleryFolder.getStructureId(), folderItem);
addGalleryEntries(folderItem, galleryFolder.getSubGalleries());
}
} | [
"private",
"void",
"addGalleryEntries",
"(",
"CmsGalleryTreeItem",
"parent",
",",
"List",
"<",
"CmsGalleryFolderEntry",
">",
"galleries",
")",
"{",
"for",
"(",
"CmsGalleryFolderEntry",
"galleryFolder",
":",
"galleries",
")",
"{",
"CmsGalleryTreeItem",
"folderItem",
"=... | Adds the gallery tree items to the parent.<p>
@param parent the parent item
@param galleries the gallery folder entries | [
"Adds",
"the",
"gallery",
"tree",
"items",
"to",
"the",
"parent",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/sitemap/client/CmsSitemapView.java#L1518-L1526 |
elibom/jogger | src/main/java/com/elibom/jogger/middleware/router/RouterMiddleware.java | RouterMiddleware.getRoute | private Route getRoute(String httpMethod, String path) {
Preconditions.notEmpty(httpMethod, "no httpMethod provided.");
Preconditions.notNull(path, "no path provided.");
String cleanPath = parsePath(path);
for (Route route : routes) {
if (matchesPath(route.getPath(), cleanPath) && route.getHttpMethod().toString().equalsIgnoreCase(httpMethod)) {
return route;
}
}
return null;
} | java | private Route getRoute(String httpMethod, String path) {
Preconditions.notEmpty(httpMethod, "no httpMethod provided.");
Preconditions.notNull(path, "no path provided.");
String cleanPath = parsePath(path);
for (Route route : routes) {
if (matchesPath(route.getPath(), cleanPath) && route.getHttpMethod().toString().equalsIgnoreCase(httpMethod)) {
return route;
}
}
return null;
} | [
"private",
"Route",
"getRoute",
"(",
"String",
"httpMethod",
",",
"String",
"path",
")",
"{",
"Preconditions",
".",
"notEmpty",
"(",
"httpMethod",
",",
"\"no httpMethod provided.\"",
")",
";",
"Preconditions",
".",
"notNull",
"(",
"path",
",",
"\"no path provided.... | Retrieves the {@link Route} that matches the specified <code>httpMethod</code> and <code>path</code>.
@param httpMethod the HTTP method to match. Should not be null or empty.
@param path the path to match. Should not be null but can be empty (which is interpreted as /)
@return a {@link Route} object that matches the arguments or null if no route matches. | [
"Retrieves",
"the",
"{",
"@link",
"Route",
"}",
"that",
"matches",
"the",
"specified",
"<code",
">",
"httpMethod<",
"/",
"code",
">",
"and",
"<code",
">",
"path<",
"/",
"code",
">",
"."
] | train | https://github.com/elibom/jogger/blob/d5892ff45e76328d444a68b5a38c26e7bdd0692b/src/main/java/com/elibom/jogger/middleware/router/RouterMiddleware.java#L111-L124 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/serializer/NamespaceMappings.java | NamespaceMappings.pushNamespace | public boolean pushNamespace(String prefix, String uri, int elemDepth)
{
// Prefixes "xml" and "xmlns" cannot be redefined
if (prefix.startsWith(XML_PREFIX))
{
return false;
}
Stack stack;
// Get the stack that contains URIs for the specified prefix
if ((stack = (Stack) m_namespaces.get(prefix)) == null)
{
m_namespaces.put(prefix, stack = new Stack());
}
if (!stack.empty())
{
MappingRecord mr = (MappingRecord)stack.peek();
if (uri.equals(mr.m_uri) || elemDepth == mr.m_declarationDepth) {
// If the same prefix/uri mapping is already on the stack
// don't push this one.
// Or if we have a mapping at the same depth
// don't replace by pushing this one.
return false;
}
}
MappingRecord map = new MappingRecord(prefix,uri,elemDepth);
stack.push(map);
m_nodeStack.push(map);
return true;
} | java | public boolean pushNamespace(String prefix, String uri, int elemDepth)
{
// Prefixes "xml" and "xmlns" cannot be redefined
if (prefix.startsWith(XML_PREFIX))
{
return false;
}
Stack stack;
// Get the stack that contains URIs for the specified prefix
if ((stack = (Stack) m_namespaces.get(prefix)) == null)
{
m_namespaces.put(prefix, stack = new Stack());
}
if (!stack.empty())
{
MappingRecord mr = (MappingRecord)stack.peek();
if (uri.equals(mr.m_uri) || elemDepth == mr.m_declarationDepth) {
// If the same prefix/uri mapping is already on the stack
// don't push this one.
// Or if we have a mapping at the same depth
// don't replace by pushing this one.
return false;
}
}
MappingRecord map = new MappingRecord(prefix,uri,elemDepth);
stack.push(map);
m_nodeStack.push(map);
return true;
} | [
"public",
"boolean",
"pushNamespace",
"(",
"String",
"prefix",
",",
"String",
"uri",
",",
"int",
"elemDepth",
")",
"{",
"// Prefixes \"xml\" and \"xmlns\" cannot be redefined",
"if",
"(",
"prefix",
".",
"startsWith",
"(",
"XML_PREFIX",
")",
")",
"{",
"return",
"fa... | Declare a mapping of a prefix to namespace URI at the given element depth.
@param prefix a String with the prefix for a qualified name
@param uri a String with the uri to which the prefix is to map
@param elemDepth the depth of current declaration | [
"Declare",
"a",
"mapping",
"of",
"a",
"prefix",
"to",
"namespace",
"URI",
"at",
"the",
"given",
"element",
"depth",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/serializer/NamespaceMappings.java#L225-L255 |
iobeam/iobeam-client-java | src/main/java/com/iobeam/api/resource/Import.java | Import.addDataPoint | public void addDataPoint(String series, DataPoint dataPoint) {
DataSet set = store.get(series);
if (set == null) {
set = new DataSet();
store.put(series, set);
}
set.add(dataPoint);
} | java | public void addDataPoint(String series, DataPoint dataPoint) {
DataSet set = store.get(series);
if (set == null) {
set = new DataSet();
store.put(series, set);
}
set.add(dataPoint);
} | [
"public",
"void",
"addDataPoint",
"(",
"String",
"series",
",",
"DataPoint",
"dataPoint",
")",
"{",
"DataSet",
"set",
"=",
"store",
".",
"get",
"(",
"series",
")",
";",
"if",
"(",
"set",
"==",
"null",
")",
"{",
"set",
"=",
"new",
"DataSet",
"(",
")",... | Adds a new data point to a particular series.
@param series The series this data point should be added to. If it doesn't exist, it will
be created.
@param dataPoint Data to be added. | [
"Adds",
"a",
"new",
"data",
"point",
"to",
"a",
"particular",
"series",
"."
] | train | https://github.com/iobeam/iobeam-client-java/blob/06e7aeb2a313503392358a3671de7d28628d0e33/src/main/java/com/iobeam/api/resource/Import.java#L119-L126 |
cloudfoundry/uaa | server/src/main/java/org/cloudfoundry/identity/uaa/oauth/UaaAuthorizationRequestManager.java | UaaAuthorizationRequestManager.setScopesToResources | public void setScopesToResources(Map<String, String> scopeToResource) {
this.scopeToResource = new HashMap<String, String>(scopeToResource);
} | java | public void setScopesToResources(Map<String, String> scopeToResource) {
this.scopeToResource = new HashMap<String, String>(scopeToResource);
} | [
"public",
"void",
"setScopesToResources",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"scopeToResource",
")",
"{",
"this",
".",
"scopeToResource",
"=",
"new",
"HashMap",
"<",
"String",
",",
"String",
">",
"(",
"scopeToResource",
")",
";",
"}"
] | A map from scope name to resource id, for cases (like openid) that cannot
be extracted from the scope name.
@param scopeToResource the map to use | [
"A",
"map",
"from",
"scope",
"name",
"to",
"resource",
"id",
"for",
"cases",
"(",
"like",
"openid",
")",
"that",
"cannot",
"be",
"extracted",
"from",
"the",
"scope",
"name",
"."
] | train | https://github.com/cloudfoundry/uaa/blob/e8df3d7060580c92d33461106399f9e4f36e3cd2/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/UaaAuthorizationRequestManager.java#L118-L120 |
jbundle/jbundle | base/base/src/main/java/org/jbundle/base/thread/BaseRecordOwner.java | BaseRecordOwner.setProperties | public void setProperties(Map<String, Object> properties)
{
if (this.getParentRecordOwner() != null)
this.getParentRecordOwner().setProperties(properties);
} | java | public void setProperties(Map<String, Object> properties)
{
if (this.getParentRecordOwner() != null)
this.getParentRecordOwner().setProperties(properties);
} | [
"public",
"void",
"setProperties",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"properties",
")",
"{",
"if",
"(",
"this",
".",
"getParentRecordOwner",
"(",
")",
"!=",
"null",
")",
"this",
".",
"getParentRecordOwner",
"(",
")",
".",
"setProperties",
"(",... | Set the properties.
@param strProperties The properties to set.
Override this to do something. | [
"Set",
"the",
"properties",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/thread/BaseRecordOwner.java#L363-L367 |
eclipse/hawkbit | hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/RolloutStatusCache.java | RolloutStatusCache.putRolloutStatus | public void putRolloutStatus(final Long rolloutId, final List<TotalTargetCountActionStatus> status) {
final Cache cache = cacheManager.getCache(CACHE_RO_NAME);
putIntoCache(rolloutId, status, cache);
} | java | public void putRolloutStatus(final Long rolloutId, final List<TotalTargetCountActionStatus> status) {
final Cache cache = cacheManager.getCache(CACHE_RO_NAME);
putIntoCache(rolloutId, status, cache);
} | [
"public",
"void",
"putRolloutStatus",
"(",
"final",
"Long",
"rolloutId",
",",
"final",
"List",
"<",
"TotalTargetCountActionStatus",
">",
"status",
")",
"{",
"final",
"Cache",
"cache",
"=",
"cacheManager",
".",
"getCache",
"(",
"CACHE_RO_NAME",
")",
";",
"putInto... | Put {@link TotalTargetCountActionStatus} for one {@link Rollout}s into
cache.
@param rolloutId
the cache entries belong to
@param status
list to cache | [
"Put",
"{",
"@link",
"TotalTargetCountActionStatus",
"}",
"for",
"one",
"{",
"@link",
"Rollout",
"}",
"s",
"into",
"cache",
"."
] | train | https://github.com/eclipse/hawkbit/blob/9884452ad42f3b4827461606d8a9215c8625a7fe/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/RolloutStatusCache.java#L145-L148 |
apache/groovy | subprojects/groovy-servlet/src/main/java/groovy/servlet/TemplateServlet.java | TemplateServlet.createAndStoreTemplate | private Template createAndStoreTemplate(String key, InputStream inputStream, File file) throws Exception {
if (verbose) {
log("Creating new template from " + key + "...");
}
Reader reader = null;
try {
String fileEncoding = (fileEncodingParamVal != null) ? fileEncodingParamVal :
System.getProperty(GROOVY_SOURCE_ENCODING);
reader = fileEncoding == null ? new InputStreamReader(inputStream) : new InputStreamReader(inputStream, fileEncoding);
Template template = engine.createTemplate(reader);
cache.put(key, new TemplateCacheEntry(file, template, verbose));
if (verbose) {
log("Created and added template to cache. [key=" + key + "] " + cache.get(key));
}
//
// Last sanity check.
//
if (template == null) {
throw new ServletException("Template is null? Should not happen here!");
}
return template;
} finally {
if (reader != null) {
reader.close();
} else if (inputStream != null) {
inputStream.close();
}
}
} | java | private Template createAndStoreTemplate(String key, InputStream inputStream, File file) throws Exception {
if (verbose) {
log("Creating new template from " + key + "...");
}
Reader reader = null;
try {
String fileEncoding = (fileEncodingParamVal != null) ? fileEncodingParamVal :
System.getProperty(GROOVY_SOURCE_ENCODING);
reader = fileEncoding == null ? new InputStreamReader(inputStream) : new InputStreamReader(inputStream, fileEncoding);
Template template = engine.createTemplate(reader);
cache.put(key, new TemplateCacheEntry(file, template, verbose));
if (verbose) {
log("Created and added template to cache. [key=" + key + "] " + cache.get(key));
}
//
// Last sanity check.
//
if (template == null) {
throw new ServletException("Template is null? Should not happen here!");
}
return template;
} finally {
if (reader != null) {
reader.close();
} else if (inputStream != null) {
inputStream.close();
}
}
} | [
"private",
"Template",
"createAndStoreTemplate",
"(",
"String",
"key",
",",
"InputStream",
"inputStream",
",",
"File",
"file",
")",
"throws",
"Exception",
"{",
"if",
"(",
"verbose",
")",
"{",
"log",
"(",
"\"Creating new template from \"",
"+",
"key",
"+",
"\"...... | Compile the template and store it in the cache.
@param key a unique key for the template, such as a file's absolutePath or a URL.
@param inputStream an InputStream for the template's source.
@param file a file to be used to determine if the cached template is stale. May be null.
@return the created template.
@throws Exception Any exception when creating the template. | [
"Compile",
"the",
"template",
"and",
"store",
"it",
"in",
"the",
"cache",
"."
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-servlet/src/main/java/groovy/servlet/TemplateServlet.java#L241-L276 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/impl/PtoPInputHandler.java | PtoPInputHandler.reportRepeatedMessages | @Override
public void reportRepeatedMessages(String sourceMEUuid, int percent)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "reportRepeatedMessages", new Object[] { sourceMEUuid, new Integer(percent) });
if (_isLink)
{
// "{0} percent repeated messages received from bus {1} on link {2} on messaging engine {3}"
SibTr.info(tc, "REPEATED_MESSAGE_THRESHOLD_REACHED_ON_LINK_CWSIP0794",
new Object[] { new Integer(percent),
((LinkHandler) _destination).getBusName(),
_destination.getName(),
_messageProcessor.getMessagingEngineName() });
}
else
{
// "{0} percent repeated messages received from messaging engine {1} on messaging engine {2} for destination {3}"
SibTr.info(tc, "REPEATED_MESSAGE_THRESHOLD_REACHED_ON_DESTINATION_CWSIP0795",
new Object[] { new Integer(percent),
SIMPUtils.getMENameFromUuid(sourceMEUuid),
_messageProcessor.getMessagingEngineName(),
_destination.getName() });
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "reportRepeatedMessages");
} | java | @Override
public void reportRepeatedMessages(String sourceMEUuid, int percent)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "reportRepeatedMessages", new Object[] { sourceMEUuid, new Integer(percent) });
if (_isLink)
{
// "{0} percent repeated messages received from bus {1} on link {2} on messaging engine {3}"
SibTr.info(tc, "REPEATED_MESSAGE_THRESHOLD_REACHED_ON_LINK_CWSIP0794",
new Object[] { new Integer(percent),
((LinkHandler) _destination).getBusName(),
_destination.getName(),
_messageProcessor.getMessagingEngineName() });
}
else
{
// "{0} percent repeated messages received from messaging engine {1} on messaging engine {2} for destination {3}"
SibTr.info(tc, "REPEATED_MESSAGE_THRESHOLD_REACHED_ON_DESTINATION_CWSIP0795",
new Object[] { new Integer(percent),
SIMPUtils.getMENameFromUuid(sourceMEUuid),
_messageProcessor.getMessagingEngineName(),
_destination.getName() });
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "reportRepeatedMessages");
} | [
"@",
"Override",
"public",
"void",
"reportRepeatedMessages",
"(",
"String",
"sourceMEUuid",
",",
"int",
"percent",
")",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"SibTr",
".",
"e... | Report a high proportion of repeated messages being sent from a remote ME (510343)
@param sourceMEUUID
@param percent | [
"Report",
"a",
"high",
"proportion",
"of",
"repeated",
"messages",
"being",
"sent",
"from",
"a",
"remote",
"ME",
"(",
"510343",
")"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/impl/PtoPInputHandler.java#L3573-L3600 |
jMotif/SAX | src/main/java/net/seninp/jmotif/sax/SAXProcessor.java | SAXProcessor.ts2saxByChunking | public SAXRecords ts2saxByChunking(double[] ts, int paaSize, double[] cuts, double nThreshold)
throws SAXException {
SAXRecords saxFrequencyData = new SAXRecords();
// Z normalize it
double[] normalizedTS = tsProcessor.znorm(ts, nThreshold);
// perform PAA conversion if needed
double[] paa = tsProcessor.paa(normalizedTS, paaSize);
// Convert the PAA to a string.
char[] currentString = tsProcessor.ts2String(paa, cuts);
// create the datastructure
for (int i = 0; i < currentString.length; i++) {
char c = currentString[i];
int pos = (int) Math.floor(i * ts.length / currentString.length);
saxFrequencyData.add(String.valueOf(c).toCharArray(), pos);
}
return saxFrequencyData;
} | java | public SAXRecords ts2saxByChunking(double[] ts, int paaSize, double[] cuts, double nThreshold)
throws SAXException {
SAXRecords saxFrequencyData = new SAXRecords();
// Z normalize it
double[] normalizedTS = tsProcessor.znorm(ts, nThreshold);
// perform PAA conversion if needed
double[] paa = tsProcessor.paa(normalizedTS, paaSize);
// Convert the PAA to a string.
char[] currentString = tsProcessor.ts2String(paa, cuts);
// create the datastructure
for (int i = 0; i < currentString.length; i++) {
char c = currentString[i];
int pos = (int) Math.floor(i * ts.length / currentString.length);
saxFrequencyData.add(String.valueOf(c).toCharArray(), pos);
}
return saxFrequencyData;
} | [
"public",
"SAXRecords",
"ts2saxByChunking",
"(",
"double",
"[",
"]",
"ts",
",",
"int",
"paaSize",
",",
"double",
"[",
"]",
"cuts",
",",
"double",
"nThreshold",
")",
"throws",
"SAXException",
"{",
"SAXRecords",
"saxFrequencyData",
"=",
"new",
"SAXRecords",
"(",... | Converts the input time series into a SAX data structure via chunking and Z normalization.
@param ts the input data.
@param paaSize the PAA size.
@param cuts the Alphabet cuts.
@param nThreshold the normalization threshold value.
@return SAX representation of the time series.
@throws SAXException if error occurs. | [
"Converts",
"the",
"input",
"time",
"series",
"into",
"a",
"SAX",
"data",
"structure",
"via",
"chunking",
"and",
"Z",
"normalization",
"."
] | train | https://github.com/jMotif/SAX/blob/39ee07a69facaa330def5130b8790aeda85f1061/src/main/java/net/seninp/jmotif/sax/SAXProcessor.java#L73-L96 |
PeterisP/LVTagger | src/main/java/edu/stanford/nlp/ie/pascal/PascalTemplate.java | PascalTemplate.mergeCliqueTemplates | public static PascalTemplate mergeCliqueTemplates(DateTemplate dt, String location, InfoTemplate wi) {
PascalTemplate pt = new PascalTemplate();
pt.setValue("workshopnotificationofacceptancedate", dt.noadate);
pt.setValue("workshopcamerareadycopydate", dt.crcdate);
pt.setValue("workshopdate", dt.workdate);
pt.setValue("workshoppapersubmissiondate", dt.subdate);
pt.setValue("workshoplocation", location);
pt.setValue("workshopacronym", wi.wacronym);
pt.setValue("workshophomepage", wi.whomepage);
pt.setValue("workshopname", wi.wname);
pt.setValue("conferenceacronym", wi.cacronym);
pt.setValue("conferencehomepage", wi.chomepage);
pt.setValue("conferencename", wi.cname);
return pt;
} | java | public static PascalTemplate mergeCliqueTemplates(DateTemplate dt, String location, InfoTemplate wi) {
PascalTemplate pt = new PascalTemplate();
pt.setValue("workshopnotificationofacceptancedate", dt.noadate);
pt.setValue("workshopcamerareadycopydate", dt.crcdate);
pt.setValue("workshopdate", dt.workdate);
pt.setValue("workshoppapersubmissiondate", dt.subdate);
pt.setValue("workshoplocation", location);
pt.setValue("workshopacronym", wi.wacronym);
pt.setValue("workshophomepage", wi.whomepage);
pt.setValue("workshopname", wi.wname);
pt.setValue("conferenceacronym", wi.cacronym);
pt.setValue("conferencehomepage", wi.chomepage);
pt.setValue("conferencename", wi.cname);
return pt;
} | [
"public",
"static",
"PascalTemplate",
"mergeCliqueTemplates",
"(",
"DateTemplate",
"dt",
",",
"String",
"location",
",",
"InfoTemplate",
"wi",
")",
"{",
"PascalTemplate",
"pt",
"=",
"new",
"PascalTemplate",
"(",
")",
";",
"pt",
".",
"setValue",
"(",
"\"workshopn... | Merges partial (clique) templates into a full one.
@param dt date template
@param location location
@param wi workshop/conference info template
@return the {@link PascalTemplate} resulting from this merge. | [
"Merges",
"partial",
"(",
"clique",
")",
"templates",
"into",
"a",
"full",
"one",
"."
] | train | https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/ie/pascal/PascalTemplate.java#L129-L143 |
jamesdbloom/mockserver | mockserver-core/src/main/java/org/mockserver/model/HttpRequest.java | HttpRequest.withQueryStringParameter | public HttpRequest withQueryStringParameter(String name, String... values) {
this.queryStringParameters.withEntry(name, values);
return this;
} | java | public HttpRequest withQueryStringParameter(String name, String... values) {
this.queryStringParameters.withEntry(name, values);
return this;
} | [
"public",
"HttpRequest",
"withQueryStringParameter",
"(",
"String",
"name",
",",
"String",
"...",
"values",
")",
"{",
"this",
".",
"queryStringParameters",
".",
"withEntry",
"(",
"name",
",",
"values",
")",
";",
"return",
"this",
";",
"}"
] | Adds one query string parameter to match which can specified using plain strings or regular expressions
(for more details of the supported regex syntax see http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html)
@param name the parameter name
@param values the parameter values which can be a varags of strings or regular expressions | [
"Adds",
"one",
"query",
"string",
"parameter",
"to",
"match",
"which",
"can",
"specified",
"using",
"plain",
"strings",
"or",
"regular",
"expressions",
"(",
"for",
"more",
"details",
"of",
"the",
"supported",
"regex",
"syntax",
"see",
"http",
":",
"//",
"doc... | train | https://github.com/jamesdbloom/mockserver/blob/8b84fdd877e57b4eb780c9f8c8b1d65bcb448025/mockserver-core/src/main/java/org/mockserver/model/HttpRequest.java#L198-L201 |
aboutsip/sipstack | sipstack-example/src/main/java/io/sipstack/example/netty/sip/proxyregistrar/ProxyRegistrarHandler.java | ProxyRegistrarHandler.proxyTo | private void proxyTo(final SipURI destination, final SipRequest msg) {
final int port = destination.getPort();
final Connection connection = this.stack.connect(destination.getHost(), port == -1 ? 5060 : port);
// SIP is pretty powerful but there are a lot of little details to get things working.
// E.g., this sample application is acting as a stateless proxy and in order to
// correctly relay re-transmissions or e.g. CANCELs we have to make sure to always
// generate the same branch-id of the same request. Since a CANCEL will have the same
// branch-id as the request it cancels, we must ensure we generate the same branch-id as
// we did when we proxied the initial INVITE. If we don't, then the cancel will not be
// matched by the "other" side and their phone wouldn't stop ringing.
// SO, for this example, we'll just grab the previous value and append "-abc" to it so
// now we are relying on the upstream element to do the right thing :-)
//
// See section 16.11 in RFC3263 for more information.
final Buffer otherBranch = msg.getViaHeader().getBranch();
final Buffer myBranch = Buffers.createBuffer(otherBranch.getReadableBytes() + 4);
otherBranch.getBytes(myBranch);
myBranch.write((byte) '-');
myBranch.write((byte) 'a');
myBranch.write((byte) 'b');
myBranch.write((byte) 'c');
final ViaHeader via = ViaHeader.with().host("10.0.1.28").port(5060).transportUDP().branch(myBranch).build();
// This is how you should generate the branch parameter if you are a stateful proxy:
// Note the ViaHeader.generateBranch()...
// ViaHeader.with().host("10.0.1.28").port(5060).transportUDP().branch(ViaHeader.generateBranch()).build();
msg.addHeaderFirst(via);
try {
connection.send(msg);
} catch (final IndexOutOfBoundsException e) {
System.out.println("this is the message:");
System.out.println(msg.getRequestUri());
System.out.println(msg.getMethod());
System.out.println(msg);
e.printStackTrace();
}
} | java | private void proxyTo(final SipURI destination, final SipRequest msg) {
final int port = destination.getPort();
final Connection connection = this.stack.connect(destination.getHost(), port == -1 ? 5060 : port);
// SIP is pretty powerful but there are a lot of little details to get things working.
// E.g., this sample application is acting as a stateless proxy and in order to
// correctly relay re-transmissions or e.g. CANCELs we have to make sure to always
// generate the same branch-id of the same request. Since a CANCEL will have the same
// branch-id as the request it cancels, we must ensure we generate the same branch-id as
// we did when we proxied the initial INVITE. If we don't, then the cancel will not be
// matched by the "other" side and their phone wouldn't stop ringing.
// SO, for this example, we'll just grab the previous value and append "-abc" to it so
// now we are relying on the upstream element to do the right thing :-)
//
// See section 16.11 in RFC3263 for more information.
final Buffer otherBranch = msg.getViaHeader().getBranch();
final Buffer myBranch = Buffers.createBuffer(otherBranch.getReadableBytes() + 4);
otherBranch.getBytes(myBranch);
myBranch.write((byte) '-');
myBranch.write((byte) 'a');
myBranch.write((byte) 'b');
myBranch.write((byte) 'c');
final ViaHeader via = ViaHeader.with().host("10.0.1.28").port(5060).transportUDP().branch(myBranch).build();
// This is how you should generate the branch parameter if you are a stateful proxy:
// Note the ViaHeader.generateBranch()...
// ViaHeader.with().host("10.0.1.28").port(5060).transportUDP().branch(ViaHeader.generateBranch()).build();
msg.addHeaderFirst(via);
try {
connection.send(msg);
} catch (final IndexOutOfBoundsException e) {
System.out.println("this is the message:");
System.out.println(msg.getRequestUri());
System.out.println(msg.getMethod());
System.out.println(msg);
e.printStackTrace();
}
} | [
"private",
"void",
"proxyTo",
"(",
"final",
"SipURI",
"destination",
",",
"final",
"SipRequest",
"msg",
")",
"{",
"final",
"int",
"port",
"=",
"destination",
".",
"getPort",
"(",
")",
";",
"final",
"Connection",
"connection",
"=",
"this",
".",
"stack",
"."... | Whenever we proxy a request we must also add a Via-header, which essentially says that the
request went "via this network address using this protocol". The {@link ViaHeader}s are used
for responses to find their way back the exact same path as the request took.
@param destination
@param msg | [
"Whenever",
"we",
"proxy",
"a",
"request",
"we",
"must",
"also",
"add",
"a",
"Via",
"-",
"header",
"which",
"essentially",
"says",
"that",
"the",
"request",
"went",
"via",
"this",
"network",
"address",
"using",
"this",
"protocol",
".",
"The",
"{",
"@link",... | train | https://github.com/aboutsip/sipstack/blob/33f2db1d580738f0385687b0429fab0630118f42/sipstack-example/src/main/java/io/sipstack/example/netty/sip/proxyregistrar/ProxyRegistrarHandler.java#L141-L180 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.