repository_name stringlengths 7 58 | func_path_in_repository stringlengths 11 218 | func_name stringlengths 4 140 | whole_func_string stringlengths 153 5.32k | language stringclasses 1
value | func_code_string stringlengths 72 4k | func_code_tokens listlengths 20 832 | func_documentation_string stringlengths 61 2k | func_documentation_tokens listlengths 1 647 | split_name stringclasses 1
value | func_code_url stringlengths 102 339 |
|---|---|---|---|---|---|---|---|---|---|---|
minio/minio-java | api/src/main/java/io/minio/MinioClient.java | MinioClient.presignedGetObject | public String presignedGetObject(String bucketName, String objectName, Integer expires,
Map<String, String> reqParams)
throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException,
InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException,
InternalException, InvalidExpiresRangeException {
"""
Returns an presigned URL to download the object in the bucket with given expiry time with custom request params.
</p><b>Example:</b><br>
<pre>{@code String url = minioClient.presignedGetObject("my-bucketname", "my-objectname", 60 * 60 * 24, reqParams);
System.out.println(url); }</pre>
@param bucketName Bucket name.
@param objectName Object name in the bucket.
@param expires Expiration time in seconds of presigned URL.
@param reqParams Override values for set of response headers. Currently supported request parameters are
[response-expires, response-content-type, response-cache-control, response-content-disposition]
@return string contains URL to download the object.
@throws InvalidBucketNameException upon invalid bucket name is given
@throws NoSuchAlgorithmException
upon requested algorithm was not found during signature calculation
@throws InsufficientDataException upon getting EOFException while reading given
InputStream even before reading given length
@throws IOException upon connection error
@throws InvalidKeyException
upon an invalid access key or secret key
@throws NoResponseException upon no response from server
@throws XmlPullParserException upon parsing response xml
@throws ErrorResponseException upon unsuccessful execution
@throws InternalException upon internal library error
@throws InvalidExpiresRangeException upon input expires is out of range
"""
return getPresignedObjectUrl(Method.GET, bucketName, objectName, expires, reqParams);
} | java | public String presignedGetObject(String bucketName, String objectName, Integer expires,
Map<String, String> reqParams)
throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException,
InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException,
InternalException, InvalidExpiresRangeException {
return getPresignedObjectUrl(Method.GET, bucketName, objectName, expires, reqParams);
} | [
"public",
"String",
"presignedGetObject",
"(",
"String",
"bucketName",
",",
"String",
"objectName",
",",
"Integer",
"expires",
",",
"Map",
"<",
"String",
",",
"String",
">",
"reqParams",
")",
"throws",
"InvalidBucketNameException",
",",
"NoSuchAlgorithmException",
"... | Returns an presigned URL to download the object in the bucket with given expiry time with custom request params.
</p><b>Example:</b><br>
<pre>{@code String url = minioClient.presignedGetObject("my-bucketname", "my-objectname", 60 * 60 * 24, reqParams);
System.out.println(url); }</pre>
@param bucketName Bucket name.
@param objectName Object name in the bucket.
@param expires Expiration time in seconds of presigned URL.
@param reqParams Override values for set of response headers. Currently supported request parameters are
[response-expires, response-content-type, response-cache-control, response-content-disposition]
@return string contains URL to download the object.
@throws InvalidBucketNameException upon invalid bucket name is given
@throws NoSuchAlgorithmException
upon requested algorithm was not found during signature calculation
@throws InsufficientDataException upon getting EOFException while reading given
InputStream even before reading given length
@throws IOException upon connection error
@throws InvalidKeyException
upon an invalid access key or secret key
@throws NoResponseException upon no response from server
@throws XmlPullParserException upon parsing response xml
@throws ErrorResponseException upon unsuccessful execution
@throws InternalException upon internal library error
@throws InvalidExpiresRangeException upon input expires is out of range | [
"Returns",
"an",
"presigned",
"URL",
"to",
"download",
"the",
"object",
"in",
"the",
"bucket",
"with",
"given",
"expiry",
"time",
"with",
"custom",
"request",
"params",
"."
] | train | https://github.com/minio/minio-java/blob/b2028f56403c89ce2d5900ae813bc1314c87bc7f/api/src/main/java/io/minio/MinioClient.java#L2401-L2407 |
actframework/actframework | src/main/java/act/event/EventBus.java | EventBus.emitSync | public synchronized EventBus emitSync(SysEventId eventId) {
"""
Emit a system event by {@link SysEventId event ID} and force event listeners
be invoked synchronously without regarding to how listeners are bound.
**Note** this method shall not be used by application developer.
@param eventId
the {@link SysEventId system event ID}
@return
this event bus instance
@see #emit(SysEventId)
"""
if (isDestroyed()) {
return this;
}
if (null != onceBus) {
onceBus.emit(eventId);
}
return _emit(false, false, eventId);
} | java | public synchronized EventBus emitSync(SysEventId eventId) {
if (isDestroyed()) {
return this;
}
if (null != onceBus) {
onceBus.emit(eventId);
}
return _emit(false, false, eventId);
} | [
"public",
"synchronized",
"EventBus",
"emitSync",
"(",
"SysEventId",
"eventId",
")",
"{",
"if",
"(",
"isDestroyed",
"(",
")",
")",
"{",
"return",
"this",
";",
"}",
"if",
"(",
"null",
"!=",
"onceBus",
")",
"{",
"onceBus",
".",
"emit",
"(",
"eventId",
")... | Emit a system event by {@link SysEventId event ID} and force event listeners
be invoked synchronously without regarding to how listeners are bound.
**Note** this method shall not be used by application developer.
@param eventId
the {@link SysEventId system event ID}
@return
this event bus instance
@see #emit(SysEventId) | [
"Emit",
"a",
"system",
"event",
"by",
"{",
"@link",
"SysEventId",
"event",
"ID",
"}",
"and",
"force",
"event",
"listeners",
"be",
"invoked",
"synchronously",
"without",
"regarding",
"to",
"how",
"listeners",
"are",
"bound",
"."
] | train | https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/event/EventBus.java#L1060-L1068 |
alibaba/jstorm | jstorm-core/src/main/java/backtype/storm/ConfigValidation.java | ConfigValidation.mapFv | public static NestableFieldValidator mapFv(final NestableFieldValidator key,
final NestableFieldValidator val, final boolean nullAllowed) {
"""
Returns a new NestableFieldValidator for a Map.
@param key a validator for the keys in the map
@param val a validator for the values in the map
@param nullAllowed whether or not a value of null is valid
@return a NestableFieldValidator for a Map
"""
return new NestableFieldValidator() {
@SuppressWarnings("unchecked")
@Override
public void validateField(String pd, String name, Object field) throws IllegalArgumentException {
if (nullAllowed && field == null) {
return;
}
if (field instanceof Map) {
for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) field).entrySet()) {
key.validateField("Each key of the map ", name, entry.getKey());
val.validateField("Each value in the map ", name, entry.getValue());
}
return;
}
throw new IllegalArgumentException("Field " + name + " must be a Map");
}
};
} | java | public static NestableFieldValidator mapFv(final NestableFieldValidator key,
final NestableFieldValidator val, final boolean nullAllowed) {
return new NestableFieldValidator() {
@SuppressWarnings("unchecked")
@Override
public void validateField(String pd, String name, Object field) throws IllegalArgumentException {
if (nullAllowed && field == null) {
return;
}
if (field instanceof Map) {
for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) field).entrySet()) {
key.validateField("Each key of the map ", name, entry.getKey());
val.validateField("Each value in the map ", name, entry.getValue());
}
return;
}
throw new IllegalArgumentException("Field " + name + " must be a Map");
}
};
} | [
"public",
"static",
"NestableFieldValidator",
"mapFv",
"(",
"final",
"NestableFieldValidator",
"key",
",",
"final",
"NestableFieldValidator",
"val",
",",
"final",
"boolean",
"nullAllowed",
")",
"{",
"return",
"new",
"NestableFieldValidator",
"(",
")",
"{",
"@",
"Sup... | Returns a new NestableFieldValidator for a Map.
@param key a validator for the keys in the map
@param val a validator for the values in the map
@param nullAllowed whether or not a value of null is valid
@return a NestableFieldValidator for a Map | [
"Returns",
"a",
"new",
"NestableFieldValidator",
"for",
"a",
"Map",
"."
] | train | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/ConfigValidation.java#L138-L157 |
broadinstitute/barclay | src/main/java/org/broadinstitute/barclay/argparser/CommandLineArgumentParser.java | CommandLineArgumentParser.isSpecialFlagSet | private boolean isSpecialFlagSet(final OptionSet parsedArguments, final String flagName) {
"""
helper to deal with the case of special flags that are evaluated before the options are properly set
"""
if (parsedArguments.has(flagName)){
Object value = parsedArguments.valueOf(flagName);
return (value == null || !value.equals("false"));
} else{
return false;
}
} | java | private boolean isSpecialFlagSet(final OptionSet parsedArguments, final String flagName){
if (parsedArguments.has(flagName)){
Object value = parsedArguments.valueOf(flagName);
return (value == null || !value.equals("false"));
} else{
return false;
}
} | [
"private",
"boolean",
"isSpecialFlagSet",
"(",
"final",
"OptionSet",
"parsedArguments",
",",
"final",
"String",
"flagName",
")",
"{",
"if",
"(",
"parsedArguments",
".",
"has",
"(",
"flagName",
")",
")",
"{",
"Object",
"value",
"=",
"parsedArguments",
".",
"val... | helper to deal with the case of special flags that are evaluated before the options are properly set | [
"helper",
"to",
"deal",
"with",
"the",
"case",
"of",
"special",
"flags",
"that",
"are",
"evaluated",
"before",
"the",
"options",
"are",
"properly",
"set"
] | train | https://github.com/broadinstitute/barclay/blob/7e56d725766b0da3baff23e79a31c3d01c3589c2/src/main/java/org/broadinstitute/barclay/argparser/CommandLineArgumentParser.java#L541-L548 |
Whiley/WhileyCompiler | src/main/java/wyil/check/FlowTypeCheck.java | FlowTypeCheck.checkNonEmpty | private void checkNonEmpty(Decl.Variable d, LifetimeRelation lifetimes) {
"""
Check that a given variable declaration is not empty. That is, the declared
type is not equivalent to void. This is an important sanity check.
@param d
"""
if (relaxedSubtypeOperator.isVoid(d.getType(), lifetimes)) {
syntaxError(d.getType(), EMPTY_TYPE);
}
} | java | private void checkNonEmpty(Decl.Variable d, LifetimeRelation lifetimes) {
if (relaxedSubtypeOperator.isVoid(d.getType(), lifetimes)) {
syntaxError(d.getType(), EMPTY_TYPE);
}
} | [
"private",
"void",
"checkNonEmpty",
"(",
"Decl",
".",
"Variable",
"d",
",",
"LifetimeRelation",
"lifetimes",
")",
"{",
"if",
"(",
"relaxedSubtypeOperator",
".",
"isVoid",
"(",
"d",
".",
"getType",
"(",
")",
",",
"lifetimes",
")",
")",
"{",
"syntaxError",
"... | Check that a given variable declaration is not empty. That is, the declared
type is not equivalent to void. This is an important sanity check.
@param d | [
"Check",
"that",
"a",
"given",
"variable",
"declaration",
"is",
"not",
"empty",
".",
"That",
"is",
"the",
"declared",
"type",
"is",
"not",
"equivalent",
"to",
"void",
".",
"This",
"is",
"an",
"important",
"sanity",
"check",
"."
] | train | https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyil/check/FlowTypeCheck.java#L1862-L1866 |
dustin/java-memcached-client | src/main/java/net/spy/memcached/MemcachedConnection.java | MemcachedConnection.setTimeout | private static void setTimeout(final Operation op, final boolean isTimeout) {
"""
Set the continuous timeout on an operation.
Ignore operations which have no handling nodes set yet (which may happen before nodes are properly
authenticated).
@param op the operation to use.
@param isTimeout is timed out or not.
"""
Logger logger = LoggerFactory.getLogger(MemcachedConnection.class);
try {
if (op == null || op.isTimedOutUnsent()) {
return;
}
MemcachedNode node = op.getHandlingNode();
if (node != null) {
node.setContinuousTimeout(isTimeout);
}
} catch (Exception e) {
logger.error(e.getMessage());
}
} | java | private static void setTimeout(final Operation op, final boolean isTimeout) {
Logger logger = LoggerFactory.getLogger(MemcachedConnection.class);
try {
if (op == null || op.isTimedOutUnsent()) {
return;
}
MemcachedNode node = op.getHandlingNode();
if (node != null) {
node.setContinuousTimeout(isTimeout);
}
} catch (Exception e) {
logger.error(e.getMessage());
}
} | [
"private",
"static",
"void",
"setTimeout",
"(",
"final",
"Operation",
"op",
",",
"final",
"boolean",
"isTimeout",
")",
"{",
"Logger",
"logger",
"=",
"LoggerFactory",
".",
"getLogger",
"(",
"MemcachedConnection",
".",
"class",
")",
";",
"try",
"{",
"if",
"(",... | Set the continuous timeout on an operation.
Ignore operations which have no handling nodes set yet (which may happen before nodes are properly
authenticated).
@param op the operation to use.
@param isTimeout is timed out or not. | [
"Set",
"the",
"continuous",
"timeout",
"on",
"an",
"operation",
"."
] | train | https://github.com/dustin/java-memcached-client/blob/c232307ad8e0c7ccc926e495dd7d5aad2d713318/src/main/java/net/spy/memcached/MemcachedConnection.java#L1424-L1439 |
apache/flink | flink-streaming-java/src/main/java/org/apache/flink/streaming/api/datastream/KeyedStream.java | KeyedStream.maxBy | public SingleOutputStreamOperator<T> maxBy(String field, boolean first) {
"""
Applies an aggregation that gives the current maximum element of the
data stream by the given field expression by the given key. An
independent aggregate is kept per key. A field expression is either the
name of a public field or a getter method with parentheses of the
{@link DataStream}'s underlying type. A dot can be used to drill down into
objects, as in {@code "field1.fieldxy" }.
@param field
In case of a POJO, Scala case class, or Tuple type, the
name of the (public) field on which to perform the aggregation.
Additionally, a dot can be used to drill down into nested
objects, as in {@code "field1.fieldxy" }.
Furthermore "*" can be specified in case of a basic type
(which is considered as having only one field).
@param first
If True then in case of field equality the first object will
be returned
@return The transformed DataStream.
"""
return aggregate(new ComparableAggregator<>(field, getType(), AggregationFunction.AggregationType.MAXBY,
first, getExecutionConfig()));
} | java | public SingleOutputStreamOperator<T> maxBy(String field, boolean first) {
return aggregate(new ComparableAggregator<>(field, getType(), AggregationFunction.AggregationType.MAXBY,
first, getExecutionConfig()));
} | [
"public",
"SingleOutputStreamOperator",
"<",
"T",
">",
"maxBy",
"(",
"String",
"field",
",",
"boolean",
"first",
")",
"{",
"return",
"aggregate",
"(",
"new",
"ComparableAggregator",
"<>",
"(",
"field",
",",
"getType",
"(",
")",
",",
"AggregationFunction",
".",... | Applies an aggregation that gives the current maximum element of the
data stream by the given field expression by the given key. An
independent aggregate is kept per key. A field expression is either the
name of a public field or a getter method with parentheses of the
{@link DataStream}'s underlying type. A dot can be used to drill down into
objects, as in {@code "field1.fieldxy" }.
@param field
In case of a POJO, Scala case class, or Tuple type, the
name of the (public) field on which to perform the aggregation.
Additionally, a dot can be used to drill down into nested
objects, as in {@code "field1.fieldxy" }.
Furthermore "*" can be specified in case of a basic type
(which is considered as having only one field).
@param first
If True then in case of field equality the first object will
be returned
@return The transformed DataStream. | [
"Applies",
"an",
"aggregation",
"that",
"gives",
"the",
"current",
"maximum",
"element",
"of",
"the",
"data",
"stream",
"by",
"the",
"given",
"field",
"expression",
"by",
"the",
"given",
"key",
".",
"An",
"independent",
"aggregate",
"is",
"kept",
"per",
"key... | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/datastream/KeyedStream.java#L874-L877 |
CleverTap/clevertap-android-sdk | clevertap-android-sdk/src/main/java/com/clevertap/android/sdk/ProfileHandler.java | ProfileHandler.addMultiValuesForKey | @Deprecated
public void addMultiValuesForKey(final String key, final ArrayList<String> values) {
"""
Add a collection of unique values to a multi-value user profile property
If the property does not exist it will be created
<p/>
Max 100 values, on reaching 100 cap, oldest value(s) will be removed.
Values must be Strings and are limited to 512 characters.
<p/>
If the key currently contains a scalar value, the key will be promoted to a multi-value property
with the current value cast to a string and the new value(s) added
@param key String
@param values {@link ArrayList} with String values
@deprecated use {@link CleverTapAPI#addMultiValuesForKey(String key, ArrayList values)}
"""
CleverTapAPI cleverTapAPI = weakReference.get();
if (cleverTapAPI == null) {
Logger.d("CleverTap Instance is null.");
} else {
cleverTapAPI.addMultiValuesForKey(key, values);
}
} | java | @Deprecated
public void addMultiValuesForKey(final String key, final ArrayList<String> values) {
CleverTapAPI cleverTapAPI = weakReference.get();
if (cleverTapAPI == null) {
Logger.d("CleverTap Instance is null.");
} else {
cleverTapAPI.addMultiValuesForKey(key, values);
}
} | [
"@",
"Deprecated",
"public",
"void",
"addMultiValuesForKey",
"(",
"final",
"String",
"key",
",",
"final",
"ArrayList",
"<",
"String",
">",
"values",
")",
"{",
"CleverTapAPI",
"cleverTapAPI",
"=",
"weakReference",
".",
"get",
"(",
")",
";",
"if",
"(",
"clever... | Add a collection of unique values to a multi-value user profile property
If the property does not exist it will be created
<p/>
Max 100 values, on reaching 100 cap, oldest value(s) will be removed.
Values must be Strings and are limited to 512 characters.
<p/>
If the key currently contains a scalar value, the key will be promoted to a multi-value property
with the current value cast to a string and the new value(s) added
@param key String
@param values {@link ArrayList} with String values
@deprecated use {@link CleverTapAPI#addMultiValuesForKey(String key, ArrayList values)} | [
"Add",
"a",
"collection",
"of",
"unique",
"values",
"to",
"a",
"multi",
"-",
"value",
"user",
"profile",
"property",
"If",
"the",
"property",
"does",
"not",
"exist",
"it",
"will",
"be",
"created",
"<p",
"/",
">",
"Max",
"100",
"values",
"on",
"reaching",... | train | https://github.com/CleverTap/clevertap-android-sdk/blob/be134c06a4f07494c398335ad9ff4976633743e1/clevertap-android-sdk/src/main/java/com/clevertap/android/sdk/ProfileHandler.java#L75-L83 |
landawn/AbacusUtil | src/com/landawn/abacus/util/DateUtil.java | DateUtil.parseDate | public static Date parseDate(final String date, final String format, final TimeZone timeZone) {
"""
Converts the specified <code>date</code> with the specified {@code format} to a new instance of java.sql.Date.
<code>null</code> is returned if the specified <code>date</code> is null or empty.
@param date
@param format
@param timeZone
@return
"""
if (N.isNullOrEmpty(date) || (date.length() == 4 && "null".equalsIgnoreCase(date))) {
return null;
}
return createDate(parse(date, format, timeZone));
} | java | public static Date parseDate(final String date, final String format, final TimeZone timeZone) {
if (N.isNullOrEmpty(date) || (date.length() == 4 && "null".equalsIgnoreCase(date))) {
return null;
}
return createDate(parse(date, format, timeZone));
} | [
"public",
"static",
"Date",
"parseDate",
"(",
"final",
"String",
"date",
",",
"final",
"String",
"format",
",",
"final",
"TimeZone",
"timeZone",
")",
"{",
"if",
"(",
"N",
".",
"isNullOrEmpty",
"(",
"date",
")",
"||",
"(",
"date",
".",
"length",
"(",
")... | Converts the specified <code>date</code> with the specified {@code format} to a new instance of java.sql.Date.
<code>null</code> is returned if the specified <code>date</code> is null or empty.
@param date
@param format
@param timeZone
@return | [
"Converts",
"the",
"specified",
"<code",
">",
"date<",
"/",
"code",
">",
"with",
"the",
"specified",
"{",
"@code",
"format",
"}",
"to",
"a",
"new",
"instance",
"of",
"java",
".",
"sql",
".",
"Date",
".",
"<code",
">",
"null<",
"/",
"code",
">",
"is",... | train | https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/DateUtil.java#L408-L414 |
javamelody/javamelody | javamelody-core/src/main/java/net/bull/javamelody/internal/model/CacheInformations.java | CacheInformations.invokeStatisticsMethod | private static long invokeStatisticsMethod(Object statistics, String methodName) {
"""
on ne doit pas référencer la classe Statistics dans les déclarations de méthodes (issue 335)
"""
try {
// getInMemoryHits, getCacheHits et getCacheMisses existent en v1.2.1 et v1.2.3
// mais avec int comme résultat et existent depuis v1.2.4 avec long comme résultat
// donc on cast en Number et non en Integer ou en Long
final Number result = (Number) Statistics.class.getMethod(methodName, (Class<?>[]) null)
.invoke(statistics, (Object[]) null);
return result.longValue();
} catch (final NoSuchMethodException e) {
throw new IllegalArgumentException(e);
} catch (final InvocationTargetException e) {
throw new IllegalStateException(e.getCause());
} catch (final IllegalAccessException e) {
throw new IllegalStateException(e);
}
} | java | private static long invokeStatisticsMethod(Object statistics, String methodName) {
try {
// getInMemoryHits, getCacheHits et getCacheMisses existent en v1.2.1 et v1.2.3
// mais avec int comme résultat et existent depuis v1.2.4 avec long comme résultat
// donc on cast en Number et non en Integer ou en Long
final Number result = (Number) Statistics.class.getMethod(methodName, (Class<?>[]) null)
.invoke(statistics, (Object[]) null);
return result.longValue();
} catch (final NoSuchMethodException e) {
throw new IllegalArgumentException(e);
} catch (final InvocationTargetException e) {
throw new IllegalStateException(e.getCause());
} catch (final IllegalAccessException e) {
throw new IllegalStateException(e);
}
} | [
"private",
"static",
"long",
"invokeStatisticsMethod",
"(",
"Object",
"statistics",
",",
"String",
"methodName",
")",
"{",
"try",
"{",
"// getInMemoryHits, getCacheHits et getCacheMisses existent en v1.2.1 et v1.2.3\r",
"// mais avec int comme résultat et existent depuis v1.2.4 avec lo... | on ne doit pas référencer la classe Statistics dans les déclarations de méthodes (issue 335) | [
"on",
"ne",
"doit",
"pas",
"référencer",
"la",
"classe",
"Statistics",
"dans",
"les",
"déclarations",
"de",
"méthodes",
"(",
"issue",
"335",
")"
] | train | https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/internal/model/CacheInformations.java#L130-L145 |
UrielCh/ovh-java-sdk | ovh-java-sdk-hostingprivateDatabase/src/main/java/net/minidev/ovh/api/ApiOvhHostingprivateDatabase.java | ApiOvhHostingprivateDatabase.serviceName_dump_GET | public ArrayList<Long> serviceName_dump_GET(String serviceName, String databaseName, Boolean orphan) throws IOException {
"""
Dumps available for your private database service
REST: GET /hosting/privateDatabase/{serviceName}/dump
@param databaseName [required] Filter the value of databaseName property (like)
@param orphan [required] Filter the value of orphan property (=)
@param serviceName [required] The internal name of your private database
"""
String qPath = "/hosting/privateDatabase/{serviceName}/dump";
StringBuilder sb = path(qPath, serviceName);
query(sb, "databaseName", databaseName);
query(sb, "orphan", orphan);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t3);
} | java | public ArrayList<Long> serviceName_dump_GET(String serviceName, String databaseName, Boolean orphan) throws IOException {
String qPath = "/hosting/privateDatabase/{serviceName}/dump";
StringBuilder sb = path(qPath, serviceName);
query(sb, "databaseName", databaseName);
query(sb, "orphan", orphan);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t3);
} | [
"public",
"ArrayList",
"<",
"Long",
">",
"serviceName_dump_GET",
"(",
"String",
"serviceName",
",",
"String",
"databaseName",
",",
"Boolean",
"orphan",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/hosting/privateDatabase/{serviceName}/dump\"",
";",
"... | Dumps available for your private database service
REST: GET /hosting/privateDatabase/{serviceName}/dump
@param databaseName [required] Filter the value of databaseName property (like)
@param orphan [required] Filter the value of orphan property (=)
@param serviceName [required] The internal name of your private database | [
"Dumps",
"available",
"for",
"your",
"private",
"database",
"service"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-hostingprivateDatabase/src/main/java/net/minidev/ovh/api/ApiOvhHostingprivateDatabase.java#L655-L662 |
jboss/jboss-jsf-api_spec | src/main/java/javax/faces/context/PartialResponseWriter.java | PartialResponseWriter.updateAttributes | public void updateAttributes(String targetId, Map<String, String> attributes)
throws IOException {
"""
<p class="changed_added_2_0">Write an attribute update operation.</p>
@param targetId ID of the node to be updated
@param attributes Map of attribute name/value pairs to be updated
@throws IOException if an input/output error occurs
@since 2.0
"""
startChangesIfNecessary();
ResponseWriter writer = getWrapped();
writer.startElement("attributes", null);
writer.writeAttribute("id", targetId, null);
for (Map.Entry<String, String> entry : attributes.entrySet()) {
writer.startElement("attribute", null);
writer.writeAttribute("name", entry.getKey(), null);
writer.writeAttribute("value", entry.getValue(), null);
writer.endElement("attribute");
}
writer.endElement("attributes");
} | java | public void updateAttributes(String targetId, Map<String, String> attributes)
throws IOException {
startChangesIfNecessary();
ResponseWriter writer = getWrapped();
writer.startElement("attributes", null);
writer.writeAttribute("id", targetId, null);
for (Map.Entry<String, String> entry : attributes.entrySet()) {
writer.startElement("attribute", null);
writer.writeAttribute("name", entry.getKey(), null);
writer.writeAttribute("value", entry.getValue(), null);
writer.endElement("attribute");
}
writer.endElement("attributes");
} | [
"public",
"void",
"updateAttributes",
"(",
"String",
"targetId",
",",
"Map",
"<",
"String",
",",
"String",
">",
"attributes",
")",
"throws",
"IOException",
"{",
"startChangesIfNecessary",
"(",
")",
";",
"ResponseWriter",
"writer",
"=",
"getWrapped",
"(",
")",
... | <p class="changed_added_2_0">Write an attribute update operation.</p>
@param targetId ID of the node to be updated
@param attributes Map of attribute name/value pairs to be updated
@throws IOException if an input/output error occurs
@since 2.0 | [
"<p",
"class",
"=",
"changed_added_2_0",
">",
"Write",
"an",
"attribute",
"update",
"operation",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/jboss/jboss-jsf-api_spec/blob/cb33d215acbab847f2db5cdf2c6fe4d99c0a01c3/src/main/java/javax/faces/context/PartialResponseWriter.java#L249-L262 |
mapbox/mapbox-navigation-android | libandroid-navigation-ui/src/main/java/com/mapbox/services/android/navigation/ui/v5/ThemeSwitcher.java | ThemeSwitcher.retrieveNavigationViewStyle | public static int retrieveNavigationViewStyle(Context context, int styleResId) {
"""
Looks are current theme and retrieves the style
for the given resId set in the theme.
@param context to retrieve the resolved attribute
@param styleResId for the given style
@return resolved style resource Id
"""
TypedValue outValue = resolveAttributeFromId(context, styleResId);
return outValue.resourceId;
} | java | public static int retrieveNavigationViewStyle(Context context, int styleResId) {
TypedValue outValue = resolveAttributeFromId(context, styleResId);
return outValue.resourceId;
} | [
"public",
"static",
"int",
"retrieveNavigationViewStyle",
"(",
"Context",
"context",
",",
"int",
"styleResId",
")",
"{",
"TypedValue",
"outValue",
"=",
"resolveAttributeFromId",
"(",
"context",
",",
"styleResId",
")",
";",
"return",
"outValue",
".",
"resourceId",
... | Looks are current theme and retrieves the style
for the given resId set in the theme.
@param context to retrieve the resolved attribute
@param styleResId for the given style
@return resolved style resource Id | [
"Looks",
"are",
"current",
"theme",
"and",
"retrieves",
"the",
"style",
"for",
"the",
"given",
"resId",
"set",
"in",
"the",
"theme",
"."
] | train | https://github.com/mapbox/mapbox-navigation-android/blob/375a89c017d360b9defc2c90d0c03468165162ec/libandroid-navigation-ui/src/main/java/com/mapbox/services/android/navigation/ui/v5/ThemeSwitcher.java#L74-L77 |
jcuda/jcuda | JCudaJava/src/main/java/jcuda/Pointer.java | Pointer.getByteBuffer | public ByteBuffer getByteBuffer(long byteOffset, long byteSize) {
"""
Returns a ByteBuffer that corresponds to the specified
segment of the memory that this pointer points to.<br>
<br>
The returned byte buffer will have the byte order that is implied
by <code>ByteOrder#nativeOrder()</code>. It will be a slice of the
buffer that is stored internally. So it will share the same memory,
but its position and limit will be independent of the internal buffer.
<br>
This function may only be applied to pointers that have been set to
point to a region of host- or unified memory using one of these
methods:
<ul>
<li>{@link jcuda.driver.JCudaDriver#cuMemAllocHost}</li>
<li>{@link jcuda.driver.JCudaDriver#cuMemHostAlloc}</li>
<li>{@link jcuda.driver.JCudaDriver#cuMemAllocManaged}</li>
<li>{@link jcuda.runtime.JCuda#cudaMallocHost}</li>
<li>{@link jcuda.runtime.JCuda#cudaHostAlloc}</li>
<li>{@link jcuda.runtime.JCuda#cudaMallocManaged}</li>
<li>{@link Pointer#to(byte[])}</li>
</ul>
<br>
For other pointer types, <code>null</code> is returned.
@param byteOffset The offset in bytes
@param byteSize The size of the byte buffer, in bytes
@return The byte buffer
@throws IllegalArgumentException If the <code>byteOffset</code> and
<code>byteSize</code> describe an invalid memory range (for example,
when the <code>byteOffset</code> is negative)
@throws ArithmeticException If the <code>byteOffset</code> or
<code>byteOffset + byteSize</code> overflows an <code>int</code>.
"""
if (buffer == null)
{
return null;
}
if (!(buffer instanceof ByteBuffer))
{
return null;
}
ByteBuffer internalByteBuffer = (ByteBuffer)buffer;
ByteBuffer byteBuffer = internalByteBuffer.slice();
byteBuffer.limit(Math.toIntExact(byteOffset + byteSize));
byteBuffer.position(Math.toIntExact(byteOffset));
return byteBuffer.slice().order(ByteOrder.nativeOrder());
} | java | public ByteBuffer getByteBuffer(long byteOffset, long byteSize)
{
if (buffer == null)
{
return null;
}
if (!(buffer instanceof ByteBuffer))
{
return null;
}
ByteBuffer internalByteBuffer = (ByteBuffer)buffer;
ByteBuffer byteBuffer = internalByteBuffer.slice();
byteBuffer.limit(Math.toIntExact(byteOffset + byteSize));
byteBuffer.position(Math.toIntExact(byteOffset));
return byteBuffer.slice().order(ByteOrder.nativeOrder());
} | [
"public",
"ByteBuffer",
"getByteBuffer",
"(",
"long",
"byteOffset",
",",
"long",
"byteSize",
")",
"{",
"if",
"(",
"buffer",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"!",
"(",
"buffer",
"instanceof",
"ByteBuffer",
")",
")",
"{",
"r... | Returns a ByteBuffer that corresponds to the specified
segment of the memory that this pointer points to.<br>
<br>
The returned byte buffer will have the byte order that is implied
by <code>ByteOrder#nativeOrder()</code>. It will be a slice of the
buffer that is stored internally. So it will share the same memory,
but its position and limit will be independent of the internal buffer.
<br>
This function may only be applied to pointers that have been set to
point to a region of host- or unified memory using one of these
methods:
<ul>
<li>{@link jcuda.driver.JCudaDriver#cuMemAllocHost}</li>
<li>{@link jcuda.driver.JCudaDriver#cuMemHostAlloc}</li>
<li>{@link jcuda.driver.JCudaDriver#cuMemAllocManaged}</li>
<li>{@link jcuda.runtime.JCuda#cudaMallocHost}</li>
<li>{@link jcuda.runtime.JCuda#cudaHostAlloc}</li>
<li>{@link jcuda.runtime.JCuda#cudaMallocManaged}</li>
<li>{@link Pointer#to(byte[])}</li>
</ul>
<br>
For other pointer types, <code>null</code> is returned.
@param byteOffset The offset in bytes
@param byteSize The size of the byte buffer, in bytes
@return The byte buffer
@throws IllegalArgumentException If the <code>byteOffset</code> and
<code>byteSize</code> describe an invalid memory range (for example,
when the <code>byteOffset</code> is negative)
@throws ArithmeticException If the <code>byteOffset</code> or
<code>byteOffset + byteSize</code> overflows an <code>int</code>. | [
"Returns",
"a",
"ByteBuffer",
"that",
"corresponds",
"to",
"the",
"specified",
"segment",
"of",
"the",
"memory",
"that",
"this",
"pointer",
"points",
"to",
".",
"<br",
">",
"<br",
">",
"The",
"returned",
"byte",
"buffer",
"will",
"have",
"the",
"byte",
"or... | train | https://github.com/jcuda/jcuda/blob/468528b5b9b37dfceb6ed83fcfd889e9b359f984/JCudaJava/src/main/java/jcuda/Pointer.java#L553-L568 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/mfp/impl/JsDestinationAddressFactoryImpl.java | JsDestinationAddressFactoryImpl.createSIDestinationAddress | public final SIDestinationAddress createSIDestinationAddress(String destinationName
,boolean localOnly
)
throws NullPointerException {
"""
Create a new SIDestinationAddress to represent an SIBus Destination.
@param destinationName The name of the SIBus Destination
@param localOnly Indicates that the Destination should be limited
to only the queue or mediation point on the Messaging
Engine that the application is connected to, if one
exists. If no such message point exists then the option
is ignored.
@return SIDestinationAddress The new SIDestinationAddress.
@exception NullPointerException Thrown if the destinationName parameter is null.
"""
if (destinationName == null) {
throw new NullPointerException("destinationName");
}
return new JsDestinationAddressImpl(destinationName, localOnly, null, null, false);
} | java | public final SIDestinationAddress createSIDestinationAddress(String destinationName
,boolean localOnly
)
throws NullPointerException {
if (destinationName == null) {
throw new NullPointerException("destinationName");
}
return new JsDestinationAddressImpl(destinationName, localOnly, null, null, false);
} | [
"public",
"final",
"SIDestinationAddress",
"createSIDestinationAddress",
"(",
"String",
"destinationName",
",",
"boolean",
"localOnly",
")",
"throws",
"NullPointerException",
"{",
"if",
"(",
"destinationName",
"==",
"null",
")",
"{",
"throw",
"new",
"NullPointerExceptio... | Create a new SIDestinationAddress to represent an SIBus Destination.
@param destinationName The name of the SIBus Destination
@param localOnly Indicates that the Destination should be limited
to only the queue or mediation point on the Messaging
Engine that the application is connected to, if one
exists. If no such message point exists then the option
is ignored.
@return SIDestinationAddress The new SIDestinationAddress.
@exception NullPointerException Thrown if the destinationName parameter is null. | [
"Create",
"a",
"new",
"SIDestinationAddress",
"to",
"represent",
"an",
"SIBus",
"Destination",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/mfp/impl/JsDestinationAddressFactoryImpl.java#L58-L66 |
alkacon/opencms-core | src/org/opencms/workplace/tools/CmsToolManager.java | CmsToolManager.jspForwardPage | public void jspForwardPage(CmsWorkplace wp, String pagePath, Map<String, String[]> params)
throws IOException, ServletException {
"""
Redirects to the given page with the given parameters.<p>
@param wp the workplace object
@param pagePath the path to the page to redirect to
@param params the parameters to send
@throws IOException in case of errors during forwarding
@throws ServletException in case of errors during forwarding
"""
Map<String, String[]> newParams = createToolParams(wp, pagePath, params);
if (pagePath.indexOf("?") > 0) {
pagePath = pagePath.substring(0, pagePath.indexOf("?"));
}
wp.setForwarded(true);
// forward to the requested page uri
CmsRequestUtil.forwardRequest(
wp.getJsp().link(pagePath),
CmsRequestUtil.createParameterMap(newParams),
wp.getJsp().getRequest(),
wp.getJsp().getResponse());
} | java | public void jspForwardPage(CmsWorkplace wp, String pagePath, Map<String, String[]> params)
throws IOException, ServletException {
Map<String, String[]> newParams = createToolParams(wp, pagePath, params);
if (pagePath.indexOf("?") > 0) {
pagePath = pagePath.substring(0, pagePath.indexOf("?"));
}
wp.setForwarded(true);
// forward to the requested page uri
CmsRequestUtil.forwardRequest(
wp.getJsp().link(pagePath),
CmsRequestUtil.createParameterMap(newParams),
wp.getJsp().getRequest(),
wp.getJsp().getResponse());
} | [
"public",
"void",
"jspForwardPage",
"(",
"CmsWorkplace",
"wp",
",",
"String",
"pagePath",
",",
"Map",
"<",
"String",
",",
"String",
"[",
"]",
">",
"params",
")",
"throws",
"IOException",
",",
"ServletException",
"{",
"Map",
"<",
"String",
",",
"String",
"[... | Redirects to the given page with the given parameters.<p>
@param wp the workplace object
@param pagePath the path to the page to redirect to
@param params the parameters to send
@throws IOException in case of errors during forwarding
@throws ServletException in case of errors during forwarding | [
"Redirects",
"to",
"the",
"given",
"page",
"with",
"the",
"given",
"parameters",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/workplace/tools/CmsToolManager.java#L475-L490 |
lessthanoptimal/ejml | main/ejml-ddense/src/org/ejml/dense/row/CommonOps_DDRM.java | CommonOps_DDRM.elementPower | public static void elementPower(DMatrixD1 A , double b, DMatrixD1 C ) {
"""
<p>
Element-wise power operation <br>
c<sub>ij</sub> = a<sub>ij</sub> ^ b
<p>
@param A left side
@param b right scalar
@param C output (modified)
"""
if( A.numRows != C.numRows || A.numCols != C.numCols ) {
throw new MatrixDimensionException("All matrices must be the same shape");
}
int size = A.getNumElements();
for( int i = 0; i < size; i++ ) {
C.data[i] = Math.pow(A.data[i], b);
}
} | java | public static void elementPower(DMatrixD1 A , double b, DMatrixD1 C ) {
if( A.numRows != C.numRows || A.numCols != C.numCols ) {
throw new MatrixDimensionException("All matrices must be the same shape");
}
int size = A.getNumElements();
for( int i = 0; i < size; i++ ) {
C.data[i] = Math.pow(A.data[i], b);
}
} | [
"public",
"static",
"void",
"elementPower",
"(",
"DMatrixD1",
"A",
",",
"double",
"b",
",",
"DMatrixD1",
"C",
")",
"{",
"if",
"(",
"A",
".",
"numRows",
"!=",
"C",
".",
"numRows",
"||",
"A",
".",
"numCols",
"!=",
"C",
".",
"numCols",
")",
"{",
"thro... | <p>
Element-wise power operation <br>
c<sub>ij</sub> = a<sub>ij</sub> ^ b
<p>
@param A left side
@param b right scalar
@param C output (modified) | [
"<p",
">",
"Element",
"-",
"wise",
"power",
"operation",
"<br",
">",
"c<sub",
">",
"ij<",
"/",
"sub",
">",
"=",
"a<sub",
">",
"ij<",
"/",
"sub",
">",
"^",
"b",
"<p",
">"
] | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/row/CommonOps_DDRM.java#L1686-L1696 |
Azure/azure-sdk-for-java | datamigration/resource-manager/v2017_11_15_preview/src/main/java/com/microsoft/azure/management/datamigration/v2017_11_15_preview/implementation/ServicesInner.java | ServicesInner.beginDelete | public void beginDelete(String groupName, String serviceName) {
"""
Delete DMS Service Instance.
The services resource is the top-level resource that represents the Data Migration Service. The DELETE method deletes a service. Any running tasks will be canceled.
@param groupName Name of the resource group
@param serviceName Name of the service
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ApiErrorException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
"""
beginDeleteWithServiceResponseAsync(groupName, serviceName).toBlocking().single().body();
} | java | public void beginDelete(String groupName, String serviceName) {
beginDeleteWithServiceResponseAsync(groupName, serviceName).toBlocking().single().body();
} | [
"public",
"void",
"beginDelete",
"(",
"String",
"groupName",
",",
"String",
"serviceName",
")",
"{",
"beginDeleteWithServiceResponseAsync",
"(",
"groupName",
",",
"serviceName",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
"body",
"(",
")",
... | Delete DMS Service Instance.
The services resource is the top-level resource that represents the Data Migration Service. The DELETE method deletes a service. Any running tasks will be canceled.
@param groupName Name of the resource group
@param serviceName Name of the service
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ApiErrorException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent | [
"Delete",
"DMS",
"Service",
"Instance",
".",
"The",
"services",
"resource",
"is",
"the",
"top",
"-",
"level",
"resource",
"that",
"represents",
"the",
"Data",
"Migration",
"Service",
".",
"The",
"DELETE",
"method",
"deletes",
"a",
"service",
".",
"Any",
"run... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/datamigration/resource-manager/v2017_11_15_preview/src/main/java/com/microsoft/azure/management/datamigration/v2017_11_15_preview/implementation/ServicesInner.java#L581-L583 |
hazelcast/hazelcast | hazelcast/src/main/java/com/hazelcast/util/JsonUtil.java | JsonUtil.getArray | public static JsonArray getArray(JsonObject object, String field) {
"""
Returns a field in a Json object as an array.
Throws IllegalArgumentException if the field value is null.
@param object the Json Object
@param field the field in the Json object to return
@return the Json field value as an array
"""
final JsonValue value = object.get(field);
throwExceptionIfNull(value, field);
return value.asArray();
} | java | public static JsonArray getArray(JsonObject object, String field) {
final JsonValue value = object.get(field);
throwExceptionIfNull(value, field);
return value.asArray();
} | [
"public",
"static",
"JsonArray",
"getArray",
"(",
"JsonObject",
"object",
",",
"String",
"field",
")",
"{",
"final",
"JsonValue",
"value",
"=",
"object",
".",
"get",
"(",
"field",
")",
";",
"throwExceptionIfNull",
"(",
"value",
",",
"field",
")",
";",
"ret... | Returns a field in a Json object as an array.
Throws IllegalArgumentException if the field value is null.
@param object the Json Object
@param field the field in the Json object to return
@return the Json field value as an array | [
"Returns",
"a",
"field",
"in",
"a",
"Json",
"object",
"as",
"an",
"array",
".",
"Throws",
"IllegalArgumentException",
"if",
"the",
"field",
"value",
"is",
"null",
"."
] | train | https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/util/JsonUtil.java#L230-L234 |
OpenBEL/openbel-framework | org.openbel.framework.common/src/main/java/org/openbel/framework/common/model/Document.java | Document.getNamespaceMap | public Map<String, Namespace> getNamespaceMap() {
"""
Returns the document's namespaces as a mapped keyed by namespace
{@link Namespace#getPrefix() namespace prefix}.
@return Map of namespaces to instances
"""
final Map<String, Namespace> ret = new HashMap<String, Namespace>();
if (namespaceGroup == null) {
return ret;
}
final List<Namespace> namespaces = namespaceGroup.getNamespaces();
if (hasItems(namespaces)) {
for (final Namespace ns : namespaces)
ret.put(ns.getPrefix(), ns);
}
final String defns = namespaceGroup.getDefaultResourceLocation();
if (defns != null) {
Namespace ns = new Namespace(DEFAULT_NAMESPACE_PREFIX, defns);
ret.put(DEFAULT_NAMESPACE_PREFIX, ns);
}
return ret;
} | java | public Map<String, Namespace> getNamespaceMap() {
final Map<String, Namespace> ret = new HashMap<String, Namespace>();
if (namespaceGroup == null) {
return ret;
}
final List<Namespace> namespaces = namespaceGroup.getNamespaces();
if (hasItems(namespaces)) {
for (final Namespace ns : namespaces)
ret.put(ns.getPrefix(), ns);
}
final String defns = namespaceGroup.getDefaultResourceLocation();
if (defns != null) {
Namespace ns = new Namespace(DEFAULT_NAMESPACE_PREFIX, defns);
ret.put(DEFAULT_NAMESPACE_PREFIX, ns);
}
return ret;
} | [
"public",
"Map",
"<",
"String",
",",
"Namespace",
">",
"getNamespaceMap",
"(",
")",
"{",
"final",
"Map",
"<",
"String",
",",
"Namespace",
">",
"ret",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Namespace",
">",
"(",
")",
";",
"if",
"(",
"namespaceGroup... | Returns the document's namespaces as a mapped keyed by namespace
{@link Namespace#getPrefix() namespace prefix}.
@return Map of namespaces to instances | [
"Returns",
"the",
"document",
"s",
"namespaces",
"as",
"a",
"mapped",
"keyed",
"by",
"namespace",
"{",
"@link",
"Namespace#getPrefix",
"()",
"namespace",
"prefix",
"}",
"."
] | train | https://github.com/OpenBEL/openbel-framework/blob/149f80b1d6eabb15ab15815b6f745b0afa9fd2d3/org.openbel.framework.common/src/main/java/org/openbel/framework/common/model/Document.java#L272-L291 |
kiegroup/drools | drools-core/src/main/java/org/drools/core/util/DroolsStreamUtils.java | DroolsStreamUtils.streamIn | public static Object streamIn(byte[] bytes, ClassLoader classLoader)
throws IOException, ClassNotFoundException {
"""
This method reads the contents from the given byte array and returns the object. It is expected that
the contents in the given buffer was not compressed, and the content stream was written by the corresponding
streamOut methods of this class.
@param bytes
@param classLoader
@return
@throws IOException
@throws ClassNotFoundException
"""
return streamIn(bytes, classLoader, false);
} | java | public static Object streamIn(byte[] bytes, ClassLoader classLoader)
throws IOException, ClassNotFoundException {
return streamIn(bytes, classLoader, false);
} | [
"public",
"static",
"Object",
"streamIn",
"(",
"byte",
"[",
"]",
"bytes",
",",
"ClassLoader",
"classLoader",
")",
"throws",
"IOException",
",",
"ClassNotFoundException",
"{",
"return",
"streamIn",
"(",
"bytes",
",",
"classLoader",
",",
"false",
")",
";",
"}"
] | This method reads the contents from the given byte array and returns the object. It is expected that
the contents in the given buffer was not compressed, and the content stream was written by the corresponding
streamOut methods of this class.
@param bytes
@param classLoader
@return
@throws IOException
@throws ClassNotFoundException | [
"This",
"method",
"reads",
"the",
"contents",
"from",
"the",
"given",
"byte",
"array",
"and",
"returns",
"the",
"object",
".",
"It",
"is",
"expected",
"that",
"the",
"contents",
"in",
"the",
"given",
"buffer",
"was",
"not",
"compressed",
"and",
"the",
"con... | train | https://github.com/kiegroup/drools/blob/22b0275d6dbe93070b8090948502cf46eda543c4/drools-core/src/main/java/org/drools/core/util/DroolsStreamUtils.java#L129-L132 |
weld/core | impl/src/main/java/org/jboss/weld/util/Beans.java | Beans.isAlternative | public static boolean isAlternative(EnhancedAnnotated<?, ?> annotated, MergedStereotypes<?, ?> mergedStereotypes) {
"""
Is alternative.
@param annotated the annotated
@param mergedStereotypes merged stereotypes
@return true if alternative, false otherwise
"""
return annotated.isAnnotationPresent(Alternative.class) || mergedStereotypes.isAlternative();
} | java | public static boolean isAlternative(EnhancedAnnotated<?, ?> annotated, MergedStereotypes<?, ?> mergedStereotypes) {
return annotated.isAnnotationPresent(Alternative.class) || mergedStereotypes.isAlternative();
} | [
"public",
"static",
"boolean",
"isAlternative",
"(",
"EnhancedAnnotated",
"<",
"?",
",",
"?",
">",
"annotated",
",",
"MergedStereotypes",
"<",
"?",
",",
"?",
">",
"mergedStereotypes",
")",
"{",
"return",
"annotated",
".",
"isAnnotationPresent",
"(",
"Alternative... | Is alternative.
@param annotated the annotated
@param mergedStereotypes merged stereotypes
@return true if alternative, false otherwise | [
"Is",
"alternative",
"."
] | train | https://github.com/weld/core/blob/567a2eaf95b168597d23a56be89bf05a7834b2aa/impl/src/main/java/org/jboss/weld/util/Beans.java#L255-L257 |
joniles/mpxj | src/main/java/net/sf/mpxj/ProjectCalendar.java | ProjectCalendar.getWork | public Duration getWork(Date date, TimeUnit format) {
"""
Retrieves the amount of work on a given day, and
returns it in the specified format.
@param date target date
@param format required format
@return work duration
"""
ProjectCalendarDateRanges ranges = getRanges(date, null, null);
long time = getTotalTime(ranges);
return convertFormat(time, format);
} | java | public Duration getWork(Date date, TimeUnit format)
{
ProjectCalendarDateRanges ranges = getRanges(date, null, null);
long time = getTotalTime(ranges);
return convertFormat(time, format);
} | [
"public",
"Duration",
"getWork",
"(",
"Date",
"date",
",",
"TimeUnit",
"format",
")",
"{",
"ProjectCalendarDateRanges",
"ranges",
"=",
"getRanges",
"(",
"date",
",",
"null",
",",
"null",
")",
";",
"long",
"time",
"=",
"getTotalTime",
"(",
"ranges",
")",
";... | Retrieves the amount of work on a given day, and
returns it in the specified format.
@param date target date
@param format required format
@return work duration | [
"Retrieves",
"the",
"amount",
"of",
"work",
"on",
"a",
"given",
"day",
"and",
"returns",
"it",
"in",
"the",
"specified",
"format",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/ProjectCalendar.java#L1186-L1191 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/equals/EqualsHelper.java | EqualsHelper.equalsIgnoreCase | @SuppressFBWarnings ( {
"""
Check if the passed strings are equals case insensitive handling
<code>null</code> appropriately.
@param sObj1
First object to compare
@param sObj2
Second object to compare
@return <code>true</code> if they are equal case insensitive,
<code>false</code> otherwise.
""" "ES_COMPARING_PARAMETER_STRING_WITH_EQ" })
public static boolean equalsIgnoreCase (@Nullable final String sObj1, @Nullable final String sObj2)
{
return sObj1 == null ? sObj2 == null : sObj1.equalsIgnoreCase (sObj2);
} | java | @SuppressFBWarnings ({ "ES_COMPARING_PARAMETER_STRING_WITH_EQ" })
public static boolean equalsIgnoreCase (@Nullable final String sObj1, @Nullable final String sObj2)
{
return sObj1 == null ? sObj2 == null : sObj1.equalsIgnoreCase (sObj2);
} | [
"@",
"SuppressFBWarnings",
"(",
"{",
"\"ES_COMPARING_PARAMETER_STRING_WITH_EQ\"",
"}",
")",
"public",
"static",
"boolean",
"equalsIgnoreCase",
"(",
"@",
"Nullable",
"final",
"String",
"sObj1",
",",
"@",
"Nullable",
"final",
"String",
"sObj2",
")",
"{",
"return",
"... | Check if the passed strings are equals case insensitive handling
<code>null</code> appropriately.
@param sObj1
First object to compare
@param sObj2
Second object to compare
@return <code>true</code> if they are equal case insensitive,
<code>false</code> otherwise. | [
"Check",
"if",
"the",
"passed",
"strings",
"are",
"equals",
"case",
"insensitive",
"handling",
"<code",
">",
"null<",
"/",
"code",
">",
"appropriately",
"."
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/equals/EqualsHelper.java#L218-L222 |
http-builder-ng/http-builder-ng | http-builder-ng-core/src/main/java/groovyx/net/http/util/IoUtils.java | IoUtils.copyAsString | public static String copyAsString(final BufferedInputStream inputStream) throws IOException, IllegalStateException {
"""
Safely copies the contents of the {@link BufferedInputStream} to a {@link String} and resets the stream.
This method is generally only useful for testing and logging purposes.
@param inputStream the BufferedInputStream
@return a String copy of the stream contents
@throws IOException if something goes wrong with the stream
@throws IllegalStateException if the stream cannot be reset
"""
if (inputStream == null) return null;
try {
inputStream.mark(Integer.MAX_VALUE);
return new String(streamToBytes(inputStream, false));
} finally {
try {
inputStream.reset();
} catch (IOException ioe) {
throw new IllegalStateException("Unable to reset stream - original stream content may be corrupted");
}
}
} | java | public static String copyAsString(final BufferedInputStream inputStream) throws IOException, IllegalStateException {
if (inputStream == null) return null;
try {
inputStream.mark(Integer.MAX_VALUE);
return new String(streamToBytes(inputStream, false));
} finally {
try {
inputStream.reset();
} catch (IOException ioe) {
throw new IllegalStateException("Unable to reset stream - original stream content may be corrupted");
}
}
} | [
"public",
"static",
"String",
"copyAsString",
"(",
"final",
"BufferedInputStream",
"inputStream",
")",
"throws",
"IOException",
",",
"IllegalStateException",
"{",
"if",
"(",
"inputStream",
"==",
"null",
")",
"return",
"null",
";",
"try",
"{",
"inputStream",
".",
... | Safely copies the contents of the {@link BufferedInputStream} to a {@link String} and resets the stream.
This method is generally only useful for testing and logging purposes.
@param inputStream the BufferedInputStream
@return a String copy of the stream contents
@throws IOException if something goes wrong with the stream
@throws IllegalStateException if the stream cannot be reset | [
"Safely",
"copies",
"the",
"contents",
"of",
"the",
"{",
"@link",
"BufferedInputStream",
"}",
"to",
"a",
"{",
"@link",
"String",
"}",
"and",
"resets",
"the",
"stream",
".",
"This",
"method",
"is",
"generally",
"only",
"useful",
"for",
"testing",
"and",
"lo... | train | https://github.com/http-builder-ng/http-builder-ng/blob/865f37732c102c748d3db8b905199dac9222a525/http-builder-ng-core/src/main/java/groovyx/net/http/util/IoUtils.java#L67-L80 |
facebookarchive/hadoop-20 | src/hdfs/org/apache/hadoop/hdfs/DFSUtil.java | DFSUtil.getAddresses | public static List<InetSocketAddress> getAddresses(Configuration conf,
String defaultAddress, String... keys) {
"""
Returns list of InetSocketAddress for a given set of keys.
@param conf configuration
@param defaultAddress default address to return in case key is not found
@param keys Set of keys to look for in the order of preference
@return list of InetSocketAddress corresponding to the key
"""
return getAddresses(conf, getNameServiceIds(conf), defaultAddress, keys);
} | java | public static List<InetSocketAddress> getAddresses(Configuration conf,
String defaultAddress, String... keys) {
return getAddresses(conf, getNameServiceIds(conf), defaultAddress, keys);
} | [
"public",
"static",
"List",
"<",
"InetSocketAddress",
">",
"getAddresses",
"(",
"Configuration",
"conf",
",",
"String",
"defaultAddress",
",",
"String",
"...",
"keys",
")",
"{",
"return",
"getAddresses",
"(",
"conf",
",",
"getNameServiceIds",
"(",
"conf",
")",
... | Returns list of InetSocketAddress for a given set of keys.
@param conf configuration
@param defaultAddress default address to return in case key is not found
@param keys Set of keys to look for in the order of preference
@return list of InetSocketAddress corresponding to the key | [
"Returns",
"list",
"of",
"InetSocketAddress",
"for",
"a",
"given",
"set",
"of",
"keys",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/DFSUtil.java#L491-L494 |
apache/flink | flink-libraries/flink-gelly/src/main/java/org/apache/flink/graph/Graph.java | Graph.fromTuple2DataSet | public static <K> Graph<K, NullValue, NullValue> fromTuple2DataSet(DataSet<Tuple2<K, K>> edges,
ExecutionEnvironment context) {
"""
Creates a graph from a DataSet of Tuple2 objects for edges.
Each Tuple2 will become one Edge, where the source ID will be the first field of the Tuple2
and the target ID will be the second field of the Tuple2.
<p>Edge value types and Vertex values types will be set to NullValue.
@param edges a DataSet of Tuple2.
@param context the flink execution environment.
@return the newly created graph.
"""
DataSet<Edge<K, NullValue>> edgeDataSet = edges
.map(new Tuple2ToEdgeMap<>())
.name("To Edge");
return fromDataSet(edgeDataSet, context);
} | java | public static <K> Graph<K, NullValue, NullValue> fromTuple2DataSet(DataSet<Tuple2<K, K>> edges,
ExecutionEnvironment context) {
DataSet<Edge<K, NullValue>> edgeDataSet = edges
.map(new Tuple2ToEdgeMap<>())
.name("To Edge");
return fromDataSet(edgeDataSet, context);
} | [
"public",
"static",
"<",
"K",
">",
"Graph",
"<",
"K",
",",
"NullValue",
",",
"NullValue",
">",
"fromTuple2DataSet",
"(",
"DataSet",
"<",
"Tuple2",
"<",
"K",
",",
"K",
">",
">",
"edges",
",",
"ExecutionEnvironment",
"context",
")",
"{",
"DataSet",
"<",
... | Creates a graph from a DataSet of Tuple2 objects for edges.
Each Tuple2 will become one Edge, where the source ID will be the first field of the Tuple2
and the target ID will be the second field of the Tuple2.
<p>Edge value types and Vertex values types will be set to NullValue.
@param edges a DataSet of Tuple2.
@param context the flink execution environment.
@return the newly created graph. | [
"Creates",
"a",
"graph",
"from",
"a",
"DataSet",
"of",
"Tuple2",
"objects",
"for",
"edges",
".",
"Each",
"Tuple2",
"will",
"become",
"one",
"Edge",
"where",
"the",
"source",
"ID",
"will",
"be",
"the",
"first",
"field",
"of",
"the",
"Tuple2",
"and",
"the"... | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-libraries/flink-gelly/src/main/java/org/apache/flink/graph/Graph.java#L342-L350 |
jenkinsci/github-plugin | src/main/java/org/jenkinsci/plugins/github/util/JobInfoHelpers.java | JobInfoHelpers.withTrigger | public static <ITEM extends Item> Predicate<ITEM> withTrigger(final Class<? extends Trigger> clazz) {
"""
@param clazz trigger class to check in job
@return predicate with true on apply if job contains trigger of given class
"""
return new Predicate<ITEM>() {
public boolean apply(Item item) {
return triggerFrom(item, clazz) != null;
}
};
} | java | public static <ITEM extends Item> Predicate<ITEM> withTrigger(final Class<? extends Trigger> clazz) {
return new Predicate<ITEM>() {
public boolean apply(Item item) {
return triggerFrom(item, clazz) != null;
}
};
} | [
"public",
"static",
"<",
"ITEM",
"extends",
"Item",
">",
"Predicate",
"<",
"ITEM",
">",
"withTrigger",
"(",
"final",
"Class",
"<",
"?",
"extends",
"Trigger",
">",
"clazz",
")",
"{",
"return",
"new",
"Predicate",
"<",
"ITEM",
">",
"(",
")",
"{",
"public... | @param clazz trigger class to check in job
@return predicate with true on apply if job contains trigger of given class | [
"@param",
"clazz",
"trigger",
"class",
"to",
"check",
"in",
"job"
] | train | https://github.com/jenkinsci/github-plugin/blob/4e05b9aeb488af5342c78f78aa3c55114e8d462a/src/main/java/org/jenkinsci/plugins/github/util/JobInfoHelpers.java#L38-L44 |
apache/incubator-gobblin | gobblin-utility/src/main/java/org/apache/gobblin/util/JobLauncherUtils.java | JobLauncherUtils.cleanStagingData | public static void cleanStagingData(List<? extends State> states, Logger logger) throws IOException {
"""
Cleanup the staging data for a list of Gobblin tasks. This method calls the
{@link #cleanTaskStagingData(State, Logger)} method.
@param states a {@link List} of {@link State}s that need their staging data cleaned
"""
for (State state : states) {
JobLauncherUtils.cleanTaskStagingData(state, logger);
}
} | java | public static void cleanStagingData(List<? extends State> states, Logger logger) throws IOException {
for (State state : states) {
JobLauncherUtils.cleanTaskStagingData(state, logger);
}
} | [
"public",
"static",
"void",
"cleanStagingData",
"(",
"List",
"<",
"?",
"extends",
"State",
">",
"states",
",",
"Logger",
"logger",
")",
"throws",
"IOException",
"{",
"for",
"(",
"State",
"state",
":",
"states",
")",
"{",
"JobLauncherUtils",
".",
"cleanTaskSt... | Cleanup the staging data for a list of Gobblin tasks. This method calls the
{@link #cleanTaskStagingData(State, Logger)} method.
@param states a {@link List} of {@link State}s that need their staging data cleaned | [
"Cleanup",
"the",
"staging",
"data",
"for",
"a",
"list",
"of",
"Gobblin",
"tasks",
".",
"This",
"method",
"calls",
"the",
"{",
"@link",
"#cleanTaskStagingData",
"(",
"State",
"Logger",
")",
"}",
"method",
"."
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/JobLauncherUtils.java#L122-L126 |
Netflix/Nicobar | nicobar-core/src/main/java/com/netflix/nicobar/core/module/GraphUtils.java | GraphUtils.addOutgoingEdges | public static <V> void addOutgoingEdges(DirectedGraph<V, DefaultEdge> graph, V source, Set<V> targets) {
"""
Add dependencies to the given source vertex. Whether duplicates are created is dependent
on the underlying {@link DirectedGraph} implementation.
@param graph graph to be mutated
@param source source vertex of the new edges
@param targets target vertices for the new edges
"""
if (!graph.containsVertex(source)) {
graph.addVertex(source);
}
for (V target : targets) {
if (!graph.containsVertex(target)) {
graph.addVertex(target);
}
graph.addEdge(source, target);
}
} | java | public static <V> void addOutgoingEdges(DirectedGraph<V, DefaultEdge> graph, V source, Set<V> targets) {
if (!graph.containsVertex(source)) {
graph.addVertex(source);
}
for (V target : targets) {
if (!graph.containsVertex(target)) {
graph.addVertex(target);
}
graph.addEdge(source, target);
}
} | [
"public",
"static",
"<",
"V",
">",
"void",
"addOutgoingEdges",
"(",
"DirectedGraph",
"<",
"V",
",",
"DefaultEdge",
">",
"graph",
",",
"V",
"source",
",",
"Set",
"<",
"V",
">",
"targets",
")",
"{",
"if",
"(",
"!",
"graph",
".",
"containsVertex",
"(",
... | Add dependencies to the given source vertex. Whether duplicates are created is dependent
on the underlying {@link DirectedGraph} implementation.
@param graph graph to be mutated
@param source source vertex of the new edges
@param targets target vertices for the new edges | [
"Add",
"dependencies",
"to",
"the",
"given",
"source",
"vertex",
".",
"Whether",
"duplicates",
"are",
"created",
"is",
"dependent",
"on",
"the",
"underlying",
"{"
] | train | https://github.com/Netflix/Nicobar/blob/507173dcae4a86a955afc3df222a855862fab8d7/nicobar-core/src/main/java/com/netflix/nicobar/core/module/GraphUtils.java#L93-L103 |
podio/podio-java | src/main/java/com/podio/task/TaskAPI.java | TaskAPI.createTask | public int createTask(TaskCreate task, boolean silent, boolean hook) {
"""
Creates a new task with no reference to other objects.
@param task
The data of the task to be created
@param silent
Disable notifications
@param hook
Execute hooks for the change
@return The id of the newly created task
"""
TaskCreateResponse response = getResourceFactory()
.getApiResource("/task/")
.queryParam("silent", silent ? "1" : "0")
.queryParam("hook", hook ? "1" : "0")
.entity(task, MediaType.APPLICATION_JSON_TYPE)
.post(TaskCreateResponse.class);
return response.getId();
} | java | public int createTask(TaskCreate task, boolean silent, boolean hook) {
TaskCreateResponse response = getResourceFactory()
.getApiResource("/task/")
.queryParam("silent", silent ? "1" : "0")
.queryParam("hook", hook ? "1" : "0")
.entity(task, MediaType.APPLICATION_JSON_TYPE)
.post(TaskCreateResponse.class);
return response.getId();
} | [
"public",
"int",
"createTask",
"(",
"TaskCreate",
"task",
",",
"boolean",
"silent",
",",
"boolean",
"hook",
")",
"{",
"TaskCreateResponse",
"response",
"=",
"getResourceFactory",
"(",
")",
".",
"getApiResource",
"(",
"\"/task/\"",
")",
".",
"queryParam",
"(",
... | Creates a new task with no reference to other objects.
@param task
The data of the task to be created
@param silent
Disable notifications
@param hook
Execute hooks for the change
@return The id of the newly created task | [
"Creates",
"a",
"new",
"task",
"with",
"no",
"reference",
"to",
"other",
"objects",
"."
] | train | https://github.com/podio/podio-java/blob/a520b23bac118c957ce02cdd8ff42a6c7d17b49a/src/main/java/com/podio/task/TaskAPI.java#L174-L183 |
sdaschner/jaxrs-analyzer | src/main/java/com/sebastian_daschner/jaxrs_analyzer/analysis/bytecode/MethodContentAnalyzer.java | MethodContentAnalyzer.addProjectMethods | private void addProjectMethods(final List<Instruction> instructions, final Set<ProjectMethod> projectMethods) {
"""
Adds all project methods called in the given {@code instructions} to the {@code projectMethods} recursively.
@param instructions The instructions of the current method
@param projectMethods All found project methods
"""
Set<MethodIdentifier> projectMethodIdentifiers = findUnhandledProjectMethodIdentifiers(instructions, projectMethods);
for (MethodIdentifier identifier : projectMethodIdentifiers) {
// TODO cache results -> singleton pool?
final MethodResult methodResult = visitProjectMethod(identifier);
if (methodResult == null) {
continue;
}
final List<Instruction> nestedMethodInstructions = interpretRelevantInstructions(methodResult.getInstructions());
projectMethods.add(new ProjectMethod(identifier, nestedMethodInstructions));
addProjectMethods(nestedMethodInstructions, projectMethods);
}
} | java | private void addProjectMethods(final List<Instruction> instructions, final Set<ProjectMethod> projectMethods) {
Set<MethodIdentifier> projectMethodIdentifiers = findUnhandledProjectMethodIdentifiers(instructions, projectMethods);
for (MethodIdentifier identifier : projectMethodIdentifiers) {
// TODO cache results -> singleton pool?
final MethodResult methodResult = visitProjectMethod(identifier);
if (methodResult == null) {
continue;
}
final List<Instruction> nestedMethodInstructions = interpretRelevantInstructions(methodResult.getInstructions());
projectMethods.add(new ProjectMethod(identifier, nestedMethodInstructions));
addProjectMethods(nestedMethodInstructions, projectMethods);
}
} | [
"private",
"void",
"addProjectMethods",
"(",
"final",
"List",
"<",
"Instruction",
">",
"instructions",
",",
"final",
"Set",
"<",
"ProjectMethod",
">",
"projectMethods",
")",
"{",
"Set",
"<",
"MethodIdentifier",
">",
"projectMethodIdentifiers",
"=",
"findUnhandledPro... | Adds all project methods called in the given {@code instructions} to the {@code projectMethods} recursively.
@param instructions The instructions of the current method
@param projectMethods All found project methods | [
"Adds",
"all",
"project",
"methods",
"called",
"in",
"the",
"given",
"{",
"@code",
"instructions",
"}",
"to",
"the",
"{",
"@code",
"projectMethods",
"}",
"recursively",
"."
] | train | https://github.com/sdaschner/jaxrs-analyzer/blob/4ac62942202d05632977d6c14d3cd7e2d27e2b9b/src/main/java/com/sebastian_daschner/jaxrs_analyzer/analysis/bytecode/MethodContentAnalyzer.java#L99-L114 |
buschmais/extended-objects | impl/src/main/java/com/buschmais/xo/impl/metadata/MetadataProviderImpl.java | MetadataProviderImpl.getMetadata | private <T extends TypeMetadata> T getMetadata(Class<?> type, Class<T> metadataType) {
"""
Return the {@link TypeMetadata} instance representing the given type.
@param type
The type.
@param metadataType
The expected metadata type.
@param <T>
The metadata type.
@return The {@link TypeMetadata} instance.
"""
TypeMetadata typeMetadata = metadataByType.get(type);
if (typeMetadata == null) {
throw new XOException("Cannot resolve metadata for type " + type.getName() + ".");
}
if (!metadataType.isAssignableFrom(typeMetadata.getClass())) {
throw new XOException(
"Expected metadata of type '" + metadataType.getName() + "' but got '" + typeMetadata.getClass() + "' for type '" + type + "'");
}
return metadataType.cast(typeMetadata);
} | java | private <T extends TypeMetadata> T getMetadata(Class<?> type, Class<T> metadataType) {
TypeMetadata typeMetadata = metadataByType.get(type);
if (typeMetadata == null) {
throw new XOException("Cannot resolve metadata for type " + type.getName() + ".");
}
if (!metadataType.isAssignableFrom(typeMetadata.getClass())) {
throw new XOException(
"Expected metadata of type '" + metadataType.getName() + "' but got '" + typeMetadata.getClass() + "' for type '" + type + "'");
}
return metadataType.cast(typeMetadata);
} | [
"private",
"<",
"T",
"extends",
"TypeMetadata",
">",
"T",
"getMetadata",
"(",
"Class",
"<",
"?",
">",
"type",
",",
"Class",
"<",
"T",
">",
"metadataType",
")",
"{",
"TypeMetadata",
"typeMetadata",
"=",
"metadataByType",
".",
"get",
"(",
"type",
")",
";",... | Return the {@link TypeMetadata} instance representing the given type.
@param type
The type.
@param metadataType
The expected metadata type.
@param <T>
The metadata type.
@return The {@link TypeMetadata} instance. | [
"Return",
"the",
"{",
"@link",
"TypeMetadata",
"}",
"instance",
"representing",
"the",
"given",
"type",
"."
] | train | https://github.com/buschmais/extended-objects/blob/186431e81f3d8d26c511cfe1143dee59b03c2e7a/impl/src/main/java/com/buschmais/xo/impl/metadata/MetadataProviderImpl.java#L612-L622 |
citrusframework/citrus | modules/citrus-mail/src/main/java/com/consol/citrus/mail/message/MailMessageConverter.java | MailMessageConverter.handleTextPart | protected BodyPart handleTextPart(MimePart textPart, String contentType) throws IOException, MessagingException {
"""
Construct simple binary body part with base64 data.
@param textPart
@param contentType
@return
@throws IOException
"""
String content;
if (textPart.getContent() instanceof String) {
content = (String) textPart.getContent();
} else if (textPart.getContent() instanceof InputStream) {
content = FileUtils.readToString((InputStream) textPart.getContent(), Charset.forName(parseCharsetFromContentType(contentType)));
} else {
throw new CitrusRuntimeException("Cannot handle text content of type: " + textPart.getContent().getClass().toString());
}
return new BodyPart(stripMailBodyEnding(content), contentType);
} | java | protected BodyPart handleTextPart(MimePart textPart, String contentType) throws IOException, MessagingException {
String content;
if (textPart.getContent() instanceof String) {
content = (String) textPart.getContent();
} else if (textPart.getContent() instanceof InputStream) {
content = FileUtils.readToString((InputStream) textPart.getContent(), Charset.forName(parseCharsetFromContentType(contentType)));
} else {
throw new CitrusRuntimeException("Cannot handle text content of type: " + textPart.getContent().getClass().toString());
}
return new BodyPart(stripMailBodyEnding(content), contentType);
} | [
"protected",
"BodyPart",
"handleTextPart",
"(",
"MimePart",
"textPart",
",",
"String",
"contentType",
")",
"throws",
"IOException",
",",
"MessagingException",
"{",
"String",
"content",
";",
"if",
"(",
"textPart",
".",
"getContent",
"(",
")",
"instanceof",
"String"... | Construct simple binary body part with base64 data.
@param textPart
@param contentType
@return
@throws IOException | [
"Construct",
"simple",
"binary",
"body",
"part",
"with",
"base64",
"data",
"."
] | train | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-mail/src/main/java/com/consol/citrus/mail/message/MailMessageConverter.java#L262-L274 |
DDTH/ddth-commons | ddth-commons-core/src/main/java/com/github/ddth/commons/redis/JedisUtils.java | JedisUtils.newShardedJedisPool | public static ShardedJedisPool newShardedJedisPool(String hostsAndPorts, String password) {
"""
Create a new {@link ShardedJedisPool} with default pool configs.
@param hostsAndPorts
format {@code host1:port1,host2:port2,...}, default Redis port is used if not
specified
@param password
@return
"""
return newShardedJedisPool(defaultJedisPoolConfig(), hostsAndPorts, password);
} | java | public static ShardedJedisPool newShardedJedisPool(String hostsAndPorts, String password) {
return newShardedJedisPool(defaultJedisPoolConfig(), hostsAndPorts, password);
} | [
"public",
"static",
"ShardedJedisPool",
"newShardedJedisPool",
"(",
"String",
"hostsAndPorts",
",",
"String",
"password",
")",
"{",
"return",
"newShardedJedisPool",
"(",
"defaultJedisPoolConfig",
"(",
")",
",",
"hostsAndPorts",
",",
"password",
")",
";",
"}"
] | Create a new {@link ShardedJedisPool} with default pool configs.
@param hostsAndPorts
format {@code host1:port1,host2:port2,...}, default Redis port is used if not
specified
@param password
@return | [
"Create",
"a",
"new",
"{",
"@link",
"ShardedJedisPool",
"}",
"with",
"default",
"pool",
"configs",
"."
] | train | https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/redis/JedisUtils.java#L394-L396 |
apereo/cas | core/cas-server-core-tickets-api/src/main/java/org/apereo/cas/ticket/factory/DefaultTicketFactory.java | DefaultTicketFactory.addTicketFactory | public DefaultTicketFactory addTicketFactory(final @NonNull Class<? extends Ticket> ticketClass, final @NonNull TicketFactory factory) {
"""
Add ticket factory.
@param ticketClass the ticket class
@param factory the factory
@return the default ticket factory
"""
this.factoryMap.put(ticketClass.getCanonicalName(), factory);
return this;
} | java | public DefaultTicketFactory addTicketFactory(final @NonNull Class<? extends Ticket> ticketClass, final @NonNull TicketFactory factory) {
this.factoryMap.put(ticketClass.getCanonicalName(), factory);
return this;
} | [
"public",
"DefaultTicketFactory",
"addTicketFactory",
"(",
"final",
"@",
"NonNull",
"Class",
"<",
"?",
"extends",
"Ticket",
">",
"ticketClass",
",",
"final",
"@",
"NonNull",
"TicketFactory",
"factory",
")",
"{",
"this",
".",
"factoryMap",
".",
"put",
"(",
"tic... | Add ticket factory.
@param ticketClass the ticket class
@param factory the factory
@return the default ticket factory | [
"Add",
"ticket",
"factory",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-tickets-api/src/main/java/org/apereo/cas/ticket/factory/DefaultTicketFactory.java#L34-L37 |
jaxio/celerio | celerio-engine/src/main/java/com/jaxio/celerio/template/ContentWriter.java | ContentWriter.getFullPathForLog | private String getFullPathForLog(OutputResult or, String targetFilename) {
"""
Use it only to display proper path in log
@param targetFilename
"""
if (or.sameDirectory()) {
return targetFilename;
} else {
return or.getGeneratedSource().getFullPath(targetFilename);
}
} | java | private String getFullPathForLog(OutputResult or, String targetFilename) {
if (or.sameDirectory()) {
return targetFilename;
} else {
return or.getGeneratedSource().getFullPath(targetFilename);
}
} | [
"private",
"String",
"getFullPathForLog",
"(",
"OutputResult",
"or",
",",
"String",
"targetFilename",
")",
"{",
"if",
"(",
"or",
".",
"sameDirectory",
"(",
")",
")",
"{",
"return",
"targetFilename",
";",
"}",
"else",
"{",
"return",
"or",
".",
"getGeneratedSo... | Use it only to display proper path in log
@param targetFilename | [
"Use",
"it",
"only",
"to",
"display",
"proper",
"path",
"in",
"log"
] | train | https://github.com/jaxio/celerio/blob/fbfacb639e286f9f3f3a18986f74ea275bebd887/celerio-engine/src/main/java/com/jaxio/celerio/template/ContentWriter.java#L109-L115 |
jenkinsci/support-core-plugin | src/main/java/com/cloudbees/jenkins/support/api/SupportProviderDescriptor.java | SupportProviderDescriptor.newDefaultInstance | public SupportProvider newDefaultInstance() {
"""
Construct a default instance of the {@link SupportProvider}. This method is used when there is no current
selected {@link SupportProvider} and this provider has been selected to act as the default {@link
SupportProvider}
@return the instance.
"""
try {
return clazz.newInstance();
} catch (InstantiationException e) {
throw new RuntimeException("Failed to instantiate " + clazz, e);
} catch (IllegalAccessException e) {
throw new RuntimeException("Failed to instantiate " + clazz, e);
}
} | java | public SupportProvider newDefaultInstance() {
try {
return clazz.newInstance();
} catch (InstantiationException e) {
throw new RuntimeException("Failed to instantiate " + clazz, e);
} catch (IllegalAccessException e) {
throw new RuntimeException("Failed to instantiate " + clazz, e);
}
} | [
"public",
"SupportProvider",
"newDefaultInstance",
"(",
")",
"{",
"try",
"{",
"return",
"clazz",
".",
"newInstance",
"(",
")",
";",
"}",
"catch",
"(",
"InstantiationException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Failed to instantiate \"",
... | Construct a default instance of the {@link SupportProvider}. This method is used when there is no current
selected {@link SupportProvider} and this provider has been selected to act as the default {@link
SupportProvider}
@return the instance. | [
"Construct",
"a",
"default",
"instance",
"of",
"the",
"{",
"@link",
"SupportProvider",
"}",
".",
"This",
"method",
"is",
"used",
"when",
"there",
"is",
"no",
"current",
"selected",
"{",
"@link",
"SupportProvider",
"}",
"and",
"this",
"provider",
"has",
"been... | train | https://github.com/jenkinsci/support-core-plugin/blob/bcbe1dfd5bf48ac89903645cd48ed897c1a04688/src/main/java/com/cloudbees/jenkins/support/api/SupportProviderDescriptor.java#L43-L51 |
ckpoint/CheckPoint | src/main/java/hsim/checkpoint/setting/controller/MsgSettingController.java | MsgSettingController.downloadApiJsonAll | @GetMapping("/setting/download/api/json/all")
public void downloadApiJsonAll(HttpServletRequest req, HttpServletResponse res) {
"""
Download api json all.
@param req the req
@param res the res
"""
this.validationSessionComponent.sessionCheck(req);
List<ValidationData> list = this.msgSettingService.getAllValidationData();
ValidationFileUtil.sendFileToHttpServiceResponse("validation.json", list, res);
} | java | @GetMapping("/setting/download/api/json/all")
public void downloadApiJsonAll(HttpServletRequest req, HttpServletResponse res) {
this.validationSessionComponent.sessionCheck(req);
List<ValidationData> list = this.msgSettingService.getAllValidationData();
ValidationFileUtil.sendFileToHttpServiceResponse("validation.json", list, res);
} | [
"@",
"GetMapping",
"(",
"\"/setting/download/api/json/all\"",
")",
"public",
"void",
"downloadApiJsonAll",
"(",
"HttpServletRequest",
"req",
",",
"HttpServletResponse",
"res",
")",
"{",
"this",
".",
"validationSessionComponent",
".",
"sessionCheck",
"(",
"req",
")",
"... | Download api json all.
@param req the req
@param res the res | [
"Download",
"api",
"json",
"all",
"."
] | train | https://github.com/ckpoint/CheckPoint/blob/2c2b1a87a88485d49ea6afa34acdf16ef4134f19/src/main/java/hsim/checkpoint/setting/controller/MsgSettingController.java#L74-L79 |
UrielCh/ovh-java-sdk | ovh-java-sdk-dedicatedserver/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedserver.java | ApiOvhDedicatedserver.serviceName_serviceMonitoring_monitoringId_alert_sms_POST | public OvhSmsAlert serviceName_serviceMonitoring_monitoringId_alert_sms_POST(String serviceName, Long monitoringId, Long fromHour, OvhAlertLanguageEnum language, String phoneNumberTo, String smsAccount, Long toHour) throws IOException {
"""
Create a SMS alert
REST: POST /dedicated/server/{serviceName}/serviceMonitoring/{monitoringId}/alert/sms
@param smsAccount [required] Your SMS account
@param fromHour [required] Daily hour start time for SMS notification
@param toHour [required] Daily hour end time for SMS notification
@param language [required] Alert language
@param phoneNumberTo [required] Alert destination
@param serviceName [required] The internal name of your dedicated server
@param monitoringId [required] This monitoring id
"""
String qPath = "/dedicated/server/{serviceName}/serviceMonitoring/{monitoringId}/alert/sms";
StringBuilder sb = path(qPath, serviceName, monitoringId);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "fromHour", fromHour);
addBody(o, "language", language);
addBody(o, "phoneNumberTo", phoneNumberTo);
addBody(o, "smsAccount", smsAccount);
addBody(o, "toHour", toHour);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhSmsAlert.class);
} | java | public OvhSmsAlert serviceName_serviceMonitoring_monitoringId_alert_sms_POST(String serviceName, Long monitoringId, Long fromHour, OvhAlertLanguageEnum language, String phoneNumberTo, String smsAccount, Long toHour) throws IOException {
String qPath = "/dedicated/server/{serviceName}/serviceMonitoring/{monitoringId}/alert/sms";
StringBuilder sb = path(qPath, serviceName, monitoringId);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "fromHour", fromHour);
addBody(o, "language", language);
addBody(o, "phoneNumberTo", phoneNumberTo);
addBody(o, "smsAccount", smsAccount);
addBody(o, "toHour", toHour);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhSmsAlert.class);
} | [
"public",
"OvhSmsAlert",
"serviceName_serviceMonitoring_monitoringId_alert_sms_POST",
"(",
"String",
"serviceName",
",",
"Long",
"monitoringId",
",",
"Long",
"fromHour",
",",
"OvhAlertLanguageEnum",
"language",
",",
"String",
"phoneNumberTo",
",",
"String",
"smsAccount",
",... | Create a SMS alert
REST: POST /dedicated/server/{serviceName}/serviceMonitoring/{monitoringId}/alert/sms
@param smsAccount [required] Your SMS account
@param fromHour [required] Daily hour start time for SMS notification
@param toHour [required] Daily hour end time for SMS notification
@param language [required] Alert language
@param phoneNumberTo [required] Alert destination
@param serviceName [required] The internal name of your dedicated server
@param monitoringId [required] This monitoring id | [
"Create",
"a",
"SMS",
"alert"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dedicatedserver/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedserver.java#L2127-L2138 |
OpenLiberty/open-liberty | dev/com.ibm.ws.security.fat.common.jwt/src/com/ibm/ws/security/fat/common/jwt/actions/JwtTokenActions.java | JwtTokenActions.getJwtTokenUsingBuilder | public String getJwtTokenUsingBuilder(String testName, LibertyServer server, String builderId, List<NameValuePair> extraClaims) throws Exception {
"""
anyone calling this method needs to add upn to the extraClaims that it passes in (if they need it)
"""
String jwtBuilderUrl = SecurityFatHttpUtils.getServerUrlBase(server) + "/jwtbuilder/build";
List<NameValuePair> requestParams = setRequestParms(builderId, extraClaims);
WebClient webClient = new WebClient();
Page response = invokeUrlWithParameters(testName, webClient, jwtBuilderUrl, requestParams);
Log.info(thisClass, testName, "JWT builder app response: " + WebResponseUtils.getResponseText(response));
Cookie jwtCookie = webClient.getCookieManager().getCookie("JWT");
Log.info(thisClass, testName, "Built JWT cookie: " + jwtCookie);
Log.info(thisClass, testName, "Cookie value: " + jwtCookie.getValue());
return jwtCookie.getValue();
} | java | public String getJwtTokenUsingBuilder(String testName, LibertyServer server, String builderId, List<NameValuePair> extraClaims) throws Exception {
String jwtBuilderUrl = SecurityFatHttpUtils.getServerUrlBase(server) + "/jwtbuilder/build";
List<NameValuePair> requestParams = setRequestParms(builderId, extraClaims);
WebClient webClient = new WebClient();
Page response = invokeUrlWithParameters(testName, webClient, jwtBuilderUrl, requestParams);
Log.info(thisClass, testName, "JWT builder app response: " + WebResponseUtils.getResponseText(response));
Cookie jwtCookie = webClient.getCookieManager().getCookie("JWT");
Log.info(thisClass, testName, "Built JWT cookie: " + jwtCookie);
Log.info(thisClass, testName, "Cookie value: " + jwtCookie.getValue());
return jwtCookie.getValue();
} | [
"public",
"String",
"getJwtTokenUsingBuilder",
"(",
"String",
"testName",
",",
"LibertyServer",
"server",
",",
"String",
"builderId",
",",
"List",
"<",
"NameValuePair",
">",
"extraClaims",
")",
"throws",
"Exception",
"{",
"String",
"jwtBuilderUrl",
"=",
"SecurityFat... | anyone calling this method needs to add upn to the extraClaims that it passes in (if they need it) | [
"anyone",
"calling",
"this",
"method",
"needs",
"to",
"add",
"upn",
"to",
"the",
"extraClaims",
"that",
"it",
"passes",
"in",
"(",
"if",
"they",
"need",
"it",
")"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.fat.common.jwt/src/com/ibm/ws/security/fat/common/jwt/actions/JwtTokenActions.java#L32-L47 |
facebookarchive/hadoop-20 | src/core/org/apache/hadoop/ipc/RPC.java | RPC.getProtocolProxy | public static <T extends VersionedProtocol> ProtocolProxy<T> getProtocolProxy(
Class<T> protocol,
long clientVersion, InetSocketAddress addr, Configuration conf,
SocketFactory factory) throws IOException {
"""
Construct a client-side protocol proxy that contains a set of server
methods and a proxy object implementing the named protocol,
talking to a server at the named address.
"""
UserGroupInformation ugi = null;
try {
ugi = UserGroupInformation.login(conf);
} catch (LoginException le) {
throw new RuntimeException("Couldn't login!");
}
return getProtocolProxy(protocol, clientVersion, addr, ugi, conf, factory);
} | java | public static <T extends VersionedProtocol> ProtocolProxy<T> getProtocolProxy(
Class<T> protocol,
long clientVersion, InetSocketAddress addr, Configuration conf,
SocketFactory factory) throws IOException {
UserGroupInformation ugi = null;
try {
ugi = UserGroupInformation.login(conf);
} catch (LoginException le) {
throw new RuntimeException("Couldn't login!");
}
return getProtocolProxy(protocol, clientVersion, addr, ugi, conf, factory);
} | [
"public",
"static",
"<",
"T",
"extends",
"VersionedProtocol",
">",
"ProtocolProxy",
"<",
"T",
">",
"getProtocolProxy",
"(",
"Class",
"<",
"T",
">",
"protocol",
",",
"long",
"clientVersion",
",",
"InetSocketAddress",
"addr",
",",
"Configuration",
"conf",
",",
"... | Construct a client-side protocol proxy that contains a set of server
methods and a proxy object implementing the named protocol,
talking to a server at the named address. | [
"Construct",
"a",
"client",
"-",
"side",
"protocol",
"proxy",
"that",
"contains",
"a",
"set",
"of",
"server",
"methods",
"and",
"a",
"proxy",
"object",
"implementing",
"the",
"named",
"protocol",
"talking",
"to",
"a",
"server",
"at",
"the",
"named",
"address... | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/ipc/RPC.java#L514-L525 |
kuali/ojb-1.0.4 | src/java/org/apache/ojb/broker/accesslayer/RowReaderDefaultImpl.java | RowReaderDefaultImpl.readObjectFrom | public Object readObjectFrom(Map row) throws PersistenceBrokerException {
"""
materialize a single object, described by cld,
from the first row of the ResultSet rs.
There are two possible strategies:
1. The persistent class defines a public constructor with arguments matching the persistent
primitive attributes of the class. In this case we build an array args of arguments from rs
and call Constructor.newInstance(args) to build an object.
2. The persistent class does not provide such a constructor, but only a public default
constructor. In this case we create an empty instance with Class.newInstance().
This empty instance is then filled by calling Field::set(obj,getObject(matchingColumn))
for each attribute.
The second strategy needs n calls to Field::set() which are much more expensive
than the filling of the args array in the first strategy.
client applications should therefore define adequate constructors to benefit from
performance gain of the first strategy.
MBAIRD: The rowreader is told what type of object to materialize, so we have to trust
it is asked for the right type. It is possible someone marked an extent in the repository,
but not in java, or vice versa and this could cause problems in what is returned.
we *have* to be able to materialize an object from a row that has a objConcreteClass, as we
retrieve ALL rows belonging to that table. The objects using the rowReader will make sure they
know what they are asking for, so we don't have to make sure a descriptor is assignable from the
selectClassDescriptor. This allows us to map both inherited classes and unrelated classes to the
same table.
"""
// allow to select a specific classdescriptor
ClassDescriptor cld = selectClassDescriptor(row);
return buildOrRefreshObject(row, cld, null);
} | java | public Object readObjectFrom(Map row) throws PersistenceBrokerException
{
// allow to select a specific classdescriptor
ClassDescriptor cld = selectClassDescriptor(row);
return buildOrRefreshObject(row, cld, null);
} | [
"public",
"Object",
"readObjectFrom",
"(",
"Map",
"row",
")",
"throws",
"PersistenceBrokerException",
"{",
"// allow to select a specific classdescriptor\r",
"ClassDescriptor",
"cld",
"=",
"selectClassDescriptor",
"(",
"row",
")",
";",
"return",
"buildOrRefreshObject",
"(",... | materialize a single object, described by cld,
from the first row of the ResultSet rs.
There are two possible strategies:
1. The persistent class defines a public constructor with arguments matching the persistent
primitive attributes of the class. In this case we build an array args of arguments from rs
and call Constructor.newInstance(args) to build an object.
2. The persistent class does not provide such a constructor, but only a public default
constructor. In this case we create an empty instance with Class.newInstance().
This empty instance is then filled by calling Field::set(obj,getObject(matchingColumn))
for each attribute.
The second strategy needs n calls to Field::set() which are much more expensive
than the filling of the args array in the first strategy.
client applications should therefore define adequate constructors to benefit from
performance gain of the first strategy.
MBAIRD: The rowreader is told what type of object to materialize, so we have to trust
it is asked for the right type. It is possible someone marked an extent in the repository,
but not in java, or vice versa and this could cause problems in what is returned.
we *have* to be able to materialize an object from a row that has a objConcreteClass, as we
retrieve ALL rows belonging to that table. The objects using the rowReader will make sure they
know what they are asking for, so we don't have to make sure a descriptor is assignable from the
selectClassDescriptor. This allows us to map both inherited classes and unrelated classes to the
same table. | [
"materialize",
"a",
"single",
"object",
"described",
"by",
"cld",
"from",
"the",
"first",
"row",
"of",
"the",
"ResultSet",
"rs",
".",
"There",
"are",
"two",
"possible",
"strategies",
":",
"1",
".",
"The",
"persistent",
"class",
"defines",
"a",
"public",
"c... | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/accesslayer/RowReaderDefaultImpl.java#L80-L85 |
VoltDB/voltdb | src/frontend/org/voltdb/export/ExportDataSource.java | ExportDataSource.handleQueryMessage | public void handleQueryMessage(final long senderHSId, long requestId, long gapStart) {
"""
Query whether a master exists for the given partition, if not try to promote the local data source.
"""
m_es.execute(new Runnable() {
@Override
public void run() {
long lastSeq = Long.MIN_VALUE;
Pair<Long, Long> range = m_gapTracker.getRangeContaining(gapStart);
if (range != null) {
lastSeq = range.getSecond();
}
sendQueryResponse(senderHSId, requestId, lastSeq);
}
});
} | java | public void handleQueryMessage(final long senderHSId, long requestId, long gapStart) {
m_es.execute(new Runnable() {
@Override
public void run() {
long lastSeq = Long.MIN_VALUE;
Pair<Long, Long> range = m_gapTracker.getRangeContaining(gapStart);
if (range != null) {
lastSeq = range.getSecond();
}
sendQueryResponse(senderHSId, requestId, lastSeq);
}
});
} | [
"public",
"void",
"handleQueryMessage",
"(",
"final",
"long",
"senderHSId",
",",
"long",
"requestId",
",",
"long",
"gapStart",
")",
"{",
"m_es",
".",
"execute",
"(",
"new",
"Runnable",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"run",
"(",
")",
"{... | Query whether a master exists for the given partition, if not try to promote the local data source. | [
"Query",
"whether",
"a",
"master",
"exists",
"for",
"the",
"given",
"partition",
"if",
"not",
"try",
"to",
"promote",
"the",
"local",
"data",
"source",
"."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/export/ExportDataSource.java#L1781-L1793 |
hamnis/json-collection | src/main/java/net/hamnaberg/json/DataContainer.java | DataContainer.set | @SuppressWarnings("unchecked")
public A set(Iterable<Property> props) {
"""
Replaces all properties.
@param props the property to add
@return a new copy of the template.
"""
if (Iterables.isEmpty(props)) {
return (A) this;
}
return copy(delegate.put("data", Property.toArrayNode(props)));
} | java | @SuppressWarnings("unchecked")
public A set(Iterable<Property> props) {
if (Iterables.isEmpty(props)) {
return (A) this;
}
return copy(delegate.put("data", Property.toArrayNode(props)));
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"A",
"set",
"(",
"Iterable",
"<",
"Property",
">",
"props",
")",
"{",
"if",
"(",
"Iterables",
".",
"isEmpty",
"(",
"props",
")",
")",
"{",
"return",
"(",
"A",
")",
"this",
";",
"}",
"retur... | Replaces all properties.
@param props the property to add
@return a new copy of the template. | [
"Replaces",
"all",
"properties",
"."
] | train | https://github.com/hamnis/json-collection/blob/fbd4a1c6ab75b70b3b4cb981b608b395e9c8c180/src/main/java/net/hamnaberg/json/DataContainer.java#L77-L83 |
haifengl/smile | plot/src/main/java/smile/plot/Graphics.java | Graphics.drawRectBaseRatio | public void drawRectBaseRatio(double[] topLeft, double[] rightBottom) {
"""
Draw the outline of the specified rectangle. The logical coordinates
are proportional to the base coordinates.
"""
if (!(projection instanceof Projection2D)) {
throw new UnsupportedOperationException("Only 2D graphics supports drawing rectangles.");
}
int[] sc = projection.screenProjectionBaseRatio(topLeft);
int[] sc2 = projection.screenProjectionBaseRatio(rightBottom);
g2d.drawRect(sc[0], sc[1], sc2[0] - sc[0], sc2[1] - sc[1]);
} | java | public void drawRectBaseRatio(double[] topLeft, double[] rightBottom) {
if (!(projection instanceof Projection2D)) {
throw new UnsupportedOperationException("Only 2D graphics supports drawing rectangles.");
}
int[] sc = projection.screenProjectionBaseRatio(topLeft);
int[] sc2 = projection.screenProjectionBaseRatio(rightBottom);
g2d.drawRect(sc[0], sc[1], sc2[0] - sc[0], sc2[1] - sc[1]);
} | [
"public",
"void",
"drawRectBaseRatio",
"(",
"double",
"[",
"]",
"topLeft",
",",
"double",
"[",
"]",
"rightBottom",
")",
"{",
"if",
"(",
"!",
"(",
"projection",
"instanceof",
"Projection2D",
")",
")",
"{",
"throw",
"new",
"UnsupportedOperationException",
"(",
... | Draw the outline of the specified rectangle. The logical coordinates
are proportional to the base coordinates. | [
"Draw",
"the",
"outline",
"of",
"the",
"specified",
"rectangle",
".",
"The",
"logical",
"coordinates",
"are",
"proportional",
"to",
"the",
"base",
"coordinates",
"."
] | train | https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/plot/src/main/java/smile/plot/Graphics.java#L533-L542 |
JoeKerouac/utils | src/main/java/com/joe/utils/img/ImgUtil.java | ImgUtil.changeAlpha | public static void changeAlpha(String oldPath, String newPath, byte alpha) throws IOException {
"""
更改图片alpha值
@param oldPath 图片本地路径
@param newPath 更改alpha值后的图片保存路径
@param alpha 要设置的alpha值
@throws IOException IOException
"""
changeAlpha(new FileInputStream(oldPath), new FileOutputStream(newPath), alpha);
} | java | public static void changeAlpha(String oldPath, String newPath, byte alpha) throws IOException {
changeAlpha(new FileInputStream(oldPath), new FileOutputStream(newPath), alpha);
} | [
"public",
"static",
"void",
"changeAlpha",
"(",
"String",
"oldPath",
",",
"String",
"newPath",
",",
"byte",
"alpha",
")",
"throws",
"IOException",
"{",
"changeAlpha",
"(",
"new",
"FileInputStream",
"(",
"oldPath",
")",
",",
"new",
"FileOutputStream",
"(",
"new... | 更改图片alpha值
@param oldPath 图片本地路径
@param newPath 更改alpha值后的图片保存路径
@param alpha 要设置的alpha值
@throws IOException IOException | [
"更改图片alpha值"
] | train | https://github.com/JoeKerouac/utils/blob/45e1b2dc4d736956674fc4dcbe6cf84eaee69278/src/main/java/com/joe/utils/img/ImgUtil.java#L29-L31 |
Netflix/conductor | es5-persistence/src/main/java/com/netflix/conductor/dao/es5/index/ElasticSearchRestDAOV5.java | ElasticSearchRestDAOV5.addMappingToIndex | private void addMappingToIndex(final String index, final String mappingType, final String mappingFilename) throws IOException {
"""
Adds a mapping type to an index if it does not exist.
@param index The name of the index.
@param mappingType The name of the mapping type.
@param mappingFilename The name of the mapping file to use to add the mapping if it does not exist.
@throws IOException If an error occurred during requests to ES.
"""
logger.info("Adding '{}' mapping to index '{}'...", mappingType, index);
String resourcePath = "/" + index + "/_mapping/" + mappingType;
if (doesResourceNotExist(resourcePath)) {
InputStream stream = ElasticSearchDAOV5.class.getResourceAsStream(mappingFilename);
byte[] mappingSource = IOUtils.toByteArray(stream);
HttpEntity entity = new NByteArrayEntity(mappingSource, ContentType.APPLICATION_JSON);
elasticSearchAdminClient.performRequest(HttpMethod.PUT, resourcePath, Collections.emptyMap(), entity);
logger.info("Added '{}' mapping", mappingType);
} else {
logger.info("Mapping '{}' already exists", mappingType);
}
} | java | private void addMappingToIndex(final String index, final String mappingType, final String mappingFilename) throws IOException {
logger.info("Adding '{}' mapping to index '{}'...", mappingType, index);
String resourcePath = "/" + index + "/_mapping/" + mappingType;
if (doesResourceNotExist(resourcePath)) {
InputStream stream = ElasticSearchDAOV5.class.getResourceAsStream(mappingFilename);
byte[] mappingSource = IOUtils.toByteArray(stream);
HttpEntity entity = new NByteArrayEntity(mappingSource, ContentType.APPLICATION_JSON);
elasticSearchAdminClient.performRequest(HttpMethod.PUT, resourcePath, Collections.emptyMap(), entity);
logger.info("Added '{}' mapping", mappingType);
} else {
logger.info("Mapping '{}' already exists", mappingType);
}
} | [
"private",
"void",
"addMappingToIndex",
"(",
"final",
"String",
"index",
",",
"final",
"String",
"mappingType",
",",
"final",
"String",
"mappingFilename",
")",
"throws",
"IOException",
"{",
"logger",
".",
"info",
"(",
"\"Adding '{}' mapping to index '{}'...\"",
",",
... | Adds a mapping type to an index if it does not exist.
@param index The name of the index.
@param mappingType The name of the mapping type.
@param mappingFilename The name of the mapping file to use to add the mapping if it does not exist.
@throws IOException If an error occurred during requests to ES. | [
"Adds",
"a",
"mapping",
"type",
"to",
"an",
"index",
"if",
"it",
"does",
"not",
"exist",
"."
] | train | https://github.com/Netflix/conductor/blob/78fae0ed9ddea22891f9eebb96a2ec0b2783dca0/es5-persistence/src/main/java/com/netflix/conductor/dao/es5/index/ElasticSearchRestDAOV5.java#L262-L278 |
kuali/ojb-1.0.4 | src/xdoclet/java/src/xdoclet/modules/ojb/OjbTagsHandler.java | OjbTagsHandler.forAllIndexDescriptorDefinitions | public void forAllIndexDescriptorDefinitions(String template, Properties attributes) throws XDocletException {
"""
Processes the template for all index descriptors of the current class definition.
@param template The template
@param attributes The attributes of the tag
@exception XDocletException if an error occurs
@doc.tag type="block"
"""
for (Iterator it = _curClassDef.getIndexDescriptors(); it.hasNext(); )
{
_curIndexDescriptorDef = (IndexDescriptorDef)it.next();
generate(template);
}
_curIndexDescriptorDef = null;
} | java | public void forAllIndexDescriptorDefinitions(String template, Properties attributes) throws XDocletException
{
for (Iterator it = _curClassDef.getIndexDescriptors(); it.hasNext(); )
{
_curIndexDescriptorDef = (IndexDescriptorDef)it.next();
generate(template);
}
_curIndexDescriptorDef = null;
} | [
"public",
"void",
"forAllIndexDescriptorDefinitions",
"(",
"String",
"template",
",",
"Properties",
"attributes",
")",
"throws",
"XDocletException",
"{",
"for",
"(",
"Iterator",
"it",
"=",
"_curClassDef",
".",
"getIndexDescriptors",
"(",
")",
";",
"it",
".",
"hasN... | Processes the template for all index descriptors of the current class definition.
@param template The template
@param attributes The attributes of the tag
@exception XDocletException if an error occurs
@doc.tag type="block" | [
"Processes",
"the",
"template",
"for",
"all",
"index",
"descriptors",
"of",
"the",
"current",
"class",
"definition",
"."
] | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/xdoclet/java/src/xdoclet/modules/ojb/OjbTagsHandler.java#L419-L427 |
albfernandez/itext2 | src/main/java/com/lowagie/text/MarkedSection.java | MarkedSection.addSection | public MarkedSection addSection(float indentation, int numberDepth) {
"""
Creates a <CODE>Section</CODE>, adds it to this <CODE>Section</CODE> and returns it.
@param indentation the indentation of the new section
@param numberDepth the numberDepth of the section
@return a new Section object
"""
MarkedSection section = ((Section)element).addMarkedSection();
section.setIndentation(indentation);
section.setNumberDepth(numberDepth);
return section;
} | java | public MarkedSection addSection(float indentation, int numberDepth) {
MarkedSection section = ((Section)element).addMarkedSection();
section.setIndentation(indentation);
section.setNumberDepth(numberDepth);
return section;
} | [
"public",
"MarkedSection",
"addSection",
"(",
"float",
"indentation",
",",
"int",
"numberDepth",
")",
"{",
"MarkedSection",
"section",
"=",
"(",
"(",
"Section",
")",
"element",
")",
".",
"addMarkedSection",
"(",
")",
";",
"section",
".",
"setIndentation",
"(",... | Creates a <CODE>Section</CODE>, adds it to this <CODE>Section</CODE> and returns it.
@param indentation the indentation of the new section
@param numberDepth the numberDepth of the section
@return a new Section object | [
"Creates",
"a",
"<CODE",
">",
"Section<",
"/",
"CODE",
">",
"adds",
"it",
"to",
"this",
"<CODE",
">",
"Section<",
"/",
"CODE",
">",
"and",
"returns",
"it",
"."
] | train | https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/MarkedSection.java#L145-L150 |
jaxio/celerio | celerio-engine/src/main/java/com/jaxio/celerio/util/MiscUtil.java | MiscUtil.endsWithIgnoreCase | public static boolean endsWithIgnoreCase(String name, Iterable<String> patterns) {
"""
Does the given column name ends with one of pattern given in parameter. Not case sensitive
"""
String nameUpper = name.toUpperCase();
for (String pattern : patterns) {
String patternUpper = pattern.toUpperCase();
if (nameUpper.equals(patternUpper) || nameUpper.endsWith(patternUpper)) {
return true;
}
}
return false;
} | java | public static boolean endsWithIgnoreCase(String name, Iterable<String> patterns) {
String nameUpper = name.toUpperCase();
for (String pattern : patterns) {
String patternUpper = pattern.toUpperCase();
if (nameUpper.equals(patternUpper) || nameUpper.endsWith(patternUpper)) {
return true;
}
}
return false;
} | [
"public",
"static",
"boolean",
"endsWithIgnoreCase",
"(",
"String",
"name",
",",
"Iterable",
"<",
"String",
">",
"patterns",
")",
"{",
"String",
"nameUpper",
"=",
"name",
".",
"toUpperCase",
"(",
")",
";",
"for",
"(",
"String",
"pattern",
":",
"patterns",
... | Does the given column name ends with one of pattern given in parameter. Not case sensitive | [
"Does",
"the",
"given",
"column",
"name",
"ends",
"with",
"one",
"of",
"pattern",
"given",
"in",
"parameter",
".",
"Not",
"case",
"sensitive"
] | train | https://github.com/jaxio/celerio/blob/fbfacb639e286f9f3f3a18986f74ea275bebd887/celerio-engine/src/main/java/com/jaxio/celerio/util/MiscUtil.java#L162-L172 |
goldmansachs/reladomo | reladomo/src/main/java/com/gs/fw/common/mithra/MithraBusinessException.java | MithraBusinessException.ifRetriableWaitElseThrow | public int ifRetriableWaitElseThrow(String msg, int retriesLeft, Logger logger) {
"""
must not be called from within a transaction, unless the work is being done async in a non-tx thread.
"""
if (this.isRetriable() && --retriesLeft > 0)
{
logger.warn(msg+ " " + this.getMessage());
if (logger.isDebugEnabled())
{
logger.debug("find failed with retriable error. retrying.", this);
}
cleanupAndRecreateTempContexts();
this.waitBeforeRetrying();
}
else throw this;
return retriesLeft;
} | java | public int ifRetriableWaitElseThrow(String msg, int retriesLeft, Logger logger)
{
if (this.isRetriable() && --retriesLeft > 0)
{
logger.warn(msg+ " " + this.getMessage());
if (logger.isDebugEnabled())
{
logger.debug("find failed with retriable error. retrying.", this);
}
cleanupAndRecreateTempContexts();
this.waitBeforeRetrying();
}
else throw this;
return retriesLeft;
} | [
"public",
"int",
"ifRetriableWaitElseThrow",
"(",
"String",
"msg",
",",
"int",
"retriesLeft",
",",
"Logger",
"logger",
")",
"{",
"if",
"(",
"this",
".",
"isRetriable",
"(",
")",
"&&",
"--",
"retriesLeft",
">",
"0",
")",
"{",
"logger",
".",
"warn",
"(",
... | must not be called from within a transaction, unless the work is being done async in a non-tx thread. | [
"must",
"not",
"be",
"called",
"from",
"within",
"a",
"transaction",
"unless",
"the",
"work",
"is",
"being",
"done",
"async",
"in",
"a",
"non",
"-",
"tx",
"thread",
"."
] | train | https://github.com/goldmansachs/reladomo/blob/e9a069452eece7a6ef9551caf81a69d3d9a3d990/reladomo/src/main/java/com/gs/fw/common/mithra/MithraBusinessException.java#L53-L67 |
exoplatform/jcr | exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/lucene/AbstractIndex.java | AbstractIndex.getIndexWriter | protected synchronized IndexWriter getIndexWriter() throws IOException {
"""
Returns an <code>IndexWriter</code> on this index.
@return an <code>IndexWriter</code> on this index.
@throws IOException if the writer cannot be obtained.
"""
if (indexReader != null)
{
indexReader.close();
log.debug("closing IndexReader.");
indexReader = null;
}
if (indexWriter == null)
{
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_36, analyzer);
config.setSimilarity(similarity);
if (config.getMergePolicy() instanceof LogMergePolicy)
{
((LogMergePolicy)config.getMergePolicy()).setUseCompoundFile(useCompoundFile);
}
else if (config.getMergePolicy() instanceof TieredMergePolicy)
{
((TieredMergePolicy)config.getMergePolicy()).setUseCompoundFile(useCompoundFile);
}
else
{
log.error("Can't set \"UseCompoundFile\". Merge policy is not an instance of LogMergePolicy. ");
}
indexWriter = new IndexWriter(directory, config);
setUseCompoundFile(useCompoundFile);
indexWriter.setInfoStream(STREAM_LOGGER);
}
return indexWriter;
} | java | protected synchronized IndexWriter getIndexWriter() throws IOException
{
if (indexReader != null)
{
indexReader.close();
log.debug("closing IndexReader.");
indexReader = null;
}
if (indexWriter == null)
{
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_36, analyzer);
config.setSimilarity(similarity);
if (config.getMergePolicy() instanceof LogMergePolicy)
{
((LogMergePolicy)config.getMergePolicy()).setUseCompoundFile(useCompoundFile);
}
else if (config.getMergePolicy() instanceof TieredMergePolicy)
{
((TieredMergePolicy)config.getMergePolicy()).setUseCompoundFile(useCompoundFile);
}
else
{
log.error("Can't set \"UseCompoundFile\". Merge policy is not an instance of LogMergePolicy. ");
}
indexWriter = new IndexWriter(directory, config);
setUseCompoundFile(useCompoundFile);
indexWriter.setInfoStream(STREAM_LOGGER);
}
return indexWriter;
} | [
"protected",
"synchronized",
"IndexWriter",
"getIndexWriter",
"(",
")",
"throws",
"IOException",
"{",
"if",
"(",
"indexReader",
"!=",
"null",
")",
"{",
"indexReader",
".",
"close",
"(",
")",
";",
"log",
".",
"debug",
"(",
"\"closing IndexReader.\"",
")",
";",
... | Returns an <code>IndexWriter</code> on this index.
@return an <code>IndexWriter</code> on this index.
@throws IOException if the writer cannot be obtained. | [
"Returns",
"an",
"<code",
">",
"IndexWriter<",
"/",
"code",
">",
"on",
"this",
"index",
"."
] | train | https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/lucene/AbstractIndex.java#L348-L377 |
mongodb/stitch-android-sdk | core/services/mongodb-remote/src/main/java/com/mongodb/stitch/core/services/mongodb/remote/internal/CoreRemoteMongoCollectionImpl.java | CoreRemoteMongoCollectionImpl.findOneAndUpdate | public DocumentT findOneAndUpdate(final Bson filter, final Bson update) {
"""
Finds a document in the collection and performs the given update.
@param filter the query filter
@param update the update document
@return the resulting document
"""
return operations.findOneAndModify(
"findOneAndUpdate",
filter,
update,
new RemoteFindOneAndModifyOptions(),
documentClass).execute(service);
} | java | public DocumentT findOneAndUpdate(final Bson filter, final Bson update) {
return operations.findOneAndModify(
"findOneAndUpdate",
filter,
update,
new RemoteFindOneAndModifyOptions(),
documentClass).execute(service);
} | [
"public",
"DocumentT",
"findOneAndUpdate",
"(",
"final",
"Bson",
"filter",
",",
"final",
"Bson",
"update",
")",
"{",
"return",
"operations",
".",
"findOneAndModify",
"(",
"\"findOneAndUpdate\"",
",",
"filter",
",",
"update",
",",
"new",
"RemoteFindOneAndModifyOption... | Finds a document in the collection and performs the given update.
@param filter the query filter
@param update the update document
@return the resulting document | [
"Finds",
"a",
"document",
"in",
"the",
"collection",
"and",
"performs",
"the",
"given",
"update",
"."
] | train | https://github.com/mongodb/stitch-android-sdk/blob/159b9334b1f1a827285544be5ee20cdf7b04e4cc/core/services/mongodb-remote/src/main/java/com/mongodb/stitch/core/services/mongodb/remote/internal/CoreRemoteMongoCollectionImpl.java#L463-L470 |
raydac/java-binary-block-parser | jbbp/src/main/java/com/igormaznitsa/jbbp/io/JBBPBitOutputStream.java | JBBPBitOutputStream.writeFloat | public void writeFloat(final float value, final JBBPByteOrder byteOrder) throws IOException {
"""
Write an float value into the output stream.
@param value a value to be written into the output stream.
@param byteOrder the byte order of the value bytes to be used for writing.
@throws IOException it will be thrown for transport errors
@see JBBPByteOrder#BIG_ENDIAN
@see JBBPByteOrder#LITTLE_ENDIAN
@since 1.4.0
"""
final int intValue = Float.floatToIntBits(value);
if (byteOrder == JBBPByteOrder.BIG_ENDIAN) {
this.writeShort(intValue >>> 16, byteOrder);
this.writeShort(intValue, byteOrder);
} else {
this.writeShort(intValue, byteOrder);
this.writeShort(intValue >>> 16, byteOrder);
}
} | java | public void writeFloat(final float value, final JBBPByteOrder byteOrder) throws IOException {
final int intValue = Float.floatToIntBits(value);
if (byteOrder == JBBPByteOrder.BIG_ENDIAN) {
this.writeShort(intValue >>> 16, byteOrder);
this.writeShort(intValue, byteOrder);
} else {
this.writeShort(intValue, byteOrder);
this.writeShort(intValue >>> 16, byteOrder);
}
} | [
"public",
"void",
"writeFloat",
"(",
"final",
"float",
"value",
",",
"final",
"JBBPByteOrder",
"byteOrder",
")",
"throws",
"IOException",
"{",
"final",
"int",
"intValue",
"=",
"Float",
".",
"floatToIntBits",
"(",
"value",
")",
";",
"if",
"(",
"byteOrder",
"=... | Write an float value into the output stream.
@param value a value to be written into the output stream.
@param byteOrder the byte order of the value bytes to be used for writing.
@throws IOException it will be thrown for transport errors
@see JBBPByteOrder#BIG_ENDIAN
@see JBBPByteOrder#LITTLE_ENDIAN
@since 1.4.0 | [
"Write",
"an",
"float",
"value",
"into",
"the",
"output",
"stream",
"."
] | train | https://github.com/raydac/java-binary-block-parser/blob/6d98abcab01e0c72d525ebcc9e7b694f9ce49f5b/jbbp/src/main/java/com/igormaznitsa/jbbp/io/JBBPBitOutputStream.java#L131-L140 |
windup/windup | rules-java/api/src/main/java/org/jboss/windup/rules/apps/mavenize/MavenizationService.java | MavenizationService.mavenizeApp | void mavenizeApp(ProjectModel projectModel) {
"""
For the given application (Windup input), creates a stub of Mavenized project.
<p>
The resulting structure is: (+--- is "module", +~~~ is a dependency)
<pre>
Parent POM
+--- BOM
+~~~ JBoss EAP BOM
+--- JAR submodule
+~~~ library JARs
+--- WAR
+~~~ library JARs
+~~~ JAR submodule
+--- EAR
+~~~ library JAR
+~~~ JAR submodule
+~~~ WAR submodule
</pre>
"""
LOG.info("Mavenizing ProjectModel " + projectModel.toPrettyString());
MavenizationContext mavCtx = new MavenizationContext();
mavCtx.graphContext = grCtx;
WindupConfigurationModel config = grCtx.getUnique(WindupConfigurationModel.class);
mavCtx.mavenizedBaseDir = config.getOutputPath().asFile().toPath().resolve(OUTPUT_SUBDIR_MAVENIZED);
mavCtx.unifiedGroupId = new ModuleAnalysisHelper(grCtx).deriveGroupId(projectModel);
mavCtx.unifiedAppName = normalizeDirName(projectModel.getName());
mavCtx.unifiedVersion = "1.0";
// 1) create the overall structure - a parent, and a BOM.
// Root pom.xml ( serves as a parent pom.xml in our resulting structure).
mavCtx.rootPom = new Pom(new MavenCoord(mavCtx.getUnifiedGroupId(), mavCtx.getUnifiedAppName() + "-parent", mavCtx.getUnifiedVersion()));
mavCtx.rootPom.role = Pom.ModuleRole.PARENT;
mavCtx.rootPom.name = projectModel.getName() + " - Parent";
mavCtx.rootPom.description = "Parent of " + projectModel.getName();
mavCtx.rootPom.root = true;
final String bomArtifactId = mavCtx.getUnifiedAppName() + "-bom";
// BOM
Pom bom = new Pom(new MavenCoord(mavCtx.getUnifiedGroupId(), bomArtifactId, mavCtx.getUnifiedVersion()));
bom.bom = getTargetTechnologies().contains("eap7")
? MavenizeRuleProvider.JBOSS_BOM_JAVAEE7_WITH_ALL
: MavenizeRuleProvider.JBOSS_BOM_JAVAEE6_WITH_ALL;
bom.role = Pom.ModuleRole.BOM;
bom.parent = new Pom(MavenizeRuleProvider.JBOSS_PARENT);
bom.description = "Bill of Materials. See https://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html";
bom.name = projectModel.getName() + " - BOM";
mavCtx.getRootPom().submodules.put(bomArtifactId, bom);
mavCtx.bom = bom;
// BOM - dependencyManagement dependencies
for( ArchiveCoordinateModel dep : grCtx.getUnique(GlobalBomModel.class).getDependencies() ){
LOG.info("Adding dep to BOM: " + dep.toPrettyString());
bom.dependencies.add(new SimpleDependency(Dependency.Role.LIBRARY, MavenCoord.from(dep)));
}
// 2) Recursively add the modules.
mavCtx.rootAppPom = mavenizeModule(mavCtx, projectModel, null);
// TODO: MIGR-236 Sort the modules.
///mavCtx.rootPom.submodules = sortSubmodulesToReflectDependencies(mavCtx.rootAppPom);
// 3) Write the pom.xml's.
new MavenStructureRenderer(mavCtx).createMavenProjectDirectoryTree();
} | java | void mavenizeApp(ProjectModel projectModel)
{
LOG.info("Mavenizing ProjectModel " + projectModel.toPrettyString());
MavenizationContext mavCtx = new MavenizationContext();
mavCtx.graphContext = grCtx;
WindupConfigurationModel config = grCtx.getUnique(WindupConfigurationModel.class);
mavCtx.mavenizedBaseDir = config.getOutputPath().asFile().toPath().resolve(OUTPUT_SUBDIR_MAVENIZED);
mavCtx.unifiedGroupId = new ModuleAnalysisHelper(grCtx).deriveGroupId(projectModel);
mavCtx.unifiedAppName = normalizeDirName(projectModel.getName());
mavCtx.unifiedVersion = "1.0";
// 1) create the overall structure - a parent, and a BOM.
// Root pom.xml ( serves as a parent pom.xml in our resulting structure).
mavCtx.rootPom = new Pom(new MavenCoord(mavCtx.getUnifiedGroupId(), mavCtx.getUnifiedAppName() + "-parent", mavCtx.getUnifiedVersion()));
mavCtx.rootPom.role = Pom.ModuleRole.PARENT;
mavCtx.rootPom.name = projectModel.getName() + " - Parent";
mavCtx.rootPom.description = "Parent of " + projectModel.getName();
mavCtx.rootPom.root = true;
final String bomArtifactId = mavCtx.getUnifiedAppName() + "-bom";
// BOM
Pom bom = new Pom(new MavenCoord(mavCtx.getUnifiedGroupId(), bomArtifactId, mavCtx.getUnifiedVersion()));
bom.bom = getTargetTechnologies().contains("eap7")
? MavenizeRuleProvider.JBOSS_BOM_JAVAEE7_WITH_ALL
: MavenizeRuleProvider.JBOSS_BOM_JAVAEE6_WITH_ALL;
bom.role = Pom.ModuleRole.BOM;
bom.parent = new Pom(MavenizeRuleProvider.JBOSS_PARENT);
bom.description = "Bill of Materials. See https://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html";
bom.name = projectModel.getName() + " - BOM";
mavCtx.getRootPom().submodules.put(bomArtifactId, bom);
mavCtx.bom = bom;
// BOM - dependencyManagement dependencies
for( ArchiveCoordinateModel dep : grCtx.getUnique(GlobalBomModel.class).getDependencies() ){
LOG.info("Adding dep to BOM: " + dep.toPrettyString());
bom.dependencies.add(new SimpleDependency(Dependency.Role.LIBRARY, MavenCoord.from(dep)));
}
// 2) Recursively add the modules.
mavCtx.rootAppPom = mavenizeModule(mavCtx, projectModel, null);
// TODO: MIGR-236 Sort the modules.
///mavCtx.rootPom.submodules = sortSubmodulesToReflectDependencies(mavCtx.rootAppPom);
// 3) Write the pom.xml's.
new MavenStructureRenderer(mavCtx).createMavenProjectDirectoryTree();
} | [
"void",
"mavenizeApp",
"(",
"ProjectModel",
"projectModel",
")",
"{",
"LOG",
".",
"info",
"(",
"\"Mavenizing ProjectModel \"",
"+",
"projectModel",
".",
"toPrettyString",
"(",
")",
")",
";",
"MavenizationContext",
"mavCtx",
"=",
"new",
"MavenizationContext",
"(",
... | For the given application (Windup input), creates a stub of Mavenized project.
<p>
The resulting structure is: (+--- is "module", +~~~ is a dependency)
<pre>
Parent POM
+--- BOM
+~~~ JBoss EAP BOM
+--- JAR submodule
+~~~ library JARs
+--- WAR
+~~~ library JARs
+~~~ JAR submodule
+--- EAR
+~~~ library JAR
+~~~ JAR submodule
+~~~ WAR submodule
</pre> | [
"For",
"the",
"given",
"application",
"(",
"Windup",
"input",
")",
"creates",
"a",
"stub",
"of",
"Mavenized",
"project",
".",
"<p",
">",
"The",
"resulting",
"structure",
"is",
":",
"(",
"+",
"---",
"is",
"module",
"+",
"~~~",
"is",
"a",
"dependency",
"... | train | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/rules-java/api/src/main/java/org/jboss/windup/rules/apps/mavenize/MavenizationService.java#L62-L110 |
CloudSlang/cs-actions | cs-date-time/src/main/java/io/cloudslang/content/datetime/utils/DateTimeUtils.java | DateTimeUtils.getDateFormatter | public static DateTimeFormatter getDateFormatter(String format, String lang, String country) {
"""
Generates a DateTimeFormatter using a custom pattern with the default locale or a new one
according to what language and country are provided as params.
@param format the pattern
@param lang the language
@param country the country
@return the DateTimeFormatter generated
"""
if (StringUtils.isNotBlank(format)) {
DateTimeFormatter dateFormat = DateTimeFormat.forPattern(format);
if (StringUtils.isNotBlank(lang)) {
return dateFormat.withLocale(DateTimeUtils.getLocaleByCountry(lang, country));
}
return dateFormat;
}
return formatWithDefault(lang, country);
} | java | public static DateTimeFormatter getDateFormatter(String format, String lang, String country) {
if (StringUtils.isNotBlank(format)) {
DateTimeFormatter dateFormat = DateTimeFormat.forPattern(format);
if (StringUtils.isNotBlank(lang)) {
return dateFormat.withLocale(DateTimeUtils.getLocaleByCountry(lang, country));
}
return dateFormat;
}
return formatWithDefault(lang, country);
} | [
"public",
"static",
"DateTimeFormatter",
"getDateFormatter",
"(",
"String",
"format",
",",
"String",
"lang",
",",
"String",
"country",
")",
"{",
"if",
"(",
"StringUtils",
".",
"isNotBlank",
"(",
"format",
")",
")",
"{",
"DateTimeFormatter",
"dateFormat",
"=",
... | Generates a DateTimeFormatter using a custom pattern with the default locale or a new one
according to what language and country are provided as params.
@param format the pattern
@param lang the language
@param country the country
@return the DateTimeFormatter generated | [
"Generates",
"a",
"DateTimeFormatter",
"using",
"a",
"custom",
"pattern",
"with",
"the",
"default",
"locale",
"or",
"a",
"new",
"one",
"according",
"to",
"what",
"language",
"and",
"country",
"are",
"provided",
"as",
"params",
"."
] | train | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-date-time/src/main/java/io/cloudslang/content/datetime/utils/DateTimeUtils.java#L101-L110 |
kuali/ojb-1.0.4 | src/java/org/apache/ojb/broker/accesslayer/RelationshipPrefetcherFactory.java | RelationshipPrefetcherFactory.createRelationshipPrefetcher | public RelationshipPrefetcher createRelationshipPrefetcher(ObjectReferenceDescriptor ord) {
"""
create either a CollectionPrefetcher or a ReferencePrefetcher
"""
if (ord instanceof CollectionDescriptor)
{
CollectionDescriptor cds = (CollectionDescriptor)ord;
if (cds.isMtoNRelation())
{
return new MtoNCollectionPrefetcher(broker, cds);
}
else
{
return new CollectionPrefetcher(broker, cds);
}
}
else
{
return new ReferencePrefetcher(broker, ord);
}
} | java | public RelationshipPrefetcher createRelationshipPrefetcher(ObjectReferenceDescriptor ord)
{
if (ord instanceof CollectionDescriptor)
{
CollectionDescriptor cds = (CollectionDescriptor)ord;
if (cds.isMtoNRelation())
{
return new MtoNCollectionPrefetcher(broker, cds);
}
else
{
return new CollectionPrefetcher(broker, cds);
}
}
else
{
return new ReferencePrefetcher(broker, ord);
}
} | [
"public",
"RelationshipPrefetcher",
"createRelationshipPrefetcher",
"(",
"ObjectReferenceDescriptor",
"ord",
")",
"{",
"if",
"(",
"ord",
"instanceof",
"CollectionDescriptor",
")",
"{",
"CollectionDescriptor",
"cds",
"=",
"(",
"CollectionDescriptor",
")",
"ord",
";",
"if... | create either a CollectionPrefetcher or a ReferencePrefetcher | [
"create",
"either",
"a",
"CollectionPrefetcher",
"or",
"a",
"ReferencePrefetcher"
] | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/accesslayer/RelationshipPrefetcherFactory.java#L42-L60 |
alkacon/opencms-core | src-gwt/org/opencms/ade/sitemap/client/control/CmsSitemapController.java | CmsSitemapController.loadCategories | public void loadCategories(final boolean openLocalCategories, final CmsUUID openItemId) {
"""
Loads and displays the category data.<p>
@param openLocalCategories true if the local category tree should be opened
@param openItemId the id of the item to open
"""
CmsRpcAction<CmsSitemapCategoryData> action = new CmsRpcAction<CmsSitemapCategoryData>() {
@Override
public void execute() {
start(200, false);
getService().getCategoryData(getEntryPoint(), this);
}
@Override
protected void onResponse(CmsSitemapCategoryData result) {
stop(false);
m_categoryData = result;
CmsSitemapView.getInstance().displayCategoryData(result, openLocalCategories, openItemId);
}
};
action.execute();
} | java | public void loadCategories(final boolean openLocalCategories, final CmsUUID openItemId) {
CmsRpcAction<CmsSitemapCategoryData> action = new CmsRpcAction<CmsSitemapCategoryData>() {
@Override
public void execute() {
start(200, false);
getService().getCategoryData(getEntryPoint(), this);
}
@Override
protected void onResponse(CmsSitemapCategoryData result) {
stop(false);
m_categoryData = result;
CmsSitemapView.getInstance().displayCategoryData(result, openLocalCategories, openItemId);
}
};
action.execute();
} | [
"public",
"void",
"loadCategories",
"(",
"final",
"boolean",
"openLocalCategories",
",",
"final",
"CmsUUID",
"openItemId",
")",
"{",
"CmsRpcAction",
"<",
"CmsSitemapCategoryData",
">",
"action",
"=",
"new",
"CmsRpcAction",
"<",
"CmsSitemapCategoryData",
">",
"(",
")... | Loads and displays the category data.<p>
@param openLocalCategories true if the local category tree should be opened
@param openItemId the id of the item to open | [
"Loads",
"and",
"displays",
"the",
"category",
"data",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/sitemap/client/control/CmsSitemapController.java#L1451-L1471 |
lessthanoptimal/ejml | main/ejml-dsparse/src/org/ejml/sparse/csc/CommonOps_DSCC.java | CommonOps_DSCC.columnMaxAbs | public static void columnMaxAbs( DMatrixSparseCSC A , double []values ) {
"""
Finds the maximum abs in each column of A and stores it into values
@param A (Input) Matrix
@param values (Output) storage for column max abs
"""
if( values.length < A.numCols )
throw new IllegalArgumentException("Array is too small. "+values.length+" < "+A.numCols);
for (int i = 0; i < A.numCols; i++) {
int idx0 = A.col_idx[i];
int idx1 = A.col_idx[i+1];
double maxabs = 0;
for (int j = idx0; j < idx1; j++) {
double v = Math.abs(A.nz_values[j]);
if( v > maxabs )
maxabs = v;
}
values[i] = maxabs;
}
} | java | public static void columnMaxAbs( DMatrixSparseCSC A , double []values ) {
if( values.length < A.numCols )
throw new IllegalArgumentException("Array is too small. "+values.length+" < "+A.numCols);
for (int i = 0; i < A.numCols; i++) {
int idx0 = A.col_idx[i];
int idx1 = A.col_idx[i+1];
double maxabs = 0;
for (int j = idx0; j < idx1; j++) {
double v = Math.abs(A.nz_values[j]);
if( v > maxabs )
maxabs = v;
}
values[i] = maxabs;
}
} | [
"public",
"static",
"void",
"columnMaxAbs",
"(",
"DMatrixSparseCSC",
"A",
",",
"double",
"[",
"]",
"values",
")",
"{",
"if",
"(",
"values",
".",
"length",
"<",
"A",
".",
"numCols",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Array is too small. \"... | Finds the maximum abs in each column of A and stores it into values
@param A (Input) Matrix
@param values (Output) storage for column max abs | [
"Finds",
"the",
"maximum",
"abs",
"in",
"each",
"column",
"of",
"A",
"and",
"stores",
"it",
"into",
"values"
] | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-dsparse/src/org/ejml/sparse/csc/CommonOps_DSCC.java#L579-L595 |
BorderTech/wcomponents | wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/theme/WRadioButtonSelectExample.java | WRadioButtonSelectExample.addReadOnlyExamples | private void addReadOnlyExamples() {
"""
Examples of readonly states. When in a read only state only the selected option is output. Since a
WRadioButtonSeelct can only have 0 or 1 selected option the LAYOUT and FRAME are ignored.
"""
add(new WHeading(HeadingLevel.H3, "Read-only WRadioButtonSelect examples"));
add(new ExplanatoryText("These examples all use the same list of options: the states and territories list from the editable examples above. "
+ "When the readOnly state is specified only that option which is selected is output.\n"
+ "Since no more than one option is able to be selected the layout and frame settings are ignored in the read only state."));
WFieldLayout layout = new WFieldLayout();
add(layout);
WRadioButtonSelect select = new WRadioButtonSelect("australian_state");
select.setReadOnly(true);
layout.addField("Read only with no selection", select);
select = new SelectWithSelection("australian_state");
select.setReadOnly(true);
layout.addField("Read only with selection", select);
} | java | private void addReadOnlyExamples() {
add(new WHeading(HeadingLevel.H3, "Read-only WRadioButtonSelect examples"));
add(new ExplanatoryText("These examples all use the same list of options: the states and territories list from the editable examples above. "
+ "When the readOnly state is specified only that option which is selected is output.\n"
+ "Since no more than one option is able to be selected the layout and frame settings are ignored in the read only state."));
WFieldLayout layout = new WFieldLayout();
add(layout);
WRadioButtonSelect select = new WRadioButtonSelect("australian_state");
select.setReadOnly(true);
layout.addField("Read only with no selection", select);
select = new SelectWithSelection("australian_state");
select.setReadOnly(true);
layout.addField("Read only with selection", select);
} | [
"private",
"void",
"addReadOnlyExamples",
"(",
")",
"{",
"add",
"(",
"new",
"WHeading",
"(",
"HeadingLevel",
".",
"H3",
",",
"\"Read-only WRadioButtonSelect examples\"",
")",
")",
";",
"add",
"(",
"new",
"ExplanatoryText",
"(",
"\"These examples all use the same list ... | Examples of readonly states. When in a read only state only the selected option is output. Since a
WRadioButtonSeelct can only have 0 or 1 selected option the LAYOUT and FRAME are ignored. | [
"Examples",
"of",
"readonly",
"states",
".",
"When",
"in",
"a",
"read",
"only",
"state",
"only",
"the",
"selected",
"option",
"is",
"output",
".",
"Since",
"a",
"WRadioButtonSeelct",
"can",
"only",
"have",
"0",
"or",
"1",
"selected",
"option",
"the",
"LAYO... | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/theme/WRadioButtonSelectExample.java#L279-L295 |
Azure/azure-sdk-for-java | common/azure-common/src/main/java/com/azure/common/implementation/serializer/HttpResponseBodyDecoder.java | HttpResponseBodyDecoder.isErrorStatus | static boolean isErrorStatus(HttpResponse httpResponse, HttpResponseDecodeData decodeData) {
"""
Checks the response status code is considered as error.
@param httpResponse the response to check
@param decodeData the response metadata
@return true if the response status code is considered as error, false otherwise.
"""
final int[] expectedStatuses = decodeData.expectedStatusCodes();
if (expectedStatuses != null) {
return !contains(expectedStatuses, httpResponse.statusCode());
} else {
return httpResponse.statusCode() / 100 != 2;
}
} | java | static boolean isErrorStatus(HttpResponse httpResponse, HttpResponseDecodeData decodeData) {
final int[] expectedStatuses = decodeData.expectedStatusCodes();
if (expectedStatuses != null) {
return !contains(expectedStatuses, httpResponse.statusCode());
} else {
return httpResponse.statusCode() / 100 != 2;
}
} | [
"static",
"boolean",
"isErrorStatus",
"(",
"HttpResponse",
"httpResponse",
",",
"HttpResponseDecodeData",
"decodeData",
")",
"{",
"final",
"int",
"[",
"]",
"expectedStatuses",
"=",
"decodeData",
".",
"expectedStatusCodes",
"(",
")",
";",
"if",
"(",
"expectedStatuses... | Checks the response status code is considered as error.
@param httpResponse the response to check
@param decodeData the response metadata
@return true if the response status code is considered as error, false otherwise. | [
"Checks",
"the",
"response",
"status",
"code",
"is",
"considered",
"as",
"error",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/common/azure-common/src/main/java/com/azure/common/implementation/serializer/HttpResponseBodyDecoder.java#L138-L145 |
Red5/red5-server-common | src/main/java/org/red5/server/scope/Scope.java | Scope.getBasicScope | public IBasicScope getBasicScope(ScopeType type, String name) {
"""
Return base scope of given type with given name
@param type Scope type
@param name Scope name
@return Basic scope object
"""
return children.getBasicScope(type, name);
} | java | public IBasicScope getBasicScope(ScopeType type, String name) {
return children.getBasicScope(type, name);
} | [
"public",
"IBasicScope",
"getBasicScope",
"(",
"ScopeType",
"type",
",",
"String",
"name",
")",
"{",
"return",
"children",
".",
"getBasicScope",
"(",
"type",
",",
"name",
")",
";",
"}"
] | Return base scope of given type with given name
@param type Scope type
@param name Scope name
@return Basic scope object | [
"Return",
"base",
"scope",
"of",
"given",
"type",
"with",
"given",
"name"
] | train | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/scope/Scope.java#L455-L457 |
b3dgs/lionengine | lionengine-network/src/main/java/com/b3dgs/lionengine/network/message/NetworkMessageEntity.java | NetworkMessageEntity.addAction | public void addAction(M element, short value) {
"""
Add an action.
@param element The action type.
@param value The action value.
"""
actions.put(element, Short.valueOf(value));
} | java | public void addAction(M element, short value)
{
actions.put(element, Short.valueOf(value));
} | [
"public",
"void",
"addAction",
"(",
"M",
"element",
",",
"short",
"value",
")",
"{",
"actions",
".",
"put",
"(",
"element",
",",
"Short",
".",
"valueOf",
"(",
"value",
")",
")",
";",
"}"
] | Add an action.
@param element The action type.
@param value The action value. | [
"Add",
"an",
"action",
"."
] | train | https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-network/src/main/java/com/b3dgs/lionengine/network/message/NetworkMessageEntity.java#L144-L147 |
jbundle/jbundle | base/screen/view/xml/src/main/java/org/jbundle/base/screen/view/xml/XBasePanel.java | XBasePanel.printControlStartForm | public void printControlStartForm(PrintWriter out, int iPrintOptions) {
"""
Display the start form in input format.
@param out The out stream.
@param iPrintOptions The view specific attributes.
"""
if (((iPrintOptions & HtmlConstants.HEADING_SCREEN) == HtmlConstants.HEADING_SCREEN)
|| ((iPrintOptions & HtmlConstants.FOOTING_SCREEN) == HtmlConstants.FOOTING_SCREEN)
|| ((iPrintOptions & HtmlConstants.DETAIL_SCREEN) == HtmlConstants.DETAIL_SCREEN))
return; // Don't need on nested forms
super.printControlStartForm(out, iPrintOptions);
String strAction = "post";
BasePanel modelScreen = (BasePanel)this.getScreenField();
//? strAction = "postxml";
out.println(Utility.startTag("hidden-params"));
this.addHiddenParams(out, this.getHiddenParams());
out.println(Utility.endTag("hidden-params"));
out.println("<xform id=\"form1\">");
out.println(" <submission");
out.println(" id=\"submit1\"");
out.println(" method=\"" + strAction + "\"");
out.println(" localfile=\"temp.xml\"");
out.println(" action=\"" + modelScreen.getServletPath(null) + "\" />");
//? out.println(" <model href=\"form.xsd\">");
//? out.println(" <!-- The model is currently ignored -->");
//? out.println(" </model>");
//? out.println(" <instance id=\"instance1\" xmlns=\"\">");
} | java | public void printControlStartForm(PrintWriter out, int iPrintOptions)
{
if (((iPrintOptions & HtmlConstants.HEADING_SCREEN) == HtmlConstants.HEADING_SCREEN)
|| ((iPrintOptions & HtmlConstants.FOOTING_SCREEN) == HtmlConstants.FOOTING_SCREEN)
|| ((iPrintOptions & HtmlConstants.DETAIL_SCREEN) == HtmlConstants.DETAIL_SCREEN))
return; // Don't need on nested forms
super.printControlStartForm(out, iPrintOptions);
String strAction = "post";
BasePanel modelScreen = (BasePanel)this.getScreenField();
//? strAction = "postxml";
out.println(Utility.startTag("hidden-params"));
this.addHiddenParams(out, this.getHiddenParams());
out.println(Utility.endTag("hidden-params"));
out.println("<xform id=\"form1\">");
out.println(" <submission");
out.println(" id=\"submit1\"");
out.println(" method=\"" + strAction + "\"");
out.println(" localfile=\"temp.xml\"");
out.println(" action=\"" + modelScreen.getServletPath(null) + "\" />");
//? out.println(" <model href=\"form.xsd\">");
//? out.println(" <!-- The model is currently ignored -->");
//? out.println(" </model>");
//? out.println(" <instance id=\"instance1\" xmlns=\"\">");
} | [
"public",
"void",
"printControlStartForm",
"(",
"PrintWriter",
"out",
",",
"int",
"iPrintOptions",
")",
"{",
"if",
"(",
"(",
"(",
"iPrintOptions",
"&",
"HtmlConstants",
".",
"HEADING_SCREEN",
")",
"==",
"HtmlConstants",
".",
"HEADING_SCREEN",
")",
"||",
"(",
"... | Display the start form in input format.
@param out The out stream.
@param iPrintOptions The view specific attributes. | [
"Display",
"the",
"start",
"form",
"in",
"input",
"format",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/screen/view/xml/src/main/java/org/jbundle/base/screen/view/xml/XBasePanel.java#L386-L410 |
floragunncom/search-guard | src/main/java/com/floragunn/searchguard/support/WildcardMatcher.java | WildcardMatcher.checkRegionMatches | private static boolean checkRegionMatches(final String str, final int strStartIndex, final String search) {
"""
Checks if one string contains another at a specific index using the case-sensitivity rule.
<p>
This method mimics parts of {@link String#regionMatches(boolean, int, String, int, int)}
but takes case-sensitivity into account.
@param str the string to check, not null
@param strStartIndex the index to start at in str
@param search the start to search for, not null
@return true if equal using the case rules
@throws NullPointerException if either string is null
"""
return str.regionMatches(false, strStartIndex, search, 0, search.length());
} | java | private static boolean checkRegionMatches(final String str, final int strStartIndex, final String search) {
return str.regionMatches(false, strStartIndex, search, 0, search.length());
} | [
"private",
"static",
"boolean",
"checkRegionMatches",
"(",
"final",
"String",
"str",
",",
"final",
"int",
"strStartIndex",
",",
"final",
"String",
"search",
")",
"{",
"return",
"str",
".",
"regionMatches",
"(",
"false",
",",
"strStartIndex",
",",
"search",
","... | Checks if one string contains another at a specific index using the case-sensitivity rule.
<p>
This method mimics parts of {@link String#regionMatches(boolean, int, String, int, int)}
but takes case-sensitivity into account.
@param str the string to check, not null
@param strStartIndex the index to start at in str
@param search the start to search for, not null
@return true if equal using the case rules
@throws NullPointerException if either string is null | [
"Checks",
"if",
"one",
"string",
"contains",
"another",
"at",
"a",
"specific",
"index",
"using",
"the",
"case",
"-",
"sensitivity",
"rule",
".",
"<p",
">",
"This",
"method",
"mimics",
"parts",
"of",
"{",
"@link",
"String#regionMatches",
"(",
"boolean",
"int"... | train | https://github.com/floragunncom/search-guard/blob/f9828004e11dc0e4b6da4dead1fafcf3be8f7f6d/src/main/java/com/floragunn/searchguard/support/WildcardMatcher.java#L623-L625 |
JakeWharton/NineOldAndroids | sample/src/com/jakewharton/nineoldandroids/sample/pathanimation/PathPoint.java | PathPoint.curveTo | public static PathPoint curveTo(float c0X, float c0Y, float c1X, float c1Y, float x, float y) {
"""
Constructs and returns a PathPoint object that describes a cubic B�zier curve to the
given xy location with the control points at c0 and c1.
"""
return new PathPoint(c0X, c0Y, c1X, c1Y, x, y);
} | java | public static PathPoint curveTo(float c0X, float c0Y, float c1X, float c1Y, float x, float y) {
return new PathPoint(c0X, c0Y, c1X, c1Y, x, y);
} | [
"public",
"static",
"PathPoint",
"curveTo",
"(",
"float",
"c0X",
",",
"float",
"c0Y",
",",
"float",
"c1X",
",",
"float",
"c1Y",
",",
"float",
"x",
",",
"float",
"y",
")",
"{",
"return",
"new",
"PathPoint",
"(",
"c0X",
",",
"c0Y",
",",
"c1X",
",",
"... | Constructs and returns a PathPoint object that describes a cubic B�zier curve to the
given xy location with the control points at c0 and c1. | [
"Constructs",
"and",
"returns",
"a",
"PathPoint",
"object",
"that",
"describes",
"a",
"cubic",
"B�zier",
"curve",
"to",
"the",
"given",
"xy",
"location",
"with",
"the",
"control",
"points",
"at",
"c0",
"and",
"c1",
"."
] | train | https://github.com/JakeWharton/NineOldAndroids/blob/d582f0ec8e79013e9fa96c07986160b52e662e63/sample/src/com/jakewharton/nineoldandroids/sample/pathanimation/PathPoint.java#L90-L92 |
landawn/AbacusUtil | src/com/landawn/abacus/dataSource/PoolablePreparedStatement.java | PoolablePreparedStatement.setArray | @Override
public void setArray(int parameterIndex, Array x) throws SQLException {
"""
Method setArray.
@param parameterIndex
@param x
@throws SQLException
@see java.sql.PreparedStatement#setArray(int, Array)
"""
internalStmt.setArray(parameterIndex, x);
} | java | @Override
public void setArray(int parameterIndex, Array x) throws SQLException {
internalStmt.setArray(parameterIndex, x);
} | [
"@",
"Override",
"public",
"void",
"setArray",
"(",
"int",
"parameterIndex",
",",
"Array",
"x",
")",
"throws",
"SQLException",
"{",
"internalStmt",
".",
"setArray",
"(",
"parameterIndex",
",",
"x",
")",
";",
"}"
] | Method setArray.
@param parameterIndex
@param x
@throws SQLException
@see java.sql.PreparedStatement#setArray(int, Array) | [
"Method",
"setArray",
"."
] | train | https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/dataSource/PoolablePreparedStatement.java#L443-L446 |
adessoAG/wicked-charts | wicket/wicked-charts-wicket7/src/main/java/de/adesso/wickedcharts/wicket7/JavaScriptExpressionSendingAjaxBehavior.java | JavaScriptExpressionSendingAjaxBehavior.addJavaScriptValues | public void addJavaScriptValues(Map<String, String> parameterMap) {
"""
Adds a set of javascript expressions to be passed from client to server.
@param parameterMap a map containing the name of a parameter as key and a javascript
expression as value
@see #addJavaScriptValue(String, String)
"""
for (Map.Entry<String, String> entry : parameterMap.entrySet()) {
String parameterName = entry.getKey();
String parameterValue = entry.getValue();
this.javascriptExpressions.put(parameterName, parameterValue);
}
} | java | public void addJavaScriptValues(Map<String, String> parameterMap) {
for (Map.Entry<String, String> entry : parameterMap.entrySet()) {
String parameterName = entry.getKey();
String parameterValue = entry.getValue();
this.javascriptExpressions.put(parameterName, parameterValue);
}
} | [
"public",
"void",
"addJavaScriptValues",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"parameterMap",
")",
"{",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"String",
">",
"entry",
":",
"parameterMap",
".",
"entrySet",
"(",
")",
")",
"{",
"St... | Adds a set of javascript expressions to be passed from client to server.
@param parameterMap a map containing the name of a parameter as key and a javascript
expression as value
@see #addJavaScriptValue(String, String) | [
"Adds",
"a",
"set",
"of",
"javascript",
"expressions",
"to",
"be",
"passed",
"from",
"client",
"to",
"server",
"."
] | train | https://github.com/adessoAG/wicked-charts/blob/498aceff025f612e22ba5135b26531afeabac03c/wicket/wicked-charts-wicket7/src/main/java/de/adesso/wickedcharts/wicket7/JavaScriptExpressionSendingAjaxBehavior.java#L84-L90 |
pravega/pravega | client/src/main/java/io/pravega/client/segment/impl/SegmentOutputStreamImpl.java | SegmentOutputStreamImpl.getConnection | CompletableFuture<ClientConnection> getConnection() throws SegmentSealedException {
"""
Establish a connection and wait for it to be setup. (Retries built in)
"""
if (state.isClosed()) {
throw new IllegalStateException("SegmentOutputStream is already closed", state.getException());
}
if (state.isAlreadySealed()) {
throw new SegmentSealedException(this.segmentName);
}
if (state.getConnection() == null) {
reconnect();
}
CompletableFuture<ClientConnection> future = new CompletableFuture<>();
state.setupConnection.register(future);
return future;
} | java | CompletableFuture<ClientConnection> getConnection() throws SegmentSealedException {
if (state.isClosed()) {
throw new IllegalStateException("SegmentOutputStream is already closed", state.getException());
}
if (state.isAlreadySealed()) {
throw new SegmentSealedException(this.segmentName);
}
if (state.getConnection() == null) {
reconnect();
}
CompletableFuture<ClientConnection> future = new CompletableFuture<>();
state.setupConnection.register(future);
return future;
} | [
"CompletableFuture",
"<",
"ClientConnection",
">",
"getConnection",
"(",
")",
"throws",
"SegmentSealedException",
"{",
"if",
"(",
"state",
".",
"isClosed",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"SegmentOutputStream is already closed\"",
"... | Establish a connection and wait for it to be setup. (Retries built in) | [
"Establish",
"a",
"connection",
"and",
"wait",
"for",
"it",
"to",
"be",
"setup",
".",
"(",
"Retries",
"built",
"in",
")"
] | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/client/src/main/java/io/pravega/client/segment/impl/SegmentOutputStreamImpl.java#L455-L468 |
svenkubiak/mangooio | mangooio-core/src/main/java/io/mangoo/routing/bindings/Validator.java | Validator.validateTrue | public void validateTrue(boolean value, String name, String message) {
"""
Validates a given value to be true
@param value The value to check
@param name The name of the field to display the error message
@param message A custom error message instead of the default one
"""
if (!value) {
addError(name, Optional.ofNullable(message).orElse(messages.get(Validation.TRUE_KEY.name(), name)));
}
} | java | public void validateTrue(boolean value, String name, String message) {
if (!value) {
addError(name, Optional.ofNullable(message).orElse(messages.get(Validation.TRUE_KEY.name(), name)));
}
} | [
"public",
"void",
"validateTrue",
"(",
"boolean",
"value",
",",
"String",
"name",
",",
"String",
"message",
")",
"{",
"if",
"(",
"!",
"value",
")",
"{",
"addError",
"(",
"name",
",",
"Optional",
".",
"ofNullable",
"(",
"message",
")",
".",
"orElse",
"(... | Validates a given value to be true
@param value The value to check
@param name The name of the field to display the error message
@param message A custom error message instead of the default one | [
"Validates",
"a",
"given",
"value",
"to",
"be",
"true"
] | train | https://github.com/svenkubiak/mangooio/blob/b3beb6d09510dbbab0ed947d5069c463e1fda6e7/mangooio-core/src/main/java/io/mangoo/routing/bindings/Validator.java#L429-L433 |
Stratio/cassandra-lucene-index | plugin/src/main/java/com/stratio/cassandra/lucene/search/SearchBuilders.java | SearchBuilders.geoShape | public static GeoShapeConditionBuilder geoShape(String field, String shape) {
"""
Returns a new {@link GeoShapeConditionBuilder} with the specified field reference point.
/** Constructor receiving the name of the field and the shape.
@param field the name of the field
@param shape the shape in <a href="http://en.wikipedia.org/wiki/Well-known_text"> WKT</a> format
@return a new geo shape condition builder
"""
return new GeoShapeConditionBuilder(field, new GeoShape.WKT(shape));
} | java | public static GeoShapeConditionBuilder geoShape(String field, String shape) {
return new GeoShapeConditionBuilder(field, new GeoShape.WKT(shape));
} | [
"public",
"static",
"GeoShapeConditionBuilder",
"geoShape",
"(",
"String",
"field",
",",
"String",
"shape",
")",
"{",
"return",
"new",
"GeoShapeConditionBuilder",
"(",
"field",
",",
"new",
"GeoShape",
".",
"WKT",
"(",
"shape",
")",
")",
";",
"}"
] | Returns a new {@link GeoShapeConditionBuilder} with the specified field reference point.
/** Constructor receiving the name of the field and the shape.
@param field the name of the field
@param shape the shape in <a href="http://en.wikipedia.org/wiki/Well-known_text"> WKT</a> format
@return a new geo shape condition builder | [
"Returns",
"a",
"new",
"{",
"@link",
"GeoShapeConditionBuilder",
"}",
"with",
"the",
"specified",
"field",
"reference",
"point",
"."
] | train | https://github.com/Stratio/cassandra-lucene-index/blob/a94a4d9af6c25d40e1108729974c35c27c54441c/plugin/src/main/java/com/stratio/cassandra/lucene/search/SearchBuilders.java#L265-L267 |
VoltDB/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/dbinfo/DatabaseInformationMain.java | DatabaseInformationMain.createBlankTable | protected final Table createBlankTable(HsqlName name) {
"""
Creates a new primoidal system table with the specified name. <p>
@return a new system table
@param name of the table
"""
Table table = new Table(database, name, TableBase.SYSTEM_TABLE);
return table;
} | java | protected final Table createBlankTable(HsqlName name) {
Table table = new Table(database, name, TableBase.SYSTEM_TABLE);
return table;
} | [
"protected",
"final",
"Table",
"createBlankTable",
"(",
"HsqlName",
"name",
")",
"{",
"Table",
"table",
"=",
"new",
"Table",
"(",
"database",
",",
"name",
",",
"TableBase",
".",
"SYSTEM_TABLE",
")",
";",
"return",
"table",
";",
"}"
] | Creates a new primoidal system table with the specified name. <p>
@return a new system table
@param name of the table | [
"Creates",
"a",
"new",
"primoidal",
"system",
"table",
"with",
"the",
"specified",
"name",
".",
"<p",
">"
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/dbinfo/DatabaseInformationMain.java#L464-L469 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jca.inbound.security/src/com/ibm/ws/jca/security/internal/J2CSecurityHelper.java | J2CSecurityHelper.getCacheKey | public static String getCacheKey(String uniqueId, String appRealm) {
"""
This method constructs the cache key that is required by security for caching
the Subject.
@param uniqueId The unique Id of the user
@param appRealm The application realm that the user belongs to
@return the cache key
"""
StringBuilder cacheKey = new StringBuilder();
if (uniqueId == null || appRealm == null) {
cacheKey.append(CACHE_KEY_PREFIX);
} else {
cacheKey.append(CACHE_KEY_PREFIX).append(uniqueId).append(CACHE_KEY_SEPARATOR).append(appRealm);
}
return cacheKey.toString();
} | java | public static String getCacheKey(String uniqueId, String appRealm) {
StringBuilder cacheKey = new StringBuilder();
if (uniqueId == null || appRealm == null) {
cacheKey.append(CACHE_KEY_PREFIX);
} else {
cacheKey.append(CACHE_KEY_PREFIX).append(uniqueId).append(CACHE_KEY_SEPARATOR).append(appRealm);
}
return cacheKey.toString();
} | [
"public",
"static",
"String",
"getCacheKey",
"(",
"String",
"uniqueId",
",",
"String",
"appRealm",
")",
"{",
"StringBuilder",
"cacheKey",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"if",
"(",
"uniqueId",
"==",
"null",
"||",
"appRealm",
"==",
"null",
")",
... | This method constructs the cache key that is required by security for caching
the Subject.
@param uniqueId The unique Id of the user
@param appRealm The application realm that the user belongs to
@return the cache key | [
"This",
"method",
"constructs",
"the",
"cache",
"key",
"that",
"is",
"required",
"by",
"security",
"for",
"caching",
"the",
"Subject",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jca.inbound.security/src/com/ibm/ws/jca/security/internal/J2CSecurityHelper.java#L622-L630 |
line/armeria | core/src/main/java/com/linecorp/armeria/client/Clients.java | Clients.withHttpHeaders | public static SafeCloseable withHttpHeaders(Function<HttpHeaders, HttpHeaders> headerManipulator) {
"""
Sets the specified HTTP header manipulating function in a thread-local variable so that the manipulated
headers are sent by the client call made from the current thread. Use the `try-with-resources` block
with the returned {@link SafeCloseable} to unset the thread-local variable automatically:
<pre>{@code
import static com.linecorp.armeria.common.HttpHeaderNames.AUTHORIZATION;
import static com.linecorp.armeria.common.HttpHeaderNames.USER_AGENT;
try (SafeCloseable ignored = withHttpHeaders(headers -> {
headers.set(HttpHeaders.AUTHORIZATION, myCredential)
.set(HttpHeaders.USER_AGENT, myAgent);
})) {
client.executeSomething(..);
}
}</pre>
You can also nest the header manipulation:
<pre>{@code
import static com.linecorp.armeria.common.HttpHeaderNames.AUTHORIZATION;
import static com.linecorp.armeria.common.HttpHeaderNames.USER_AGENT;
try (SafeCloseable ignored = withHttpHeaders(h -> h.set(USER_AGENT, myAgent))) {
for (String secret : secrets) {
try (SafeCloseable ignored2 = withHttpHeaders(h -> h.set(AUTHORIZATION, secret))) {
// Both USER_AGENT and AUTHORIZATION will be set.
client.executeSomething(..);
}
}
}
}</pre>
@see #withHttpHeader(AsciiString, String)
"""
requireNonNull(headerManipulator, "headerManipulator");
return withContextCustomizer(ctx -> {
final HttpHeaders additionalHeaders = ctx.additionalRequestHeaders();
final DefaultHttpHeaders headers = new DefaultHttpHeaders();
if (!additionalHeaders.isEmpty()) {
headers.set(additionalHeaders);
}
final HttpHeaders manipulatedHeaders = headerManipulator.apply(headers);
ctx.setAdditionalRequestHeaders(manipulatedHeaders);
});
} | java | public static SafeCloseable withHttpHeaders(Function<HttpHeaders, HttpHeaders> headerManipulator) {
requireNonNull(headerManipulator, "headerManipulator");
return withContextCustomizer(ctx -> {
final HttpHeaders additionalHeaders = ctx.additionalRequestHeaders();
final DefaultHttpHeaders headers = new DefaultHttpHeaders();
if (!additionalHeaders.isEmpty()) {
headers.set(additionalHeaders);
}
final HttpHeaders manipulatedHeaders = headerManipulator.apply(headers);
ctx.setAdditionalRequestHeaders(manipulatedHeaders);
});
} | [
"public",
"static",
"SafeCloseable",
"withHttpHeaders",
"(",
"Function",
"<",
"HttpHeaders",
",",
"HttpHeaders",
">",
"headerManipulator",
")",
"{",
"requireNonNull",
"(",
"headerManipulator",
",",
"\"headerManipulator\"",
")",
";",
"return",
"withContextCustomizer",
"(... | Sets the specified HTTP header manipulating function in a thread-local variable so that the manipulated
headers are sent by the client call made from the current thread. Use the `try-with-resources` block
with the returned {@link SafeCloseable} to unset the thread-local variable automatically:
<pre>{@code
import static com.linecorp.armeria.common.HttpHeaderNames.AUTHORIZATION;
import static com.linecorp.armeria.common.HttpHeaderNames.USER_AGENT;
try (SafeCloseable ignored = withHttpHeaders(headers -> {
headers.set(HttpHeaders.AUTHORIZATION, myCredential)
.set(HttpHeaders.USER_AGENT, myAgent);
})) {
client.executeSomething(..);
}
}</pre>
You can also nest the header manipulation:
<pre>{@code
import static com.linecorp.armeria.common.HttpHeaderNames.AUTHORIZATION;
import static com.linecorp.armeria.common.HttpHeaderNames.USER_AGENT;
try (SafeCloseable ignored = withHttpHeaders(h -> h.set(USER_AGENT, myAgent))) {
for (String secret : secrets) {
try (SafeCloseable ignored2 = withHttpHeaders(h -> h.set(AUTHORIZATION, secret))) {
// Both USER_AGENT and AUTHORIZATION will be set.
client.executeSomething(..);
}
}
}
}</pre>
@see #withHttpHeader(AsciiString, String) | [
"Sets",
"the",
"specified",
"HTTP",
"header",
"manipulating",
"function",
"in",
"a",
"thread",
"-",
"local",
"variable",
"so",
"that",
"the",
"manipulated",
"headers",
"are",
"sent",
"by",
"the",
"client",
"call",
"made",
"from",
"the",
"current",
"thread",
... | train | https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/core/src/main/java/com/linecorp/armeria/client/Clients.java#L329-L341 |
d-michail/jheaps | src/main/java/org/jheaps/monotone/AbstractRadixHeap.java | AbstractRadixHeap.insert | @Override
@ConstantTime(amortized = true)
public void insert(K key) {
"""
{@inheritDoc}
@throws IllegalArgumentException
if the key is null
@throws IllegalArgumentException
if the key is less than the minimum allowed key
@throws IllegalArgumentException
if the key is more than the maximum allowed key
@throws IllegalArgumentException
if the key is less than the last deleted key (or the minimum
key allowed if no key has been deleted)
"""
if (key == null) {
throw new IllegalArgumentException("Null keys not permitted");
}
if (compare(key, maxKey) > 0) {
throw new IllegalArgumentException("Key is more than the maximum allowed key");
}
if (compare(key, lastDeletedKey) < 0) {
throw new IllegalArgumentException("Invalid key. Monotone heap.");
}
int b = computeBucket(key, lastDeletedKey);
buckets[b].add(key);
// update current minimum cache
if (currentMin == null || compare(key, currentMin) < 0) {
currentMin = key;
currentMinBucket = b;
currentMinPos = buckets[b].size() - 1;
}
size++;
} | java | @Override
@ConstantTime(amortized = true)
public void insert(K key) {
if (key == null) {
throw new IllegalArgumentException("Null keys not permitted");
}
if (compare(key, maxKey) > 0) {
throw new IllegalArgumentException("Key is more than the maximum allowed key");
}
if (compare(key, lastDeletedKey) < 0) {
throw new IllegalArgumentException("Invalid key. Monotone heap.");
}
int b = computeBucket(key, lastDeletedKey);
buckets[b].add(key);
// update current minimum cache
if (currentMin == null || compare(key, currentMin) < 0) {
currentMin = key;
currentMinBucket = b;
currentMinPos = buckets[b].size() - 1;
}
size++;
} | [
"@",
"Override",
"@",
"ConstantTime",
"(",
"amortized",
"=",
"true",
")",
"public",
"void",
"insert",
"(",
"K",
"key",
")",
"{",
"if",
"(",
"key",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Null keys not permitted\"",
")",
... | {@inheritDoc}
@throws IllegalArgumentException
if the key is null
@throws IllegalArgumentException
if the key is less than the minimum allowed key
@throws IllegalArgumentException
if the key is more than the maximum allowed key
@throws IllegalArgumentException
if the key is less than the last deleted key (or the minimum
key allowed if no key has been deleted) | [
"{",
"@inheritDoc",
"}"
] | train | https://github.com/d-michail/jheaps/blob/7146451dd6591c2a8559dc564c9c40428c4a2c10/src/main/java/org/jheaps/monotone/AbstractRadixHeap.java#L119-L143 |
google/closure-templates | java/src/com/google/template/soy/jssrc/internal/JsCodeBuilder.java | JsCodeBuilder.pushOutputVar | public JsCodeBuilder pushOutputVar(String outputVarName) {
"""
Pushes on a new current output variable.
@param outputVarName The new output variable name.
"""
currOutputVar = id(outputVarName);
outputVars.push(new OutputVar(currOutputVar, false));
currOutputVarIsInited = false;
return this;
} | java | public JsCodeBuilder pushOutputVar(String outputVarName) {
currOutputVar = id(outputVarName);
outputVars.push(new OutputVar(currOutputVar, false));
currOutputVarIsInited = false;
return this;
} | [
"public",
"JsCodeBuilder",
"pushOutputVar",
"(",
"String",
"outputVarName",
")",
"{",
"currOutputVar",
"=",
"id",
"(",
"outputVarName",
")",
";",
"outputVars",
".",
"push",
"(",
"new",
"OutputVar",
"(",
"currOutputVar",
",",
"false",
")",
")",
";",
"currOutput... | Pushes on a new current output variable.
@param outputVarName The new output variable name. | [
"Pushes",
"on",
"a",
"new",
"current",
"output",
"variable",
"."
] | train | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/internal/JsCodeBuilder.java#L220-L225 |
citrusframework/citrus | modules/citrus-http/src/main/java/com/consol/citrus/http/message/HttpMessageContentBuilder.java | HttpMessageContentBuilder.replaceHeaders | private void replaceHeaders(final Message from, final Message to) {
"""
Replaces all headers
@param from The message to take the headers from
@param to The message to set the headers to
"""
to.getHeaders().clear();
to.getHeaders().putAll(from.getHeaders());
} | java | private void replaceHeaders(final Message from, final Message to) {
to.getHeaders().clear();
to.getHeaders().putAll(from.getHeaders());
} | [
"private",
"void",
"replaceHeaders",
"(",
"final",
"Message",
"from",
",",
"final",
"Message",
"to",
")",
"{",
"to",
".",
"getHeaders",
"(",
")",
".",
"clear",
"(",
")",
";",
"to",
".",
"getHeaders",
"(",
")",
".",
"putAll",
"(",
"from",
".",
"getHea... | Replaces all headers
@param from The message to take the headers from
@param to The message to set the headers to | [
"Replaces",
"all",
"headers"
] | train | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-http/src/main/java/com/consol/citrus/http/message/HttpMessageContentBuilder.java#L82-L85 |
kite-sdk/kite | kite-data/kite-data-core/src/main/java/org/kitesdk/data/spi/filesystem/SignalManager.java | SignalManager.getNormalizedConstraints | public static String getNormalizedConstraints(Constraints constraints) {
"""
Get a normalized query string for the {@link Constraints} that identifies a
logical {@code View}.
The normalized constraints will match to the query portion of a URI that will
be exactly the same as another logically equivalent URI.
(where, for example, the query parameters may be re-ordered)
If the constraints are {@link Constraints#isUnbounded() unbounded} a special case
of "unbounded" will be returned.
@return a normalized query string for the specified constraints.
@since 1.1
"""
// the constraints map isn't naturally ordered
// we want to ensure that our output is
if (constraints.isUnbounded()) {
// unbounded constrains is a special case, here we just use
// "unbounded" as the constraint
return UNBOUNDED_CONSTRAINT;
}
Map<String, String> orderedConstraints = constraints.toNormalizedQueryMap();
List<String> parts = new ArrayList<String>();
// build a query portion of the URI
for (Map.Entry<String, String> entry : orderedConstraints.entrySet()) {
StringBuilder builder = new StringBuilder();
String key = entry.getKey();
String value = entry.getValue();
builder.append(key);
builder.append("=");
if (value != null) {
builder.append(value);
}
parts.add(builder.toString());
}
return Joiner.on('&').join(parts);
} | java | public static String getNormalizedConstraints(Constraints constraints) {
// the constraints map isn't naturally ordered
// we want to ensure that our output is
if (constraints.isUnbounded()) {
// unbounded constrains is a special case, here we just use
// "unbounded" as the constraint
return UNBOUNDED_CONSTRAINT;
}
Map<String, String> orderedConstraints = constraints.toNormalizedQueryMap();
List<String> parts = new ArrayList<String>();
// build a query portion of the URI
for (Map.Entry<String, String> entry : orderedConstraints.entrySet()) {
StringBuilder builder = new StringBuilder();
String key = entry.getKey();
String value = entry.getValue();
builder.append(key);
builder.append("=");
if (value != null) {
builder.append(value);
}
parts.add(builder.toString());
}
return Joiner.on('&').join(parts);
} | [
"public",
"static",
"String",
"getNormalizedConstraints",
"(",
"Constraints",
"constraints",
")",
"{",
"// the constraints map isn't naturally ordered",
"// we want to ensure that our output is",
"if",
"(",
"constraints",
".",
"isUnbounded",
"(",
")",
")",
"{",
"// unbounded ... | Get a normalized query string for the {@link Constraints} that identifies a
logical {@code View}.
The normalized constraints will match to the query portion of a URI that will
be exactly the same as another logically equivalent URI.
(where, for example, the query parameters may be re-ordered)
If the constraints are {@link Constraints#isUnbounded() unbounded} a special case
of "unbounded" will be returned.
@return a normalized query string for the specified constraints.
@since 1.1 | [
"Get",
"a",
"normalized",
"query",
"string",
"for",
"the",
"{",
"@link",
"Constraints",
"}",
"that",
"identifies",
"a",
"logical",
"{",
"@code",
"View",
"}",
"."
] | train | https://github.com/kite-sdk/kite/blob/72bfb4b1a881af85808cd7f14bc3e15160a1e811/kite-data/kite-data-core/src/main/java/org/kitesdk/data/spi/filesystem/SignalManager.java#L130-L157 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/transformer/TransformerImpl.java | TransformerImpl.getOutputPropertyNoDefault | public String getOutputPropertyNoDefault(String qnameString)
throws IllegalArgumentException {
"""
Get the value of a property, without using the default properties. This
can be used to test if a property has been explicitly set by the stylesheet
or user.
NEEDSDOC @param qnameString
@return The value of the property, or null if not found.
@throws IllegalArgumentException If the property is not supported,
and is not namespaced.
"""
String value = null;
OutputProperties props = getOutputFormat();
value = (String) props.getProperties().get(qnameString);
if (null == value)
{
if (!OutputProperties.isLegalPropertyKey(qnameString))
throw new IllegalArgumentException(XSLMessages.createMessage(XSLTErrorResources.ER_OUTPUT_PROPERTY_NOT_RECOGNIZED, new Object[]{qnameString})); //"output property not recognized: "
// + qnameString);
}
return value;
} | java | public String getOutputPropertyNoDefault(String qnameString)
throws IllegalArgumentException
{
String value = null;
OutputProperties props = getOutputFormat();
value = (String) props.getProperties().get(qnameString);
if (null == value)
{
if (!OutputProperties.isLegalPropertyKey(qnameString))
throw new IllegalArgumentException(XSLMessages.createMessage(XSLTErrorResources.ER_OUTPUT_PROPERTY_NOT_RECOGNIZED, new Object[]{qnameString})); //"output property not recognized: "
// + qnameString);
}
return value;
} | [
"public",
"String",
"getOutputPropertyNoDefault",
"(",
"String",
"qnameString",
")",
"throws",
"IllegalArgumentException",
"{",
"String",
"value",
"=",
"null",
";",
"OutputProperties",
"props",
"=",
"getOutputFormat",
"(",
")",
";",
"value",
"=",
"(",
"String",
")... | Get the value of a property, without using the default properties. This
can be used to test if a property has been explicitly set by the stylesheet
or user.
NEEDSDOC @param qnameString
@return The value of the property, or null if not found.
@throws IllegalArgumentException If the property is not supported,
and is not namespaced. | [
"Get",
"the",
"value",
"of",
"a",
"property",
"without",
"using",
"the",
"default",
"properties",
".",
"This",
"can",
"be",
"used",
"to",
"test",
"if",
"a",
"property",
"has",
"been",
"explicitly",
"set",
"by",
"the",
"stylesheet",
"or",
"user",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/transformer/TransformerImpl.java#L751-L768 |
elki-project/elki | elki/src/main/java/de/lmu/ifi/dbs/elki/index/idistance/InMemoryIDistanceIndex.java | InMemoryIDistanceIndex.rankReferencePoints | protected static <O> DoubleIntPair[] rankReferencePoints(DistanceQuery<O> distanceQuery, O obj, ArrayDBIDs referencepoints) {
"""
Sort the reference points by distance to the query object
@param distanceQuery Distance query
@param obj Query object
@param referencepoints Iterator for reference points
@return Sorted array.
"""
DoubleIntPair[] priority = new DoubleIntPair[referencepoints.size()];
// Compute distances to reference points.
for(DBIDArrayIter iter = referencepoints.iter(); iter.valid(); iter.advance()) {
final int i = iter.getOffset();
final double dist = distanceQuery.distance(obj, iter);
priority[i] = new DoubleIntPair(dist, i);
}
Arrays.sort(priority);
return priority;
} | java | protected static <O> DoubleIntPair[] rankReferencePoints(DistanceQuery<O> distanceQuery, O obj, ArrayDBIDs referencepoints) {
DoubleIntPair[] priority = new DoubleIntPair[referencepoints.size()];
// Compute distances to reference points.
for(DBIDArrayIter iter = referencepoints.iter(); iter.valid(); iter.advance()) {
final int i = iter.getOffset();
final double dist = distanceQuery.distance(obj, iter);
priority[i] = new DoubleIntPair(dist, i);
}
Arrays.sort(priority);
return priority;
} | [
"protected",
"static",
"<",
"O",
">",
"DoubleIntPair",
"[",
"]",
"rankReferencePoints",
"(",
"DistanceQuery",
"<",
"O",
">",
"distanceQuery",
",",
"O",
"obj",
",",
"ArrayDBIDs",
"referencepoints",
")",
"{",
"DoubleIntPair",
"[",
"]",
"priority",
"=",
"new",
... | Sort the reference points by distance to the query object
@param distanceQuery Distance query
@param obj Query object
@param referencepoints Iterator for reference points
@return Sorted array. | [
"Sort",
"the",
"reference",
"points",
"by",
"distance",
"to",
"the",
"query",
"object"
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki/src/main/java/de/lmu/ifi/dbs/elki/index/idistance/InMemoryIDistanceIndex.java#L258-L268 |
lessthanoptimal/BoofCV | main/boofcv-ip/src/main/java/boofcv/alg/misc/ImageBandMath.java | ImageBandMath.stdDev | public static void stdDev(Planar<GrayS16> input, GrayS16 output, @Nullable GrayS16 avg) {
"""
Computes the standard deviation for each pixel across all bands in the {@link Planar}
image.
@param input Planar image - not modified
@param output Gray scale image containing average pixel values - modified
@param avg Input Gray scale image containing average image. Can be null
"""
stdDev(input,output,avg,0,input.getNumBands() - 1);
} | java | public static void stdDev(Planar<GrayS16> input, GrayS16 output, @Nullable GrayS16 avg) {
stdDev(input,output,avg,0,input.getNumBands() - 1);
} | [
"public",
"static",
"void",
"stdDev",
"(",
"Planar",
"<",
"GrayS16",
">",
"input",
",",
"GrayS16",
"output",
",",
"@",
"Nullable",
"GrayS16",
"avg",
")",
"{",
"stdDev",
"(",
"input",
",",
"output",
",",
"avg",
",",
"0",
",",
"input",
".",
"getNumBands"... | Computes the standard deviation for each pixel across all bands in the {@link Planar}
image.
@param input Planar image - not modified
@param output Gray scale image containing average pixel values - modified
@param avg Input Gray scale image containing average image. Can be null | [
"Computes",
"the",
"standard",
"deviation",
"for",
"each",
"pixel",
"across",
"all",
"bands",
"in",
"the",
"{"
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/alg/misc/ImageBandMath.java#L361-L363 |
sonyxperiadev/gerrit-events | src/main/java/com/sonymobile/tools/gerrit/gerritevents/GerritQueryHandler.java | GerritQueryHandler.queryCurrentPatchSets | public List<JSONObject> queryCurrentPatchSets(String queryString) throws
SshException, IOException, GerritQueryException {
"""
Runs the query and returns the result as a list of Java JSONObjects.
@param queryString the query.
@return the query result as a List of JSONObjects.
@throws GerritQueryException if Gerrit reports an error with the query.
@throws SshException if there is an error in the SSH Connection.
@throws IOException for some other IO problem.
"""
return queryJava(queryString, false, true, false, false);
} | java | public List<JSONObject> queryCurrentPatchSets(String queryString) throws
SshException, IOException, GerritQueryException {
return queryJava(queryString, false, true, false, false);
} | [
"public",
"List",
"<",
"JSONObject",
">",
"queryCurrentPatchSets",
"(",
"String",
"queryString",
")",
"throws",
"SshException",
",",
"IOException",
",",
"GerritQueryException",
"{",
"return",
"queryJava",
"(",
"queryString",
",",
"false",
",",
"true",
",",
"false"... | Runs the query and returns the result as a list of Java JSONObjects.
@param queryString the query.
@return the query result as a List of JSONObjects.
@throws GerritQueryException if Gerrit reports an error with the query.
@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",
"Java",
"JSONObjects",
"."
] | train | https://github.com/sonyxperiadev/gerrit-events/blob/9a443d13dded85cc4709136ac33989f2bbb34fe2/src/main/java/com/sonymobile/tools/gerrit/gerritevents/GerritQueryHandler.java#L255-L258 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/io/IoUtil.java | IoUtil.read | public static String read(InputStream in, Charset charset) throws IORuntimeException {
"""
从流中读取内容,读取完毕后并不关闭流
@param in 输入流,读取完毕后并不关闭流
@param charset 字符集
@return 内容
@throws IORuntimeException IO异常
"""
FastByteArrayOutputStream out = read(in);
return null == charset ? out.toString() : out.toString(charset);
} | java | public static String read(InputStream in, Charset charset) throws IORuntimeException {
FastByteArrayOutputStream out = read(in);
return null == charset ? out.toString() : out.toString(charset);
} | [
"public",
"static",
"String",
"read",
"(",
"InputStream",
"in",
",",
"Charset",
"charset",
")",
"throws",
"IORuntimeException",
"{",
"FastByteArrayOutputStream",
"out",
"=",
"read",
"(",
"in",
")",
";",
"return",
"null",
"==",
"charset",
"?",
"out",
".",
"to... | 从流中读取内容,读取完毕后并不关闭流
@param in 输入流,读取完毕后并不关闭流
@param charset 字符集
@return 内容
@throws IORuntimeException IO异常 | [
"从流中读取内容,读取完毕后并不关闭流"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/io/IoUtil.java#L409-L412 |
brunocvcunha/inutils4j | src/main/java/org/brunocvcunha/inutils4j/thirdparty/DateUtils.java | DateUtils.rollMonths | public static java.sql.Date rollMonths(java.util.Date startDate, int months) {
"""
Roll the days forward or backward.
@param startDate - The start date
@param months - Negative to rollbackwards.
"""
return rollDate(startDate, Calendar.MONTH, months);
} | java | public static java.sql.Date rollMonths(java.util.Date startDate, int months) {
return rollDate(startDate, Calendar.MONTH, months);
} | [
"public",
"static",
"java",
".",
"sql",
".",
"Date",
"rollMonths",
"(",
"java",
".",
"util",
".",
"Date",
"startDate",
",",
"int",
"months",
")",
"{",
"return",
"rollDate",
"(",
"startDate",
",",
"Calendar",
".",
"MONTH",
",",
"months",
")",
";",
"}"
] | Roll the days forward or backward.
@param startDate - The start date
@param months - Negative to rollbackwards. | [
"Roll",
"the",
"days",
"forward",
"or",
"backward",
"."
] | train | https://github.com/brunocvcunha/inutils4j/blob/223c4443c2cee662576ce644e552588fa114aa94/src/main/java/org/brunocvcunha/inutils4j/thirdparty/DateUtils.java#L192-L194 |
tango-controls/JTango | server/src/main/java/org/tango/server/build/CommandBuilder.java | CommandBuilder.build | public void build(final DeviceImpl device, final Object businessObject, final Method m, final boolean isOnDeviceImpl)
throws DevFailed {
"""
Create a Tango command {@link Command}
@param device
@param businessObject
@param m
@param isOnDeviceImpl
@throws DevFailed
"""
xlogger.entry();
final Command annot = m.getAnnotation(Command.class);
// retrieve parameter type
final Class<?>[] paramTypeTable = m.getParameterTypes();
if (paramTypeTable.length > 1) {
throw DevFailedUtils.newDevFailed("INIT_FAILED", "Command can have only one parameter");
}
Class<?> paramType;
if (paramTypeTable.length == 0) {
paramType = Void.class;
} else {
paramType = paramTypeTable[0];
}
// retrieve returned type
final Class<?> returnedType = m.getReturnType();
// logger
// .debug("get returned type of cmd {}", returnedType
// .getCanonicalName());
String cmdName;
if ("".equals(annot.name())) {
cmdName = m.getName();
} else {
cmdName = annot.name();
}
logger.debug("Has a command: {} type {}", cmdName, paramType.getCanonicalName());
final CommandConfiguration config = new CommandConfiguration(cmdName, paramType, returnedType,
annot.inTypeDesc(), annot.outTypeDesc(), DispLevel.from_int(annot.displayLevel()), annot.isPolled(),
annot.pollingPeriod());
ReflectCommandBehavior behavior = null;
if (isOnDeviceImpl) {
behavior = new ReflectCommandBehavior(m, device, config);
} else {
behavior = new ReflectCommandBehavior(m, businessObject, config);
}
final CommandImpl command = new CommandImpl(behavior, device.getName());
BuilderUtils.setStateMachine(m, command);
device.addCommand(command);
xlogger.exit();
} | java | public void build(final DeviceImpl device, final Object businessObject, final Method m, final boolean isOnDeviceImpl)
throws DevFailed {
xlogger.entry();
final Command annot = m.getAnnotation(Command.class);
// retrieve parameter type
final Class<?>[] paramTypeTable = m.getParameterTypes();
if (paramTypeTable.length > 1) {
throw DevFailedUtils.newDevFailed("INIT_FAILED", "Command can have only one parameter");
}
Class<?> paramType;
if (paramTypeTable.length == 0) {
paramType = Void.class;
} else {
paramType = paramTypeTable[0];
}
// retrieve returned type
final Class<?> returnedType = m.getReturnType();
// logger
// .debug("get returned type of cmd {}", returnedType
// .getCanonicalName());
String cmdName;
if ("".equals(annot.name())) {
cmdName = m.getName();
} else {
cmdName = annot.name();
}
logger.debug("Has a command: {} type {}", cmdName, paramType.getCanonicalName());
final CommandConfiguration config = new CommandConfiguration(cmdName, paramType, returnedType,
annot.inTypeDesc(), annot.outTypeDesc(), DispLevel.from_int(annot.displayLevel()), annot.isPolled(),
annot.pollingPeriod());
ReflectCommandBehavior behavior = null;
if (isOnDeviceImpl) {
behavior = new ReflectCommandBehavior(m, device, config);
} else {
behavior = new ReflectCommandBehavior(m, businessObject, config);
}
final CommandImpl command = new CommandImpl(behavior, device.getName());
BuilderUtils.setStateMachine(m, command);
device.addCommand(command);
xlogger.exit();
} | [
"public",
"void",
"build",
"(",
"final",
"DeviceImpl",
"device",
",",
"final",
"Object",
"businessObject",
",",
"final",
"Method",
"m",
",",
"final",
"boolean",
"isOnDeviceImpl",
")",
"throws",
"DevFailed",
"{",
"xlogger",
".",
"entry",
"(",
")",
";",
"final... | Create a Tango command {@link Command}
@param device
@param businessObject
@param m
@param isOnDeviceImpl
@throws DevFailed | [
"Create",
"a",
"Tango",
"command",
"{",
"@link",
"Command",
"}"
] | train | https://github.com/tango-controls/JTango/blob/1ccc9dcb83e6de2359a9f1906d170571cacf1345/server/src/main/java/org/tango/server/build/CommandBuilder.java#L63-L105 |
randomizedtesting/randomizedtesting | junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/slave/SlaveMain.java | SlaveMain.redirectStreams | @SuppressForbidden("legitimate sysstreams.")
private static void redirectStreams(final Serializer serializer, final boolean flushFrequently) {
"""
Redirect standard streams so that the output can be passed to listeners.
"""
final PrintStream origSysOut = System.out;
final PrintStream origSysErr = System.err;
// Set warnings stream to System.err.
warnings = System.err;
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@SuppressForbidden("legitimate PrintStream with default charset.")
@Override
public Void run() {
System.setOut(new PrintStream(new BufferedOutputStream(new ChunkedStream() {
@Override
public void write(byte[] b, int off, int len) throws IOException {
if (multiplexStdStreams) {
origSysOut.write(b, off, len);
}
serializer.serialize(new AppendStdOutEvent(b, off, len));
if (flushFrequently) serializer.flush();
}
})));
System.setErr(new PrintStream(new BufferedOutputStream(new ChunkedStream() {
@Override
public void write(byte[] b, int off, int len) throws IOException {
if (multiplexStdStreams) {
origSysErr.write(b, off, len);
}
serializer.serialize(new AppendStdErrEvent(b, off, len));
if (flushFrequently) serializer.flush();
}
})));
return null;
}
});
} | java | @SuppressForbidden("legitimate sysstreams.")
private static void redirectStreams(final Serializer serializer, final boolean flushFrequently) {
final PrintStream origSysOut = System.out;
final PrintStream origSysErr = System.err;
// Set warnings stream to System.err.
warnings = System.err;
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@SuppressForbidden("legitimate PrintStream with default charset.")
@Override
public Void run() {
System.setOut(new PrintStream(new BufferedOutputStream(new ChunkedStream() {
@Override
public void write(byte[] b, int off, int len) throws IOException {
if (multiplexStdStreams) {
origSysOut.write(b, off, len);
}
serializer.serialize(new AppendStdOutEvent(b, off, len));
if (flushFrequently) serializer.flush();
}
})));
System.setErr(new PrintStream(new BufferedOutputStream(new ChunkedStream() {
@Override
public void write(byte[] b, int off, int len) throws IOException {
if (multiplexStdStreams) {
origSysErr.write(b, off, len);
}
serializer.serialize(new AppendStdErrEvent(b, off, len));
if (flushFrequently) serializer.flush();
}
})));
return null;
}
});
} | [
"@",
"SuppressForbidden",
"(",
"\"legitimate sysstreams.\"",
")",
"private",
"static",
"void",
"redirectStreams",
"(",
"final",
"Serializer",
"serializer",
",",
"final",
"boolean",
"flushFrequently",
")",
"{",
"final",
"PrintStream",
"origSysOut",
"=",
"System",
".",
... | Redirect standard streams so that the output can be passed to listeners. | [
"Redirect",
"standard",
"streams",
"so",
"that",
"the",
"output",
"can",
"be",
"passed",
"to",
"listeners",
"."
] | train | https://github.com/randomizedtesting/randomizedtesting/blob/85a0c7eff5d03d98da4d1f9502a11af74d26478a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/slave/SlaveMain.java#L470-L505 |
languagetool-org/languagetool | languagetool-core/src/main/java/org/languagetool/tools/StringTools.java | StringTools.changeFirstCharCase | @Nullable
private static String changeFirstCharCase(String str, boolean toUpperCase) {
"""
Return <code>str</code> modified so that its first character is now an
lowercase or uppercase character, depending on <code>toUpperCase</code>.
If <code>str</code> starts with non-alphabetic
characters, such as quotes or parentheses, the first character is
determined as the first alphabetic character.
"""
if (isEmpty(str)) {
return str;
}
if (str.length() == 1) {
return toUpperCase ? str.toUpperCase(Locale.ENGLISH) : str.toLowerCase();
}
int pos = 0;
int len = str.length() - 1;
while (!Character.isLetterOrDigit(str.charAt(pos)) && len > pos) {
pos++;
}
char firstChar = str.charAt(pos);
return str.substring(0, pos)
+ (toUpperCase ? Character.toUpperCase(firstChar) : Character.toLowerCase(firstChar))
+ str.substring(pos + 1);
} | java | @Nullable
private static String changeFirstCharCase(String str, boolean toUpperCase) {
if (isEmpty(str)) {
return str;
}
if (str.length() == 1) {
return toUpperCase ? str.toUpperCase(Locale.ENGLISH) : str.toLowerCase();
}
int pos = 0;
int len = str.length() - 1;
while (!Character.isLetterOrDigit(str.charAt(pos)) && len > pos) {
pos++;
}
char firstChar = str.charAt(pos);
return str.substring(0, pos)
+ (toUpperCase ? Character.toUpperCase(firstChar) : Character.toLowerCase(firstChar))
+ str.substring(pos + 1);
} | [
"@",
"Nullable",
"private",
"static",
"String",
"changeFirstCharCase",
"(",
"String",
"str",
",",
"boolean",
"toUpperCase",
")",
"{",
"if",
"(",
"isEmpty",
"(",
"str",
")",
")",
"{",
"return",
"str",
";",
"}",
"if",
"(",
"str",
".",
"length",
"(",
")",... | Return <code>str</code> modified so that its first character is now an
lowercase or uppercase character, depending on <code>toUpperCase</code>.
If <code>str</code> starts with non-alphabetic
characters, such as quotes or parentheses, the first character is
determined as the first alphabetic character. | [
"Return",
"<code",
">",
"str<",
"/",
"code",
">",
"modified",
"so",
"that",
"its",
"first",
"character",
"is",
"now",
"an",
"lowercase",
"or",
"uppercase",
"character",
"depending",
"on",
"<code",
">",
"toUpperCase<",
"/",
"code",
">",
".",
"If",
"<code",
... | train | https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-core/src/main/java/org/languagetool/tools/StringTools.java#L234-L251 |
elibom/jogger | src/main/java/com/elibom/jogger/middleware/router/loader/AbstractFileRoutesLoader.java | AbstractFileRoutesLoader.validatePath | private String validatePath(String path, int line) throws ParseException {
"""
Helper method. It validates if the path is valid.
@param path the path to be validated
@return the same path that was received as an argument.
@throws ParseException if the path is not valid.
"""
if (!path.startsWith("/")) {
throw new ParseException("Path must start with '/'", line);
}
boolean openedKey = false;
for (int i=0; i < path.length(); i++) {
boolean validChar = isValidCharForPath(path.charAt(i), openedKey);
if (!validChar) {
throw new ParseException(path, i);
}
if (path.charAt(i) == '{') {
openedKey = true;
}
if (path.charAt(i) == '}') {
openedKey = false;
}
}
return path;
} | java | private String validatePath(String path, int line) throws ParseException {
if (!path.startsWith("/")) {
throw new ParseException("Path must start with '/'", line);
}
boolean openedKey = false;
for (int i=0; i < path.length(); i++) {
boolean validChar = isValidCharForPath(path.charAt(i), openedKey);
if (!validChar) {
throw new ParseException(path, i);
}
if (path.charAt(i) == '{') {
openedKey = true;
}
if (path.charAt(i) == '}') {
openedKey = false;
}
}
return path;
} | [
"private",
"String",
"validatePath",
"(",
"String",
"path",
",",
"int",
"line",
")",
"throws",
"ParseException",
"{",
"if",
"(",
"!",
"path",
".",
"startsWith",
"(",
"\"/\"",
")",
")",
"{",
"throw",
"new",
"ParseException",
"(",
"\"Path must start with '/'\"",... | Helper method. It validates if the path is valid.
@param path the path to be validated
@return the same path that was received as an argument.
@throws ParseException if the path is not valid. | [
"Helper",
"method",
".",
"It",
"validates",
"if",
"the",
"path",
"is",
"valid",
"."
] | train | https://github.com/elibom/jogger/blob/d5892ff45e76328d444a68b5a38c26e7bdd0692b/src/main/java/com/elibom/jogger/middleware/router/loader/AbstractFileRoutesLoader.java#L167-L191 |
gmessner/gitlab4j-api | src/main/java/org/gitlab4j/api/RepositoryApi.java | RepositoryApi.getMergeBase | public Commit getMergeBase(Object projectIdOrPath, List<String> refs) throws GitLabApiException {
"""
Get the common ancestor for 2 or more refs (commit SHAs, branch names or tags).
<pre><code>GitLab Endpoint: GET /projects/:id/repository/merge_base</code></pre>
@param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
@param refs a List of 2 or more refs (commit SHAs, branch names or tags)
@return the Commit instance containing the common ancestor
@throws GitLabApiException if any exception occurs
"""
GitLabApiForm queryParams = new GitLabApiForm().withParam("refs", refs, true);
Response response = get(Response.Status.OK, queryParams.asMap(), "projects",
getProjectIdOrPath(projectIdOrPath), "repository", "merge_base");
return (response.readEntity(Commit.class));
} | java | public Commit getMergeBase(Object projectIdOrPath, List<String> refs) throws GitLabApiException {
GitLabApiForm queryParams = new GitLabApiForm().withParam("refs", refs, true);
Response response = get(Response.Status.OK, queryParams.asMap(), "projects",
getProjectIdOrPath(projectIdOrPath), "repository", "merge_base");
return (response.readEntity(Commit.class));
} | [
"public",
"Commit",
"getMergeBase",
"(",
"Object",
"projectIdOrPath",
",",
"List",
"<",
"String",
">",
"refs",
")",
"throws",
"GitLabApiException",
"{",
"GitLabApiForm",
"queryParams",
"=",
"new",
"GitLabApiForm",
"(",
")",
".",
"withParam",
"(",
"\"refs\"",
","... | Get the common ancestor for 2 or more refs (commit SHAs, branch names or tags).
<pre><code>GitLab Endpoint: GET /projects/:id/repository/merge_base</code></pre>
@param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
@param refs a List of 2 or more refs (commit SHAs, branch names or tags)
@return the Commit instance containing the common ancestor
@throws GitLabApiException if any exception occurs | [
"Get",
"the",
"common",
"ancestor",
"for",
"2",
"or",
"more",
"refs",
"(",
"commit",
"SHAs",
"branch",
"names",
"or",
"tags",
")",
"."
] | train | https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/RepositoryApi.java#L776-L781 |
TakahikoKawasaki/nv-bluetooth | src/main/java/com/neovisionaries/bluetooth/ble/advertising/ADPayloadParser.java | ADPayloadParser.registerBuilder | public void registerBuilder(int type, ADStructureBuilder builder) {
"""
Register an AD structure builder for the AD type. The given builder
is added at the beginning of the list of the builders for the AD type.
<p>
Note that a builder for the type <i>Manufacturer Specific Data</i>
(0xFF) should not be registered by this method. Instead, use
{@link #registerManufacturerSpecificBuilder(int,
ADManufacturerSpecificBuilder)}.
</p>
@param type
AD type. The value must be in the range from 0 to 0xFF.
@param builder
AD structure builder.
"""
if (type < 0 || 0xFF < type)
{
String message = String.format("'type' is out of the valid range: %d", type);
throw new IllegalArgumentException(message);
}
if (builder == null)
{
return;
}
// Use the AD type as the key for the builder.
Integer key = Integer.valueOf(type);
// Get the existing list of builders for the AD type.
List<ADStructureBuilder> builders = mBuilders.get(key);
// If no builder has been registered for the AD type yet.
if (builders == null)
{
builders = new ArrayList<ADStructureBuilder>();
mBuilders.put(key, builders);
}
// Register the builder at the beginning of the builder list.
builders.add(0, builder);
} | java | public void registerBuilder(int type, ADStructureBuilder builder)
{
if (type < 0 || 0xFF < type)
{
String message = String.format("'type' is out of the valid range: %d", type);
throw new IllegalArgumentException(message);
}
if (builder == null)
{
return;
}
// Use the AD type as the key for the builder.
Integer key = Integer.valueOf(type);
// Get the existing list of builders for the AD type.
List<ADStructureBuilder> builders = mBuilders.get(key);
// If no builder has been registered for the AD type yet.
if (builders == null)
{
builders = new ArrayList<ADStructureBuilder>();
mBuilders.put(key, builders);
}
// Register the builder at the beginning of the builder list.
builders.add(0, builder);
} | [
"public",
"void",
"registerBuilder",
"(",
"int",
"type",
",",
"ADStructureBuilder",
"builder",
")",
"{",
"if",
"(",
"type",
"<",
"0",
"||",
"0xFF",
"<",
"type",
")",
"{",
"String",
"message",
"=",
"String",
".",
"format",
"(",
"\"'type' is out of the valid r... | Register an AD structure builder for the AD type. The given builder
is added at the beginning of the list of the builders for the AD type.
<p>
Note that a builder for the type <i>Manufacturer Specific Data</i>
(0xFF) should not be registered by this method. Instead, use
{@link #registerManufacturerSpecificBuilder(int,
ADManufacturerSpecificBuilder)}.
</p>
@param type
AD type. The value must be in the range from 0 to 0xFF.
@param builder
AD structure builder. | [
"Register",
"an",
"AD",
"structure",
"builder",
"for",
"the",
"AD",
"type",
".",
"The",
"given",
"builder",
"is",
"added",
"at",
"the",
"beginning",
"of",
"the",
"list",
"of",
"the",
"builders",
"for",
"the",
"AD",
"type",
"."
] | train | https://github.com/TakahikoKawasaki/nv-bluetooth/blob/ef0099e941cd377571398615ea5e18cfc84cadd3/src/main/java/com/neovisionaries/bluetooth/ble/advertising/ADPayloadParser.java#L152-L180 |
liferay/com-liferay-commerce | commerce-wish-list-api/src/main/java/com/liferay/commerce/wish/list/service/persistence/CommerceWishListUtil.java | CommerceWishListUtil.findByUUID_G | public static CommerceWishList findByUUID_G(String uuid, long groupId)
throws com.liferay.commerce.wish.list.exception.NoSuchWishListException {
"""
Returns the commerce wish list where uuid = ? and groupId = ? or throws a {@link NoSuchWishListException} if it could not be found.
@param uuid the uuid
@param groupId the group ID
@return the matching commerce wish list
@throws NoSuchWishListException if a matching commerce wish list could not be found
"""
return getPersistence().findByUUID_G(uuid, groupId);
} | java | public static CommerceWishList findByUUID_G(String uuid, long groupId)
throws com.liferay.commerce.wish.list.exception.NoSuchWishListException {
return getPersistence().findByUUID_G(uuid, groupId);
} | [
"public",
"static",
"CommerceWishList",
"findByUUID_G",
"(",
"String",
"uuid",
",",
"long",
"groupId",
")",
"throws",
"com",
".",
"liferay",
".",
"commerce",
".",
"wish",
".",
"list",
".",
"exception",
".",
"NoSuchWishListException",
"{",
"return",
"getPersisten... | Returns the commerce wish list where uuid = ? and groupId = ? or throws a {@link NoSuchWishListException} if it could not be found.
@param uuid the uuid
@param groupId the group ID
@return the matching commerce wish list
@throws NoSuchWishListException if a matching commerce wish list could not be found | [
"Returns",
"the",
"commerce",
"wish",
"list",
"where",
"uuid",
"=",
"?",
";",
"and",
"groupId",
"=",
"?",
";",
"or",
"throws",
"a",
"{",
"@link",
"NoSuchWishListException",
"}",
"if",
"it",
"could",
"not",
"be",
"found",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-wish-list-api/src/main/java/com/liferay/commerce/wish/list/service/persistence/CommerceWishListUtil.java#L280-L283 |
javalite/activeweb | activeweb/src/main/java/org/javalite/activeweb/AppController.java | AppController.actionSupportsHttpMethod | public boolean actionSupportsHttpMethod(String actionMethodName, HttpMethod httpMethod) {
"""
Checks if the action supports an HTTP method, according to its configuration.
@param actionMethodName name of action method.
@param httpMethod http method
@return true if supports, false if does not.
"""
if (restful()) {
return restfulActionSupportsHttpMethod(actionMethodName, httpMethod) || standardActionSupportsHttpMethod(actionMethodName, httpMethod);
} else {
return standardActionSupportsHttpMethod(actionMethodName, httpMethod);
}
} | java | public boolean actionSupportsHttpMethod(String actionMethodName, HttpMethod httpMethod) {
if (restful()) {
return restfulActionSupportsHttpMethod(actionMethodName, httpMethod) || standardActionSupportsHttpMethod(actionMethodName, httpMethod);
} else {
return standardActionSupportsHttpMethod(actionMethodName, httpMethod);
}
} | [
"public",
"boolean",
"actionSupportsHttpMethod",
"(",
"String",
"actionMethodName",
",",
"HttpMethod",
"httpMethod",
")",
"{",
"if",
"(",
"restful",
"(",
")",
")",
"{",
"return",
"restfulActionSupportsHttpMethod",
"(",
"actionMethodName",
",",
"httpMethod",
")",
"||... | Checks if the action supports an HTTP method, according to its configuration.
@param actionMethodName name of action method.
@param httpMethod http method
@return true if supports, false if does not. | [
"Checks",
"if",
"the",
"action",
"supports",
"an",
"HTTP",
"method",
"according",
"to",
"its",
"configuration",
"."
] | train | https://github.com/javalite/activeweb/blob/f25f589da94852b6f5625182360732e0861794a6/activeweb/src/main/java/org/javalite/activeweb/AppController.java#L111-L117 |
blinkfox/zealot | src/main/java/com/blinkfox/zealot/core/Zealot.java | Zealot.buildNewSqlInfo | private static SqlInfo buildNewSqlInfo(String nameSpace, Node node, Object paramObj) {
"""
构建新的、完整的SqlInfo对象.
@param nameSpace xml命名空间
@param node dom4j对象节点
@param paramObj 参数对象
@return 返回SqlInfo对象
"""
return buildSqlInfo(nameSpace, SqlInfo.newInstance(), node, paramObj);
} | java | private static SqlInfo buildNewSqlInfo(String nameSpace, Node node, Object paramObj) {
return buildSqlInfo(nameSpace, SqlInfo.newInstance(), node, paramObj);
} | [
"private",
"static",
"SqlInfo",
"buildNewSqlInfo",
"(",
"String",
"nameSpace",
",",
"Node",
"node",
",",
"Object",
"paramObj",
")",
"{",
"return",
"buildSqlInfo",
"(",
"nameSpace",
",",
"SqlInfo",
".",
"newInstance",
"(",
")",
",",
"node",
",",
"paramObj",
"... | 构建新的、完整的SqlInfo对象.
@param nameSpace xml命名空间
@param node dom4j对象节点
@param paramObj 参数对象
@return 返回SqlInfo对象 | [
"构建新的、完整的SqlInfo对象",
"."
] | train | https://github.com/blinkfox/zealot/blob/21b00fa3e4ed42188eef3116d494e112e7a4194c/src/main/java/com/blinkfox/zealot/core/Zealot.java#L132-L134 |
petergeneric/stdlib | stdlib/src/main/java/com/peterphi/std/util/HexHelper.java | HexHelper.toHex | public static final String toHex(final char separator, final byte... bin) {
"""
Encodes a series of bytes into a hexidecimal string with each source byte (represented in the output as a 2 digit
hexidecimal pair) separated by <code>separator</code><br />
@param separator
The character to insert between each byte (for example, <code>':'</code>)
@param bin
the series of bytes to encode
@return a hexidecimal string with each source byte (represented in the output as a 2 digit hexidecimal pair) separated by
<code>separator</code>
"""
if (bin == null || bin.length == 0)
return "";
char[] buffer = new char[(bin.length * 3) - 1];
int end = bin.length - 1;
int base = 0; // Store the index of buffer we're inserting into
for (int i = 0; i < bin.length; i++)
{
byte b = bin[i];
buffer[base++] = hex[(b >> 4) & 0x0F];
buffer[base++] = hex[b & 0x0F];
if (i != end)
buffer[base++] = separator;
}
return new String(buffer);
} | java | public static final String toHex(final char separator, final byte... bin)
{
if (bin == null || bin.length == 0)
return "";
char[] buffer = new char[(bin.length * 3) - 1];
int end = bin.length - 1;
int base = 0; // Store the index of buffer we're inserting into
for (int i = 0; i < bin.length; i++)
{
byte b = bin[i];
buffer[base++] = hex[(b >> 4) & 0x0F];
buffer[base++] = hex[b & 0x0F];
if (i != end)
buffer[base++] = separator;
}
return new String(buffer);
} | [
"public",
"static",
"final",
"String",
"toHex",
"(",
"final",
"char",
"separator",
",",
"final",
"byte",
"...",
"bin",
")",
"{",
"if",
"(",
"bin",
"==",
"null",
"||",
"bin",
".",
"length",
"==",
"0",
")",
"return",
"\"\"",
";",
"char",
"[",
"]",
"b... | Encodes a series of bytes into a hexidecimal string with each source byte (represented in the output as a 2 digit
hexidecimal pair) separated by <code>separator</code><br />
@param separator
The character to insert between each byte (for example, <code>':'</code>)
@param bin
the series of bytes to encode
@return a hexidecimal string with each source byte (represented in the output as a 2 digit hexidecimal pair) separated by
<code>separator</code> | [
"Encodes",
"a",
"series",
"of",
"bytes",
"into",
"a",
"hexidecimal",
"string",
"with",
"each",
"source",
"byte",
"(",
"represented",
"in",
"the",
"output",
"as",
"a",
"2",
"digit",
"hexidecimal",
"pair",
")",
"separated",
"by",
"<code",
">",
"separator<",
... | train | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/util/HexHelper.java#L196-L215 |
VoltDB/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/Constraint.java | Constraint.findFkRef | RowIterator findFkRef(Session session, Object[] row, boolean delete) {
"""
New method to find any referencing row for a foreign key (finds row in
child table). If ON DELETE CASCADE is specified for this constraint, then
the method finds the first row among the rows of the table ordered by the
index and doesn't throw. Without ON DELETE CASCADE, the method attempts
to finds any row that exists. If no
row is found, null is returned. (fredt@users)
@param session Session
@param row array of objects for a database row
@param delete should we allow 'ON DELETE CASCADE' or 'ON UPDATE CASCADE'
@return iterator
@
"""
if (row == null || ArrayUtil.hasNull(row, core.mainCols)) {
return core.refIndex.emptyIterator();
}
PersistentStore store = session.sessionData.getRowStore(core.refTable);
return core.refIndex.findFirstRow(session, store, row, core.mainCols);
} | java | RowIterator findFkRef(Session session, Object[] row, boolean delete) {
if (row == null || ArrayUtil.hasNull(row, core.mainCols)) {
return core.refIndex.emptyIterator();
}
PersistentStore store = session.sessionData.getRowStore(core.refTable);
return core.refIndex.findFirstRow(session, store, row, core.mainCols);
} | [
"RowIterator",
"findFkRef",
"(",
"Session",
"session",
",",
"Object",
"[",
"]",
"row",
",",
"boolean",
"delete",
")",
"{",
"if",
"(",
"row",
"==",
"null",
"||",
"ArrayUtil",
".",
"hasNull",
"(",
"row",
",",
"core",
".",
"mainCols",
")",
")",
"{",
"re... | New method to find any referencing row for a foreign key (finds row in
child table). If ON DELETE CASCADE is specified for this constraint, then
the method finds the first row among the rows of the table ordered by the
index and doesn't throw. Without ON DELETE CASCADE, the method attempts
to finds any row that exists. If no
row is found, null is returned. (fredt@users)
@param session Session
@param row array of objects for a database row
@param delete should we allow 'ON DELETE CASCADE' or 'ON UPDATE CASCADE'
@return iterator
@ | [
"New",
"method",
"to",
"find",
"any",
"referencing",
"row",
"for",
"a",
"foreign",
"key",
"(",
"finds",
"row",
"in",
"child",
"table",
")",
".",
"If",
"ON",
"DELETE",
"CASCADE",
"is",
"specified",
"for",
"this",
"constraint",
"then",
"the",
"method",
"fi... | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/Constraint.java#L905-L914 |
unbescape/unbescape | src/main/java/org/unbescape/uri/UriEscape.java | UriEscape.unescapeUriQueryParam | public static void unescapeUriQueryParam(final String text, final Writer writer, final String encoding)
throws IOException {
"""
<p>
Perform am URI query parameter (name or value) <strong>unescape</strong> operation
on a <tt>String</tt> input, writing results to a <tt>Writer</tt>.
</p>
<p>
This method will unescape every percent-encoded (<tt>%HH</tt>) sequences present in input,
even for those characters that do not need to be percent-encoded in this context (unreserved characters
can be percent-encoded even if/when this is not required, though it is not generally considered a
good practice).
</p>
<p>
This method will use specified <tt>encoding</tt> in order to determine the characters specified in the
percent-encoded byte sequences.
</p>
<p>
This method is <strong>thread-safe</strong>.
</p>
@param text the <tt>String</tt> to be unescaped.
@param writer the <tt>java.io.Writer</tt> to which the unescaped result will be written. Nothing will
be written at all to this writer if input is <tt>null</tt>.
@param encoding the encoding to be used for unescaping.
@throws IOException if an input/output exception occurs
@since 1.1.2
"""
if (writer == null) {
throw new IllegalArgumentException("Argument 'writer' cannot be null");
}
if (encoding == null) {
throw new IllegalArgumentException("Argument 'encoding' cannot be null");
}
UriEscapeUtil.unescape(new InternalStringReader(text), writer, UriEscapeUtil.UriEscapeType.QUERY_PARAM, encoding);
} | java | public static void unescapeUriQueryParam(final String text, final Writer writer, final String encoding)
throws IOException {
if (writer == null) {
throw new IllegalArgumentException("Argument 'writer' cannot be null");
}
if (encoding == null) {
throw new IllegalArgumentException("Argument 'encoding' cannot be null");
}
UriEscapeUtil.unescape(new InternalStringReader(text), writer, UriEscapeUtil.UriEscapeType.QUERY_PARAM, encoding);
} | [
"public",
"static",
"void",
"unescapeUriQueryParam",
"(",
"final",
"String",
"text",
",",
"final",
"Writer",
"writer",
",",
"final",
"String",
"encoding",
")",
"throws",
"IOException",
"{",
"if",
"(",
"writer",
"==",
"null",
")",
"{",
"throw",
"new",
"Illega... | <p>
Perform am URI query parameter (name or value) <strong>unescape</strong> operation
on a <tt>String</tt> input, writing results to a <tt>Writer</tt>.
</p>
<p>
This method will unescape every percent-encoded (<tt>%HH</tt>) sequences present in input,
even for those characters that do not need to be percent-encoded in this context (unreserved characters
can be percent-encoded even if/when this is not required, though it is not generally considered a
good practice).
</p>
<p>
This method will use specified <tt>encoding</tt> in order to determine the characters specified in the
percent-encoded byte sequences.
</p>
<p>
This method is <strong>thread-safe</strong>.
</p>
@param text the <tt>String</tt> to be unescaped.
@param writer the <tt>java.io.Writer</tt> to which the unescaped result will be written. Nothing will
be written at all to this writer if input is <tt>null</tt>.
@param encoding the encoding to be used for unescaping.
@throws IOException if an input/output exception occurs
@since 1.1.2 | [
"<p",
">",
"Perform",
"am",
"URI",
"query",
"parameter",
"(",
"name",
"or",
"value",
")",
"<strong",
">",
"unescape<",
"/",
"strong",
">",
"operation",
"on",
"a",
"<tt",
">",
"String<",
"/",
"tt",
">",
"input",
"writing",
"results",
"to",
"a",
"<tt",
... | train | https://github.com/unbescape/unbescape/blob/ec5435fb3508c2eed25d8165dc27ded2602cae13/src/main/java/org/unbescape/uri/UriEscape.java#L1987-L2000 |
mapsforge/mapsforge | mapsforge-map-writer/src/main/java/org/mapsforge/map/writer/MapFileWriter.java | MapFileWriter.writeFile | public static void writeFile(MapWriterConfiguration configuration, TileBasedDataProcessor dataProcessor)
throws IOException {
"""
Writes the map file according to the given configuration using the given data processor.
@param configuration the configuration
@param dataProcessor the data processor
@throws IOException thrown if any IO error occurs
"""
EXECUTOR_SERVICE = Executors.newFixedThreadPool(configuration.getThreads());
RandomAccessFile randomAccessFile = new RandomAccessFile(configuration.getOutputFile(), "rw");
int amountOfZoomIntervals = dataProcessor.getZoomIntervalConfiguration().getNumberOfZoomIntervals();
ByteBuffer containerHeaderBuffer = ByteBuffer.allocate(HEADER_BUFFER_SIZE);
// CONTAINER HEADER
int totalHeaderSize = writeHeaderBuffer(configuration, dataProcessor, containerHeaderBuffer);
// set to mark where zoomIntervalConfig starts
containerHeaderBuffer.reset();
final LoadingCache<TDWay, Geometry> jtsGeometryCache = CacheBuilder.newBuilder()
.maximumSize(JTS_GEOMETRY_CACHE_SIZE).concurrencyLevel(Runtime.getRuntime().availableProcessors() * 2)
.build(new JTSGeometryCacheLoader(dataProcessor));
// SUB FILES
// for each zoom interval write a sub file
long currentFileSize = totalHeaderSize;
for (int i = 0; i < amountOfZoomIntervals; i++) {
// SUB FILE INDEX AND DATA
long subfileSize = writeSubfile(currentFileSize, i, dataProcessor, jtsGeometryCache, randomAccessFile,
configuration);
// SUB FILE META DATA IN CONTAINER HEADER
writeSubfileMetaDataToContainerHeader(dataProcessor.getZoomIntervalConfiguration(), i, currentFileSize,
subfileSize, containerHeaderBuffer);
currentFileSize += subfileSize;
}
randomAccessFile.seek(0);
randomAccessFile.write(containerHeaderBuffer.array(), 0, totalHeaderSize);
// WRITE FILE SIZE TO HEADER
long fileSize = randomAccessFile.length();
randomAccessFile.seek(OFFSET_FILE_SIZE);
randomAccessFile.writeLong(fileSize);
randomAccessFile.close();
CacheStats stats = jtsGeometryCache.stats();
LOGGER.fine("Tag values stats:\n" + OSMUtils.logValueTypeCount());
LOGGER.info("JTS Geometry cache hit rate: " + stats.hitRate());
LOGGER.info("JTS Geometry total load time: " + stats.totalLoadTime() / 1000);
LOGGER.info("Finished writing file.");
} | java | public static void writeFile(MapWriterConfiguration configuration, TileBasedDataProcessor dataProcessor)
throws IOException {
EXECUTOR_SERVICE = Executors.newFixedThreadPool(configuration.getThreads());
RandomAccessFile randomAccessFile = new RandomAccessFile(configuration.getOutputFile(), "rw");
int amountOfZoomIntervals = dataProcessor.getZoomIntervalConfiguration().getNumberOfZoomIntervals();
ByteBuffer containerHeaderBuffer = ByteBuffer.allocate(HEADER_BUFFER_SIZE);
// CONTAINER HEADER
int totalHeaderSize = writeHeaderBuffer(configuration, dataProcessor, containerHeaderBuffer);
// set to mark where zoomIntervalConfig starts
containerHeaderBuffer.reset();
final LoadingCache<TDWay, Geometry> jtsGeometryCache = CacheBuilder.newBuilder()
.maximumSize(JTS_GEOMETRY_CACHE_SIZE).concurrencyLevel(Runtime.getRuntime().availableProcessors() * 2)
.build(new JTSGeometryCacheLoader(dataProcessor));
// SUB FILES
// for each zoom interval write a sub file
long currentFileSize = totalHeaderSize;
for (int i = 0; i < amountOfZoomIntervals; i++) {
// SUB FILE INDEX AND DATA
long subfileSize = writeSubfile(currentFileSize, i, dataProcessor, jtsGeometryCache, randomAccessFile,
configuration);
// SUB FILE META DATA IN CONTAINER HEADER
writeSubfileMetaDataToContainerHeader(dataProcessor.getZoomIntervalConfiguration(), i, currentFileSize,
subfileSize, containerHeaderBuffer);
currentFileSize += subfileSize;
}
randomAccessFile.seek(0);
randomAccessFile.write(containerHeaderBuffer.array(), 0, totalHeaderSize);
// WRITE FILE SIZE TO HEADER
long fileSize = randomAccessFile.length();
randomAccessFile.seek(OFFSET_FILE_SIZE);
randomAccessFile.writeLong(fileSize);
randomAccessFile.close();
CacheStats stats = jtsGeometryCache.stats();
LOGGER.fine("Tag values stats:\n" + OSMUtils.logValueTypeCount());
LOGGER.info("JTS Geometry cache hit rate: " + stats.hitRate());
LOGGER.info("JTS Geometry total load time: " + stats.totalLoadTime() / 1000);
LOGGER.info("Finished writing file.");
} | [
"public",
"static",
"void",
"writeFile",
"(",
"MapWriterConfiguration",
"configuration",
",",
"TileBasedDataProcessor",
"dataProcessor",
")",
"throws",
"IOException",
"{",
"EXECUTOR_SERVICE",
"=",
"Executors",
".",
"newFixedThreadPool",
"(",
"configuration",
".",
"getThre... | Writes the map file according to the given configuration using the given data processor.
@param configuration the configuration
@param dataProcessor the data processor
@throws IOException thrown if any IO error occurs | [
"Writes",
"the",
"map",
"file",
"according",
"to",
"the",
"given",
"configuration",
"using",
"the",
"given",
"data",
"processor",
"."
] | train | https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-map-writer/src/main/java/org/mapsforge/map/writer/MapFileWriter.java#L353-L399 |
fommil/matrix-toolkits-java | src/main/java/no/uib/cipr/matrix/BandLU.java | BandLU.rcond | public double rcond(Matrix A, Norm norm) {
"""
Computes the reciprocal condition number, using either the infinity norm
of the 1 norm.
@param A
The matrix this is a decomposition of
@param norm
Either <code>Norm.One</code> or <code>Norm.Infinity</code>
@return The reciprocal condition number. Values close to unity indicate a
well-conditioned system, while numbers close to zero do not.
"""
if (norm != Norm.One && norm != Norm.Infinity)
throw new IllegalArgumentException(
"Only the 1 or the Infinity norms are supported");
if (A.numRows() != n)
throw new IllegalArgumentException("A.numRows() != n");
if (!A.isSquare())
throw new IllegalArgumentException("!A.isSquare()");
double anorm = A.norm(norm);
double[] work = new double[3 * n];
int[] lwork = new int[n];
intW info = new intW(0);
doubleW rcond = new doubleW(0);
LAPACK.getInstance().dgbcon(norm.netlib(), n, kl, ku, LU.getData(),
Matrices.ld(2 * kl + ku + 1), ipiv, anorm, rcond, work, lwork,
info);
if (info.val < 0)
throw new IllegalArgumentException();
return rcond.val;
} | java | public double rcond(Matrix A, Norm norm) {
if (norm != Norm.One && norm != Norm.Infinity)
throw new IllegalArgumentException(
"Only the 1 or the Infinity norms are supported");
if (A.numRows() != n)
throw new IllegalArgumentException("A.numRows() != n");
if (!A.isSquare())
throw new IllegalArgumentException("!A.isSquare()");
double anorm = A.norm(norm);
double[] work = new double[3 * n];
int[] lwork = new int[n];
intW info = new intW(0);
doubleW rcond = new doubleW(0);
LAPACK.getInstance().dgbcon(norm.netlib(), n, kl, ku, LU.getData(),
Matrices.ld(2 * kl + ku + 1), ipiv, anorm, rcond, work, lwork,
info);
if (info.val < 0)
throw new IllegalArgumentException();
return rcond.val;
} | [
"public",
"double",
"rcond",
"(",
"Matrix",
"A",
",",
"Norm",
"norm",
")",
"{",
"if",
"(",
"norm",
"!=",
"Norm",
".",
"One",
"&&",
"norm",
"!=",
"Norm",
".",
"Infinity",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Only the 1 or the Infinity norm... | Computes the reciprocal condition number, using either the infinity norm
of the 1 norm.
@param A
The matrix this is a decomposition of
@param norm
Either <code>Norm.One</code> or <code>Norm.Infinity</code>
@return The reciprocal condition number. Values close to unity indicate a
well-conditioned system, while numbers close to zero do not. | [
"Computes",
"the",
"reciprocal",
"condition",
"number",
"using",
"either",
"the",
"infinity",
"norm",
"of",
"the",
"1",
"norm",
"."
] | train | https://github.com/fommil/matrix-toolkits-java/blob/6157618bc86bcda3749af2a60bf869d8f3292960/src/main/java/no/uib/cipr/matrix/BandLU.java#L187-L211 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/NFRuleSet.java | NFRuleSet.setBestFractionRule | private void setBestFractionRule(int originalIndex, NFRule newRule, boolean rememberRule) {
"""
Determine the best fraction rule to use. Rules matching the decimal point from
DecimalFormatSymbols become the main set of rules to use.
@param originalIndex The index into nonNumericalRules
@param newRule The new rule to consider
@param rememberRule Should the new rule be added to fractionRules.
"""
if (rememberRule) {
if (fractionRules == null) {
fractionRules = new LinkedList<NFRule>();
}
fractionRules.add(newRule);
}
NFRule bestResult = nonNumericalRules[originalIndex];
if (bestResult == null) {
nonNumericalRules[originalIndex] = newRule;
}
else {
// We have more than one. Which one is better?
DecimalFormatSymbols decimalFormatSymbols = owner.getDecimalFormatSymbols();
if (decimalFormatSymbols.getDecimalSeparator() == newRule.getDecimalPoint()) {
nonNumericalRules[originalIndex] = newRule;
}
// else leave it alone
}
} | java | private void setBestFractionRule(int originalIndex, NFRule newRule, boolean rememberRule) {
if (rememberRule) {
if (fractionRules == null) {
fractionRules = new LinkedList<NFRule>();
}
fractionRules.add(newRule);
}
NFRule bestResult = nonNumericalRules[originalIndex];
if (bestResult == null) {
nonNumericalRules[originalIndex] = newRule;
}
else {
// We have more than one. Which one is better?
DecimalFormatSymbols decimalFormatSymbols = owner.getDecimalFormatSymbols();
if (decimalFormatSymbols.getDecimalSeparator() == newRule.getDecimalPoint()) {
nonNumericalRules[originalIndex] = newRule;
}
// else leave it alone
}
} | [
"private",
"void",
"setBestFractionRule",
"(",
"int",
"originalIndex",
",",
"NFRule",
"newRule",
",",
"boolean",
"rememberRule",
")",
"{",
"if",
"(",
"rememberRule",
")",
"{",
"if",
"(",
"fractionRules",
"==",
"null",
")",
"{",
"fractionRules",
"=",
"new",
"... | Determine the best fraction rule to use. Rules matching the decimal point from
DecimalFormatSymbols become the main set of rules to use.
@param originalIndex The index into nonNumericalRules
@param newRule The new rule to consider
@param rememberRule Should the new rule be added to fractionRules. | [
"Determine",
"the",
"best",
"fraction",
"rule",
"to",
"use",
".",
"Rules",
"matching",
"the",
"decimal",
"point",
"from",
"DecimalFormatSymbols",
"become",
"the",
"main",
"set",
"of",
"rules",
"to",
"use",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/NFRuleSet.java#L267-L286 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.