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 |
|---|---|---|---|---|---|---|---|---|---|---|
geomajas/geomajas-project-client-gwt2 | common-gwt/common-gwt/src/main/java/org/geomajas/gwt/client/util/impl/DomImpl.java | DomImpl.disAssembleId | public String disAssembleId(String id, String... suffixes) {
"""
Disassemble an DOM id, removing suffixes.
@param id
base id
@param suffixes
suffixes to remove
@return id
"""
int count = 0;
for (String s : suffixes) {
count += s.length() + Dom.ID_SEPARATOR.length();
}
return id.substring(0, id.length() - count);
} | java | public String disAssembleId(String id, String... suffixes) {
int count = 0;
for (String s : suffixes) {
count += s.length() + Dom.ID_SEPARATOR.length();
}
return id.substring(0, id.length() - count);
} | [
"public",
"String",
"disAssembleId",
"(",
"String",
"id",
",",
"String",
"...",
"suffixes",
")",
"{",
"int",
"count",
"=",
"0",
";",
"for",
"(",
"String",
"s",
":",
"suffixes",
")",
"{",
"count",
"+=",
"s",
".",
"length",
"(",
")",
"+",
"Dom",
".",... | Disassemble an DOM id, removing suffixes.
@param id
base id
@param suffixes
suffixes to remove
@return id | [
"Disassemble",
"an",
"DOM",
"id",
"removing",
"suffixes",
"."
] | train | https://github.com/geomajas/geomajas-project-client-gwt2/blob/bd8d7904e861fa80522eed7b83c4ea99844180c7/common-gwt/common-gwt/src/main/java/org/geomajas/gwt/client/util/impl/DomImpl.java#L70-L76 |
bazaarvoice/emodb | auth/auth-core/src/main/java/com/bazaarvoice/emodb/auth/jersey/AuthResourceFilterFactory.java | AuthResourceFilterFactory.getSubstitutionIndex | private int getSubstitutionIndex(String param, String path) {
"""
Gets the index in a path where the substitution parameter was found, or the negative of the number of segments
in the path if it was not found. For example:
assert(getSubstitutionIndex("id", "resource/{id}/move") == 1)
assert(getSubstitutionIndex("not_found", "path/with/four/segments") == -4)
"""
final String match = String.format("{%s}", param);
if (path.startsWith("/")) {
path = path.substring(1);
}
if (path.endsWith("/")) {
path = path.substring(0, path.length()-1);
}
String[] segments = path.split("/");
for (int i=0; i < segments.length; i++) {
if (match.equals(segments[i])) {
return i;
}
}
return -segments.length;
} | java | private int getSubstitutionIndex(String param, String path) {
final String match = String.format("{%s}", param);
if (path.startsWith("/")) {
path = path.substring(1);
}
if (path.endsWith("/")) {
path = path.substring(0, path.length()-1);
}
String[] segments = path.split("/");
for (int i=0; i < segments.length; i++) {
if (match.equals(segments[i])) {
return i;
}
}
return -segments.length;
} | [
"private",
"int",
"getSubstitutionIndex",
"(",
"String",
"param",
",",
"String",
"path",
")",
"{",
"final",
"String",
"match",
"=",
"String",
".",
"format",
"(",
"\"{%s}\"",
",",
"param",
")",
";",
"if",
"(",
"path",
".",
"startsWith",
"(",
"\"/\"",
")",... | Gets the index in a path where the substitution parameter was found, or the negative of the number of segments
in the path if it was not found. For example:
assert(getSubstitutionIndex("id", "resource/{id}/move") == 1)
assert(getSubstitutionIndex("not_found", "path/with/four/segments") == -4) | [
"Gets",
"the",
"index",
"in",
"a",
"path",
"where",
"the",
"substitution",
"parameter",
"was",
"found",
"or",
"the",
"negative",
"of",
"the",
"number",
"of",
"segments",
"in",
"the",
"path",
"if",
"it",
"was",
"not",
"found",
".",
"For",
"example",
":"
] | train | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/auth/auth-core/src/main/java/com/bazaarvoice/emodb/auth/jersey/AuthResourceFilterFactory.java#L170-L188 |
j256/ormlite-core | src/main/java/com/j256/ormlite/stmt/StatementExecutor.java | StatementExecutor.queryForId | public T queryForId(DatabaseConnection databaseConnection, ID id, ObjectCache objectCache) throws SQLException {
"""
Return the object associated with the id or null if none. This does a SQL
{@code SELECT col1,col2,... FROM ... WHERE ... = id} type query.
"""
if (mappedQueryForId == null) {
mappedQueryForId = MappedQueryForFieldEq.build(dao, tableInfo, null);
}
return mappedQueryForId.execute(databaseConnection, id, objectCache);
} | java | public T queryForId(DatabaseConnection databaseConnection, ID id, ObjectCache objectCache) throws SQLException {
if (mappedQueryForId == null) {
mappedQueryForId = MappedQueryForFieldEq.build(dao, tableInfo, null);
}
return mappedQueryForId.execute(databaseConnection, id, objectCache);
} | [
"public",
"T",
"queryForId",
"(",
"DatabaseConnection",
"databaseConnection",
",",
"ID",
"id",
",",
"ObjectCache",
"objectCache",
")",
"throws",
"SQLException",
"{",
"if",
"(",
"mappedQueryForId",
"==",
"null",
")",
"{",
"mappedQueryForId",
"=",
"MappedQueryForField... | Return the object associated with the id or null if none. This does a SQL
{@code SELECT col1,col2,... FROM ... WHERE ... = id} type query. | [
"Return",
"the",
"object",
"associated",
"with",
"the",
"id",
"or",
"null",
"if",
"none",
".",
"This",
"does",
"a",
"SQL",
"{"
] | train | https://github.com/j256/ormlite-core/blob/154d85bbb9614a0ea65a012251257831fb4fba21/src/main/java/com/j256/ormlite/stmt/StatementExecutor.java#L90-L95 |
atomix/catalyst | serializer/src/main/java/io/atomix/catalyst/serializer/util/CatalystSerializableSerializer.java | CatalystSerializableSerializer.readReference | @SuppressWarnings("unchecked")
private T readReference(Class<T> type, BufferInput<?> buffer, Serializer serializer) {
"""
Reads an object reference.
@param type The reference type.
@param buffer The reference buffer.
@param serializer The serializer with which the object is being read.
@return The reference to read.
"""
ReferencePool<?> pool = pools.get(type);
if (pool == null) {
Constructor<?> constructor = constructorMap.get(type);
if (constructor == null) {
try {
constructor = type.getDeclaredConstructor(ReferenceManager.class);
constructor.setAccessible(true);
constructorMap.put(type, constructor);
} catch (NoSuchMethodException e) {
throw new SerializationException("failed to instantiate reference: must provide a single argument constructor", e);
}
}
pool = new ReferencePool<>(createFactory(constructor));
pools.put(type, pool);
}
T object = (T) pool.acquire();
object.readObject(buffer, serializer);
return object;
} | java | @SuppressWarnings("unchecked")
private T readReference(Class<T> type, BufferInput<?> buffer, Serializer serializer) {
ReferencePool<?> pool = pools.get(type);
if (pool == null) {
Constructor<?> constructor = constructorMap.get(type);
if (constructor == null) {
try {
constructor = type.getDeclaredConstructor(ReferenceManager.class);
constructor.setAccessible(true);
constructorMap.put(type, constructor);
} catch (NoSuchMethodException e) {
throw new SerializationException("failed to instantiate reference: must provide a single argument constructor", e);
}
}
pool = new ReferencePool<>(createFactory(constructor));
pools.put(type, pool);
}
T object = (T) pool.acquire();
object.readObject(buffer, serializer);
return object;
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"private",
"T",
"readReference",
"(",
"Class",
"<",
"T",
">",
"type",
",",
"BufferInput",
"<",
"?",
">",
"buffer",
",",
"Serializer",
"serializer",
")",
"{",
"ReferencePool",
"<",
"?",
">",
"pool",
"=",
... | Reads an object reference.
@param type The reference type.
@param buffer The reference buffer.
@param serializer The serializer with which the object is being read.
@return The reference to read. | [
"Reads",
"an",
"object",
"reference",
"."
] | train | https://github.com/atomix/catalyst/blob/140e762cb975cd8ee1fd85119043c5b8bf917c5c/serializer/src/main/java/io/atomix/catalyst/serializer/util/CatalystSerializableSerializer.java#L71-L92 |
datacleaner/DataCleaner | engine/core/src/main/java/org/datacleaner/descriptors/ClasspathScanDescriptorProvider.java | ClasspathScanDescriptorProvider.scanPackage | public ClasspathScanDescriptorProvider scanPackage(final String packageName, final boolean recursive) {
"""
Scans a package in the classpath (of the current thread's context classloader) for annotated components.
@param packageName the package name to scan
@param recursive whether or not to scan subpackages recursively
@return
"""
return scanPackage(packageName, recursive, ClassLoaderUtils.getParentClassLoader(), false);
} | java | public ClasspathScanDescriptorProvider scanPackage(final String packageName, final boolean recursive) {
return scanPackage(packageName, recursive, ClassLoaderUtils.getParentClassLoader(), false);
} | [
"public",
"ClasspathScanDescriptorProvider",
"scanPackage",
"(",
"final",
"String",
"packageName",
",",
"final",
"boolean",
"recursive",
")",
"{",
"return",
"scanPackage",
"(",
"packageName",
",",
"recursive",
",",
"ClassLoaderUtils",
".",
"getParentClassLoader",
"(",
... | Scans a package in the classpath (of the current thread's context classloader) for annotated components.
@param packageName the package name to scan
@param recursive whether or not to scan subpackages recursively
@return | [
"Scans",
"a",
"package",
"in",
"the",
"classpath",
"(",
"of",
"the",
"current",
"thread",
"s",
"context",
"classloader",
")",
"for",
"annotated",
"components",
"."
] | train | https://github.com/datacleaner/DataCleaner/blob/9aa01fdac3560cef51c55df3cb2ac5c690b57639/engine/core/src/main/java/org/datacleaner/descriptors/ClasspathScanDescriptorProvider.java#L179-L181 |
datumbox/datumbox-framework | datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/sampling/SimpleRandomSampling.java | SimpleRandomSampling.minimumSampleSizeForGivenDandMaximumRisk | public static int minimumSampleSizeForGivenDandMaximumRisk(double d, double aLevel, double populationStd, int populationN) {
"""
Returns the minimum required sample size when we set a predefined limit d and a maximum probability Risk a for finite population size
@param d
@param aLevel
@param populationStd
@param populationN
@return
"""
if(populationN<=0 || aLevel<=0 || d<=0) {
throw new IllegalArgumentException("All the parameters must be positive.");
}
double a = 1.0 - aLevel/2.0;
double Za = ContinuousDistributions.gaussInverseCdf(a);
double V = Math.pow(d/Za,2);
double Ssquare = populationStd*populationStd;
double minimumSampleN = (Ssquare/V) * (1.0 / (1.0 + Ssquare/(populationN*V)) );
/*
double minimumSampleN=populationN/(
1.0+populationN*pow(d/(Za*populationStd),2)
);
*/
return (int)Math.ceil(minimumSampleN);
} | java | public static int minimumSampleSizeForGivenDandMaximumRisk(double d, double aLevel, double populationStd, int populationN) {
if(populationN<=0 || aLevel<=0 || d<=0) {
throw new IllegalArgumentException("All the parameters must be positive.");
}
double a = 1.0 - aLevel/2.0;
double Za = ContinuousDistributions.gaussInverseCdf(a);
double V = Math.pow(d/Za,2);
double Ssquare = populationStd*populationStd;
double minimumSampleN = (Ssquare/V) * (1.0 / (1.0 + Ssquare/(populationN*V)) );
/*
double minimumSampleN=populationN/(
1.0+populationN*pow(d/(Za*populationStd),2)
);
*/
return (int)Math.ceil(minimumSampleN);
} | [
"public",
"static",
"int",
"minimumSampleSizeForGivenDandMaximumRisk",
"(",
"double",
"d",
",",
"double",
"aLevel",
",",
"double",
"populationStd",
",",
"int",
"populationN",
")",
"{",
"if",
"(",
"populationN",
"<=",
"0",
"||",
"aLevel",
"<=",
"0",
"||",
"d",
... | Returns the minimum required sample size when we set a predefined limit d and a maximum probability Risk a for finite population size
@param d
@param aLevel
@param populationStd
@param populationN
@return | [
"Returns",
"the",
"minimum",
"required",
"sample",
"size",
"when",
"we",
"set",
"a",
"predefined",
"limit",
"d",
"and",
"a",
"maximum",
"probability",
"Risk",
"a",
"for",
"finite",
"population",
"size"
] | train | https://github.com/datumbox/datumbox-framework/blob/909dff0476e80834f05ecdde0624dd2390e9b0ca/datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/sampling/SimpleRandomSampling.java#L296-L314 |
riversun/string-grabber | src/main/java/org/riversun/string_grabber/StringCropper.java | StringCropper.removeHead | public String removeHead(String srcStr, int charCount) {
"""
Return the rest of the string that is cropped the number of chars from
the beginning
@param srcStr
@param charCount
@return
"""
return getRightOf(srcStr, srcStr.length() - charCount);
} | java | public String removeHead(String srcStr, int charCount) {
return getRightOf(srcStr, srcStr.length() - charCount);
} | [
"public",
"String",
"removeHead",
"(",
"String",
"srcStr",
",",
"int",
"charCount",
")",
"{",
"return",
"getRightOf",
"(",
"srcStr",
",",
"srcStr",
".",
"length",
"(",
")",
"-",
"charCount",
")",
";",
"}"
] | Return the rest of the string that is cropped the number of chars from
the beginning
@param srcStr
@param charCount
@return | [
"Return",
"the",
"rest",
"of",
"the",
"string",
"that",
"is",
"cropped",
"the",
"number",
"of",
"chars",
"from",
"the",
"beginning"
] | train | https://github.com/riversun/string-grabber/blob/b5aadc21fe15f50d35392188dec6ab81dcf8d464/src/main/java/org/riversun/string_grabber/StringCropper.java#L431-L433 |
liyiorg/weixin-popular | src/main/java/weixin/popular/client/HttpClientFactory.java | HttpClientFactory.createKeyMaterialHttpClient | public static CloseableHttpClient createKeyMaterialHttpClient(KeyStore keystore,String keyPassword,String[] supportedProtocols,int timeout,int retryExecutionCount) {
"""
Key store 类型HttpClient
@param keystore keystore
@param keyPassword keyPassword
@param supportedProtocols supportedProtocols
@param timeout timeout
@param retryExecutionCount retryExecutionCount
@return CloseableHttpClient
"""
try {
SSLContext sslContext = SSLContexts.custom().useSSL().loadKeyMaterial(keystore, keyPassword.toCharArray()).build();
SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext,supportedProtocols,
null,SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(timeout).build();
return HttpClientBuilder.create()
.setDefaultSocketConfig(socketConfig)
.setSSLSocketFactory(sf)
.setRetryHandler(new HttpRequestRetryHandlerImpl(retryExecutionCount))
.build();
} catch (KeyManagementException e) {
logger.error("", e);
} catch (NoSuchAlgorithmException e) {
logger.error("", e);
} catch (UnrecoverableKeyException e) {
logger.error("", e);
} catch (KeyStoreException e) {
logger.error("", e);
}
return null;
} | java | public static CloseableHttpClient createKeyMaterialHttpClient(KeyStore keystore,String keyPassword,String[] supportedProtocols,int timeout,int retryExecutionCount) {
try {
SSLContext sslContext = SSLContexts.custom().useSSL().loadKeyMaterial(keystore, keyPassword.toCharArray()).build();
SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext,supportedProtocols,
null,SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(timeout).build();
return HttpClientBuilder.create()
.setDefaultSocketConfig(socketConfig)
.setSSLSocketFactory(sf)
.setRetryHandler(new HttpRequestRetryHandlerImpl(retryExecutionCount))
.build();
} catch (KeyManagementException e) {
logger.error("", e);
} catch (NoSuchAlgorithmException e) {
logger.error("", e);
} catch (UnrecoverableKeyException e) {
logger.error("", e);
} catch (KeyStoreException e) {
logger.error("", e);
}
return null;
} | [
"public",
"static",
"CloseableHttpClient",
"createKeyMaterialHttpClient",
"(",
"KeyStore",
"keystore",
",",
"String",
"keyPassword",
",",
"String",
"[",
"]",
"supportedProtocols",
",",
"int",
"timeout",
",",
"int",
"retryExecutionCount",
")",
"{",
"try",
"{",
"SSLCo... | Key store 类型HttpClient
@param keystore keystore
@param keyPassword keyPassword
@param supportedProtocols supportedProtocols
@param timeout timeout
@param retryExecutionCount retryExecutionCount
@return CloseableHttpClient | [
"Key",
"store",
"类型HttpClient"
] | train | https://github.com/liyiorg/weixin-popular/blob/c64255292d41463bdb671938feaabf42a335d82c/src/main/java/weixin/popular/client/HttpClientFactory.java#L96-L117 |
gallandarakhneorg/afc | advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/mapelement/MapComposedElement.java | MapComposedElement.getPointIndex | @Pure
public int getPointIndex(int groupIndex, Point2D<?, ?> point2d) {
"""
Replies the global index of the point2d in the given group.
@param groupIndex the group index.
@param point2d is the point in the group
@return the global index of the point or <code>-1</code> if not found
"""
if (!this.containsPoint(point2d, groupIndex)) {
return -1;
}
Point2d cur = null;
int pos = -1;
for (int i = 0; i < getPointCountInGroup(groupIndex); ++i) {
cur = getPointAt(groupIndex, i);
if (cur.epsilonEquals(point2d, MapElementConstants.POINT_FUSION_DISTANCE)) {
pos = i;
break;
}
}
return (firstInGroup(groupIndex) + pos * 2) / 2;
} | java | @Pure
public int getPointIndex(int groupIndex, Point2D<?, ?> point2d) {
if (!this.containsPoint(point2d, groupIndex)) {
return -1;
}
Point2d cur = null;
int pos = -1;
for (int i = 0; i < getPointCountInGroup(groupIndex); ++i) {
cur = getPointAt(groupIndex, i);
if (cur.epsilonEquals(point2d, MapElementConstants.POINT_FUSION_DISTANCE)) {
pos = i;
break;
}
}
return (firstInGroup(groupIndex) + pos * 2) / 2;
} | [
"@",
"Pure",
"public",
"int",
"getPointIndex",
"(",
"int",
"groupIndex",
",",
"Point2D",
"<",
"?",
",",
"?",
">",
"point2d",
")",
"{",
"if",
"(",
"!",
"this",
".",
"containsPoint",
"(",
"point2d",
",",
"groupIndex",
")",
")",
"{",
"return",
"-",
"1",... | Replies the global index of the point2d in the given group.
@param groupIndex the group index.
@param point2d is the point in the group
@return the global index of the point or <code>-1</code> if not found | [
"Replies",
"the",
"global",
"index",
"of",
"the",
"point2d",
"in",
"the",
"given",
"group",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/mapelement/MapComposedElement.java#L438-L454 |
tvesalainen/util | util/src/main/java/org/vesalainen/math/Vectors.java | Vectors.isClockwise | public static final boolean isClockwise(double ox, double oy, double x1, double y1, double x2, double y2) {
"""
Returns true if vector (x2, y2) is clockwise of (x1, y1) in (ox, oy) centered
coordinate.
@param ox
@param oy
@param x1
@param y1
@param x2
@param y2
@return
"""
return isClockwise(x1-ox, y1-oy, x2-ox, y2-oy);
} | java | public static final boolean isClockwise(double ox, double oy, double x1, double y1, double x2, double y2)
{
return isClockwise(x1-ox, y1-oy, x2-ox, y2-oy);
} | [
"public",
"static",
"final",
"boolean",
"isClockwise",
"(",
"double",
"ox",
",",
"double",
"oy",
",",
"double",
"x1",
",",
"double",
"y1",
",",
"double",
"x2",
",",
"double",
"y2",
")",
"{",
"return",
"isClockwise",
"(",
"x1",
"-",
"ox",
",",
"y1",
"... | Returns true if vector (x2, y2) is clockwise of (x1, y1) in (ox, oy) centered
coordinate.
@param ox
@param oy
@param x1
@param y1
@param x2
@param y2
@return | [
"Returns",
"true",
"if",
"vector",
"(",
"x2",
"y2",
")",
"is",
"clockwise",
"of",
"(",
"x1",
"y1",
")",
"in",
"(",
"ox",
"oy",
")",
"centered",
"coordinate",
"."
] | train | https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/math/Vectors.java#L49-L52 |
Red5/red5-server-common | src/main/java/org/red5/server/api/persistence/PersistenceUtils.java | PersistenceUtils.getPersistenceStore | public static IPersistenceStore getPersistenceStore(ResourcePatternResolver resolver, String className) throws Exception {
"""
Returns persistence store object. Persistence store is a special object that stores persistence objects and provides methods to manipulate them (save, load, remove, list).
@param resolver
Resolves connection pattern into Resource object
@param className
Name of persistence class
@return IPersistence store object that provides methods for persistence object handling
@throws Exception
if error
"""
Class<?> persistenceClass = Class.forName(className);
Constructor<?> constructor = getPersistenceStoreConstructor(persistenceClass, resolver.getClass().getInterfaces());
if (constructor == null) {
// Search in superclasses of the object.
Class<?> superClass = resolver.getClass().getSuperclass();
while (superClass != null) {
constructor = getPersistenceStoreConstructor(persistenceClass, superClass.getInterfaces());
if (constructor != null) {
break;
}
superClass = superClass.getSuperclass();
}
}
if (constructor == null) {
throw new NoSuchMethodException();
}
return (IPersistenceStore) constructor.newInstance(new Object[] { resolver });
} | java | public static IPersistenceStore getPersistenceStore(ResourcePatternResolver resolver, String className) throws Exception {
Class<?> persistenceClass = Class.forName(className);
Constructor<?> constructor = getPersistenceStoreConstructor(persistenceClass, resolver.getClass().getInterfaces());
if (constructor == null) {
// Search in superclasses of the object.
Class<?> superClass = resolver.getClass().getSuperclass();
while (superClass != null) {
constructor = getPersistenceStoreConstructor(persistenceClass, superClass.getInterfaces());
if (constructor != null) {
break;
}
superClass = superClass.getSuperclass();
}
}
if (constructor == null) {
throw new NoSuchMethodException();
}
return (IPersistenceStore) constructor.newInstance(new Object[] { resolver });
} | [
"public",
"static",
"IPersistenceStore",
"getPersistenceStore",
"(",
"ResourcePatternResolver",
"resolver",
",",
"String",
"className",
")",
"throws",
"Exception",
"{",
"Class",
"<",
"?",
">",
"persistenceClass",
"=",
"Class",
".",
"forName",
"(",
"className",
")",
... | Returns persistence store object. Persistence store is a special object that stores persistence objects and provides methods to manipulate them (save, load, remove, list).
@param resolver
Resolves connection pattern into Resource object
@param className
Name of persistence class
@return IPersistence store object that provides methods for persistence object handling
@throws Exception
if error | [
"Returns",
"persistence",
"store",
"object",
".",
"Persistence",
"store",
"is",
"a",
"special",
"object",
"that",
"stores",
"persistence",
"objects",
"and",
"provides",
"methods",
"to",
"manipulate",
"them",
"(",
"save",
"load",
"remove",
"list",
")",
"."
] | train | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/api/persistence/PersistenceUtils.java#L73-L91 |
alkacon/opencms-core | src/org/opencms/flex/CmsFlexResponse.java | CmsFlexResponse.setDateHeader | @Override
public void setDateHeader(String name, long date) {
"""
Method overload from the standard HttpServletRequest API.<p>
@see javax.servlet.http.HttpServletResponse#setDateHeader(java.lang.String, long)
"""
setHeader(name, CmsDateUtil.getHeaderDate(date));
} | java | @Override
public void setDateHeader(String name, long date) {
setHeader(name, CmsDateUtil.getHeaderDate(date));
} | [
"@",
"Override",
"public",
"void",
"setDateHeader",
"(",
"String",
"name",
",",
"long",
"date",
")",
"{",
"setHeader",
"(",
"name",
",",
"CmsDateUtil",
".",
"getHeaderDate",
"(",
"date",
")",
")",
";",
"}"
] | Method overload from the standard HttpServletRequest API.<p>
@see javax.servlet.http.HttpServletResponse#setDateHeader(java.lang.String, long) | [
"Method",
"overload",
"from",
"the",
"standard",
"HttpServletRequest",
"API",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/flex/CmsFlexResponse.java#L741-L745 |
alkacon/opencms-core | src/org/opencms/ui/login/CmsTokenValidator.java | CmsTokenValidator.createToken | public static String createToken(CmsObject cms, CmsUser user, long currentTime) throws CmsException {
"""
Creates a new token for the given user and stores it in the user's additional info.<p>
@param cms the CMS context
@param user the user
@param currentTime the current time
@return the authorization token
@throws CmsException if something goes wrong
"""
String randomKey = RandomStringUtils.randomAlphanumeric(8);
String value = CmsEncoder.encodeStringsAsBase64Parameter(Arrays.asList(randomKey, "" + currentTime));
user.setAdditionalInfo(ADDINFO_KEY, value);
cms.writeUser(user);
return CmsEncoder.encodeStringsAsBase64Parameter(Arrays.asList(user.getName(), randomKey));
} | java | public static String createToken(CmsObject cms, CmsUser user, long currentTime) throws CmsException {
String randomKey = RandomStringUtils.randomAlphanumeric(8);
String value = CmsEncoder.encodeStringsAsBase64Parameter(Arrays.asList(randomKey, "" + currentTime));
user.setAdditionalInfo(ADDINFO_KEY, value);
cms.writeUser(user);
return CmsEncoder.encodeStringsAsBase64Parameter(Arrays.asList(user.getName(), randomKey));
} | [
"public",
"static",
"String",
"createToken",
"(",
"CmsObject",
"cms",
",",
"CmsUser",
"user",
",",
"long",
"currentTime",
")",
"throws",
"CmsException",
"{",
"String",
"randomKey",
"=",
"RandomStringUtils",
".",
"randomAlphanumeric",
"(",
"8",
")",
";",
"String"... | Creates a new token for the given user and stores it in the user's additional info.<p>
@param cms the CMS context
@param user the user
@param currentTime the current time
@return the authorization token
@throws CmsException if something goes wrong | [
"Creates",
"a",
"new",
"token",
"for",
"the",
"given",
"user",
"and",
"stores",
"it",
"in",
"the",
"user",
"s",
"additional",
"info",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/login/CmsTokenValidator.java#L80-L87 |
messenger4j/messenger4j | src/main/java/com/github/messenger4j/webhook/SignatureUtil.java | SignatureUtil.isSignatureValid | public static boolean isSignatureValid(String payload, String signature, String appSecret) {
"""
Verifies the provided signature of the payload.
@param payload the request body {@code JSON payload}
@param signature the SHA1 signature of the request payload
@param appSecret the {@code Application Secret} of the Facebook App
@return {@code true} if the verification was successful, otherwise {@code false}
"""
try {
final Mac mac = Mac.getInstance(HMAC_SHA1);
mac.init(new SecretKeySpec(appSecret.getBytes(), HMAC_SHA1));
final byte[] rawHmac = mac.doFinal(payload.getBytes());
final String expected = signature.substring(5);
final String actual = bytesToHexString(rawHmac);
return expected.equals(actual);
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new RuntimeException(e);
}
} | java | public static boolean isSignatureValid(String payload, String signature, String appSecret) {
try {
final Mac mac = Mac.getInstance(HMAC_SHA1);
mac.init(new SecretKeySpec(appSecret.getBytes(), HMAC_SHA1));
final byte[] rawHmac = mac.doFinal(payload.getBytes());
final String expected = signature.substring(5);
final String actual = bytesToHexString(rawHmac);
return expected.equals(actual);
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new RuntimeException(e);
}
} | [
"public",
"static",
"boolean",
"isSignatureValid",
"(",
"String",
"payload",
",",
"String",
"signature",
",",
"String",
"appSecret",
")",
"{",
"try",
"{",
"final",
"Mac",
"mac",
"=",
"Mac",
".",
"getInstance",
"(",
"HMAC_SHA1",
")",
";",
"mac",
".",
"init"... | Verifies the provided signature of the payload.
@param payload the request body {@code JSON payload}
@param signature the SHA1 signature of the request payload
@param appSecret the {@code Application Secret} of the Facebook App
@return {@code true} if the verification was successful, otherwise {@code false} | [
"Verifies",
"the",
"provided",
"signature",
"of",
"the",
"payload",
"."
] | train | https://github.com/messenger4j/messenger4j/blob/b45d3dad035e683fcec749c463b645e5567fcf72/src/main/java/com/github/messenger4j/webhook/SignatureUtil.java#L28-L41 |
FedericoPecora/meta-csp-framework | src/main/java/org/metacsp/multi/spatioTemporal/paths/TrajectoryEnvelopeSolver.java | TrajectoryEnvelopeSolver.createEnvelopes | public HashMap<Integer,ArrayList<TrajectoryEnvelope>> createEnvelopes(int firstRobotID, long durationFirstParking, long durationLastParking, Coordinate[] footprint, String ... pathFiles) {
"""
Create a trajectory envelope for each given reference to a file containing a path.
Robot IDs are assigned starting from the given integer. This method creates three envelopes for each
path: the main {@link TrajectoryEnvelope} covering the path; one {@link TrajectoryEnvelope} for the
starting position of the robot; and one one {@link TrajectoryEnvelope} for the final parking position
of the robot. The three envelopes are constrained with {@link AllenIntervalConstraint.Type#Meets} constraints.
The two parking envelopes have a given duration.
@param firstRobotID The starting robot ID.
@param durationFirstParking The duration of the first parking {@link TrajectoryEnvelope}.
@param durationLastParking The duration of the final parking {@link TrajectoryEnvelope}.
@param footprint Coordinates representing the footprint of the robot.
@param pathFiles The files containing paths over which to create the {@link TrajectoryEnvelope}s.
@return A mapping between robot IDs and the newly created sets of {@link TrajectoryEnvelope}s.
"""
Trajectory[] trajectories = new Trajectory[pathFiles.length];
for (int i = 0; i < pathFiles.length; i++) {
trajectories[i] = new Trajectory(pathFiles[i]);
}
return createEnvelopes(firstRobotID, durationFirstParking, durationLastParking, footprint, trajectories);
} | java | public HashMap<Integer,ArrayList<TrajectoryEnvelope>> createEnvelopes(int firstRobotID, long durationFirstParking, long durationLastParking, Coordinate[] footprint, String ... pathFiles) {
Trajectory[] trajectories = new Trajectory[pathFiles.length];
for (int i = 0; i < pathFiles.length; i++) {
trajectories[i] = new Trajectory(pathFiles[i]);
}
return createEnvelopes(firstRobotID, durationFirstParking, durationLastParking, footprint, trajectories);
} | [
"public",
"HashMap",
"<",
"Integer",
",",
"ArrayList",
"<",
"TrajectoryEnvelope",
">",
">",
"createEnvelopes",
"(",
"int",
"firstRobotID",
",",
"long",
"durationFirstParking",
",",
"long",
"durationLastParking",
",",
"Coordinate",
"[",
"]",
"footprint",
",",
"Stri... | Create a trajectory envelope for each given reference to a file containing a path.
Robot IDs are assigned starting from the given integer. This method creates three envelopes for each
path: the main {@link TrajectoryEnvelope} covering the path; one {@link TrajectoryEnvelope} for the
starting position of the robot; and one one {@link TrajectoryEnvelope} for the final parking position
of the robot. The three envelopes are constrained with {@link AllenIntervalConstraint.Type#Meets} constraints.
The two parking envelopes have a given duration.
@param firstRobotID The starting robot ID.
@param durationFirstParking The duration of the first parking {@link TrajectoryEnvelope}.
@param durationLastParking The duration of the final parking {@link TrajectoryEnvelope}.
@param footprint Coordinates representing the footprint of the robot.
@param pathFiles The files containing paths over which to create the {@link TrajectoryEnvelope}s.
@return A mapping between robot IDs and the newly created sets of {@link TrajectoryEnvelope}s. | [
"Create",
"a",
"trajectory",
"envelope",
"for",
"each",
"given",
"reference",
"to",
"a",
"file",
"containing",
"a",
"path",
".",
"Robot",
"IDs",
"are",
"assigned",
"starting",
"from",
"the",
"given",
"integer",
".",
"This",
"method",
"creates",
"three",
"env... | train | https://github.com/FedericoPecora/meta-csp-framework/blob/42aaef2e2b76d0f738427f0dd9653c4f62b40517/src/main/java/org/metacsp/multi/spatioTemporal/paths/TrajectoryEnvelopeSolver.java#L319-L326 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_06_01/src/main/java/com/microsoft/azure/management/network/v2018_06_01/implementation/ApplicationSecurityGroupsInner.java | ApplicationSecurityGroupsInner.beginCreateOrUpdateAsync | public Observable<ApplicationSecurityGroupInner> beginCreateOrUpdateAsync(String resourceGroupName, String applicationSecurityGroupName, ApplicationSecurityGroupInner parameters) {
"""
Creates or updates an application security group.
@param resourceGroupName The name of the resource group.
@param applicationSecurityGroupName The name of the application security group.
@param parameters Parameters supplied to the create or update ApplicationSecurityGroup operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ApplicationSecurityGroupInner object
"""
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, applicationSecurityGroupName, parameters).map(new Func1<ServiceResponse<ApplicationSecurityGroupInner>, ApplicationSecurityGroupInner>() {
@Override
public ApplicationSecurityGroupInner call(ServiceResponse<ApplicationSecurityGroupInner> response) {
return response.body();
}
});
} | java | public Observable<ApplicationSecurityGroupInner> beginCreateOrUpdateAsync(String resourceGroupName, String applicationSecurityGroupName, ApplicationSecurityGroupInner parameters) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, applicationSecurityGroupName, parameters).map(new Func1<ServiceResponse<ApplicationSecurityGroupInner>, ApplicationSecurityGroupInner>() {
@Override
public ApplicationSecurityGroupInner call(ServiceResponse<ApplicationSecurityGroupInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"ApplicationSecurityGroupInner",
">",
"beginCreateOrUpdateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"applicationSecurityGroupName",
",",
"ApplicationSecurityGroupInner",
"parameters",
")",
"{",
"return",
"beginCreateOrUpdateWithServic... | Creates or updates an application security group.
@param resourceGroupName The name of the resource group.
@param applicationSecurityGroupName The name of the application security group.
@param parameters Parameters supplied to the create or update ApplicationSecurityGroup operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ApplicationSecurityGroupInner object | [
"Creates",
"or",
"updates",
"an",
"application",
"security",
"group",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_06_01/src/main/java/com/microsoft/azure/management/network/v2018_06_01/implementation/ApplicationSecurityGroupsInner.java#L453-L460 |
liyiorg/weixin-popular | src/main/java/weixin/popular/api/PayMchAPI.java | PayMchAPI.payMicropay | public static MicropayResult payMicropay(Micropay micropay,String key) {
"""
刷卡支付 提交被扫支付API
@param micropay micropay
@param key key
@return MicropayResult
"""
Map<String,String> map = MapUtil.objectToMap(micropay);
//@since 2.8.14 detail 字段签名处理
if(micropay.getDetail() != null){
map.put("detail",JsonUtil.toJSONString(micropay.getDetail()));
}
String sign = SignatureUtil.generateSign(map,micropay.getSign_type(),key);
micropay.setSign(sign);
String closeorderXML = XMLConverUtil.convertToXML(micropay);
HttpUriRequest httpUriRequest = RequestBuilder.post()
.setHeader(xmlHeader)
.setUri(baseURI()+ "/pay/micropay")
.setEntity(new StringEntity(closeorderXML,Charset.forName("utf-8")))
.build();
return LocalHttpClient.executeXmlResult(httpUriRequest,MicropayResult.class,micropay.getSign_type(),key);
} | java | public static MicropayResult payMicropay(Micropay micropay,String key){
Map<String,String> map = MapUtil.objectToMap(micropay);
//@since 2.8.14 detail 字段签名处理
if(micropay.getDetail() != null){
map.put("detail",JsonUtil.toJSONString(micropay.getDetail()));
}
String sign = SignatureUtil.generateSign(map,micropay.getSign_type(),key);
micropay.setSign(sign);
String closeorderXML = XMLConverUtil.convertToXML(micropay);
HttpUriRequest httpUriRequest = RequestBuilder.post()
.setHeader(xmlHeader)
.setUri(baseURI()+ "/pay/micropay")
.setEntity(new StringEntity(closeorderXML,Charset.forName("utf-8")))
.build();
return LocalHttpClient.executeXmlResult(httpUriRequest,MicropayResult.class,micropay.getSign_type(),key);
} | [
"public",
"static",
"MicropayResult",
"payMicropay",
"(",
"Micropay",
"micropay",
",",
"String",
"key",
")",
"{",
"Map",
"<",
"String",
",",
"String",
">",
"map",
"=",
"MapUtil",
".",
"objectToMap",
"(",
"micropay",
")",
";",
"//@since 2.8.14 detail 字段签名处理",
"... | 刷卡支付 提交被扫支付API
@param micropay micropay
@param key key
@return MicropayResult | [
"刷卡支付",
"提交被扫支付API"
] | train | https://github.com/liyiorg/weixin-popular/blob/c64255292d41463bdb671938feaabf42a335d82c/src/main/java/weixin/popular/api/PayMchAPI.java#L122-L137 |
aws/aws-sdk-java | aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/StepExecution.java | StepExecution.withOutputs | public StepExecution withOutputs(java.util.Map<String, java.util.List<String>> outputs) {
"""
<p>
Returned values from the execution of the step.
</p>
@param outputs
Returned values from the execution of the step.
@return Returns a reference to this object so that method calls can be chained together.
"""
setOutputs(outputs);
return this;
} | java | public StepExecution withOutputs(java.util.Map<String, java.util.List<String>> outputs) {
setOutputs(outputs);
return this;
} | [
"public",
"StepExecution",
"withOutputs",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"java",
".",
"util",
".",
"List",
"<",
"String",
">",
">",
"outputs",
")",
"{",
"setOutputs",
"(",
"outputs",
")",
";",
"return",
"this",
";",
"}"
] | <p>
Returned values from the execution of the step.
</p>
@param outputs
Returned values from the execution of the step.
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"Returned",
"values",
"from",
"the",
"execution",
"of",
"the",
"step",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/StepExecution.java#L680-L683 |
Netflix/eureka | eureka-client/src/main/java/com/netflix/discovery/converters/wrappers/CodecWrappers.java | CodecWrappers.resolveDecoder | public static synchronized DecoderWrapper resolveDecoder(String name, String eurekaAccept) {
"""
Resolve the decoder to use based on the specified decoder name, as well as the specified eurekaAccept.
The eurekAccept trumps the decoder name if the decoder specified is one that is not valid for use for the
specified eurekaAccept.
"""
EurekaAccept accept = EurekaAccept.fromString(eurekaAccept);
switch (accept) {
case compact:
return getDecoder(JacksonJsonMini.class);
case full:
default:
return getDecoder(name);
}
} | java | public static synchronized DecoderWrapper resolveDecoder(String name, String eurekaAccept) {
EurekaAccept accept = EurekaAccept.fromString(eurekaAccept);
switch (accept) {
case compact:
return getDecoder(JacksonJsonMini.class);
case full:
default:
return getDecoder(name);
}
} | [
"public",
"static",
"synchronized",
"DecoderWrapper",
"resolveDecoder",
"(",
"String",
"name",
",",
"String",
"eurekaAccept",
")",
"{",
"EurekaAccept",
"accept",
"=",
"EurekaAccept",
".",
"fromString",
"(",
"eurekaAccept",
")",
";",
"switch",
"(",
"accept",
")",
... | Resolve the decoder to use based on the specified decoder name, as well as the specified eurekaAccept.
The eurekAccept trumps the decoder name if the decoder specified is one that is not valid for use for the
specified eurekaAccept. | [
"Resolve",
"the",
"decoder",
"to",
"use",
"based",
"on",
"the",
"specified",
"decoder",
"name",
"as",
"well",
"as",
"the",
"specified",
"eurekaAccept",
".",
"The",
"eurekAccept",
"trumps",
"the",
"decoder",
"name",
"if",
"the",
"decoder",
"specified",
"is",
... | train | https://github.com/Netflix/eureka/blob/48446d956be09df6650a3c00b7ebd7e2d1e1544f/eureka-client/src/main/java/com/netflix/discovery/converters/wrappers/CodecWrappers.java#L93-L102 |
JM-Lab/utils-elasticsearch | src/main/java/kr/jm/utils/elasticsearch/JMElasticsearchSearchAndCount.java | JMElasticsearchSearchAndCount.searchAllWithTargetCount | public SearchResponse searchAllWithTargetCount(String[] indices,
String[] types) {
"""
Search all with target count search response.
@param indices the indices
@param types the types
@return the search response
"""
return searchAllWithTargetCount(indices, types, null, null);
} | java | public SearchResponse searchAllWithTargetCount(String[] indices,
String[] types) {
return searchAllWithTargetCount(indices, types, null, null);
} | [
"public",
"SearchResponse",
"searchAllWithTargetCount",
"(",
"String",
"[",
"]",
"indices",
",",
"String",
"[",
"]",
"types",
")",
"{",
"return",
"searchAllWithTargetCount",
"(",
"indices",
",",
"types",
",",
"null",
",",
"null",
")",
";",
"}"
] | Search all with target count search response.
@param indices the indices
@param types the types
@return the search response | [
"Search",
"all",
"with",
"target",
"count",
"search",
"response",
"."
] | train | https://github.com/JM-Lab/utils-elasticsearch/blob/6ccec90e1e51d65d2af5efbb6d7b9f9bad90e638/src/main/java/kr/jm/utils/elasticsearch/JMElasticsearchSearchAndCount.java#L609-L612 |
btrplace/scheduler | choco/src/main/java/org/btrplace/scheduler/choco/extensions/pack/KnapsackDecorator.java | KnapsackDecorator.postAssignItem | public void postAssignItem(int item, int bin) throws
ContradictionException {
"""
update the candidate list of a bin when an item is assigned
then apply the full bin filter if sup(binLoad) is reached
this function may be recursive
@param item the assigned item
@param bin the bin
@throws ContradictionException
"""
if (!candidate.get(bin).get(item)) {
return;
}
candidate.get(bin).clear(item);
for (int d = 0; d < prop.nbDims; d++) {
knapsack(bin, d);
// The bin is full. We get rid of every candidate and set the bin load.
if (prop.loads[d][bin].getUB() == prop.assignedLoad[d][bin].get()) {
filterFullDim(bin, d);
if (candidate.get(bin).isEmpty()) {
for (int d2 = 0; d2 < prop.nbDims; d2++) {
prop.potentialLoad[d2][bin].set(prop.assignedLoad[d2][bin].get());
prop.filterLoadSup(d2, bin, prop.potentialLoad[d2][bin].get());
}
return;
}
return;
}
}
} | java | public void postAssignItem(int item, int bin) throws
ContradictionException {
if (!candidate.get(bin).get(item)) {
return;
}
candidate.get(bin).clear(item);
for (int d = 0; d < prop.nbDims; d++) {
knapsack(bin, d);
// The bin is full. We get rid of every candidate and set the bin load.
if (prop.loads[d][bin].getUB() == prop.assignedLoad[d][bin].get()) {
filterFullDim(bin, d);
if (candidate.get(bin).isEmpty()) {
for (int d2 = 0; d2 < prop.nbDims; d2++) {
prop.potentialLoad[d2][bin].set(prop.assignedLoad[d2][bin].get());
prop.filterLoadSup(d2, bin, prop.potentialLoad[d2][bin].get());
}
return;
}
return;
}
}
} | [
"public",
"void",
"postAssignItem",
"(",
"int",
"item",
",",
"int",
"bin",
")",
"throws",
"ContradictionException",
"{",
"if",
"(",
"!",
"candidate",
".",
"get",
"(",
"bin",
")",
".",
"get",
"(",
"item",
")",
")",
"{",
"return",
";",
"}",
"candidate",
... | update the candidate list of a bin when an item is assigned
then apply the full bin filter if sup(binLoad) is reached
this function may be recursive
@param item the assigned item
@param bin the bin
@throws ContradictionException | [
"update",
"the",
"candidate",
"list",
"of",
"a",
"bin",
"when",
"an",
"item",
"is",
"assigned",
"then",
"apply",
"the",
"full",
"bin",
"filter",
"if",
"sup",
"(",
"binLoad",
")",
"is",
"reached",
"this",
"function",
"may",
"be",
"recursive"
] | train | https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/choco/src/main/java/org/btrplace/scheduler/choco/extensions/pack/KnapsackDecorator.java#L163-L186 |
grails/gorm-hibernate5 | grails-datastore-gorm-hibernate5/src/main/groovy/org/grails/orm/hibernate/cfg/GrailsDomainBinder.java | GrailsDomainBinder.bindJoinedSubClass | protected void bindJoinedSubClass(HibernatePersistentEntity sub, JoinedSubclass joinedSubclass,
InFlightMetadataCollector mappings, Mapping gormMapping, String sessionFactoryBeanName) {
"""
Binds a joined sub-class mapping using table-per-subclass
@param sub The Grails sub class
@param joinedSubclass The Hibernate Subclass object
@param mappings The mappings Object
@param gormMapping The GORM mapping object
@param sessionFactoryBeanName the session factory bean name
"""
bindClass(sub, joinedSubclass, mappings);
String schemaName = getSchemaName(mappings);
String catalogName = getCatalogName(mappings);
Table mytable = mappings.addTable(
schemaName, catalogName,
getJoinedSubClassTableName(sub, joinedSubclass, null, mappings, sessionFactoryBeanName),
null, false);
joinedSubclass.setTable(mytable);
LOG.info("Mapping joined-subclass: " + joinedSubclass.getEntityName() +
" -> " + joinedSubclass.getTable().getName());
SimpleValue key = new DependantValue(metadataBuildingContext, mytable, joinedSubclass.getIdentifier());
joinedSubclass.setKey(key);
final PersistentProperty identifier = sub.getIdentity();
String columnName = getColumnNameForPropertyAndPath(identifier, EMPTY_PATH, null, sessionFactoryBeanName);
bindSimpleValue(identifier.getType().getName(), key, false, columnName, mappings);
joinedSubclass.createPrimaryKey();
// properties
createClassProperties(sub, joinedSubclass, mappings, sessionFactoryBeanName);
} | java | protected void bindJoinedSubClass(HibernatePersistentEntity sub, JoinedSubclass joinedSubclass,
InFlightMetadataCollector mappings, Mapping gormMapping, String sessionFactoryBeanName) {
bindClass(sub, joinedSubclass, mappings);
String schemaName = getSchemaName(mappings);
String catalogName = getCatalogName(mappings);
Table mytable = mappings.addTable(
schemaName, catalogName,
getJoinedSubClassTableName(sub, joinedSubclass, null, mappings, sessionFactoryBeanName),
null, false);
joinedSubclass.setTable(mytable);
LOG.info("Mapping joined-subclass: " + joinedSubclass.getEntityName() +
" -> " + joinedSubclass.getTable().getName());
SimpleValue key = new DependantValue(metadataBuildingContext, mytable, joinedSubclass.getIdentifier());
joinedSubclass.setKey(key);
final PersistentProperty identifier = sub.getIdentity();
String columnName = getColumnNameForPropertyAndPath(identifier, EMPTY_PATH, null, sessionFactoryBeanName);
bindSimpleValue(identifier.getType().getName(), key, false, columnName, mappings);
joinedSubclass.createPrimaryKey();
// properties
createClassProperties(sub, joinedSubclass, mappings, sessionFactoryBeanName);
} | [
"protected",
"void",
"bindJoinedSubClass",
"(",
"HibernatePersistentEntity",
"sub",
",",
"JoinedSubclass",
"joinedSubclass",
",",
"InFlightMetadataCollector",
"mappings",
",",
"Mapping",
"gormMapping",
",",
"String",
"sessionFactoryBeanName",
")",
"{",
"bindClass",
"(",
"... | Binds a joined sub-class mapping using table-per-subclass
@param sub The Grails sub class
@param joinedSubclass The Hibernate Subclass object
@param mappings The mappings Object
@param gormMapping The GORM mapping object
@param sessionFactoryBeanName the session factory bean name | [
"Binds",
"a",
"joined",
"sub",
"-",
"class",
"mapping",
"using",
"table",
"-",
"per",
"-",
"subclass"
] | train | https://github.com/grails/gorm-hibernate5/blob/0ebb80cd769ef2bea955723d4543828a3e9542ef/grails-datastore-gorm-hibernate5/src/main/groovy/org/grails/orm/hibernate/cfg/GrailsDomainBinder.java#L1586-L1612 |
SonarSource/sonarqube | server/sonar-server/src/main/java/org/sonar/server/util/ClassLoaderUtils.java | ClassLoaderUtils.listResources | public static Collection<String> listResources(ClassLoader classLoader, String rootPath, Predicate<String> predicate) {
"""
Finds directories and files within a given directory and its subdirectories.
@param classLoader
@param rootPath the root directory, for example org/sonar/sqale, or a file in this root directory, for example org/sonar/sqale/index.txt
@param predicate
@return a list of relative paths, for example {"org/sonar/sqale", "org/sonar/sqale/foo", "org/sonar/sqale/foo/bar.txt}. Never null.
"""
String jarPath = null;
JarFile jar = null;
try {
Collection<String> paths = new ArrayList<>();
URL root = classLoader.getResource(rootPath);
if (root != null) {
checkJarFile(root);
// Path of the root directory
// Examples :
// org/sonar/sqale/index.txt -> rootDirectory is org/sonar/sqale
// org/sonar/sqale/ -> rootDirectory is org/sonar/sqale
// org/sonar/sqale -> rootDirectory is org/sonar/sqale
String rootDirectory = rootPath;
if (StringUtils.substringAfterLast(rootPath, "/").indexOf('.') >= 0) {
rootDirectory = StringUtils.substringBeforeLast(rootPath, "/");
}
// strip out only the JAR file
jarPath = root.getPath().substring(5, root.getPath().indexOf('!'));
jar = new JarFile(URLDecoder.decode(jarPath, UTF_8.name()));
Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
String name = entries.nextElement().getName();
if (name.startsWith(rootDirectory) && predicate.test(name)) {
paths.add(name);
}
}
}
return paths;
} catch (Exception e) {
throw Throwables.propagate(e);
} finally {
closeJar(jar, jarPath);
}
} | java | public static Collection<String> listResources(ClassLoader classLoader, String rootPath, Predicate<String> predicate) {
String jarPath = null;
JarFile jar = null;
try {
Collection<String> paths = new ArrayList<>();
URL root = classLoader.getResource(rootPath);
if (root != null) {
checkJarFile(root);
// Path of the root directory
// Examples :
// org/sonar/sqale/index.txt -> rootDirectory is org/sonar/sqale
// org/sonar/sqale/ -> rootDirectory is org/sonar/sqale
// org/sonar/sqale -> rootDirectory is org/sonar/sqale
String rootDirectory = rootPath;
if (StringUtils.substringAfterLast(rootPath, "/").indexOf('.') >= 0) {
rootDirectory = StringUtils.substringBeforeLast(rootPath, "/");
}
// strip out only the JAR file
jarPath = root.getPath().substring(5, root.getPath().indexOf('!'));
jar = new JarFile(URLDecoder.decode(jarPath, UTF_8.name()));
Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
String name = entries.nextElement().getName();
if (name.startsWith(rootDirectory) && predicate.test(name)) {
paths.add(name);
}
}
}
return paths;
} catch (Exception e) {
throw Throwables.propagate(e);
} finally {
closeJar(jar, jarPath);
}
} | [
"public",
"static",
"Collection",
"<",
"String",
">",
"listResources",
"(",
"ClassLoader",
"classLoader",
",",
"String",
"rootPath",
",",
"Predicate",
"<",
"String",
">",
"predicate",
")",
"{",
"String",
"jarPath",
"=",
"null",
";",
"JarFile",
"jar",
"=",
"n... | Finds directories and files within a given directory and its subdirectories.
@param classLoader
@param rootPath the root directory, for example org/sonar/sqale, or a file in this root directory, for example org/sonar/sqale/index.txt
@param predicate
@return a list of relative paths, for example {"org/sonar/sqale", "org/sonar/sqale/foo", "org/sonar/sqale/foo/bar.txt}. Never null. | [
"Finds",
"directories",
"and",
"files",
"within",
"a",
"given",
"directory",
"and",
"its",
"subdirectories",
"."
] | train | https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/server/sonar-server/src/main/java/org/sonar/server/util/ClassLoaderUtils.java#L62-L97 |
google/j2objc | jre_emul/openjdk/src/share/classes/java/math/BigDecimal.java | BigDecimal.needIncrement | private static boolean needIncrement(long ldivisor, int roundingMode,
int qsign, long q, long r) {
"""
Tests if quotient has to be incremented according the roundingMode
"""
assert r != 0L;
int cmpFracHalf;
if (r <= HALF_LONG_MIN_VALUE || r > HALF_LONG_MAX_VALUE) {
cmpFracHalf = 1; // 2 * r can't fit into long
} else {
cmpFracHalf = longCompareMagnitude(2 * r, ldivisor);
}
return commonNeedIncrement(roundingMode, qsign, cmpFracHalf, (q & 1L) != 0L);
} | java | private static boolean needIncrement(long ldivisor, int roundingMode,
int qsign, long q, long r) {
assert r != 0L;
int cmpFracHalf;
if (r <= HALF_LONG_MIN_VALUE || r > HALF_LONG_MAX_VALUE) {
cmpFracHalf = 1; // 2 * r can't fit into long
} else {
cmpFracHalf = longCompareMagnitude(2 * r, ldivisor);
}
return commonNeedIncrement(roundingMode, qsign, cmpFracHalf, (q & 1L) != 0L);
} | [
"private",
"static",
"boolean",
"needIncrement",
"(",
"long",
"ldivisor",
",",
"int",
"roundingMode",
",",
"int",
"qsign",
",",
"long",
"q",
",",
"long",
"r",
")",
"{",
"assert",
"r",
"!=",
"0L",
";",
"int",
"cmpFracHalf",
";",
"if",
"(",
"r",
"<=",
... | Tests if quotient has to be incremented according the roundingMode | [
"Tests",
"if",
"quotient",
"has",
"to",
"be",
"incremented",
"according",
"the",
"roundingMode"
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/openjdk/src/share/classes/java/math/BigDecimal.java#L4195-L4207 |
jqno/equalsverifier | src/main/java/nl/jqno/equalsverifier/internal/prefabvalues/PrefabValues.java | PrefabValues.realizeCacheFor | public <T> void realizeCacheFor(TypeTag tag, LinkedHashSet<TypeTag> typeStack) {
"""
Makes sure that values for the specified type are present in the cache,
but doesn't return them.
@param <T> The desired type.
@param tag A description of the desired type, including generic
parameters.
@param typeStack Keeps track of recursion in the type.
"""
if (!cache.contains(tag)) {
Tuple<T> tuple = createTuple(tag, typeStack);
addToCache(tag, tuple);
}
} | java | public <T> void realizeCacheFor(TypeTag tag, LinkedHashSet<TypeTag> typeStack) {
if (!cache.contains(tag)) {
Tuple<T> tuple = createTuple(tag, typeStack);
addToCache(tag, tuple);
}
} | [
"public",
"<",
"T",
">",
"void",
"realizeCacheFor",
"(",
"TypeTag",
"tag",
",",
"LinkedHashSet",
"<",
"TypeTag",
">",
"typeStack",
")",
"{",
"if",
"(",
"!",
"cache",
".",
"contains",
"(",
"tag",
")",
")",
"{",
"Tuple",
"<",
"T",
">",
"tuple",
"=",
... | Makes sure that values for the specified type are present in the cache,
but doesn't return them.
@param <T> The desired type.
@param tag A description of the desired type, including generic
parameters.
@param typeStack Keeps track of recursion in the type. | [
"Makes",
"sure",
"that",
"values",
"for",
"the",
"specified",
"type",
"are",
"present",
"in",
"the",
"cache",
"but",
"doesn",
"t",
"return",
"them",
"."
] | train | https://github.com/jqno/equalsverifier/blob/25d73c9cb801c8b20b257d1d1283ac6e0585ef1d/src/main/java/nl/jqno/equalsverifier/internal/prefabvalues/PrefabValues.java#L145-L150 |
skuzzle/semantic-version | src/main/java/de/skuzzle/semantic/Version.java | Version.parseVersion | public static final Version parseVersion(String versionString) {
"""
Tries to parse the provided String as a semantic version. If the string does not
conform to the semantic version specification, a {@link VersionFormatException}
will be thrown.
@param versionString The String to parse.
@return The parsed version.
@throws VersionFormatException If the String is no valid version
@throws IllegalArgumentException If {@code versionString} is <code>null</code>.
"""
require(versionString != null, "versionString is null");
return parse(versionString, false);
} | java | public static final Version parseVersion(String versionString) {
require(versionString != null, "versionString is null");
return parse(versionString, false);
} | [
"public",
"static",
"final",
"Version",
"parseVersion",
"(",
"String",
"versionString",
")",
"{",
"require",
"(",
"versionString",
"!=",
"null",
",",
"\"versionString is null\"",
")",
";",
"return",
"parse",
"(",
"versionString",
",",
"false",
")",
";",
"}"
] | Tries to parse the provided String as a semantic version. If the string does not
conform to the semantic version specification, a {@link VersionFormatException}
will be thrown.
@param versionString The String to parse.
@return The parsed version.
@throws VersionFormatException If the String is no valid version
@throws IllegalArgumentException If {@code versionString} is <code>null</code>. | [
"Tries",
"to",
"parse",
"the",
"provided",
"String",
"as",
"a",
"semantic",
"version",
".",
"If",
"the",
"string",
"does",
"not",
"conform",
"to",
"the",
"semantic",
"version",
"specification",
"a",
"{",
"@link",
"VersionFormatException",
"}",
"will",
"be",
... | train | https://github.com/skuzzle/semantic-version/blob/2ddb66fb80244cd7f67c77ed5f8072d1132ad933/src/main/java/de/skuzzle/semantic/Version.java#L1373-L1376 |
exoplatform/jcr | exo.jcr.ext.services/src/main/java/org/exoplatform/services/jcr/ext/organization/MembershipHandlerImpl.java | MembershipHandlerImpl.findMembership | private MembershipByUserGroupTypeWrapper findMembership(Session session, String id) throws Exception {
"""
Use this method to search for an membership record with the given id.
"""
IdComponents ids;
try
{
ids = utils.splitId(id);
}
catch (IndexOutOfBoundsException e)
{
throw new ItemNotFoundException("Can not find membership by id=" + id, e);
}
Node groupNode = session.getNodeByUUID(ids.groupNodeId);
Node refUserNode = groupNode.getNode(JCROrganizationServiceImpl.JOS_MEMBERSHIP).getNode(ids.userName);
Node refTypeNode =
refUserNode.getNode(ids.type.equals(MembershipTypeHandler.ANY_MEMBERSHIP_TYPE)
? JCROrganizationServiceImpl.JOS_MEMBERSHIP_TYPE_ANY : ids.type);
String groupId = utils.getGroupIds(groupNode).groupId;
MembershipImpl membership = new MembershipImpl();
membership.setId(id);
membership.setGroupId(groupId);
membership.setMembershipType(ids.type);
membership.setUserName(ids.userName);
putInCache(membership);
return new MembershipByUserGroupTypeWrapper(membership, refUserNode, refTypeNode);
} | java | private MembershipByUserGroupTypeWrapper findMembership(Session session, String id) throws Exception
{
IdComponents ids;
try
{
ids = utils.splitId(id);
}
catch (IndexOutOfBoundsException e)
{
throw new ItemNotFoundException("Can not find membership by id=" + id, e);
}
Node groupNode = session.getNodeByUUID(ids.groupNodeId);
Node refUserNode = groupNode.getNode(JCROrganizationServiceImpl.JOS_MEMBERSHIP).getNode(ids.userName);
Node refTypeNode =
refUserNode.getNode(ids.type.equals(MembershipTypeHandler.ANY_MEMBERSHIP_TYPE)
? JCROrganizationServiceImpl.JOS_MEMBERSHIP_TYPE_ANY : ids.type);
String groupId = utils.getGroupIds(groupNode).groupId;
MembershipImpl membership = new MembershipImpl();
membership.setId(id);
membership.setGroupId(groupId);
membership.setMembershipType(ids.type);
membership.setUserName(ids.userName);
putInCache(membership);
return new MembershipByUserGroupTypeWrapper(membership, refUserNode, refTypeNode);
} | [
"private",
"MembershipByUserGroupTypeWrapper",
"findMembership",
"(",
"Session",
"session",
",",
"String",
"id",
")",
"throws",
"Exception",
"{",
"IdComponents",
"ids",
";",
"try",
"{",
"ids",
"=",
"utils",
".",
"splitId",
"(",
"id",
")",
";",
"}",
"catch",
... | Use this method to search for an membership record with the given id. | [
"Use",
"this",
"method",
"to",
"search",
"for",
"an",
"membership",
"record",
"with",
"the",
"given",
"id",
"."
] | train | https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.ext.services/src/main/java/org/exoplatform/services/jcr/ext/organization/MembershipHandlerImpl.java#L224-L253 |
openbaton/openbaton-client | sdk/src/main/java/org/openbaton/sdk/api/rest/NetworkServiceRecordAgent.java | NetworkServiceRecordAgent.updateVnfr | @Help(help = "Updates a VNFR to a defined VNFD in a running NSR with specific id")
public void updateVnfr(final String idNsr, final String idVnfr) throws SDKException {
"""
Updates a VNFR of a defined VNFD in a running NSR.
@param idNsr the ID of the NetworkServiceRecord
@param idVnfr the ID of the VNFR to be upgraded
@throws SDKException if the request fails
"""
String url = idNsr + "/vnfrecords" + "/" + idVnfr + "/update";
requestPost(url);
} | java | @Help(help = "Updates a VNFR to a defined VNFD in a running NSR with specific id")
public void updateVnfr(final String idNsr, final String idVnfr) throws SDKException {
String url = idNsr + "/vnfrecords" + "/" + idVnfr + "/update";
requestPost(url);
} | [
"@",
"Help",
"(",
"help",
"=",
"\"Updates a VNFR to a defined VNFD in a running NSR with specific id\"",
")",
"public",
"void",
"updateVnfr",
"(",
"final",
"String",
"idNsr",
",",
"final",
"String",
"idVnfr",
")",
"throws",
"SDKException",
"{",
"String",
"url",
"=",
... | Updates a VNFR of a defined VNFD in a running NSR.
@param idNsr the ID of the NetworkServiceRecord
@param idVnfr the ID of the VNFR to be upgraded
@throws SDKException if the request fails | [
"Updates",
"a",
"VNFR",
"of",
"a",
"defined",
"VNFD",
"in",
"a",
"running",
"NSR",
"."
] | train | https://github.com/openbaton/openbaton-client/blob/6ca6dd6b62a23940d312213d6fa489d5b636061a/sdk/src/main/java/org/openbaton/sdk/api/rest/NetworkServiceRecordAgent.java#L707-L711 |
infinispan/infinispan | core/src/main/java/org/infinispan/configuration/parsing/ParseUtils.java | ParseUtils.duplicateNamedElement | public static XMLStreamException duplicateNamedElement(final XMLStreamReader reader, final String name) {
"""
Get an exception reporting that an element of a given type and name has
already been declared in this scope.
@param reader the stream reader
@param name the name that was redeclared
@return the exception
"""
return new XMLStreamException("An element of this type named '" + name + "' has already been declared",
reader.getLocation());
} | java | public static XMLStreamException duplicateNamedElement(final XMLStreamReader reader, final String name) {
return new XMLStreamException("An element of this type named '" + name + "' has already been declared",
reader.getLocation());
} | [
"public",
"static",
"XMLStreamException",
"duplicateNamedElement",
"(",
"final",
"XMLStreamReader",
"reader",
",",
"final",
"String",
"name",
")",
"{",
"return",
"new",
"XMLStreamException",
"(",
"\"An element of this type named '\"",
"+",
"name",
"+",
"\"' has already be... | Get an exception reporting that an element of a given type and name has
already been declared in this scope.
@param reader the stream reader
@param name the name that was redeclared
@return the exception | [
"Get",
"an",
"exception",
"reporting",
"that",
"an",
"element",
"of",
"a",
"given",
"type",
"and",
"name",
"has",
"already",
"been",
"declared",
"in",
"this",
"scope",
"."
] | train | https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/core/src/main/java/org/infinispan/configuration/parsing/ParseUtils.java#L165-L168 |
super-csv/super-csv | super-csv-java8/src/main/java/org/supercsv/cellprocessor/time/ParseZoneId.java | ParseZoneId.execute | public Object execute(final Object value, final CsvContext context) {
"""
{@inheritDoc}
@throws SuperCsvCellProcessorException if value is null or is not a String
"""
validateInputNotNull(value, context);
if( !(value instanceof String) ) {
throw new SuperCsvCellProcessorException(String.class, value, context, this);
}
final ZoneId result;
try {
if( aliasMap != null ) {
result = ZoneId.of((String) value, aliasMap);
} else {
result = ZoneId.of((String) value);
}
}
catch(DateTimeException e) {
throw new SuperCsvCellProcessorException("Failed to parse value as a ZoneId", context, this, e);
}
return next.execute(result, context);
} | java | public Object execute(final Object value, final CsvContext context) {
validateInputNotNull(value, context);
if( !(value instanceof String) ) {
throw new SuperCsvCellProcessorException(String.class, value, context, this);
}
final ZoneId result;
try {
if( aliasMap != null ) {
result = ZoneId.of((String) value, aliasMap);
} else {
result = ZoneId.of((String) value);
}
}
catch(DateTimeException e) {
throw new SuperCsvCellProcessorException("Failed to parse value as a ZoneId", context, this, e);
}
return next.execute(result, context);
} | [
"public",
"Object",
"execute",
"(",
"final",
"Object",
"value",
",",
"final",
"CsvContext",
"context",
")",
"{",
"validateInputNotNull",
"(",
"value",
",",
"context",
")",
";",
"if",
"(",
"!",
"(",
"value",
"instanceof",
"String",
")",
")",
"{",
"throw",
... | {@inheritDoc}
@throws SuperCsvCellProcessorException if value is null or is not a String | [
"{",
"@inheritDoc",
"}"
] | train | https://github.com/super-csv/super-csv/blob/f18db724674dc1c4116e25142c1b5403ebf43e96/super-csv-java8/src/main/java/org/supercsv/cellprocessor/time/ParseZoneId.java#L92-L110 |
buschmais/jqa-core-framework | shared/src/main/java/com/buschmais/jqassistant/core/shared/option/OptionHelper.java | OptionHelper.verifyDeprecatedOption | public static <T> void verifyDeprecatedOption(String deprecatedOption, T value, String option) {
"""
Verify if a deprecated option has been used and emit a warning.
@param deprecatedOption
The name of the deprecated option.
@param value
The provided value.
@param option
The option to use.
@param <T>
The value type.
"""
if (value != null) {
LOGGER.warn("The option '" + deprecatedOption + "' is deprecated, use '" + option + "' instead.");
}
} | java | public static <T> void verifyDeprecatedOption(String deprecatedOption, T value, String option) {
if (value != null) {
LOGGER.warn("The option '" + deprecatedOption + "' is deprecated, use '" + option + "' instead.");
}
} | [
"public",
"static",
"<",
"T",
">",
"void",
"verifyDeprecatedOption",
"(",
"String",
"deprecatedOption",
",",
"T",
"value",
",",
"String",
"option",
")",
"{",
"if",
"(",
"value",
"!=",
"null",
")",
"{",
"LOGGER",
".",
"warn",
"(",
"\"The option '\"",
"+",
... | Verify if a deprecated option has been used and emit a warning.
@param deprecatedOption
The name of the deprecated option.
@param value
The provided value.
@param option
The option to use.
@param <T>
The value type. | [
"Verify",
"if",
"a",
"deprecated",
"option",
"has",
"been",
"used",
"and",
"emit",
"a",
"warning",
"."
] | train | https://github.com/buschmais/jqa-core-framework/blob/0e63ff509cfe52f9063539a23d5f9f183b2ea4a5/shared/src/main/java/com/buschmais/jqassistant/core/shared/option/OptionHelper.java#L46-L50 |
xcesco/kripton | kripton-processor/src/main/java/com/abubusoft/kripton/processor/core/reflect/AnnotationUtility.java | AnnotationUtility.extractString | static void extractString(Elements elementUtils, Element item, Class<? extends Annotation> annotationClass, AnnotationAttributeType attribute, OnAttributeFoundListener listener) {
"""
Extract string.
@param elementUtils the element utils
@param item the item
@param annotationClass the annotation class
@param attribute the attribute
@param listener the listener
"""
extractAttributeValue(elementUtils, item, annotationClass.getCanonicalName(), attribute, listener);
} | java | static void extractString(Elements elementUtils, Element item, Class<? extends Annotation> annotationClass, AnnotationAttributeType attribute, OnAttributeFoundListener listener) {
extractAttributeValue(elementUtils, item, annotationClass.getCanonicalName(), attribute, listener);
} | [
"static",
"void",
"extractString",
"(",
"Elements",
"elementUtils",
",",
"Element",
"item",
",",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
"annotationClass",
",",
"AnnotationAttributeType",
"attribute",
",",
"OnAttributeFoundListener",
"listener",
")",
"{",
"... | Extract string.
@param elementUtils the element utils
@param item the item
@param annotationClass the annotation class
@param attribute the attribute
@param listener the listener | [
"Extract",
"string",
"."
] | train | https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/core/reflect/AnnotationUtility.java#L340-L342 |
bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/PeerGroup.java | PeerGroup.createPeer | @GuardedBy("lock")
protected Peer createPeer(PeerAddress address, VersionMessage ver) {
"""
You can override this to customise the creation of {@link Peer} objects.
"""
return new Peer(params, ver, address, chain, downloadTxDependencyDepth);
} | java | @GuardedBy("lock")
protected Peer createPeer(PeerAddress address, VersionMessage ver) {
return new Peer(params, ver, address, chain, downloadTxDependencyDepth);
} | [
"@",
"GuardedBy",
"(",
"\"lock\"",
")",
"protected",
"Peer",
"createPeer",
"(",
"PeerAddress",
"address",
",",
"VersionMessage",
"ver",
")",
"{",
"return",
"new",
"Peer",
"(",
"params",
",",
"ver",
",",
"address",
",",
"chain",
",",
"downloadTxDependencyDepth"... | You can override this to customise the creation of {@link Peer} objects. | [
"You",
"can",
"override",
"this",
"to",
"customise",
"the",
"creation",
"of",
"{"
] | train | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/PeerGroup.java#L1381-L1384 |
netarchivesuite/heritrix3-wrapper | src/main/java/org/netarchivesuite/heritrix3wrapper/unzip/UnzipUtility.java | UnzipUtility.unzip | public void unzip(String zipFilePath, String destDirectory) throws IOException {
"""
Extracts a zip file specified by the zipFilePath to a directory specified by
destDirectory (will be created if does not exists)
@param zipFilePath
@param destDirectory
@throws IOException
"""
File destDir = new File(destDirectory);
if (!destDir.exists()) {
destDir.mkdir();
}
ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
ZipEntry entry = zipIn.getNextEntry();
while (entry != null) {
File destFile = new File(destDir, entry.getName());
long lastModified = entry.getTime();
if (!entry.isDirectory()) {
extractFile(zipIn, destFile);
if (lastModified != -1) {
destFile.setLastModified(entry.getTime());
}
} else {
destFile.mkdir();
}
zipIn.closeEntry();
entry = zipIn.getNextEntry();
}
zipIn.close();
} | java | public void unzip(String zipFilePath, String destDirectory) throws IOException {
File destDir = new File(destDirectory);
if (!destDir.exists()) {
destDir.mkdir();
}
ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
ZipEntry entry = zipIn.getNextEntry();
while (entry != null) {
File destFile = new File(destDir, entry.getName());
long lastModified = entry.getTime();
if (!entry.isDirectory()) {
extractFile(zipIn, destFile);
if (lastModified != -1) {
destFile.setLastModified(entry.getTime());
}
} else {
destFile.mkdir();
}
zipIn.closeEntry();
entry = zipIn.getNextEntry();
}
zipIn.close();
} | [
"public",
"void",
"unzip",
"(",
"String",
"zipFilePath",
",",
"String",
"destDirectory",
")",
"throws",
"IOException",
"{",
"File",
"destDir",
"=",
"new",
"File",
"(",
"destDirectory",
")",
";",
"if",
"(",
"!",
"destDir",
".",
"exists",
"(",
")",
")",
"{... | Extracts a zip file specified by the zipFilePath to a directory specified by
destDirectory (will be created if does not exists)
@param zipFilePath
@param destDirectory
@throws IOException | [
"Extracts",
"a",
"zip",
"file",
"specified",
"by",
"the",
"zipFilePath",
"to",
"a",
"directory",
"specified",
"by",
"destDirectory",
"(",
"will",
"be",
"created",
"if",
"does",
"not",
"exists",
")"
] | train | https://github.com/netarchivesuite/heritrix3-wrapper/blob/e53ec5736cbac0bdd3925b5331737dc905871629/src/main/java/org/netarchivesuite/heritrix3wrapper/unzip/UnzipUtility.java#L29-L51 |
joniles/mpxj | src/main/java/net/sf/mpxj/ProjectFile.java | ProjectFile.getDuration | @Deprecated public Duration getDuration(String calendarName, Date startDate, Date endDate) throws MPXJException {
"""
This method is used to calculate the duration of work between two fixed
dates according to the work schedule defined in the named calendar.
The name of the calendar to be used is passed as an argument.
@param calendarName name of the calendar to use
@param startDate start of the period
@param endDate end of the period
@return new Duration object
@throws MPXJException normally when no Standard calendar is available
@deprecated use calendar.getDuration(startDate, endDate)
"""
ProjectCalendar calendar = getCalendarByName(calendarName);
if (calendar == null)
{
throw new MPXJException(MPXJException.CALENDAR_ERROR + ": " + calendarName);
}
return (calendar.getDuration(startDate, endDate));
} | java | @Deprecated public Duration getDuration(String calendarName, Date startDate, Date endDate) throws MPXJException
{
ProjectCalendar calendar = getCalendarByName(calendarName);
if (calendar == null)
{
throw new MPXJException(MPXJException.CALENDAR_ERROR + ": " + calendarName);
}
return (calendar.getDuration(startDate, endDate));
} | [
"@",
"Deprecated",
"public",
"Duration",
"getDuration",
"(",
"String",
"calendarName",
",",
"Date",
"startDate",
",",
"Date",
"endDate",
")",
"throws",
"MPXJException",
"{",
"ProjectCalendar",
"calendar",
"=",
"getCalendarByName",
"(",
"calendarName",
")",
";",
"i... | This method is used to calculate the duration of work between two fixed
dates according to the work schedule defined in the named calendar.
The name of the calendar to be used is passed as an argument.
@param calendarName name of the calendar to use
@param startDate start of the period
@param endDate end of the period
@return new Duration object
@throws MPXJException normally when no Standard calendar is available
@deprecated use calendar.getDuration(startDate, endDate) | [
"This",
"method",
"is",
"used",
"to",
"calculate",
"the",
"duration",
"of",
"work",
"between",
"two",
"fixed",
"dates",
"according",
"to",
"the",
"work",
"schedule",
"defined",
"in",
"the",
"named",
"calendar",
".",
"The",
"name",
"of",
"the",
"calendar",
... | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/ProjectFile.java#L353-L363 |
VoltDB/voltdb | src/frontend/org/voltdb/VoltDB.java | VoltDB.crashLocalVoltDB | public static void crashLocalVoltDB(String errMsg, boolean stackTrace, Throwable thrown) {
"""
Exit the process with an error message, optionally with a stack trace.
"""
crashLocalVoltDB(errMsg, stackTrace, thrown, true);
} | java | public static void crashLocalVoltDB(String errMsg, boolean stackTrace, Throwable thrown) {
crashLocalVoltDB(errMsg, stackTrace, thrown, true);
} | [
"public",
"static",
"void",
"crashLocalVoltDB",
"(",
"String",
"errMsg",
",",
"boolean",
"stackTrace",
",",
"Throwable",
"thrown",
")",
"{",
"crashLocalVoltDB",
"(",
"errMsg",
",",
"stackTrace",
",",
"thrown",
",",
"true",
")",
";",
"}"
] | Exit the process with an error message, optionally with a stack trace. | [
"Exit",
"the",
"process",
"with",
"an",
"error",
"message",
"optionally",
"with",
"a",
"stack",
"trace",
"."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/VoltDB.java#L1254-L1256 |
http-builder-ng/http-builder-ng | http-builder-ng-core/src/main/java/groovyx/net/http/optional/Download.java | Download.toFile | public static void toFile(final HttpConfig config, final String contentType, final File file) {
"""
Downloads the content to a specified file with the specified content type.
@param config the `HttpConfig` instance
@param file the file where content will be downloaded
@param contentType the content type
"""
config.context(contentType, ID, file);
config.getResponse().parser(contentType, Download::fileParser);
} | java | public static void toFile(final HttpConfig config, final String contentType, final File file) {
config.context(contentType, ID, file);
config.getResponse().parser(contentType, Download::fileParser);
} | [
"public",
"static",
"void",
"toFile",
"(",
"final",
"HttpConfig",
"config",
",",
"final",
"String",
"contentType",
",",
"final",
"File",
"file",
")",
"{",
"config",
".",
"context",
"(",
"contentType",
",",
"ID",
",",
"file",
")",
";",
"config",
".",
"get... | Downloads the content to a specified file with the specified content type.
@param config the `HttpConfig` instance
@param file the file where content will be downloaded
@param contentType the content type | [
"Downloads",
"the",
"content",
"to",
"a",
"specified",
"file",
"with",
"the",
"specified",
"content",
"type",
"."
] | train | https://github.com/http-builder-ng/http-builder-ng/blob/865f37732c102c748d3db8b905199dac9222a525/http-builder-ng-core/src/main/java/groovyx/net/http/optional/Download.java#L92-L95 |
OpenLiberty/open-liberty | dev/com.ibm.ws.ssl/src/com/ibm/ws/ssl/internal/KeystoreConfig.java | KeystoreConfig.updateKeystoreConfig | synchronized boolean updateKeystoreConfig(Dictionary<String, Object> props) {
"""
Create the new keystore based on the properties provided.
Package private.
@param properties
"""
properties = props;
if (id != null) {
properties.put(Constants.SSLPROP_ALIAS, id);
}
String location = (String) properties.get(LibertyConstants.KEY_KEYSTORE_LOCATION);
if (location != null) {
properties.put(Constants.SSLPROP_KEY_STORE, locSvc.getServiceWithException().resolveString(location));
}
try {
// Try modifying the properties..
// This may throw if arguments are bad
wsKeyStore = new WSKeyStore(id, properties, this);
KeyStoreManager.getInstance().addKeyStoreToMap(id, wsKeyStore);
KeyStoreManager.getInstance().addKeyStoreToMap(pid, wsKeyStore);
return true;
} catch (Exception e) {
wsKeyStore = null;
return false;
}
} | java | synchronized boolean updateKeystoreConfig(Dictionary<String, Object> props) {
properties = props;
if (id != null) {
properties.put(Constants.SSLPROP_ALIAS, id);
}
String location = (String) properties.get(LibertyConstants.KEY_KEYSTORE_LOCATION);
if (location != null) {
properties.put(Constants.SSLPROP_KEY_STORE, locSvc.getServiceWithException().resolveString(location));
}
try {
// Try modifying the properties..
// This may throw if arguments are bad
wsKeyStore = new WSKeyStore(id, properties, this);
KeyStoreManager.getInstance().addKeyStoreToMap(id, wsKeyStore);
KeyStoreManager.getInstance().addKeyStoreToMap(pid, wsKeyStore);
return true;
} catch (Exception e) {
wsKeyStore = null;
return false;
}
} | [
"synchronized",
"boolean",
"updateKeystoreConfig",
"(",
"Dictionary",
"<",
"String",
",",
"Object",
">",
"props",
")",
"{",
"properties",
"=",
"props",
";",
"if",
"(",
"id",
"!=",
"null",
")",
"{",
"properties",
".",
"put",
"(",
"Constants",
".",
"SSLPROP_... | Create the new keystore based on the properties provided.
Package private.
@param properties | [
"Create",
"the",
"new",
"keystore",
"based",
"on",
"the",
"properties",
"provided",
".",
"Package",
"private",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ssl/src/com/ibm/ws/ssl/internal/KeystoreConfig.java#L80-L101 |
groupon/odo | client/src/main/java/com/groupon/odo/client/Client.java | Client.createPath | public void createPath(String pathName, String pathValue, String requestType) {
"""
Create a new path
@param pathName friendly name of path
@param pathValue path value or regex
@param requestType path request type. "GET", "POST", etc
"""
try {
int type = getRequestTypeFromString(requestType);
String url = BASE_PATH;
BasicNameValuePair[] params = {
new BasicNameValuePair("pathName", pathName),
new BasicNameValuePair("path", pathValue),
new BasicNameValuePair("requestType", String.valueOf(type)),
new BasicNameValuePair("profileIdentifier", this._profileName)
};
JSONObject response = new JSONObject(doPost(BASE_PATH, params));
} catch (Exception e) {
e.printStackTrace();
}
} | java | public void createPath(String pathName, String pathValue, String requestType) {
try {
int type = getRequestTypeFromString(requestType);
String url = BASE_PATH;
BasicNameValuePair[] params = {
new BasicNameValuePair("pathName", pathName),
new BasicNameValuePair("path", pathValue),
new BasicNameValuePair("requestType", String.valueOf(type)),
new BasicNameValuePair("profileIdentifier", this._profileName)
};
JSONObject response = new JSONObject(doPost(BASE_PATH, params));
} catch (Exception e) {
e.printStackTrace();
}
} | [
"public",
"void",
"createPath",
"(",
"String",
"pathName",
",",
"String",
"pathValue",
",",
"String",
"requestType",
")",
"{",
"try",
"{",
"int",
"type",
"=",
"getRequestTypeFromString",
"(",
"requestType",
")",
";",
"String",
"url",
"=",
"BASE_PATH",
";",
"... | Create a new path
@param pathName friendly name of path
@param pathValue path value or regex
@param requestType path request type. "GET", "POST", etc | [
"Create",
"a",
"new",
"path"
] | train | https://github.com/groupon/odo/blob/3bae43d5eca8ace036775e5b2d3ed9af1a9ff9b1/client/src/main/java/com/groupon/odo/client/Client.java#L767-L782 |
Azure/azure-sdk-for-java | hdinsight/resource-manager/v2018_06_01_preview/src/main/java/com/microsoft/azure/management/hdinsight/v2018_06_01_preview/implementation/ExtensionsInner.java | ExtensionsInner.beginDisableMonitoringAsync | public Observable<Void> beginDisableMonitoringAsync(String resourceGroupName, String clusterName) {
"""
Disables the Operations Management Suite (OMS) on the HDInsight cluster.
@param resourceGroupName The name of the resource group.
@param clusterName The name of the cluster.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceResponse} object if successful.
"""
return beginDisableMonitoringWithServiceResponseAsync(resourceGroupName, clusterName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | java | public Observable<Void> beginDisableMonitoringAsync(String resourceGroupName, String clusterName) {
return beginDisableMonitoringWithServiceResponseAsync(resourceGroupName, clusterName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Void",
">",
"beginDisableMonitoringAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"clusterName",
")",
"{",
"return",
"beginDisableMonitoringWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"clusterName",
")",
".",
"map",
... | Disables the Operations Management Suite (OMS) on the HDInsight cluster.
@param resourceGroupName The name of the resource group.
@param clusterName The name of the cluster.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceResponse} object if successful. | [
"Disables",
"the",
"Operations",
"Management",
"Suite",
"(",
"OMS",
")",
"on",
"the",
"HDInsight",
"cluster",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/hdinsight/resource-manager/v2018_06_01_preview/src/main/java/com/microsoft/azure/management/hdinsight/v2018_06_01_preview/implementation/ExtensionsInner.java#L459-L466 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/zip/GZIPOutputStream.java | GZIPOutputStream.writeInt | private void writeInt(int i, byte[] buf, int offset) throws IOException {
"""
/*
Writes integer in Intel byte order to a byte array, starting at a
given offset.
"""
writeShort(i & 0xffff, buf, offset);
writeShort((i >> 16) & 0xffff, buf, offset + 2);
} | java | private void writeInt(int i, byte[] buf, int offset) throws IOException {
writeShort(i & 0xffff, buf, offset);
writeShort((i >> 16) & 0xffff, buf, offset + 2);
} | [
"private",
"void",
"writeInt",
"(",
"int",
"i",
",",
"byte",
"[",
"]",
"buf",
",",
"int",
"offset",
")",
"throws",
"IOException",
"{",
"writeShort",
"(",
"i",
"&",
"0xffff",
",",
"buf",
",",
"offset",
")",
";",
"writeShort",
"(",
"(",
"i",
">>",
"1... | /*
Writes integer in Intel byte order to a byte array, starting at a
given offset. | [
"/",
"*",
"Writes",
"integer",
"in",
"Intel",
"byte",
"order",
"to",
"a",
"byte",
"array",
"starting",
"at",
"a",
"given",
"offset",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/zip/GZIPOutputStream.java#L209-L212 |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/QuantilesHelper.java | QuantilesHelper.posOfPhi | public static long posOfPhi(final double phi, final long n) {
"""
Returns the zero-based index (position) of a value in the hypothetical sorted stream of
values of size n.
@param phi the fractional position where: 0 ≤ φ ≤ 1.0.
@param n the size of the stream
@return the index, a value between 0 and n-1.
"""
final long pos = (long) Math.floor(phi * n);
return (pos == n) ? n - 1 : pos;
} | java | public static long posOfPhi(final double phi, final long n) {
final long pos = (long) Math.floor(phi * n);
return (pos == n) ? n - 1 : pos;
} | [
"public",
"static",
"long",
"posOfPhi",
"(",
"final",
"double",
"phi",
",",
"final",
"long",
"n",
")",
"{",
"final",
"long",
"pos",
"=",
"(",
"long",
")",
"Math",
".",
"floor",
"(",
"phi",
"*",
"n",
")",
";",
"return",
"(",
"pos",
"==",
"n",
")",... | Returns the zero-based index (position) of a value in the hypothetical sorted stream of
values of size n.
@param phi the fractional position where: 0 ≤ φ ≤ 1.0.
@param n the size of the stream
@return the index, a value between 0 and n-1. | [
"Returns",
"the",
"zero",
"-",
"based",
"index",
"(",
"position",
")",
"of",
"a",
"value",
"in",
"the",
"hypothetical",
"sorted",
"stream",
"of",
"values",
"of",
"size",
"n",
"."
] | train | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/QuantilesHelper.java#L35-L38 |
aws/aws-sdk-java | aws-java-sdk-api-gateway/src/main/java/com/amazonaws/services/apigateway/model/UpdateIntegrationResponseResult.java | UpdateIntegrationResponseResult.withResponseTemplates | public UpdateIntegrationResponseResult withResponseTemplates(java.util.Map<String, String> responseTemplates) {
"""
<p>
Specifies the templates used to transform the integration response body. Response templates are represented as a
key/value map, with a content-type as the key and a template as the value.
</p>
@param responseTemplates
Specifies the templates used to transform the integration response body. Response templates are
represented as a key/value map, with a content-type as the key and a template as the value.
@return Returns a reference to this object so that method calls can be chained together.
"""
setResponseTemplates(responseTemplates);
return this;
} | java | public UpdateIntegrationResponseResult withResponseTemplates(java.util.Map<String, String> responseTemplates) {
setResponseTemplates(responseTemplates);
return this;
} | [
"public",
"UpdateIntegrationResponseResult",
"withResponseTemplates",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"responseTemplates",
")",
"{",
"setResponseTemplates",
"(",
"responseTemplates",
")",
";",
"return",
"this",
";",
"}"
] | <p>
Specifies the templates used to transform the integration response body. Response templates are represented as a
key/value map, with a content-type as the key and a template as the value.
</p>
@param responseTemplates
Specifies the templates used to transform the integration response body. Response templates are
represented as a key/value map, with a content-type as the key and a template as the value.
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"Specifies",
"the",
"templates",
"used",
"to",
"transform",
"the",
"integration",
"response",
"body",
".",
"Response",
"templates",
"are",
"represented",
"as",
"a",
"key",
"/",
"value",
"map",
"with",
"a",
"content",
"-",
"type",
"as",
"the",
"k... | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-api-gateway/src/main/java/com/amazonaws/services/apigateway/model/UpdateIntegrationResponseResult.java#L351-L354 |
liyiorg/weixin-popular | src/main/java/weixin/popular/util/SignatureUtil.java | SignatureUtil.generateSign | public static String generateSign(Map<String, String> map,String sign_type,String paternerKey) {
"""
生成sign HMAC-SHA256 或 MD5 签名
@param map map
@param sign_type HMAC-SHA256 或 MD5
@param paternerKey paternerKey
@return sign
"""
Map<String, String> tmap = MapUtil.order(map);
if(tmap.containsKey("sign")){
tmap.remove("sign");
}
String str = MapUtil.mapJoin(tmap, false, false);
if(sign_type == null){
sign_type = tmap.get("sign_type");
}
if("HMAC-SHA256".equalsIgnoreCase(sign_type)){
try {
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(paternerKey.getBytes("UTF-8"), "HmacSHA256");
sha256_HMAC.init(secret_key);
return Hex.encodeHexString(sha256_HMAC.doFinal((str+"&key="+paternerKey).getBytes("UTF-8"))).toUpperCase();
} catch (Exception e) {
logger.error("", e);
}
return null;
}else{//default MD5
return DigestUtils.md5Hex(str+"&key="+paternerKey).toUpperCase();
}
} | java | public static String generateSign(Map<String, String> map,String sign_type,String paternerKey){
Map<String, String> tmap = MapUtil.order(map);
if(tmap.containsKey("sign")){
tmap.remove("sign");
}
String str = MapUtil.mapJoin(tmap, false, false);
if(sign_type == null){
sign_type = tmap.get("sign_type");
}
if("HMAC-SHA256".equalsIgnoreCase(sign_type)){
try {
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(paternerKey.getBytes("UTF-8"), "HmacSHA256");
sha256_HMAC.init(secret_key);
return Hex.encodeHexString(sha256_HMAC.doFinal((str+"&key="+paternerKey).getBytes("UTF-8"))).toUpperCase();
} catch (Exception e) {
logger.error("", e);
}
return null;
}else{//default MD5
return DigestUtils.md5Hex(str+"&key="+paternerKey).toUpperCase();
}
} | [
"public",
"static",
"String",
"generateSign",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"map",
",",
"String",
"sign_type",
",",
"String",
"paternerKey",
")",
"{",
"Map",
"<",
"String",
",",
"String",
">",
"tmap",
"=",
"MapUtil",
".",
"order",
"(",
... | 生成sign HMAC-SHA256 或 MD5 签名
@param map map
@param sign_type HMAC-SHA256 或 MD5
@param paternerKey paternerKey
@return sign | [
"生成sign",
"HMAC",
"-",
"SHA256",
"或",
"MD5",
"签名"
] | train | https://github.com/liyiorg/weixin-popular/blob/c64255292d41463bdb671938feaabf42a335d82c/src/main/java/weixin/popular/util/SignatureUtil.java#L35-L57 |
wildfly/wildfly-core | logging/src/main/java/org/jboss/as/logging/handlers/AbstractHandlerDefinition.java | AbstractHandlerDefinition.createParameters | private static Parameters createParameters(final PathElement path, final Class<? extends Handler> type,
final PropertySorter propertySorter, final AttributeDefinition[] addAttributes,
final ConfigurationProperty<?>... constructionProperties) {
"""
Creates the default {@linkplain org.jboss.as.controller.SimpleResourceDefinition.Parameters parameters} for
creating the source.
@param path the resource path
@param type the known type of the resource or {@code null} if the type is unknown
@param propertySorter the property sorter
@param addAttributes the attributes for the add operation step handler
@param constructionProperties the construction properties required for the handler
@return the default parameters
"""
return new Parameters(path, LoggingExtension.getResourceDescriptionResolver(path.getKey()))
.setAddHandler(new HandlerOperations.HandlerAddOperationStepHandler(propertySorter, type, addAttributes, constructionProperties))
.setRemoveHandler(HandlerOperations.REMOVE_HANDLER)
.setCapabilities(Capabilities.HANDLER_CAPABILITY);
} | java | private static Parameters createParameters(final PathElement path, final Class<? extends Handler> type,
final PropertySorter propertySorter, final AttributeDefinition[] addAttributes,
final ConfigurationProperty<?>... constructionProperties) {
return new Parameters(path, LoggingExtension.getResourceDescriptionResolver(path.getKey()))
.setAddHandler(new HandlerOperations.HandlerAddOperationStepHandler(propertySorter, type, addAttributes, constructionProperties))
.setRemoveHandler(HandlerOperations.REMOVE_HANDLER)
.setCapabilities(Capabilities.HANDLER_CAPABILITY);
} | [
"private",
"static",
"Parameters",
"createParameters",
"(",
"final",
"PathElement",
"path",
",",
"final",
"Class",
"<",
"?",
"extends",
"Handler",
">",
"type",
",",
"final",
"PropertySorter",
"propertySorter",
",",
"final",
"AttributeDefinition",
"[",
"]",
"addAtt... | Creates the default {@linkplain org.jboss.as.controller.SimpleResourceDefinition.Parameters parameters} for
creating the source.
@param path the resource path
@param type the known type of the resource or {@code null} if the type is unknown
@param propertySorter the property sorter
@param addAttributes the attributes for the add operation step handler
@param constructionProperties the construction properties required for the handler
@return the default parameters | [
"Creates",
"the",
"default",
"{",
"@linkplain",
"org",
".",
"jboss",
".",
"as",
".",
"controller",
".",
"SimpleResourceDefinition",
".",
"Parameters",
"parameters",
"}",
"for",
"creating",
"the",
"source",
"."
] | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/logging/src/main/java/org/jboss/as/logging/handlers/AbstractHandlerDefinition.java#L247-L254 |
alexvasilkov/GestureViews | sample/src/main/java/com/alexvasilkov/gestures/sample/demo/DemoActivity.java | DemoActivity.applyFullPagerState | private void applyFullPagerState(float position, boolean isLeaving) {
"""
Applying pager image animation state: fading out toolbar, title and background.
"""
views.fullBackground.setVisibility(position == 0f ? View.INVISIBLE : View.VISIBLE);
views.fullBackground.setAlpha(position);
views.pagerToolbar.setVisibility(position == 0f ? View.INVISIBLE : View.VISIBLE);
views.pagerToolbar.setAlpha(isSystemUiShown() ? position : 0f);
views.pagerTitle.setVisibility(position == 1f ? View.VISIBLE : View.INVISIBLE);
if (isLeaving && position == 0f) {
pagerAdapter.setActivated(false);
showSystemUi(true);
}
} | java | private void applyFullPagerState(float position, boolean isLeaving) {
views.fullBackground.setVisibility(position == 0f ? View.INVISIBLE : View.VISIBLE);
views.fullBackground.setAlpha(position);
views.pagerToolbar.setVisibility(position == 0f ? View.INVISIBLE : View.VISIBLE);
views.pagerToolbar.setAlpha(isSystemUiShown() ? position : 0f);
views.pagerTitle.setVisibility(position == 1f ? View.VISIBLE : View.INVISIBLE);
if (isLeaving && position == 0f) {
pagerAdapter.setActivated(false);
showSystemUi(true);
}
} | [
"private",
"void",
"applyFullPagerState",
"(",
"float",
"position",
",",
"boolean",
"isLeaving",
")",
"{",
"views",
".",
"fullBackground",
".",
"setVisibility",
"(",
"position",
"==",
"0f",
"?",
"View",
".",
"INVISIBLE",
":",
"View",
".",
"VISIBLE",
")",
";"... | Applying pager image animation state: fading out toolbar, title and background. | [
"Applying",
"pager",
"image",
"animation",
"state",
":",
"fading",
"out",
"toolbar",
"title",
"and",
"background",
"."
] | train | https://github.com/alexvasilkov/GestureViews/blob/f0a4c266e31dcad23bd0d9013531bc1c501b9c9f/sample/src/main/java/com/alexvasilkov/gestures/sample/demo/DemoActivity.java#L266-L279 |
fcrepo3/fcrepo | fcrepo-client/fcrepo-client-admin/src/main/java/org/fcrepo/client/utility/validate/process/ValidatorProcessParameters.java | ValidatorProcessParameters.assembleFieldSearchQuery | private FieldSearchQuery assembleFieldSearchQuery(String query, String terms) {
"""
A {@link FieldSearchQuery} may be made from a terms string or a query
string, but not both.
"""
if (terms != null) {
return new FieldSearchQuery(terms);
} else {
try {
return new FieldSearchQuery(Condition.getConditions(query));
} catch (QueryParseException e) {
throw new ValidatorProcessUsageException("Value '" + query
+ "' of parameter '" + PARAMETER_QUERY
+ "' is not a valid query string.");
}
}
} | java | private FieldSearchQuery assembleFieldSearchQuery(String query, String terms) {
if (terms != null) {
return new FieldSearchQuery(terms);
} else {
try {
return new FieldSearchQuery(Condition.getConditions(query));
} catch (QueryParseException e) {
throw new ValidatorProcessUsageException("Value '" + query
+ "' of parameter '" + PARAMETER_QUERY
+ "' is not a valid query string.");
}
}
} | [
"private",
"FieldSearchQuery",
"assembleFieldSearchQuery",
"(",
"String",
"query",
",",
"String",
"terms",
")",
"{",
"if",
"(",
"terms",
"!=",
"null",
")",
"{",
"return",
"new",
"FieldSearchQuery",
"(",
"terms",
")",
";",
"}",
"else",
"{",
"try",
"{",
"ret... | A {@link FieldSearchQuery} may be made from a terms string or a query
string, but not both. | [
"A",
"{"
] | train | https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-client/fcrepo-client-admin/src/main/java/org/fcrepo/client/utility/validate/process/ValidatorProcessParameters.java#L283-L295 |
codelibs/fess | src/main/java/org/codelibs/fess/mylasta/action/FessMessages.java | FessMessages.addErrorsPropertyTypeDate | public FessMessages addErrorsPropertyTypeDate(String property, String arg0) {
"""
Add the created action message for the key 'errors.property_type_date' with parameters.
<pre>
message: {0} should be date.
</pre>
@param property The property name for the message. (NotNull)
@param arg0 The parameter arg0 for message. (NotNull)
@return this. (NotNull)
"""
assertPropertyNotNull(property);
add(property, new UserMessage(ERRORS_property_type_date, arg0));
return this;
} | java | public FessMessages addErrorsPropertyTypeDate(String property, String arg0) {
assertPropertyNotNull(property);
add(property, new UserMessage(ERRORS_property_type_date, arg0));
return this;
} | [
"public",
"FessMessages",
"addErrorsPropertyTypeDate",
"(",
"String",
"property",
",",
"String",
"arg0",
")",
"{",
"assertPropertyNotNull",
"(",
"property",
")",
";",
"add",
"(",
"property",
",",
"new",
"UserMessage",
"(",
"ERRORS_property_type_date",
",",
"arg0",
... | Add the created action message for the key 'errors.property_type_date' with parameters.
<pre>
message: {0} should be date.
</pre>
@param property The property name for the message. (NotNull)
@param arg0 The parameter arg0 for message. (NotNull)
@return this. (NotNull) | [
"Add",
"the",
"created",
"action",
"message",
"for",
"the",
"key",
"errors",
".",
"property_type_date",
"with",
"parameters",
".",
"<pre",
">",
"message",
":",
"{",
"0",
"}",
"should",
"be",
"date",
".",
"<",
"/",
"pre",
">"
] | train | https://github.com/codelibs/fess/blob/e5e4b722549d32a4958dfd94965b21937bfe64cf/src/main/java/org/codelibs/fess/mylasta/action/FessMessages.java#L2260-L2264 |
duracloud/duracloud | common/src/main/java/org/duracloud/common/util/ChecksumUtil.java | ChecksumUtil.wrapStream | public static DigestInputStream wrapStream(InputStream inStream,
Algorithm algorithm) {
"""
Wraps an InputStream with a DigestInputStream in order to compute
a checksum as the stream is being read.
@param inStream The stream to wrap
@param algorithm The algorithm used to compute the digest
@return The original stream wrapped as a DigestInputStream
"""
MessageDigest streamDigest = null;
try {
streamDigest = MessageDigest.getInstance(algorithm.toString());
} catch (NoSuchAlgorithmException e) {
String error = "Could not create a MessageDigest because the " +
"required algorithm " + algorithm.toString() +
" is not supported.";
throw new RuntimeException(error);
}
DigestInputStream wrappedContent =
new DigestInputStream(inStream, streamDigest);
return wrappedContent;
} | java | public static DigestInputStream wrapStream(InputStream inStream,
Algorithm algorithm) {
MessageDigest streamDigest = null;
try {
streamDigest = MessageDigest.getInstance(algorithm.toString());
} catch (NoSuchAlgorithmException e) {
String error = "Could not create a MessageDigest because the " +
"required algorithm " + algorithm.toString() +
" is not supported.";
throw new RuntimeException(error);
}
DigestInputStream wrappedContent =
new DigestInputStream(inStream, streamDigest);
return wrappedContent;
} | [
"public",
"static",
"DigestInputStream",
"wrapStream",
"(",
"InputStream",
"inStream",
",",
"Algorithm",
"algorithm",
")",
"{",
"MessageDigest",
"streamDigest",
"=",
"null",
";",
"try",
"{",
"streamDigest",
"=",
"MessageDigest",
".",
"getInstance",
"(",
"algorithm",... | Wraps an InputStream with a DigestInputStream in order to compute
a checksum as the stream is being read.
@param inStream The stream to wrap
@param algorithm The algorithm used to compute the digest
@return The original stream wrapped as a DigestInputStream | [
"Wraps",
"an",
"InputStream",
"with",
"a",
"DigestInputStream",
"in",
"order",
"to",
"compute",
"a",
"checksum",
"as",
"the",
"stream",
"is",
"being",
"read",
"."
] | train | https://github.com/duracloud/duracloud/blob/dc4f3a1716d43543cc3b2e1880605f9389849b66/common/src/main/java/org/duracloud/common/util/ChecksumUtil.java#L129-L144 |
googleads/googleads-java-lib | modules/ads_lib/src/main/java/com/google/api/ads/common/lib/utils/NodeExtractor.java | NodeExtractor.extractNodeValue | public String extractNodeValue(@Nullable Node parentNode, Iterable<String> xPath) {
"""
Convenience method for getting the value of a node, handling the case where the node does not
exist.
@return the value of the node at {@code xPath} if it exists, else {@code null}.
"""
Node node = extractNode(parentNode, xPath);
if (node == null || node.getFirstChild() == null) {
return null;
}
return node.getFirstChild().getNodeValue();
} | java | public String extractNodeValue(@Nullable Node parentNode, Iterable<String> xPath) {
Node node = extractNode(parentNode, xPath);
if (node == null || node.getFirstChild() == null) {
return null;
}
return node.getFirstChild().getNodeValue();
} | [
"public",
"String",
"extractNodeValue",
"(",
"@",
"Nullable",
"Node",
"parentNode",
",",
"Iterable",
"<",
"String",
">",
"xPath",
")",
"{",
"Node",
"node",
"=",
"extractNode",
"(",
"parentNode",
",",
"xPath",
")",
";",
"if",
"(",
"node",
"==",
"null",
"|... | Convenience method for getting the value of a node, handling the case where the node does not
exist.
@return the value of the node at {@code xPath} if it exists, else {@code null}. | [
"Convenience",
"method",
"for",
"getting",
"the",
"value",
"of",
"a",
"node",
"handling",
"the",
"case",
"where",
"the",
"node",
"does",
"not",
"exist",
"."
] | train | https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/modules/ads_lib/src/main/java/com/google/api/ads/common/lib/utils/NodeExtractor.java#L40-L46 |
b3dgs/lionengine | lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/collidable/CollidableUpdater.java | CollidableUpdater.checkCollide | private static boolean checkCollide(Area area, Collidable other) {
"""
Check if current area collides other collidable area.
@param area The current area.
@param other The other collidable.
@return <code>true</code> if collide, <code>false</code> else.
"""
final List<Rectangle> others = other.getCollisionBounds();
final int size = others.size();
for (int i = 0; i < size; i++)
{
final Area current = others.get(i);
if (area.intersects(current))
{
return true;
}
}
return false;
} | java | private static boolean checkCollide(Area area, Collidable other)
{
final List<Rectangle> others = other.getCollisionBounds();
final int size = others.size();
for (int i = 0; i < size; i++)
{
final Area current = others.get(i);
if (area.intersects(current))
{
return true;
}
}
return false;
} | [
"private",
"static",
"boolean",
"checkCollide",
"(",
"Area",
"area",
",",
"Collidable",
"other",
")",
"{",
"final",
"List",
"<",
"Rectangle",
">",
"others",
"=",
"other",
".",
"getCollisionBounds",
"(",
")",
";",
"final",
"int",
"size",
"=",
"others",
".",... | Check if current area collides other collidable area.
@param area The current area.
@param other The other collidable.
@return <code>true</code> if collide, <code>false</code> else. | [
"Check",
"if",
"current",
"area",
"collides",
"other",
"collidable",
"area",
"."
] | train | https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/collidable/CollidableUpdater.java#L102-L115 |
guardtime/ksi-java-sdk | ksi-api/src/main/java/com/guardtime/ksi/publication/inmemory/InMemoryPublicationsFile.java | InMemoryPublicationsFile.verifyMagicBytes | private void verifyMagicBytes(TLVInputStream input) throws InvalidPublicationsFileException {
"""
Verifies that input stream starts with publications file magic bytes.
@param input
instance of input stream to check. not null.
"""
try {
byte[] magicBytes = new byte[PUBLICATIONS_FILE_MAGIC_BYTES_LENGTH];
input.read(magicBytes);
if (!Arrays.equals(magicBytes, FILE_BEGINNING_MAGIC_BYTES)) {
throw new InvalidPublicationsFileException("Invalid publications file magic bytes");
}
} catch (IOException e) {
throw new InvalidPublicationsFileException("Checking publications file magic bytes failed", e);
}
} | java | private void verifyMagicBytes(TLVInputStream input) throws InvalidPublicationsFileException {
try {
byte[] magicBytes = new byte[PUBLICATIONS_FILE_MAGIC_BYTES_LENGTH];
input.read(magicBytes);
if (!Arrays.equals(magicBytes, FILE_BEGINNING_MAGIC_BYTES)) {
throw new InvalidPublicationsFileException("Invalid publications file magic bytes");
}
} catch (IOException e) {
throw new InvalidPublicationsFileException("Checking publications file magic bytes failed", e);
}
} | [
"private",
"void",
"verifyMagicBytes",
"(",
"TLVInputStream",
"input",
")",
"throws",
"InvalidPublicationsFileException",
"{",
"try",
"{",
"byte",
"[",
"]",
"magicBytes",
"=",
"new",
"byte",
"[",
"PUBLICATIONS_FILE_MAGIC_BYTES_LENGTH",
"]",
";",
"input",
".",
"read"... | Verifies that input stream starts with publications file magic bytes.
@param input
instance of input stream to check. not null. | [
"Verifies",
"that",
"input",
"stream",
"starts",
"with",
"publications",
"file",
"magic",
"bytes",
"."
] | train | https://github.com/guardtime/ksi-java-sdk/blob/b2cd877050f0f392657c724452318d10a1002171/ksi-api/src/main/java/com/guardtime/ksi/publication/inmemory/InMemoryPublicationsFile.java#L155-L165 |
facebookarchive/hadoop-20 | src/contrib/data_join/src/java/org/apache/hadoop/contrib/utils/join/JobBase.java | JobBase.addLongValue | protected Long addLongValue(Object name, long inc) {
"""
Increment the given counter by the given incremental value If the counter
does not exist, one is created with value 0.
@param name
the counter name
@param inc
the incremental value
@return the updated value.
"""
Long val = this.longCounters.get(name);
Long retv = null;
if (val == null) {
retv = new Long(inc);
} else {
retv = new Long(val.longValue() + inc);
}
this.longCounters.put(name, retv);
return retv;
} | java | protected Long addLongValue(Object name, long inc) {
Long val = this.longCounters.get(name);
Long retv = null;
if (val == null) {
retv = new Long(inc);
} else {
retv = new Long(val.longValue() + inc);
}
this.longCounters.put(name, retv);
return retv;
} | [
"protected",
"Long",
"addLongValue",
"(",
"Object",
"name",
",",
"long",
"inc",
")",
"{",
"Long",
"val",
"=",
"this",
".",
"longCounters",
".",
"get",
"(",
"name",
")",
";",
"Long",
"retv",
"=",
"null",
";",
"if",
"(",
"val",
"==",
"null",
")",
"{"... | Increment the given counter by the given incremental value If the counter
does not exist, one is created with value 0.
@param name
the counter name
@param inc
the incremental value
@return the updated value. | [
"Increment",
"the",
"given",
"counter",
"by",
"the",
"given",
"incremental",
"value",
"If",
"the",
"counter",
"does",
"not",
"exist",
"one",
"is",
"created",
"with",
"value",
"0",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/data_join/src/java/org/apache/hadoop/contrib/utils/join/JobBase.java#L99-L109 |
GenesysPureEngage/workspace-client-java | src/main/java/com/genesys/workspace/VoiceApi.java | VoiceApi.setAgentReady | public void setAgentReady(KeyValueCollection reasons, KeyValueCollection extensions) throws WorkspaceApiException {
"""
Set the current agent's state to Ready on the voice channel.
@param reasons Information on causes for, and results of, actions taken by the user of the current DN. For details about reasons, refer to the [*Genesys Events and Models Reference Manual*](https://docs.genesys.com/Documentation/System/Current/GenEM/Reasons).
@param extensions Media device/hardware reason codes and similar information. For details about extensions, refer to the [*Genesys Events and Models Reference Manual*](https://docs.genesys.com/Documentation/System/Current/GenEM/Extensions). (optional)
"""
try {
VoicereadyData readyData = new VoicereadyData();
readyData.setReasons(Util.toKVList(reasons));
readyData.setExtensions(Util.toKVList(extensions));
ReadyData data = new ReadyData();
data.data(readyData);
ApiSuccessResponse response = this.voiceApi.setAgentStateReady(data);
throwIfNotOk("setAgentReady", response);
} catch (ApiException e) {
throw new WorkspaceApiException("setAgentReady failed.", e);
}
} | java | public void setAgentReady(KeyValueCollection reasons, KeyValueCollection extensions) throws WorkspaceApiException {
try {
VoicereadyData readyData = new VoicereadyData();
readyData.setReasons(Util.toKVList(reasons));
readyData.setExtensions(Util.toKVList(extensions));
ReadyData data = new ReadyData();
data.data(readyData);
ApiSuccessResponse response = this.voiceApi.setAgentStateReady(data);
throwIfNotOk("setAgentReady", response);
} catch (ApiException e) {
throw new WorkspaceApiException("setAgentReady failed.", e);
}
} | [
"public",
"void",
"setAgentReady",
"(",
"KeyValueCollection",
"reasons",
",",
"KeyValueCollection",
"extensions",
")",
"throws",
"WorkspaceApiException",
"{",
"try",
"{",
"VoicereadyData",
"readyData",
"=",
"new",
"VoicereadyData",
"(",
")",
";",
"readyData",
".",
"... | Set the current agent's state to Ready on the voice channel.
@param reasons Information on causes for, and results of, actions taken by the user of the current DN. For details about reasons, refer to the [*Genesys Events and Models Reference Manual*](https://docs.genesys.com/Documentation/System/Current/GenEM/Reasons).
@param extensions Media device/hardware reason codes and similar information. For details about extensions, refer to the [*Genesys Events and Models Reference Manual*](https://docs.genesys.com/Documentation/System/Current/GenEM/Extensions). (optional) | [
"Set",
"the",
"current",
"agent",
"s",
"state",
"to",
"Ready",
"on",
"the",
"voice",
"channel",
"."
] | train | https://github.com/GenesysPureEngage/workspace-client-java/blob/509fdd9e89b9359d012f9a72be95037a3cef53e6/src/main/java/com/genesys/workspace/VoiceApi.java#L321-L334 |
khuxtable/seaglass | src/main/java/com/seaglasslookandfeel/painter/TitlePaneIconifyButtonPainter.java | TitlePaneIconifyButtonPainter.paintMinimizeHover | private void paintMinimizeHover(Graphics2D g, JComponent c, int width, int height) {
"""
Paint the foreground minimized button mouse-over state.
@param g the Graphics2D context to paint with.
@param c the component.
@param width the width of the component.
@param height the height of the component.
"""
iconifyPainter.paintHover(g, c, width, height);
} | java | private void paintMinimizeHover(Graphics2D g, JComponent c, int width, int height) {
iconifyPainter.paintHover(g, c, width, height);
} | [
"private",
"void",
"paintMinimizeHover",
"(",
"Graphics2D",
"g",
",",
"JComponent",
"c",
",",
"int",
"width",
",",
"int",
"height",
")",
"{",
"iconifyPainter",
".",
"paintHover",
"(",
"g",
",",
"c",
",",
"width",
",",
"height",
")",
";",
"}"
] | Paint the foreground minimized button mouse-over state.
@param g the Graphics2D context to paint with.
@param c the component.
@param width the width of the component.
@param height the height of the component. | [
"Paint",
"the",
"foreground",
"minimized",
"button",
"mouse",
"-",
"over",
"state",
"."
] | train | https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/painter/TitlePaneIconifyButtonPainter.java#L183-L185 |
sporniket/core | sporniket-core-io/src/main/java/com/sporniket/libre/io/FileTools.java | FileTools.createReaderForInputStream | public static Reader createReaderForInputStream(InputStream source, String encoding)
throws FileNotFoundException, UnsupportedEncodingException {
"""
Instanciate a Reader for a InputStream using the given encoding.
@param source
source stream.
@param encoding
<code>null</code> or empty for using system encoding.
@return the reader.
@throws FileNotFoundException
if there is a problem to deal with.
@throws UnsupportedEncodingException
if there is a problem to deal with.
@since 12.06.01
"""
return (IS_EMPTY.test(encoding)) ? new InputStreamReader(source) : new InputStreamReader(source, encoding);
} | java | public static Reader createReaderForInputStream(InputStream source, String encoding)
throws FileNotFoundException, UnsupportedEncodingException
{
return (IS_EMPTY.test(encoding)) ? new InputStreamReader(source) : new InputStreamReader(source, encoding);
} | [
"public",
"static",
"Reader",
"createReaderForInputStream",
"(",
"InputStream",
"source",
",",
"String",
"encoding",
")",
"throws",
"FileNotFoundException",
",",
"UnsupportedEncodingException",
"{",
"return",
"(",
"IS_EMPTY",
".",
"test",
"(",
"encoding",
")",
")",
... | Instanciate a Reader for a InputStream using the given encoding.
@param source
source stream.
@param encoding
<code>null</code> or empty for using system encoding.
@return the reader.
@throws FileNotFoundException
if there is a problem to deal with.
@throws UnsupportedEncodingException
if there is a problem to deal with.
@since 12.06.01 | [
"Instanciate",
"a",
"Reader",
"for",
"a",
"InputStream",
"using",
"the",
"given",
"encoding",
"."
] | train | https://github.com/sporniket/core/blob/3480ebd72a07422fcc09971be2607ee25efb2c26/sporniket-core-io/src/main/java/com/sporniket/libre/io/FileTools.java#L191-L195 |
stratosphere/stratosphere | stratosphere-runtime/src/main/java/eu/stratosphere/pact/runtime/sort/NormalizedKeySorter.java | NormalizedKeySorter.writeToOutput | @Override
public void writeToOutput(final ChannelWriterOutputView output, final int start, int num) throws IOException {
"""
Writes a subset of the records in this buffer in their logical order to the given output.
@param output The output view to write the records to.
@param start The logical start position of the subset.
@param num The number of elements to write.
@throws IOException Thrown, if an I/O exception occurred writing to the output view.
"""
int currentMemSeg = start / this.indexEntriesPerSegment;
int offset = (start % this.indexEntriesPerSegment) * this.indexEntrySize;
while (num > 0)
{
final MemorySegment currentIndexSegment = this.sortIndex.get(currentMemSeg++);
// check whether we have a full or partially full segment
if (num >= this.indexEntriesPerSegment && offset == 0) {
// full segment
for (;offset <= this.lastIndexEntryOffset; offset += this.indexEntrySize) {
final long pointer = currentIndexSegment.getLong(offset);
this.recordBuffer.setReadPosition(pointer);
this.serializer.copy(this.recordBuffer, output);
}
num -= this.indexEntriesPerSegment;
} else {
// partially filled segment
for (; num > 0 && offset <= this.lastIndexEntryOffset; num--, offset += this.indexEntrySize)
{
final long pointer = currentIndexSegment.getLong(offset);
this.recordBuffer.setReadPosition(pointer);
this.serializer.copy(this.recordBuffer, output);
}
}
offset = 0;
}
} | java | @Override
public void writeToOutput(final ChannelWriterOutputView output, final int start, int num) throws IOException {
int currentMemSeg = start / this.indexEntriesPerSegment;
int offset = (start % this.indexEntriesPerSegment) * this.indexEntrySize;
while (num > 0)
{
final MemorySegment currentIndexSegment = this.sortIndex.get(currentMemSeg++);
// check whether we have a full or partially full segment
if (num >= this.indexEntriesPerSegment && offset == 0) {
// full segment
for (;offset <= this.lastIndexEntryOffset; offset += this.indexEntrySize) {
final long pointer = currentIndexSegment.getLong(offset);
this.recordBuffer.setReadPosition(pointer);
this.serializer.copy(this.recordBuffer, output);
}
num -= this.indexEntriesPerSegment;
} else {
// partially filled segment
for (; num > 0 && offset <= this.lastIndexEntryOffset; num--, offset += this.indexEntrySize)
{
final long pointer = currentIndexSegment.getLong(offset);
this.recordBuffer.setReadPosition(pointer);
this.serializer.copy(this.recordBuffer, output);
}
}
offset = 0;
}
} | [
"@",
"Override",
"public",
"void",
"writeToOutput",
"(",
"final",
"ChannelWriterOutputView",
"output",
",",
"final",
"int",
"start",
",",
"int",
"num",
")",
"throws",
"IOException",
"{",
"int",
"currentMemSeg",
"=",
"start",
"/",
"this",
".",
"indexEntriesPerSeg... | Writes a subset of the records in this buffer in their logical order to the given output.
@param output The output view to write the records to.
@param start The logical start position of the subset.
@param num The number of elements to write.
@throws IOException Thrown, if an I/O exception occurred writing to the output view. | [
"Writes",
"a",
"subset",
"of",
"the",
"records",
"in",
"this",
"buffer",
"in",
"their",
"logical",
"order",
"to",
"the",
"given",
"output",
"."
] | train | https://github.com/stratosphere/stratosphere/blob/c543a08f9676c5b2b0a7088123bd6e795a8ae0c8/stratosphere-runtime/src/main/java/eu/stratosphere/pact/runtime/sort/NormalizedKeySorter.java#L470-L498 |
RoaringBitmap/RoaringBitmap | roaringbitmap/src/main/java/org/roaringbitmap/buffer/MappeableContainer.java | MappeableContainer.rangeOfOnes | public static MappeableContainer rangeOfOnes(final int start, final int last) {
"""
Create a container initialized with a range of consecutive values
@param start first index
@param last last index (range is exclusive)
@return a new container initialized with the specified values
"""
final int arrayContainerOverRunThreshold = 2;
final int cardinality = last - start;
if (cardinality <= arrayContainerOverRunThreshold) {
return new MappeableArrayContainer(start, last);
}
return new MappeableRunContainer(start, last);
} | java | public static MappeableContainer rangeOfOnes(final int start, final int last) {
final int arrayContainerOverRunThreshold = 2;
final int cardinality = last - start;
if (cardinality <= arrayContainerOverRunThreshold) {
return new MappeableArrayContainer(start, last);
}
return new MappeableRunContainer(start, last);
} | [
"public",
"static",
"MappeableContainer",
"rangeOfOnes",
"(",
"final",
"int",
"start",
",",
"final",
"int",
"last",
")",
"{",
"final",
"int",
"arrayContainerOverRunThreshold",
"=",
"2",
";",
"final",
"int",
"cardinality",
"=",
"last",
"-",
"start",
";",
"if",
... | Create a container initialized with a range of consecutive values
@param start first index
@param last last index (range is exclusive)
@return a new container initialized with the specified values | [
"Create",
"a",
"container",
"initialized",
"with",
"a",
"range",
"of",
"consecutive",
"values"
] | train | https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/buffer/MappeableContainer.java#L28-L36 |
BioPAX/Paxtools | pattern/src/main/java/org/biopax/paxtools/pattern/PatternBox.java | PatternBox.controlsStateChangeBothControlAndPart | public static Pattern controlsStateChangeBothControlAndPart() {
"""
Pattern for a EntityReference has a member PhysicalEntity that is controlling a state change
reaction of another EntityReference. In this case the controller is also an input to the
reaction. The affected protein is the one that is represented with different non-generic
physical entities at left and right of the reaction.
@return the pattern
"""
Pattern p = new Pattern(SequenceEntityReference.class, "controller ER");
p.add(linkedER(true), "controller ER", "controller generic ER");
p.add(erToPE(), "controller generic ER", "controller simple PE");
p.add(linkToComplex(), "controller simple PE", "controller PE");
p.add(peToControl(), "controller PE", "Control");
p.add(controlToConv(), "Control", "Conversion");
// the controller PE is also an input
p.add(new ParticipatesInConv(RelType.INPUT), "controller PE", "Conversion");
// same controller simple PE is also an output
p.add(linkToComplex(), "controller simple PE", "special output PE");
p.add(equal(false), "special output PE", "controller PE");
p.add(new ParticipatesInConv(RelType.OUTPUT), "special output PE", "Conversion");
stateChange(p, "Control");
// non-generic input and outputs are only associated with one side
p.add(equal(false), "input simple PE", "output simple PE");
p.add(new NOT(simplePEToConv(RelType.OUTPUT)), "input simple PE", "Conversion");
p.add(new NOT(simplePEToConv(RelType.INPUT)), "output simple PE", "Conversion");
p.add(equal(false), "controller ER", "changed ER");
p.add(type(SequenceEntityReference.class), "changed ER");
return p;
} | java | public static Pattern controlsStateChangeBothControlAndPart()
{
Pattern p = new Pattern(SequenceEntityReference.class, "controller ER");
p.add(linkedER(true), "controller ER", "controller generic ER");
p.add(erToPE(), "controller generic ER", "controller simple PE");
p.add(linkToComplex(), "controller simple PE", "controller PE");
p.add(peToControl(), "controller PE", "Control");
p.add(controlToConv(), "Control", "Conversion");
// the controller PE is also an input
p.add(new ParticipatesInConv(RelType.INPUT), "controller PE", "Conversion");
// same controller simple PE is also an output
p.add(linkToComplex(), "controller simple PE", "special output PE");
p.add(equal(false), "special output PE", "controller PE");
p.add(new ParticipatesInConv(RelType.OUTPUT), "special output PE", "Conversion");
stateChange(p, "Control");
// non-generic input and outputs are only associated with one side
p.add(equal(false), "input simple PE", "output simple PE");
p.add(new NOT(simplePEToConv(RelType.OUTPUT)), "input simple PE", "Conversion");
p.add(new NOT(simplePEToConv(RelType.INPUT)), "output simple PE", "Conversion");
p.add(equal(false), "controller ER", "changed ER");
p.add(type(SequenceEntityReference.class), "changed ER");
return p;
} | [
"public",
"static",
"Pattern",
"controlsStateChangeBothControlAndPart",
"(",
")",
"{",
"Pattern",
"p",
"=",
"new",
"Pattern",
"(",
"SequenceEntityReference",
".",
"class",
",",
"\"controller ER\"",
")",
";",
"p",
".",
"add",
"(",
"linkedER",
"(",
"true",
")",
... | Pattern for a EntityReference has a member PhysicalEntity that is controlling a state change
reaction of another EntityReference. In this case the controller is also an input to the
reaction. The affected protein is the one that is represented with different non-generic
physical entities at left and right of the reaction.
@return the pattern | [
"Pattern",
"for",
"a",
"EntityReference",
"has",
"a",
"member",
"PhysicalEntity",
"that",
"is",
"controlling",
"a",
"state",
"change",
"reaction",
"of",
"another",
"EntityReference",
".",
"In",
"this",
"case",
"the",
"controller",
"is",
"also",
"an",
"input",
... | train | https://github.com/BioPAX/Paxtools/blob/2f93afa94426bf8b5afc2e0e61cd4b269a83288d/pattern/src/main/java/org/biopax/paxtools/pattern/PatternBox.java#L114-L142 |
hyperledger/fabric-sdk-java | src/main/java/org/hyperledger/fabric/sdk/helper/Utils.java | Utils.generateDirectoryHash | public static String generateDirectoryHash(String rootDir, String chaincodeDir, String hash) throws IOException {
"""
Generate hash of a chaincode directory
@param rootDir Root directory
@param chaincodeDir Channel code directory
@param hash Previous hash (if any)
@return hash of the directory
@throws IOException
"""
// Generate the project directory
Path projectPath = null;
if (rootDir == null) {
projectPath = Paths.get(chaincodeDir);
} else {
projectPath = Paths.get(rootDir, chaincodeDir);
}
File dir = projectPath.toFile();
if (!dir.exists() || !dir.isDirectory()) {
throw new IOException(format("The chaincode path \"%s\" is invalid", projectPath));
}
StringBuilder hashBuilder = new StringBuilder(hash);
Files.walk(projectPath)
.sorted(Comparator.naturalOrder())
.filter(Files::isRegularFile)
.map(Path::toFile)
.forEach(file -> {
try {
byte[] buf = readFile(file);
byte[] toHash = Arrays.concatenate(buf, hashBuilder.toString().getBytes(UTF_8));
hashBuilder.setLength(0);
hashBuilder.append(Hex.toHexString(hash(toHash, new SHA3Digest())));
} catch (IOException ex) {
throw new RuntimeException(format("Error while reading file %s", file.getAbsolutePath()), ex);
}
});
// If original hash and final hash are the same, it indicates that no new contents were found
if (hashBuilder.toString().equals(hash)) {
throw new IOException(format("The chaincode directory \"%s\" has no files", projectPath));
}
return hashBuilder.toString();
} | java | public static String generateDirectoryHash(String rootDir, String chaincodeDir, String hash) throws IOException {
// Generate the project directory
Path projectPath = null;
if (rootDir == null) {
projectPath = Paths.get(chaincodeDir);
} else {
projectPath = Paths.get(rootDir, chaincodeDir);
}
File dir = projectPath.toFile();
if (!dir.exists() || !dir.isDirectory()) {
throw new IOException(format("The chaincode path \"%s\" is invalid", projectPath));
}
StringBuilder hashBuilder = new StringBuilder(hash);
Files.walk(projectPath)
.sorted(Comparator.naturalOrder())
.filter(Files::isRegularFile)
.map(Path::toFile)
.forEach(file -> {
try {
byte[] buf = readFile(file);
byte[] toHash = Arrays.concatenate(buf, hashBuilder.toString().getBytes(UTF_8));
hashBuilder.setLength(0);
hashBuilder.append(Hex.toHexString(hash(toHash, new SHA3Digest())));
} catch (IOException ex) {
throw new RuntimeException(format("Error while reading file %s", file.getAbsolutePath()), ex);
}
});
// If original hash and final hash are the same, it indicates that no new contents were found
if (hashBuilder.toString().equals(hash)) {
throw new IOException(format("The chaincode directory \"%s\" has no files", projectPath));
}
return hashBuilder.toString();
} | [
"public",
"static",
"String",
"generateDirectoryHash",
"(",
"String",
"rootDir",
",",
"String",
"chaincodeDir",
",",
"String",
"hash",
")",
"throws",
"IOException",
"{",
"// Generate the project directory",
"Path",
"projectPath",
"=",
"null",
";",
"if",
"(",
"rootDi... | Generate hash of a chaincode directory
@param rootDir Root directory
@param chaincodeDir Channel code directory
@param hash Previous hash (if any)
@return hash of the directory
@throws IOException | [
"Generate",
"hash",
"of",
"a",
"chaincode",
"directory"
] | train | https://github.com/hyperledger/fabric-sdk-java/blob/4a2d7b3408b8b0a1ed812aa36942c438159c37a0/src/main/java/org/hyperledger/fabric/sdk/helper/Utils.java#L95-L130 |
ModeShape/modeshape | modeshape-schematic/src/main/java/org/modeshape/schematic/internal/document/JsonReader.java | JsonReader.readMultiple | public DocumentSequence readMultiple( Reader reader,
boolean introspectStringValues ) {
"""
Return a {@link DocumentSequence} that can be used to pull multiple documents from the stream.
@param reader the IO reader; may not be null
@param introspectStringValues true if the string values should be examined for common patterns, or false otherwise
@return the sequence that can be used to get one or more Document instances from a single input
"""
// Create an object so that this reader is thread safe ...
final Tokenizer tokenizer = new Tokenizer(reader);
ValueMatcher matcher = introspectStringValues ? DATE_VALUE_MATCHER : SIMPLE_VALUE_MATCHER;
final Parser parser = new Parser(tokenizer, VALUE_FACTORY, matcher);
return () -> {
if (tokenizer.isFinished()) return null;
Document doc = parser.parseDocument(false);
// System.out.println(Json.writePretty(doc));
return doc;
};
} | java | public DocumentSequence readMultiple( Reader reader,
boolean introspectStringValues ) {
// Create an object so that this reader is thread safe ...
final Tokenizer tokenizer = new Tokenizer(reader);
ValueMatcher matcher = introspectStringValues ? DATE_VALUE_MATCHER : SIMPLE_VALUE_MATCHER;
final Parser parser = new Parser(tokenizer, VALUE_FACTORY, matcher);
return () -> {
if (tokenizer.isFinished()) return null;
Document doc = parser.parseDocument(false);
// System.out.println(Json.writePretty(doc));
return doc;
};
} | [
"public",
"DocumentSequence",
"readMultiple",
"(",
"Reader",
"reader",
",",
"boolean",
"introspectStringValues",
")",
"{",
"// Create an object so that this reader is thread safe ...",
"final",
"Tokenizer",
"tokenizer",
"=",
"new",
"Tokenizer",
"(",
"reader",
")",
";",
"V... | Return a {@link DocumentSequence} that can be used to pull multiple documents from the stream.
@param reader the IO reader; may not be null
@param introspectStringValues true if the string values should be examined for common patterns, or false otherwise
@return the sequence that can be used to get one or more Document instances from a single input | [
"Return",
"a",
"{",
"@link",
"DocumentSequence",
"}",
"that",
"can",
"be",
"used",
"to",
"pull",
"multiple",
"documents",
"from",
"the",
"stream",
"."
] | train | https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-schematic/src/main/java/org/modeshape/schematic/internal/document/JsonReader.java#L260-L272 |
SvenEwald/xmlbeam | src/main/java/org/xmlbeam/DefaultXPathBinder.java | DefaultXPathBinder.asInt | @Override
public CloseableValue<Integer> asInt() {
"""
Evaluates the XPath as a int value. This method is just a shortcut for as(Integer.TYPE);
@return int value of evaluation result.
"""
final Class<?> callerClass = ReflectionHelper.getDirectCallerClass();
return bindSingeValue(Integer.TYPE, callerClass);
} | java | @Override
public CloseableValue<Integer> asInt() {
final Class<?> callerClass = ReflectionHelper.getDirectCallerClass();
return bindSingeValue(Integer.TYPE, callerClass);
} | [
"@",
"Override",
"public",
"CloseableValue",
"<",
"Integer",
">",
"asInt",
"(",
")",
"{",
"final",
"Class",
"<",
"?",
">",
"callerClass",
"=",
"ReflectionHelper",
".",
"getDirectCallerClass",
"(",
")",
";",
"return",
"bindSingeValue",
"(",
"Integer",
".",
"T... | Evaluates the XPath as a int value. This method is just a shortcut for as(Integer.TYPE);
@return int value of evaluation result. | [
"Evaluates",
"the",
"XPath",
"as",
"a",
"int",
"value",
".",
"This",
"method",
"is",
"just",
"a",
"shortcut",
"for",
"as",
"(",
"Integer",
".",
"TYPE",
")",
";"
] | train | https://github.com/SvenEwald/xmlbeam/blob/acaac1b8fa28d246f17187f5e3c6696458a0b447/src/main/java/org/xmlbeam/DefaultXPathBinder.java#L87-L91 |
albfernandez/itext2 | src/main/java/com/lowagie/text/FontFactoryImp.java | FontFactoryImp.registerFamily | public void registerFamily(String familyName, String fullName, String path) {
"""
Register a font by giving explicitly the font family and name.
@param familyName the font family
@param fullName the font name
@param path the font path
"""
if (path != null)
trueTypeFonts.setProperty(fullName, path);
ArrayList tmp = (ArrayList) fontFamilies.get(familyName);
if (tmp == null) {
tmp = new ArrayList();
tmp.add(fullName);
fontFamilies.put(familyName, tmp);
}
else {
int fullNameLength = fullName.length();
boolean inserted = false;
for (int j = 0; j < tmp.size(); ++j) {
if (((String)tmp.get(j)).length() >= fullNameLength) {
tmp.add(j, fullName);
inserted = true;
break;
}
}
if (!inserted)
tmp.add(fullName);
}
} | java | public void registerFamily(String familyName, String fullName, String path) {
if (path != null)
trueTypeFonts.setProperty(fullName, path);
ArrayList tmp = (ArrayList) fontFamilies.get(familyName);
if (tmp == null) {
tmp = new ArrayList();
tmp.add(fullName);
fontFamilies.put(familyName, tmp);
}
else {
int fullNameLength = fullName.length();
boolean inserted = false;
for (int j = 0; j < tmp.size(); ++j) {
if (((String)tmp.get(j)).length() >= fullNameLength) {
tmp.add(j, fullName);
inserted = true;
break;
}
}
if (!inserted)
tmp.add(fullName);
}
} | [
"public",
"void",
"registerFamily",
"(",
"String",
"familyName",
",",
"String",
"fullName",
",",
"String",
"path",
")",
"{",
"if",
"(",
"path",
"!=",
"null",
")",
"trueTypeFonts",
".",
"setProperty",
"(",
"fullName",
",",
"path",
")",
";",
"ArrayList",
"tm... | Register a font by giving explicitly the font family and name.
@param familyName the font family
@param fullName the font name
@param path the font path | [
"Register",
"a",
"font",
"by",
"giving",
"explicitly",
"the",
"font",
"family",
"and",
"name",
"."
] | train | https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/FontFactoryImp.java#L486-L508 |
box/box-android-sdk | box-content-sdk/src/main/java/com/box/androidsdk/content/utils/SdkUtils.java | SdkUtils.setCollabNumberThumb | public static void setCollabNumberThumb(Context context, TextView initialsView, int collabNumber) {
"""
Helper method to display number of collaborators. If there are more than 99 collaborators it
would show "99+" due to the width constraint in the view.
@param context current context
@param initialsView TextView used to display number of collaborators
@param collabNumber Number of collaborators
"""
String collabNumberDisplay = (collabNumber >= 100) ? "+99" : "+" + Integer.toString(collabNumber);
setColorForCollabNumberThumb(initialsView);
initialsView.setTextColor(COLLAB_NUMBER_THUMB_COLOR);
initialsView.setText(collabNumberDisplay);
} | java | public static void setCollabNumberThumb(Context context, TextView initialsView, int collabNumber) {
String collabNumberDisplay = (collabNumber >= 100) ? "+99" : "+" + Integer.toString(collabNumber);
setColorForCollabNumberThumb(initialsView);
initialsView.setTextColor(COLLAB_NUMBER_THUMB_COLOR);
initialsView.setText(collabNumberDisplay);
} | [
"public",
"static",
"void",
"setCollabNumberThumb",
"(",
"Context",
"context",
",",
"TextView",
"initialsView",
",",
"int",
"collabNumber",
")",
"{",
"String",
"collabNumberDisplay",
"=",
"(",
"collabNumber",
">=",
"100",
")",
"?",
"\"+99\"",
":",
"\"+\"",
"+",
... | Helper method to display number of collaborators. If there are more than 99 collaborators it
would show "99+" due to the width constraint in the view.
@param context current context
@param initialsView TextView used to display number of collaborators
@param collabNumber Number of collaborators | [
"Helper",
"method",
"to",
"display",
"number",
"of",
"collaborators",
".",
"If",
"there",
"are",
"more",
"than",
"99",
"collaborators",
"it",
"would",
"show",
"99",
"+",
"due",
"to",
"the",
"width",
"constraint",
"in",
"the",
"view",
"."
] | train | https://github.com/box/box-android-sdk/blob/a621ad5ddebf23067fec27529130d72718fc0e88/box-content-sdk/src/main/java/com/box/androidsdk/content/utils/SdkUtils.java#L576-L581 |
bitcoinj/bitcoinj | wallettemplate/src/main/java/wallettemplate/utils/AlertWindowController.java | AlertWindowController.informational | public void informational(Stage stage, String message, String details) {
"""
Initialize this alert for general information: OK button only, nothing happens on dismissal.
"""
messageLabel.setText(message);
detailsLabel.setText(details);
cancelButton.setVisible(false);
actionButton.setVisible(false);
okButton.setOnAction(actionEvent -> stage.close());
} | java | public void informational(Stage stage, String message, String details) {
messageLabel.setText(message);
detailsLabel.setText(details);
cancelButton.setVisible(false);
actionButton.setVisible(false);
okButton.setOnAction(actionEvent -> stage.close());
} | [
"public",
"void",
"informational",
"(",
"Stage",
"stage",
",",
"String",
"message",
",",
"String",
"details",
")",
"{",
"messageLabel",
".",
"setText",
"(",
"message",
")",
";",
"detailsLabel",
".",
"setText",
"(",
"details",
")",
";",
"cancelButton",
".",
... | Initialize this alert for general information: OK button only, nothing happens on dismissal. | [
"Initialize",
"this",
"alert",
"for",
"general",
"information",
":",
"OK",
"button",
"only",
"nothing",
"happens",
"on",
"dismissal",
"."
] | train | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/wallettemplate/src/main/java/wallettemplate/utils/AlertWindowController.java#L41-L47 |
jbundle/jbundle | base/screen/model/src/main/java/org/jbundle/base/screen/model/util/SwitchSubScreenHandler.java | SwitchSubScreenHandler.init | public void init(BaseField field, BasePanel screenParent, BasePanel subScreen) {
"""
Constructor.
@param field The basefield owner of this listener (usually null and set on setOwner()).
@param screenParent The parent screen of this sub-screen.
@param subScreen The current sub-screen.
"""
super.init(field);
m_iCurrentScreenNo = -1;
m_screenParent = screenParent;
this.setCurrentSubScreen(subScreen);
} | java | public void init(BaseField field, BasePanel screenParent, BasePanel subScreen)
{
super.init(field);
m_iCurrentScreenNo = -1;
m_screenParent = screenParent;
this.setCurrentSubScreen(subScreen);
} | [
"public",
"void",
"init",
"(",
"BaseField",
"field",
",",
"BasePanel",
"screenParent",
",",
"BasePanel",
"subScreen",
")",
"{",
"super",
".",
"init",
"(",
"field",
")",
";",
"m_iCurrentScreenNo",
"=",
"-",
"1",
";",
"m_screenParent",
"=",
"screenParent",
";"... | Constructor.
@param field The basefield owner of this listener (usually null and set on setOwner()).
@param screenParent The parent screen of this sub-screen.
@param subScreen The current sub-screen. | [
"Constructor",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/screen/model/src/main/java/org/jbundle/base/screen/model/util/SwitchSubScreenHandler.java#L68-L74 |
op4j/op4j | src/main/java/org/op4j/functions/FnString.java | FnString.toInteger | public static final Function<String,Integer> toInteger(final RoundingMode roundingMode, final Locale locale) {
"""
<p>
Converts a String into an Integer, using the specified locale for determining
decimal point. Rounding mode is used for removing the
decimal part of the number. The integer part of the input string must be between
{@link Integer#MIN_VALUE} and {@link Integer#MAX_VALUE}
</p>
@param roundingMode the rounding mode to be used when setting the scale
@param locale the locale defining the way in which the number was written
@return the resulting Integer object
"""
return new ToInteger(roundingMode, locale);
} | java | public static final Function<String,Integer> toInteger(final RoundingMode roundingMode, final Locale locale) {
return new ToInteger(roundingMode, locale);
} | [
"public",
"static",
"final",
"Function",
"<",
"String",
",",
"Integer",
">",
"toInteger",
"(",
"final",
"RoundingMode",
"roundingMode",
",",
"final",
"Locale",
"locale",
")",
"{",
"return",
"new",
"ToInteger",
"(",
"roundingMode",
",",
"locale",
")",
";",
"}... | <p>
Converts a String into an Integer, using the specified locale for determining
decimal point. Rounding mode is used for removing the
decimal part of the number. The integer part of the input string must be between
{@link Integer#MIN_VALUE} and {@link Integer#MAX_VALUE}
</p>
@param roundingMode the rounding mode to be used when setting the scale
@param locale the locale defining the way in which the number was written
@return the resulting Integer object | [
"<p",
">",
"Converts",
"a",
"String",
"into",
"an",
"Integer",
"using",
"the",
"specified",
"locale",
"for",
"determining",
"decimal",
"point",
".",
"Rounding",
"mode",
"is",
"used",
"for",
"removing",
"the",
"decimal",
"part",
"of",
"the",
"number",
".",
... | train | https://github.com/op4j/op4j/blob/b577596dfe462089d3dd169666defc6de7ad289a/src/main/java/org/op4j/functions/FnString.java#L955-L957 |
OpenLiberty/open-liberty | dev/com.ibm.ws.container.service/src/com/ibm/ws/container/service/app/deploy/ManifestClassPathUtils.java | ManifestClassPathUtils.findClassPathEntry | private static Entry findClassPathEntry(Entry jarEntry, URI pathUri) throws URISyntaxException, UnableToAdaptException {
"""
calculate the class path entry based on the jar entry
@param jarEntry
@param pathUri
@return
@throws URISyntaxException
@throws UnableToAdaptException
"""
URI relativeJarUri = new URI("/").relativize(new URI(jarEntry.getPath()));
URI targetUri = null;
targetUri = relativeJarUri.resolve(pathUri);
if (targetUri.toString().startsWith("..")) {
Entry rootEntry = jarEntry.getRoot().adapt(Entry.class);
if (rootEntry == null || rootEntry.getPath().isEmpty()) { //already at the outermost
return null;
}
return findClassPathEntry(rootEntry, new URI("..").relativize(targetUri)); // <----
} else {
return jarEntry.getRoot().getEntry(targetUri.toString());
}
} | java | private static Entry findClassPathEntry(Entry jarEntry, URI pathUri) throws URISyntaxException, UnableToAdaptException {
URI relativeJarUri = new URI("/").relativize(new URI(jarEntry.getPath()));
URI targetUri = null;
targetUri = relativeJarUri.resolve(pathUri);
if (targetUri.toString().startsWith("..")) {
Entry rootEntry = jarEntry.getRoot().adapt(Entry.class);
if (rootEntry == null || rootEntry.getPath().isEmpty()) { //already at the outermost
return null;
}
return findClassPathEntry(rootEntry, new URI("..").relativize(targetUri)); // <----
} else {
return jarEntry.getRoot().getEntry(targetUri.toString());
}
} | [
"private",
"static",
"Entry",
"findClassPathEntry",
"(",
"Entry",
"jarEntry",
",",
"URI",
"pathUri",
")",
"throws",
"URISyntaxException",
",",
"UnableToAdaptException",
"{",
"URI",
"relativeJarUri",
"=",
"new",
"URI",
"(",
"\"/\"",
")",
".",
"relativize",
"(",
"... | calculate the class path entry based on the jar entry
@param jarEntry
@param pathUri
@return
@throws URISyntaxException
@throws UnableToAdaptException | [
"calculate",
"the",
"class",
"path",
"entry",
"based",
"on",
"the",
"jar",
"entry"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.container.service/src/com/ibm/ws/container/service/app/deploy/ManifestClassPathUtils.java#L194-L208 |
twilliamson/mogwee-logging | src/main/java/com/mogwee/logging/Logger.java | Logger.errorf | public final void errorf(Throwable cause, String message, Object... args) {
"""
Logs a formatted message and stack trace if ERROR logging is enabled.
@param cause an exception to print stack trace of
@param message a <a href="http://download.oracle.com/javase/6/docs/api/java/util/Formatter.html#syntax">format string</a>
@param args arguments referenced by the format specifiers in the format string.
"""
logf(Level.ERROR, cause, message, args);
} | java | public final void errorf(Throwable cause, String message, Object... args)
{
logf(Level.ERROR, cause, message, args);
} | [
"public",
"final",
"void",
"errorf",
"(",
"Throwable",
"cause",
",",
"String",
"message",
",",
"Object",
"...",
"args",
")",
"{",
"logf",
"(",
"Level",
".",
"ERROR",
",",
"cause",
",",
"message",
",",
"args",
")",
";",
"}"
] | Logs a formatted message and stack trace if ERROR logging is enabled.
@param cause an exception to print stack trace of
@param message a <a href="http://download.oracle.com/javase/6/docs/api/java/util/Formatter.html#syntax">format string</a>
@param args arguments referenced by the format specifiers in the format string. | [
"Logs",
"a",
"formatted",
"message",
"and",
"stack",
"trace",
"if",
"ERROR",
"logging",
"is",
"enabled",
"."
] | train | https://github.com/twilliamson/mogwee-logging/blob/30b99c2649de455432d956a8f6a74316de4cd62c/src/main/java/com/mogwee/logging/Logger.java#L267-L270 |
google/closure-templates | java/src/com/google/template/soy/jbcsrc/restricted/Expression.java | Expression.checkAssignableTo | @FormatMethod
public final void checkAssignableTo(Type expected, String fmt, Object... args) {
"""
Check that this expression is assignable to {@code expected}.
"""
if (Flags.DEBUG && !BytecodeUtils.isPossiblyAssignableFrom(expected, resultType())) {
String message =
String.format(
"Type mismatch. %s not assignable to %s.",
resultType().getClassName(), expected.getClassName());
if (!fmt.isEmpty()) {
message = String.format(fmt, args) + ". " + message;
}
throw new IllegalArgumentException(message);
}
} | java | @FormatMethod
public final void checkAssignableTo(Type expected, String fmt, Object... args) {
if (Flags.DEBUG && !BytecodeUtils.isPossiblyAssignableFrom(expected, resultType())) {
String message =
String.format(
"Type mismatch. %s not assignable to %s.",
resultType().getClassName(), expected.getClassName());
if (!fmt.isEmpty()) {
message = String.format(fmt, args) + ". " + message;
}
throw new IllegalArgumentException(message);
}
} | [
"@",
"FormatMethod",
"public",
"final",
"void",
"checkAssignableTo",
"(",
"Type",
"expected",
",",
"String",
"fmt",
",",
"Object",
"...",
"args",
")",
"{",
"if",
"(",
"Flags",
".",
"DEBUG",
"&&",
"!",
"BytecodeUtils",
".",
"isPossiblyAssignableFrom",
"(",
"e... | Check that this expression is assignable to {@code expected}. | [
"Check",
"that",
"this",
"expression",
"is",
"assignable",
"to",
"{"
] | train | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/restricted/Expression.java#L257-L270 |
gmessner/gitlab4j-api | src/main/java/org/gitlab4j/api/MergeRequestApi.java | MergeRequestApi.updateMergeRequest | public MergeRequest updateMergeRequest(Object projectIdOrPath, Integer mergeRequestIid,
String targetBranch, String title, Integer assigneeId, String description,
StateEvent stateEvent, String labels, Integer milestoneId, Boolean removeSourceBranch,
Boolean squash, Boolean discussionLocked, Boolean allowCollaboration)
throws GitLabApiException {
"""
Updates an existing merge request. You can change branches, title, or even close the MR.
<p>NOTE: GitLab API V4 uses IID (internal ID), V3 uses ID to identify the merge request.</p>
<pre><code>GitLab Endpoint: PUT /projects/:id/merge_requests/:merge_request_iid</code></pre>
@param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
@param mergeRequestIid the internal ID of the merge request to update
@param targetBranch the target branch, optional
@param title the title for the merge request
@param assigneeId the Assignee user ID, optional
@param description the description of the merge request, optional
@param stateEvent new state for the merge request, optional
@param labels comma separated list of labels, optional
@param milestoneId the ID of a milestone, optional
@param removeSourceBranch Flag indicating if a merge request should remove the source
branch when merging, optional
@param squash Squash commits into a single commit when merging, optional
@param discussionLocked Flag indicating if the merge request's discussion is locked, optional
@param allowCollaboration Allow commits from members who can merge to the target branch,
optional
@return the updated merge request
@throws GitLabApiException if any exception occurs
"""
Form formData = new GitLabApiForm()
.withParam("target_branch", targetBranch)
.withParam("title", title)
.withParam("assignee_id", assigneeId)
.withParam("description", description)
.withParam("state_event", stateEvent)
.withParam("labels", labels)
.withParam("milestone_id", milestoneId)
.withParam("remove_source_branch", removeSourceBranch)
.withParam("squash", squash)
.withParam("discussion_locked", discussionLocked)
.withParam("allow_collaboration", allowCollaboration);
return updateMergeRequest(projectIdOrPath, mergeRequestIid, formData);
} | java | public MergeRequest updateMergeRequest(Object projectIdOrPath, Integer mergeRequestIid,
String targetBranch, String title, Integer assigneeId, String description,
StateEvent stateEvent, String labels, Integer milestoneId, Boolean removeSourceBranch,
Boolean squash, Boolean discussionLocked, Boolean allowCollaboration)
throws GitLabApiException {
Form formData = new GitLabApiForm()
.withParam("target_branch", targetBranch)
.withParam("title", title)
.withParam("assignee_id", assigneeId)
.withParam("description", description)
.withParam("state_event", stateEvent)
.withParam("labels", labels)
.withParam("milestone_id", milestoneId)
.withParam("remove_source_branch", removeSourceBranch)
.withParam("squash", squash)
.withParam("discussion_locked", discussionLocked)
.withParam("allow_collaboration", allowCollaboration);
return updateMergeRequest(projectIdOrPath, mergeRequestIid, formData);
} | [
"public",
"MergeRequest",
"updateMergeRequest",
"(",
"Object",
"projectIdOrPath",
",",
"Integer",
"mergeRequestIid",
",",
"String",
"targetBranch",
",",
"String",
"title",
",",
"Integer",
"assigneeId",
",",
"String",
"description",
",",
"StateEvent",
"stateEvent",
","... | Updates an existing merge request. You can change branches, title, or even close the MR.
<p>NOTE: GitLab API V4 uses IID (internal ID), V3 uses ID to identify the merge request.</p>
<pre><code>GitLab Endpoint: PUT /projects/:id/merge_requests/:merge_request_iid</code></pre>
@param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
@param mergeRequestIid the internal ID of the merge request to update
@param targetBranch the target branch, optional
@param title the title for the merge request
@param assigneeId the Assignee user ID, optional
@param description the description of the merge request, optional
@param stateEvent new state for the merge request, optional
@param labels comma separated list of labels, optional
@param milestoneId the ID of a milestone, optional
@param removeSourceBranch Flag indicating if a merge request should remove the source
branch when merging, optional
@param squash Squash commits into a single commit when merging, optional
@param discussionLocked Flag indicating if the merge request's discussion is locked, optional
@param allowCollaboration Allow commits from members who can merge to the target branch,
optional
@return the updated merge request
@throws GitLabApiException if any exception occurs | [
"Updates",
"an",
"existing",
"merge",
"request",
".",
"You",
"can",
"change",
"branches",
"title",
"or",
"even",
"close",
"the",
"MR",
"."
] | train | https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/MergeRequestApi.java#L445-L465 |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/memcached/MemcachedServer.java | MemcachedServer.main | public static void main(String[] args) {
"""
Program entry point that runs the memcached server as a standalone
server just like any other memcached server...
@param args Program arguments (not used)
"""
try {
VBucketInfo vbi[] = new VBucketInfo[1024];
for (int ii = 0; ii < vbi.length; ++ii) {
vbi[ii] = new VBucketInfo();
}
MemcachedServer server = new MemcachedServer(null, null, 11211, vbi, false);
for (VBucketInfo aVbi : vbi) {
aVbi.setOwner(server);
}
server.run();
} catch (IOException e) {
Logger.getLogger(MemcachedServer.class.getName()).log(Level.SEVERE, "Fatal error! failed to create socket: ", e);
}
} | java | public static void main(String[] args) {
try {
VBucketInfo vbi[] = new VBucketInfo[1024];
for (int ii = 0; ii < vbi.length; ++ii) {
vbi[ii] = new VBucketInfo();
}
MemcachedServer server = new MemcachedServer(null, null, 11211, vbi, false);
for (VBucketInfo aVbi : vbi) {
aVbi.setOwner(server);
}
server.run();
} catch (IOException e) {
Logger.getLogger(MemcachedServer.class.getName()).log(Level.SEVERE, "Fatal error! failed to create socket: ", e);
}
} | [
"public",
"static",
"void",
"main",
"(",
"String",
"[",
"]",
"args",
")",
"{",
"try",
"{",
"VBucketInfo",
"vbi",
"[",
"]",
"=",
"new",
"VBucketInfo",
"[",
"1024",
"]",
";",
"for",
"(",
"int",
"ii",
"=",
"0",
";",
"ii",
"<",
"vbi",
".",
"length",
... | Program entry point that runs the memcached server as a standalone
server just like any other memcached server...
@param args Program arguments (not used) | [
"Program",
"entry",
"point",
"that",
"runs",
"the",
"memcached",
"server",
"as",
"a",
"standalone",
"server",
"just",
"like",
"any",
"other",
"memcached",
"server",
"..."
] | train | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/memcached/MemcachedServer.java#L651-L665 |
apereo/cas | core/cas-server-core-rest/src/main/java/org/apereo/cas/rest/factory/CasProtocolServiceTicketResourceEntityResponseFactory.java | CasProtocolServiceTicketResourceEntityResponseFactory.grantServiceTicket | protected String grantServiceTicket(final String ticketGrantingTicket, final Service service, final AuthenticationResult authenticationResult) {
"""
Grant service ticket service ticket.
@param ticketGrantingTicket the ticket granting ticket
@param service the service
@param authenticationResult the authentication result
@return the service ticket
"""
val ticket = centralAuthenticationService.grantServiceTicket(ticketGrantingTicket, service, authenticationResult);
LOGGER.debug("Generated service ticket [{}]", ticket.getId());
return ticket.getId();
} | java | protected String grantServiceTicket(final String ticketGrantingTicket, final Service service, final AuthenticationResult authenticationResult) {
val ticket = centralAuthenticationService.grantServiceTicket(ticketGrantingTicket, service, authenticationResult);
LOGGER.debug("Generated service ticket [{}]", ticket.getId());
return ticket.getId();
} | [
"protected",
"String",
"grantServiceTicket",
"(",
"final",
"String",
"ticketGrantingTicket",
",",
"final",
"Service",
"service",
",",
"final",
"AuthenticationResult",
"authenticationResult",
")",
"{",
"val",
"ticket",
"=",
"centralAuthenticationService",
".",
"grantServic... | Grant service ticket service ticket.
@param ticketGrantingTicket the ticket granting ticket
@param service the service
@param authenticationResult the authentication result
@return the service ticket | [
"Grant",
"service",
"ticket",
"service",
"ticket",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-rest/src/main/java/org/apereo/cas/rest/factory/CasProtocolServiceTicketResourceEntityResponseFactory.java#L42-L47 |
TheHortonMachine/hortonmachine | hmachine/src/main/java/org/hortonmachine/hmachine/modules/networktools/epanet/core/EpanetWrapper.java | EpanetWrapper.ENgetnodevalue | public float ENgetnodevalue( int index, NodeParameters code ) throws EpanetException {
"""
Retrieves the value of a specific link (node?) parameter.
@param index the node index.
@param code the parameter code.
@return the value at the node.
@throws EpanetException
"""
float[] nodeValue = new float[1];
int error = epanet.ENgetnodevalue(index, code.getCode(), nodeValue);
checkError(error);
return nodeValue[0];
} | java | public float ENgetnodevalue( int index, NodeParameters code ) throws EpanetException {
float[] nodeValue = new float[1];
int error = epanet.ENgetnodevalue(index, code.getCode(), nodeValue);
checkError(error);
return nodeValue[0];
} | [
"public",
"float",
"ENgetnodevalue",
"(",
"int",
"index",
",",
"NodeParameters",
"code",
")",
"throws",
"EpanetException",
"{",
"float",
"[",
"]",
"nodeValue",
"=",
"new",
"float",
"[",
"1",
"]",
";",
"int",
"error",
"=",
"epanet",
".",
"ENgetnodevalue",
"... | Retrieves the value of a specific link (node?) parameter.
@param index the node index.
@param code the parameter code.
@return the value at the node.
@throws EpanetException | [
"Retrieves",
"the",
"value",
"of",
"a",
"specific",
"link",
"(",
"node?",
")",
"parameter",
"."
] | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/hmachine/src/main/java/org/hortonmachine/hmachine/modules/networktools/epanet/core/EpanetWrapper.java#L491-L496 |
EsotericSoftware/kryo | src/com/esotericsoftware/kryo/io/Input.java | Input.setBuffer | public void setBuffer (byte[] bytes, int offset, int count) {
"""
Sets a new buffer to read from. The bytes are not copied, the old buffer is discarded and the new buffer used in its place.
The position and total are reset. The {@link #setInputStream(InputStream) InputStream} is set to null.
"""
if (bytes == null) throw new IllegalArgumentException("bytes cannot be null.");
buffer = bytes;
position = offset;
limit = offset + count;
capacity = bytes.length;
total = 0;
inputStream = null;
} | java | public void setBuffer (byte[] bytes, int offset, int count) {
if (bytes == null) throw new IllegalArgumentException("bytes cannot be null.");
buffer = bytes;
position = offset;
limit = offset + count;
capacity = bytes.length;
total = 0;
inputStream = null;
} | [
"public",
"void",
"setBuffer",
"(",
"byte",
"[",
"]",
"bytes",
",",
"int",
"offset",
",",
"int",
"count",
")",
"{",
"if",
"(",
"bytes",
"==",
"null",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"bytes cannot be null.\"",
")",
";",
"buffer",
"="... | Sets a new buffer to read from. The bytes are not copied, the old buffer is discarded and the new buffer used in its place.
The position and total are reset. The {@link #setInputStream(InputStream) InputStream} is set to null. | [
"Sets",
"a",
"new",
"buffer",
"to",
"read",
"from",
".",
"The",
"bytes",
"are",
"not",
"copied",
"the",
"old",
"buffer",
"is",
"discarded",
"and",
"the",
"new",
"buffer",
"used",
"in",
"its",
"place",
".",
"The",
"position",
"and",
"total",
"are",
"res... | train | https://github.com/EsotericSoftware/kryo/blob/a8be1ab26f347f299a3c3f7171d6447dd5390845/src/com/esotericsoftware/kryo/io/Input.java#L91-L99 |
morfologik/morfologik-stemming | morfologik-fsa/src/main/java/morfologik/fsa/FSA.java | FSA.visitInPreOrder | public <T extends StateVisitor> T visitInPreOrder(T v, int node) {
"""
Visits all states in preorder. Returning false from
{@link StateVisitor#accept(int)} skips traversal of all sub-states of a
given state.
@param v Visitor to receive traversal calls.
@param <T> A subclass of {@link StateVisitor}.
@param node Identifier of the node.
@return Returns the argument (for access to anonymous class fields).
"""
visitInPreOrder(v, node, new BitSet());
return v;
} | java | public <T extends StateVisitor> T visitInPreOrder(T v, int node) {
visitInPreOrder(v, node, new BitSet());
return v;
} | [
"public",
"<",
"T",
"extends",
"StateVisitor",
">",
"T",
"visitInPreOrder",
"(",
"T",
"v",
",",
"int",
"node",
")",
"{",
"visitInPreOrder",
"(",
"v",
",",
"node",
",",
"new",
"BitSet",
"(",
")",
")",
";",
"return",
"v",
";",
"}"
] | Visits all states in preorder. Returning false from
{@link StateVisitor#accept(int)} skips traversal of all sub-states of a
given state.
@param v Visitor to receive traversal calls.
@param <T> A subclass of {@link StateVisitor}.
@param node Identifier of the node.
@return Returns the argument (for access to anonymous class fields). | [
"Visits",
"all",
"states",
"in",
"preorder",
".",
"Returning",
"false",
"from",
"{",
"@link",
"StateVisitor#accept",
"(",
"int",
")",
"}",
"skips",
"traversal",
"of",
"all",
"sub",
"-",
"states",
"of",
"a",
"given",
"state",
"."
] | train | https://github.com/morfologik/morfologik-stemming/blob/9d9099cc5ec4155a0eb8dfecdc23d01cbd734f6e/morfologik-fsa/src/main/java/morfologik/fsa/FSA.java#L263-L266 |
gallandarakhneorg/afc | advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/location/GeoLocationUtil.java | GeoLocationUtil.makeInternalId | @Pure
public static String makeInternalId(float minx, float miny, float maxx, float maxy) {
"""
Compute and replies the internal identifier that may
be used to create a GeoId from the given rectangle.
@param minx minimum x coordinate of the bounding rectangle.
@param miny minimum y coordinate of the bounding rectangle.
@param maxx maximum x coordinate of the bounding rectangle.
@param maxy maximum y coordinate of the bounding rectangle.
@return the internal identifier.
"""
final StringBuilder buf = new StringBuilder("rectangle"); //$NON-NLS-1$
buf.append('(');
buf.append(minx);
buf.append(';');
buf.append(miny);
buf.append(")-("); //$NON-NLS-1$
buf.append(maxx);
buf.append(';');
buf.append(maxy);
buf.append(')');
return Encryption.md5(buf.toString());
} | java | @Pure
public static String makeInternalId(float minx, float miny, float maxx, float maxy) {
final StringBuilder buf = new StringBuilder("rectangle"); //$NON-NLS-1$
buf.append('(');
buf.append(minx);
buf.append(';');
buf.append(miny);
buf.append(")-("); //$NON-NLS-1$
buf.append(maxx);
buf.append(';');
buf.append(maxy);
buf.append(')');
return Encryption.md5(buf.toString());
} | [
"@",
"Pure",
"public",
"static",
"String",
"makeInternalId",
"(",
"float",
"minx",
",",
"float",
"miny",
",",
"float",
"maxx",
",",
"float",
"maxy",
")",
"{",
"final",
"StringBuilder",
"buf",
"=",
"new",
"StringBuilder",
"(",
"\"rectangle\"",
")",
";",
"//... | Compute and replies the internal identifier that may
be used to create a GeoId from the given rectangle.
@param minx minimum x coordinate of the bounding rectangle.
@param miny minimum y coordinate of the bounding rectangle.
@param maxx maximum x coordinate of the bounding rectangle.
@param maxy maximum y coordinate of the bounding rectangle.
@return the internal identifier. | [
"Compute",
"and",
"replies",
"the",
"internal",
"identifier",
"that",
"may",
"be",
"used",
"to",
"create",
"a",
"GeoId",
"from",
"the",
"given",
"rectangle",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/location/GeoLocationUtil.java#L376-L389 |
aleksandr-m/gitflow-maven-plugin | src/main/java/com/amashchenko/maven/plugin/gitflow/AbstractGitFlowMojo.java | AbstractGitFlowMojo.readModel | private Model readModel(MavenProject project) throws MojoFailureException {
"""
Reads model from Maven project pom.xml.
@param project
Maven project
@return Maven model
@throws MojoFailureException
"""
try {
// read pom.xml
Model model;
FileReader fileReader = new FileReader(project.getFile().getAbsoluteFile());
MavenXpp3Reader mavenReader = new MavenXpp3Reader();
try {
model = mavenReader.read(fileReader);
} finally {
if (fileReader != null) {
fileReader.close();
}
}
return model;
} catch (Exception e) {
throw new MojoFailureException("", e);
}
} | java | private Model readModel(MavenProject project) throws MojoFailureException {
try {
// read pom.xml
Model model;
FileReader fileReader = new FileReader(project.getFile().getAbsoluteFile());
MavenXpp3Reader mavenReader = new MavenXpp3Reader();
try {
model = mavenReader.read(fileReader);
} finally {
if (fileReader != null) {
fileReader.close();
}
}
return model;
} catch (Exception e) {
throw new MojoFailureException("", e);
}
} | [
"private",
"Model",
"readModel",
"(",
"MavenProject",
"project",
")",
"throws",
"MojoFailureException",
"{",
"try",
"{",
"// read pom.xml",
"Model",
"model",
";",
"FileReader",
"fileReader",
"=",
"new",
"FileReader",
"(",
"project",
".",
"getFile",
"(",
")",
"."... | Reads model from Maven project pom.xml.
@param project
Maven project
@return Maven model
@throws MojoFailureException | [
"Reads",
"model",
"from",
"Maven",
"project",
"pom",
".",
"xml",
"."
] | train | https://github.com/aleksandr-m/gitflow-maven-plugin/blob/d7be13c653d885c1cb1d8cd0337fa9db985c381e/src/main/java/com/amashchenko/maven/plugin/gitflow/AbstractGitFlowMojo.java#L245-L262 |
alkacon/opencms-core | src/org/opencms/workflow/CmsExtendedWorkflowManager.java | CmsExtendedWorkflowManager.clearLocks | protected void clearLocks(CmsProject project, List<CmsResource> resources) throws CmsException {
"""
Ensures that the resources to be released are unlocked.<p>
@param project the project in which to operate
@param resources the resources for which the locks should be removed
@throws CmsException if something goes wrong
"""
CmsObject rootCms = OpenCms.initCmsObject(m_adminCms);
rootCms.getRequestContext().setCurrentProject(project);
rootCms.getRequestContext().setSiteRoot("");
for (CmsResource resource : resources) {
CmsLock lock = rootCms.getLock(resource);
if (lock.isUnlocked()) {
continue;
}
String currentPath = resource.getRootPath();
while (lock.isInherited()) {
currentPath = CmsResource.getParentFolder(currentPath);
lock = rootCms.getLock(currentPath);
}
rootCms.changeLock(currentPath);
rootCms.unlockResource(currentPath);
}
} | java | protected void clearLocks(CmsProject project, List<CmsResource> resources) throws CmsException {
CmsObject rootCms = OpenCms.initCmsObject(m_adminCms);
rootCms.getRequestContext().setCurrentProject(project);
rootCms.getRequestContext().setSiteRoot("");
for (CmsResource resource : resources) {
CmsLock lock = rootCms.getLock(resource);
if (lock.isUnlocked()) {
continue;
}
String currentPath = resource.getRootPath();
while (lock.isInherited()) {
currentPath = CmsResource.getParentFolder(currentPath);
lock = rootCms.getLock(currentPath);
}
rootCms.changeLock(currentPath);
rootCms.unlockResource(currentPath);
}
} | [
"protected",
"void",
"clearLocks",
"(",
"CmsProject",
"project",
",",
"List",
"<",
"CmsResource",
">",
"resources",
")",
"throws",
"CmsException",
"{",
"CmsObject",
"rootCms",
"=",
"OpenCms",
".",
"initCmsObject",
"(",
"m_adminCms",
")",
";",
"rootCms",
".",
"... | Ensures that the resources to be released are unlocked.<p>
@param project the project in which to operate
@param resources the resources for which the locks should be removed
@throws CmsException if something goes wrong | [
"Ensures",
"that",
"the",
"resources",
"to",
"be",
"released",
"are",
"unlocked",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/workflow/CmsExtendedWorkflowManager.java#L437-L455 |
apiman/apiman | gateway/platforms/war/micro/src/main/java/io/apiman/gateway/platforms/war/micro/GatewayMicroService.java | GatewayMicroService.setConfigProperty | protected void setConfigProperty(String propName, String propValue) {
"""
Sets a system property if it's not already set.
@param propName
@param propValue
"""
if (System.getProperty(propName) == null) {
System.setProperty(propName, propValue);
}
} | java | protected void setConfigProperty(String propName, String propValue) {
if (System.getProperty(propName) == null) {
System.setProperty(propName, propValue);
}
} | [
"protected",
"void",
"setConfigProperty",
"(",
"String",
"propName",
",",
"String",
"propValue",
")",
"{",
"if",
"(",
"System",
".",
"getProperty",
"(",
"propName",
")",
"==",
"null",
")",
"{",
"System",
".",
"setProperty",
"(",
"propName",
",",
"propValue",... | Sets a system property if it's not already set.
@param propName
@param propValue | [
"Sets",
"a",
"system",
"property",
"if",
"it",
"s",
"not",
"already",
"set",
"."
] | train | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/platforms/war/micro/src/main/java/io/apiman/gateway/platforms/war/micro/GatewayMicroService.java#L258-L262 |
Azure/azure-sdk-for-java | applicationinsights/resource-manager/v2015_05_01/src/main/java/com/microsoft/azure/management/applicationinsights/v2015_05_01/implementation/AnnotationsInner.java | AnnotationsInner.getAsync | public Observable<List<AnnotationInner>> getAsync(String resourceGroupName, String resourceName, String annotationId) {
"""
Get the annotation for given id.
@param resourceGroupName The name of the resource group.
@param resourceName The name of the Application Insights component resource.
@param annotationId The unique annotation ID. This is unique within a Application Insights component.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the List<AnnotationInner> object
"""
return getWithServiceResponseAsync(resourceGroupName, resourceName, annotationId).map(new Func1<ServiceResponse<List<AnnotationInner>>, List<AnnotationInner>>() {
@Override
public List<AnnotationInner> call(ServiceResponse<List<AnnotationInner>> response) {
return response.body();
}
});
} | java | public Observable<List<AnnotationInner>> getAsync(String resourceGroupName, String resourceName, String annotationId) {
return getWithServiceResponseAsync(resourceGroupName, resourceName, annotationId).map(new Func1<ServiceResponse<List<AnnotationInner>>, List<AnnotationInner>>() {
@Override
public List<AnnotationInner> call(ServiceResponse<List<AnnotationInner>> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"List",
"<",
"AnnotationInner",
">",
">",
"getAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"resourceName",
",",
"String",
"annotationId",
")",
"{",
"return",
"getWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"re... | Get the annotation for given id.
@param resourceGroupName The name of the resource group.
@param resourceName The name of the Application Insights component resource.
@param annotationId The unique annotation ID. This is unique within a Application Insights component.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the List<AnnotationInner> object | [
"Get",
"the",
"annotation",
"for",
"given",
"id",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/applicationinsights/resource-manager/v2015_05_01/src/main/java/com/microsoft/azure/management/applicationinsights/v2015_05_01/implementation/AnnotationsInner.java#L408-L415 |
joniles/mpxj | src/main/java/net/sf/mpxj/ResourceAssignment.java | ResourceAssignment.setText | public void setText(int index, String value) {
"""
Set a text value.
@param index text index (1-30)
@param value text value
"""
set(selectField(AssignmentFieldLists.CUSTOM_TEXT, index), value);
} | java | public void setText(int index, String value)
{
set(selectField(AssignmentFieldLists.CUSTOM_TEXT, index), value);
} | [
"public",
"void",
"setText",
"(",
"int",
"index",
",",
"String",
"value",
")",
"{",
"set",
"(",
"selectField",
"(",
"AssignmentFieldLists",
".",
"CUSTOM_TEXT",
",",
"index",
")",
",",
"value",
")",
";",
"}"
] | Set a text value.
@param index text index (1-30)
@param value text value | [
"Set",
"a",
"text",
"value",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/ResourceAssignment.java#L1518-L1521 |
code4craft/webmagic | webmagic-core/src/main/java/us/codecraft/webmagic/Site.java | Site.addHeader | public Site addHeader(String key, String value) {
"""
Put an Http header for downloader. <br>
Use {@link #addCookie(String, String)} for cookie and {@link #setUserAgent(String)} for user-agent. <br>
@param key key of http header, there are some keys constant in {@link HttpConstant.Header}
@param value value of header
@return this
"""
headers.put(key, value);
return this;
} | java | public Site addHeader(String key, String value) {
headers.put(key, value);
return this;
} | [
"public",
"Site",
"addHeader",
"(",
"String",
"key",
",",
"String",
"value",
")",
"{",
"headers",
".",
"put",
"(",
"key",
",",
"value",
")",
";",
"return",
"this",
";",
"}"
] | Put an Http header for downloader. <br>
Use {@link #addCookie(String, String)} for cookie and {@link #setUserAgent(String)} for user-agent. <br>
@param key key of http header, there are some keys constant in {@link HttpConstant.Header}
@param value value of header
@return this | [
"Put",
"an",
"Http",
"header",
"for",
"downloader",
".",
"<br",
">",
"Use",
"{",
"@link",
"#addCookie",
"(",
"String",
"String",
")",
"}",
"for",
"cookie",
"and",
"{",
"@link",
"#setUserAgent",
"(",
"String",
")",
"}",
"for",
"user",
"-",
"agent",
".",... | train | https://github.com/code4craft/webmagic/blob/be892b80bf6682cd063d30ac25a79be0c079a901/webmagic-core/src/main/java/us/codecraft/webmagic/Site.java#L247-L250 |
mgm-tp/jfunk | jfunk-data-generator/src/main/java/com/mgmtp/jfunk/data/generator/field/FieldFactory.java | FieldFactory.createField | public Field createField(final MathRandom random, final Element element, final String characterSetId) {
"""
Searches for the Field Child tag in the specified element or takes the Field_Ref Tag and
generates a new field instance based on the tag data. So this method has to be called with an
element as parameter that contains a field or a field_ref element, respectively.
"""
Field field = null;
Element fieldElement = null;
Element fieldRefElement = element.getChild(XMLTags.FIELD_REF);
if (fieldRefElement != null) {
fieldElement = getElementFinder(element).findElementById(fieldRefElement);
} else {
fieldElement = element.getChild(XMLTags.FIELD);
}
checkState(fieldElement != null, "Could not find a Field tag or FieldRef tag");
Class<? extends Field> classObject = null;
try {
classObject = getClassObject(fieldElement);
Constructor<? extends Field> constructor = classObject.getConstructor(new Class[] { MathRandom.class, Element.class, String.class });
field = constructor.newInstance(new Object[] { random, fieldElement, characterSetId });
} catch (Exception e) {
throw new IllegalStateException("Could not initialise object of class " + classObject, e);
}
return field;
} | java | public Field createField(final MathRandom random, final Element element, final String characterSetId) {
Field field = null;
Element fieldElement = null;
Element fieldRefElement = element.getChild(XMLTags.FIELD_REF);
if (fieldRefElement != null) {
fieldElement = getElementFinder(element).findElementById(fieldRefElement);
} else {
fieldElement = element.getChild(XMLTags.FIELD);
}
checkState(fieldElement != null, "Could not find a Field tag or FieldRef tag");
Class<? extends Field> classObject = null;
try {
classObject = getClassObject(fieldElement);
Constructor<? extends Field> constructor = classObject.getConstructor(new Class[] { MathRandom.class, Element.class, String.class });
field = constructor.newInstance(new Object[] { random, fieldElement, characterSetId });
} catch (Exception e) {
throw new IllegalStateException("Could not initialise object of class " + classObject, e);
}
return field;
} | [
"public",
"Field",
"createField",
"(",
"final",
"MathRandom",
"random",
",",
"final",
"Element",
"element",
",",
"final",
"String",
"characterSetId",
")",
"{",
"Field",
"field",
"=",
"null",
";",
"Element",
"fieldElement",
"=",
"null",
";",
"Element",
"fieldRe... | Searches for the Field Child tag in the specified element or takes the Field_Ref Tag and
generates a new field instance based on the tag data. So this method has to be called with an
element as parameter that contains a field or a field_ref element, respectively. | [
"Searches",
"for",
"the",
"Field",
"Child",
"tag",
"in",
"the",
"specified",
"element",
"or",
"takes",
"the",
"Field_Ref",
"Tag",
"and",
"generates",
"a",
"new",
"field",
"instance",
"based",
"on",
"the",
"tag",
"data",
".",
"So",
"this",
"method",
"has",
... | train | https://github.com/mgm-tp/jfunk/blob/5b9fecac5778b988bb458085ded39ea9a4c7c2ae/jfunk-data-generator/src/main/java/com/mgmtp/jfunk/data/generator/field/FieldFactory.java#L53-L74 |
Azure/azure-sdk-for-java | batch/data-plane/src/main/java/com/microsoft/azure/batch/JobOperations.java | JobOperations.patchJob | public void patchJob(String jobId, OnAllTasksComplete onAllTasksComplete) throws BatchErrorException, IOException {
"""
Updates the specified job.
This method only replaces the properties specified with non-null values.
@param jobId The ID of the job.
@param onAllTasksComplete Specifies an action the Batch service should take when all tasks in the job are in the completed state.
@throws BatchErrorException Exception thrown when an error response is received from the Batch service.
@throws IOException Exception thrown when there is an error in serialization/deserialization of data sent to/received from the Batch service.
"""
patchJob(jobId, null, null, null, onAllTasksComplete, null, null);
} | java | public void patchJob(String jobId, OnAllTasksComplete onAllTasksComplete) throws BatchErrorException, IOException {
patchJob(jobId, null, null, null, onAllTasksComplete, null, null);
} | [
"public",
"void",
"patchJob",
"(",
"String",
"jobId",
",",
"OnAllTasksComplete",
"onAllTasksComplete",
")",
"throws",
"BatchErrorException",
",",
"IOException",
"{",
"patchJob",
"(",
"jobId",
",",
"null",
",",
"null",
",",
"null",
",",
"onAllTasksComplete",
",",
... | Updates the specified job.
This method only replaces the properties specified with non-null values.
@param jobId The ID of the job.
@param onAllTasksComplete Specifies an action the Batch service should take when all tasks in the job are in the completed state.
@throws BatchErrorException Exception thrown when an error response is received from the Batch service.
@throws IOException Exception thrown when there is an error in serialization/deserialization of data sent to/received from the Batch service. | [
"Updates",
"the",
"specified",
"job",
".",
"This",
"method",
"only",
"replaces",
"the",
"properties",
"specified",
"with",
"non",
"-",
"null",
"values",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/JobOperations.java#L517-L519 |
alexa/alexa-skills-kit-sdk-for-java | ask-sdk-core/src/com/amazon/ask/util/UserAgentUtils.java | UserAgentUtils.getUserAgent | public static String getUserAgent(String customUserAgent) {
"""
Returns the user agent string. Format is "(SDK name)/(SDK version) (Language)/(Language version)"
Custom user agent will be appended to the end of the standard user agent.
@param customUserAgent custom user agent to append to end of standard user agent
@return user agent string
"""
Properties systemProperties;
try {
systemProperties = System.getProperties();
} catch (SecurityException e) {
logger.debug("Unable to determine JVM version due to security restrictions.");
systemProperties = null;
}
return internalGetUserAgent(systemProperties, customUserAgent);
} | java | public static String getUserAgent(String customUserAgent) {
Properties systemProperties;
try {
systemProperties = System.getProperties();
} catch (SecurityException e) {
logger.debug("Unable to determine JVM version due to security restrictions.");
systemProperties = null;
}
return internalGetUserAgent(systemProperties, customUserAgent);
} | [
"public",
"static",
"String",
"getUserAgent",
"(",
"String",
"customUserAgent",
")",
"{",
"Properties",
"systemProperties",
";",
"try",
"{",
"systemProperties",
"=",
"System",
".",
"getProperties",
"(",
")",
";",
"}",
"catch",
"(",
"SecurityException",
"e",
")",... | Returns the user agent string. Format is "(SDK name)/(SDK version) (Language)/(Language version)"
Custom user agent will be appended to the end of the standard user agent.
@param customUserAgent custom user agent to append to end of standard user agent
@return user agent string | [
"Returns",
"the",
"user",
"agent",
"string",
".",
"Format",
"is",
"(",
"SDK",
"name",
")",
"/",
"(",
"SDK",
"version",
")",
"(",
"Language",
")",
"/",
"(",
"Language",
"version",
")",
"Custom",
"user",
"agent",
"will",
"be",
"appended",
"to",
"the",
... | train | https://github.com/alexa/alexa-skills-kit-sdk-for-java/blob/c49194da0693898c70f3f2c4a372f5a12da04e3e/ask-sdk-core/src/com/amazon/ask/util/UserAgentUtils.java#L45-L54 |
jillesvangurp/jsonj | src/main/java/com/github/jsonj/tools/JsonBuilder.java | JsonBuilder.put | public @Nonnull JsonBuilder put(String key, boolean b) {
"""
Add a boolean value to the object.
@param key key
@param b value
@return the builder
"""
object.put(key, primitive(b));
return this;
} | java | public @Nonnull JsonBuilder put(String key, boolean b) {
object.put(key, primitive(b));
return this;
} | [
"public",
"@",
"Nonnull",
"JsonBuilder",
"put",
"(",
"String",
"key",
",",
"boolean",
"b",
")",
"{",
"object",
".",
"put",
"(",
"key",
",",
"primitive",
"(",
"b",
")",
")",
";",
"return",
"this",
";",
"}"
] | Add a boolean value to the object.
@param key key
@param b value
@return the builder | [
"Add",
"a",
"boolean",
"value",
"to",
"the",
"object",
"."
] | train | https://github.com/jillesvangurp/jsonj/blob/1da0c44c5bdb60c0cd806c48d2da5a8a75bf84af/src/main/java/com/github/jsonj/tools/JsonBuilder.java#L100-L103 |
TheHortonMachine/hortonmachine | gears/src/main/java/org/hortonmachine/gears/libs/modules/HMModel.java | HMModel.dumpVector | public void dumpVector( SimpleFeatureCollection vector, String source ) throws Exception {
"""
Fast default writing of vector to source.
<p>Mind that if either vector or source are <code>null</code>, the method will
return without warning.</p>
@param vector the {@link SimpleFeatureCollection} to write.
@param source the source to which to write to.
@throws Exception
"""
if (vector == null || source == null)
return;
OmsVectorWriter writer = new OmsVectorWriter();
writer.pm = pm;
writer.file = source;
writer.inVector = vector;
writer.process();
} | java | public void dumpVector( SimpleFeatureCollection vector, String source ) throws Exception {
if (vector == null || source == null)
return;
OmsVectorWriter writer = new OmsVectorWriter();
writer.pm = pm;
writer.file = source;
writer.inVector = vector;
writer.process();
} | [
"public",
"void",
"dumpVector",
"(",
"SimpleFeatureCollection",
"vector",
",",
"String",
"source",
")",
"throws",
"Exception",
"{",
"if",
"(",
"vector",
"==",
"null",
"||",
"source",
"==",
"null",
")",
"return",
";",
"OmsVectorWriter",
"writer",
"=",
"new",
... | Fast default writing of vector to source.
<p>Mind that if either vector or source are <code>null</code>, the method will
return without warning.</p>
@param vector the {@link SimpleFeatureCollection} to write.
@param source the source to which to write to.
@throws Exception | [
"Fast",
"default",
"writing",
"of",
"vector",
"to",
"source",
"."
] | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/libs/modules/HMModel.java#L341-L349 |
apptentive/apptentive-android | apptentive/src/main/java/com/apptentive/android/sdk/notifications/ApptentiveNotificationObserverList.java | ApptentiveNotificationObserverList.addObserver | boolean addObserver(ApptentiveNotificationObserver observer, boolean useWeakReference) {
"""
Adds an observer to the list without duplicates.
@param useWeakReference - use weak reference if <code>true</code>
@return <code>true</code> - if observer was added
"""
if (observer == null) {
throw new IllegalArgumentException("Observer is null");
}
if (!contains(observer)) {
observers.add(useWeakReference ? new ObserverWeakReference(observer) : observer);
return true;
}
return false;
} | java | boolean addObserver(ApptentiveNotificationObserver observer, boolean useWeakReference) {
if (observer == null) {
throw new IllegalArgumentException("Observer is null");
}
if (!contains(observer)) {
observers.add(useWeakReference ? new ObserverWeakReference(observer) : observer);
return true;
}
return false;
} | [
"boolean",
"addObserver",
"(",
"ApptentiveNotificationObserver",
"observer",
",",
"boolean",
"useWeakReference",
")",
"{",
"if",
"(",
"observer",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Observer is null\"",
")",
";",
"}",
"if",
... | Adds an observer to the list without duplicates.
@param useWeakReference - use weak reference if <code>true</code>
@return <code>true</code> - if observer was added | [
"Adds",
"an",
"observer",
"to",
"the",
"list",
"without",
"duplicates",
"."
] | train | https://github.com/apptentive/apptentive-android/blob/887c08d7bd5ae6488a90366dfb58f58938861a93/apptentive/src/main/java/com/apptentive/android/sdk/notifications/ApptentiveNotificationObserverList.java#L78-L89 |
NessComputing/service-discovery | jms/src/main/java/com/nesscomputing/jms/activemq/ServiceDiscoveryTransportFactory.java | ServiceDiscoveryTransportFactory.getDiscoveryClient | private ReadOnlyDiscoveryClient getDiscoveryClient(Map<String, String> params) throws IOException {
"""
Locate the appropriate DiscoveryClient for a given discoveryId
"""
final UUID discoveryId = getDiscoveryId(params);
final ReadOnlyDiscoveryClient discoveryClient = DISCO_CLIENTS.get(discoveryId);
if (discoveryClient == null) {
throw new IOException("No discovery client registered for id " + discoveryId);
}
return discoveryClient;
} | java | private ReadOnlyDiscoveryClient getDiscoveryClient(Map<String, String> params) throws IOException {
final UUID discoveryId = getDiscoveryId(params);
final ReadOnlyDiscoveryClient discoveryClient = DISCO_CLIENTS.get(discoveryId);
if (discoveryClient == null) {
throw new IOException("No discovery client registered for id " + discoveryId);
}
return discoveryClient;
} | [
"private",
"ReadOnlyDiscoveryClient",
"getDiscoveryClient",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"params",
")",
"throws",
"IOException",
"{",
"final",
"UUID",
"discoveryId",
"=",
"getDiscoveryId",
"(",
"params",
")",
";",
"final",
"ReadOnlyDiscoveryClient"... | Locate the appropriate DiscoveryClient for a given discoveryId | [
"Locate",
"the",
"appropriate",
"DiscoveryClient",
"for",
"a",
"given",
"discoveryId"
] | train | https://github.com/NessComputing/service-discovery/blob/5091ffdb1de6b12d216d1c238f72858037c7b765/jms/src/main/java/com/nesscomputing/jms/activemq/ServiceDiscoveryTransportFactory.java#L120-L129 |
xcesco/kripton | kripton-processor/src/main/java/com/abubusoft/kripton/processor/core/reflect/AnnotationUtility.java | AnnotationUtility.extractAsClassName | public static String extractAsClassName(Element item, Class<? extends Annotation> annotationClass, AnnotationAttributeType attributeName) {
"""
Extract from an annotation of a method the attribute value specified.
@param item the item
@param annotationClass the annotation class
@param attributeName the attribute name
@return attribute value extracted as class typeName
"""
final Elements elementUtils=BindDataSourceSubProcessor.elementUtils;
final One<String> result = new One<String>();
extractString(elementUtils, item, annotationClass, attributeName, new OnAttributeFoundListener() {
@Override
public void onFound(String value) {
result.value0 = AnnotationUtility.extractAsArrayOfClassName(value).get(0);
}
});
return result.value0;
} | java | public static String extractAsClassName(Element item, Class<? extends Annotation> annotationClass, AnnotationAttributeType attributeName) {
final Elements elementUtils=BindDataSourceSubProcessor.elementUtils;
final One<String> result = new One<String>();
extractString(elementUtils, item, annotationClass, attributeName, new OnAttributeFoundListener() {
@Override
public void onFound(String value) {
result.value0 = AnnotationUtility.extractAsArrayOfClassName(value).get(0);
}
});
return result.value0;
} | [
"public",
"static",
"String",
"extractAsClassName",
"(",
"Element",
"item",
",",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
"annotationClass",
",",
"AnnotationAttributeType",
"attributeName",
")",
"{",
"final",
"Elements",
"elementUtils",
"=",
"BindDataSourceSub... | Extract from an annotation of a method the attribute value specified.
@param item the item
@param annotationClass the annotation class
@param attributeName the attribute name
@return attribute value extracted as class typeName | [
"Extract",
"from",
"an",
"annotation",
"of",
"a",
"method",
"the",
"attribute",
"value",
"specified",
"."
] | train | https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/core/reflect/AnnotationUtility.java#L217-L230 |
Azure/azure-sdk-for-java | keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java | KeyVaultClientBaseImpl.getCertificatePolicy | public CertificatePolicy getCertificatePolicy(String vaultBaseUrl, String certificateName) {
"""
Lists the policy for a certificate.
The GetCertificatePolicy operation returns the specified certificate policy resources in the specified key vault. This operation requires the certificates/get permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param certificateName The name of the certificate in a given key vault.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws KeyVaultErrorException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the CertificatePolicy object if successful.
"""
return getCertificatePolicyWithServiceResponseAsync(vaultBaseUrl, certificateName).toBlocking().single().body();
} | java | public CertificatePolicy getCertificatePolicy(String vaultBaseUrl, String certificateName) {
return getCertificatePolicyWithServiceResponseAsync(vaultBaseUrl, certificateName).toBlocking().single().body();
} | [
"public",
"CertificatePolicy",
"getCertificatePolicy",
"(",
"String",
"vaultBaseUrl",
",",
"String",
"certificateName",
")",
"{",
"return",
"getCertificatePolicyWithServiceResponseAsync",
"(",
"vaultBaseUrl",
",",
"certificateName",
")",
".",
"toBlocking",
"(",
")",
".",
... | Lists the policy for a certificate.
The GetCertificatePolicy operation returns the specified certificate policy resources in the specified key vault. This operation requires the certificates/get permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param certificateName The name of the certificate in a given key vault.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws KeyVaultErrorException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the CertificatePolicy object if successful. | [
"Lists",
"the",
"policy",
"for",
"a",
"certificate",
".",
"The",
"GetCertificatePolicy",
"operation",
"returns",
"the",
"specified",
"certificate",
"policy",
"resources",
"in",
"the",
"specified",
"key",
"vault",
".",
"This",
"operation",
"requires",
"the",
"certi... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L7152-L7154 |
elastic/elasticsearch-hadoop | mr/src/main/java/org/elasticsearch/hadoop/rest/RestService.java | RestService.initMultiIndices | private static RestRepository initMultiIndices(Settings settings, long currentInstance, Resource resource, Log log) {
"""
Creates a RestRepository for use with a multi-index resource pattern. The client is left pinned
to the original node that it was pinned to since the shard locations cannot be determined at all.
@param settings Job settings
@param currentInstance Partition number
@param resource Configured write resource
@param log Logger to use
@return The RestRepository to be used by the partition writer
"""
if (log.isDebugEnabled()) {
log.debug(String.format("Resource [%s] resolves as an index pattern", resource));
}
// multi-index write - since we don't know before hand what index will be used, use an already selected node
String node = SettingsUtils.getPinnedNode(settings);
if (log.isDebugEnabled()) {
log.debug(String.format("Partition writer instance [%s] assigned to [%s]", currentInstance, node));
}
return new RestRepository(settings);
} | java | private static RestRepository initMultiIndices(Settings settings, long currentInstance, Resource resource, Log log) {
if (log.isDebugEnabled()) {
log.debug(String.format("Resource [%s] resolves as an index pattern", resource));
}
// multi-index write - since we don't know before hand what index will be used, use an already selected node
String node = SettingsUtils.getPinnedNode(settings);
if (log.isDebugEnabled()) {
log.debug(String.format("Partition writer instance [%s] assigned to [%s]", currentInstance, node));
}
return new RestRepository(settings);
} | [
"private",
"static",
"RestRepository",
"initMultiIndices",
"(",
"Settings",
"settings",
",",
"long",
"currentInstance",
",",
"Resource",
"resource",
",",
"Log",
"log",
")",
"{",
"if",
"(",
"log",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"log",
".",
"debug"... | Creates a RestRepository for use with a multi-index resource pattern. The client is left pinned
to the original node that it was pinned to since the shard locations cannot be determined at all.
@param settings Job settings
@param currentInstance Partition number
@param resource Configured write resource
@param log Logger to use
@return The RestRepository to be used by the partition writer | [
"Creates",
"a",
"RestRepository",
"for",
"use",
"with",
"a",
"multi",
"-",
"index",
"resource",
"pattern",
".",
"The",
"client",
"is",
"left",
"pinned",
"to",
"the",
"original",
"node",
"that",
"it",
"was",
"pinned",
"to",
"since",
"the",
"shard",
"locatio... | train | https://github.com/elastic/elasticsearch-hadoop/blob/f3acaba268ff96efae8eb946088c748c777c22cc/mr/src/main/java/org/elasticsearch/hadoop/rest/RestService.java#L732-L744 |
lucee/Lucee | core/src/main/java/lucee/transformer/bytecode/Page.java | Page.registerString | public Range registerString(BytecodeContext bc, String str) throws IOException {
"""
return null if not possible to register
@param bc
@param str
@return
@throws IOException
"""
boolean append = true;
if (staticTextLocation == null) {
if (bc.getPageSource() == null) return null;
PageSource ps = bc.getPageSource();
Mapping m = ps.getMapping();
staticTextLocation = m.getClassRootDirectory();
staticTextLocation.mkdirs();
staticTextLocation = staticTextLocation.getRealResource(ps.getClassName().replace('.', '/') + ".txt");
if (staticTextLocation.exists()) append = false;
else staticTextLocation.createFile(true);
off = 0;
}
IOUtil.write(staticTextLocation, str, CharsetUtil.UTF8, append);
Range r = new Range(off, str.length());
off += str.length();
return r;
} | java | public Range registerString(BytecodeContext bc, String str) throws IOException {
boolean append = true;
if (staticTextLocation == null) {
if (bc.getPageSource() == null) return null;
PageSource ps = bc.getPageSource();
Mapping m = ps.getMapping();
staticTextLocation = m.getClassRootDirectory();
staticTextLocation.mkdirs();
staticTextLocation = staticTextLocation.getRealResource(ps.getClassName().replace('.', '/') + ".txt");
if (staticTextLocation.exists()) append = false;
else staticTextLocation.createFile(true);
off = 0;
}
IOUtil.write(staticTextLocation, str, CharsetUtil.UTF8, append);
Range r = new Range(off, str.length());
off += str.length();
return r;
} | [
"public",
"Range",
"registerString",
"(",
"BytecodeContext",
"bc",
",",
"String",
"str",
")",
"throws",
"IOException",
"{",
"boolean",
"append",
"=",
"true",
";",
"if",
"(",
"staticTextLocation",
"==",
"null",
")",
"{",
"if",
"(",
"bc",
".",
"getPageSource",... | return null if not possible to register
@param bc
@param str
@return
@throws IOException | [
"return",
"null",
"if",
"not",
"possible",
"to",
"register"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/transformer/bytecode/Page.java#L1612-L1634 |
kotcrab/vis-ui | ui/src/main/java/com/kotcrab/vis/ui/widget/PopupMenu.java | PopupMenu.getDefaultInputListener | public InputListener getDefaultInputListener (final int mouseButton) {
"""
Returns input listener that can be added to scene2d actor. When mouse button is pressed on that actor,
menu will be displayed
@param mouseButton from {@link Buttons}
"""
if (defaultInputListener == null) {
defaultInputListener = new InputListener() {
@Override
public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
return true;
}
@Override
public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
if (event.getButton() == mouseButton)
showMenu(event.getStage(), event.getStageX(), event.getStageY());
}
};
}
return defaultInputListener;
} | java | public InputListener getDefaultInputListener (final int mouseButton) {
if (defaultInputListener == null) {
defaultInputListener = new InputListener() {
@Override
public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
return true;
}
@Override
public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
if (event.getButton() == mouseButton)
showMenu(event.getStage(), event.getStageX(), event.getStageY());
}
};
}
return defaultInputListener;
} | [
"public",
"InputListener",
"getDefaultInputListener",
"(",
"final",
"int",
"mouseButton",
")",
"{",
"if",
"(",
"defaultInputListener",
"==",
"null",
")",
"{",
"defaultInputListener",
"=",
"new",
"InputListener",
"(",
")",
"{",
"@",
"Override",
"public",
"boolean",... | Returns input listener that can be added to scene2d actor. When mouse button is pressed on that actor,
menu will be displayed
@param mouseButton from {@link Buttons} | [
"Returns",
"input",
"listener",
"that",
"can",
"be",
"added",
"to",
"scene2d",
"actor",
".",
"When",
"mouse",
"button",
"is",
"pressed",
"on",
"that",
"actor",
"menu",
"will",
"be",
"displayed"
] | train | https://github.com/kotcrab/vis-ui/blob/3b68f82d94ae32bffa2a3399c63f432e0f4908e0/ui/src/main/java/com/kotcrab/vis/ui/widget/PopupMenu.java#L258-L275 |
OpenBEL/openbel-framework | org.openbel.framework.common/src/main/java/org/openbel/framework/common/model/Term.java | Term.replaceParameters | private static void replaceParameters(Term t, StringBuilder b) {
"""
Builds a {@link String term string} where {@link Parameter parameters}
are replaced with {@code #} characters.
@param t {@link Term}
@param b {@link StringBuilder}
"""
FunctionEnum f = t.getFunctionEnum();
String fx = f.getShortestForm();
b.append(fx).append("(");
if (hasItems(t.getFunctionArguments())) {
for (BELObject bo : t.getFunctionArguments()) {
if (Term.class.isAssignableFrom(bo.getClass())) {
Term inner = (Term) bo;
if (inner.getFunctionEnum() == PROTEIN_MODIFICATION ||
inner.getFunctionEnum() == SUBSTITUTION ||
inner.getFunctionEnum() == TRUNCATION) {
b.append(inner.toBELShortForm());
} else {
replaceParameters((Term) bo, b);
}
} else {
b.append("#");
}
b.append(",");
}
b.deleteCharAt(b.length() - 1);
b.append(")");
}
} | java | private static void replaceParameters(Term t, StringBuilder b) {
FunctionEnum f = t.getFunctionEnum();
String fx = f.getShortestForm();
b.append(fx).append("(");
if (hasItems(t.getFunctionArguments())) {
for (BELObject bo : t.getFunctionArguments()) {
if (Term.class.isAssignableFrom(bo.getClass())) {
Term inner = (Term) bo;
if (inner.getFunctionEnum() == PROTEIN_MODIFICATION ||
inner.getFunctionEnum() == SUBSTITUTION ||
inner.getFunctionEnum() == TRUNCATION) {
b.append(inner.toBELShortForm());
} else {
replaceParameters((Term) bo, b);
}
} else {
b.append("#");
}
b.append(",");
}
b.deleteCharAt(b.length() - 1);
b.append(")");
}
} | [
"private",
"static",
"void",
"replaceParameters",
"(",
"Term",
"t",
",",
"StringBuilder",
"b",
")",
"{",
"FunctionEnum",
"f",
"=",
"t",
".",
"getFunctionEnum",
"(",
")",
";",
"String",
"fx",
"=",
"f",
".",
"getShortestForm",
"(",
")",
";",
"b",
".",
"a... | Builds a {@link String term string} where {@link Parameter parameters}
are replaced with {@code #} characters.
@param t {@link Term}
@param b {@link StringBuilder} | [
"Builds",
"a",
"{",
"@link",
"String",
"term",
"string",
"}",
"where",
"{",
"@link",
"Parameter",
"parameters",
"}",
"are",
"replaced",
"with",
"{",
"@code",
"#",
"}",
"characters",
"."
] | train | https://github.com/OpenBEL/openbel-framework/blob/149f80b1d6eabb15ab15815b6f745b0afa9fd2d3/org.openbel.framework.common/src/main/java/org/openbel/framework/common/model/Term.java#L592-L615 |
orbisgis/h2gis | h2gis-utilities/src/main/java/org/h2gis/utilities/TableUtilities.java | TableUtilities.caseIdentifier | public static String caseIdentifier(TableLocation requestedTable, String tableName, boolean isH2) {
"""
Return the table identifier in the best fit depending on database type
@param requestedTable Catalog and schema used
@param tableName Table without quotes
@param isH2 True if H2, false if PostGRES
@return Find table identifier
"""
return new TableLocation(requestedTable.getCatalog(), requestedTable.getSchema(),
TableLocation.parse(tableName, isH2).getTable()).toString();
} | java | public static String caseIdentifier(TableLocation requestedTable, String tableName, boolean isH2) {
return new TableLocation(requestedTable.getCatalog(), requestedTable.getSchema(),
TableLocation.parse(tableName, isH2).getTable()).toString();
} | [
"public",
"static",
"String",
"caseIdentifier",
"(",
"TableLocation",
"requestedTable",
",",
"String",
"tableName",
",",
"boolean",
"isH2",
")",
"{",
"return",
"new",
"TableLocation",
"(",
"requestedTable",
".",
"getCatalog",
"(",
")",
",",
"requestedTable",
".",
... | Return the table identifier in the best fit depending on database type
@param requestedTable Catalog and schema used
@param tableName Table without quotes
@param isH2 True if H2, false if PostGRES
@return Find table identifier | [
"Return",
"the",
"table",
"identifier",
"in",
"the",
"best",
"fit",
"depending",
"on",
"database",
"type"
] | train | https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-utilities/src/main/java/org/h2gis/utilities/TableUtilities.java#L133-L136 |
Azure/azure-sdk-for-java | keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java | KeyVaultClientBaseImpl.getStorageAccountsAsync | public Observable<Page<StorageAccountItem>> getStorageAccountsAsync(final String vaultBaseUrl, final Integer maxresults) {
"""
List storage accounts managed by the specified key vault. This operation requires the storage/list permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<StorageAccountItem> object
"""
return getStorageAccountsWithServiceResponseAsync(vaultBaseUrl, maxresults)
.map(new Func1<ServiceResponse<Page<StorageAccountItem>>, Page<StorageAccountItem>>() {
@Override
public Page<StorageAccountItem> call(ServiceResponse<Page<StorageAccountItem>> response) {
return response.body();
}
});
} | java | public Observable<Page<StorageAccountItem>> getStorageAccountsAsync(final String vaultBaseUrl, final Integer maxresults) {
return getStorageAccountsWithServiceResponseAsync(vaultBaseUrl, maxresults)
.map(new Func1<ServiceResponse<Page<StorageAccountItem>>, Page<StorageAccountItem>>() {
@Override
public Page<StorageAccountItem> call(ServiceResponse<Page<StorageAccountItem>> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Page",
"<",
"StorageAccountItem",
">",
">",
"getStorageAccountsAsync",
"(",
"final",
"String",
"vaultBaseUrl",
",",
"final",
"Integer",
"maxresults",
")",
"{",
"return",
"getStorageAccountsWithServiceResponseAsync",
"(",
"vaultBaseUrl",
","... | List storage accounts managed by the specified key vault. This operation requires the storage/list permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<StorageAccountItem> object | [
"List",
"storage",
"accounts",
"managed",
"by",
"the",
"specified",
"key",
"vault",
".",
"This",
"operation",
"requires",
"the",
"storage",
"/",
"list",
"permission",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L8942-L8950 |
xiaosunzhu/resource-utils | src/main/java/net/sunyijun/resource/config/OneProperties.java | OneProperties.modifyConfig | protected void modifyConfig(IConfigKey key, String value) throws IOException {
"""
Modify one config and write new config into properties file.
@param key need update config key
@param value new value
"""
if (propertiesFilePath == null) {
LOGGER.warn("Config " + propertiesAbsoluteClassPath + " is not a file, maybe just a resource in library.");
}
if (configs == null) {
loadConfigs();
}
configs.setProperty(key.getKeyString(), value);
PropertiesIO.store(propertiesFilePath, configs);
} | java | protected void modifyConfig(IConfigKey key, String value) throws IOException {
if (propertiesFilePath == null) {
LOGGER.warn("Config " + propertiesAbsoluteClassPath + " is not a file, maybe just a resource in library.");
}
if (configs == null) {
loadConfigs();
}
configs.setProperty(key.getKeyString(), value);
PropertiesIO.store(propertiesFilePath, configs);
} | [
"protected",
"void",
"modifyConfig",
"(",
"IConfigKey",
"key",
",",
"String",
"value",
")",
"throws",
"IOException",
"{",
"if",
"(",
"propertiesFilePath",
"==",
"null",
")",
"{",
"LOGGER",
".",
"warn",
"(",
"\"Config \"",
"+",
"propertiesAbsoluteClassPath",
"+",... | Modify one config and write new config into properties file.
@param key need update config key
@param value new value | [
"Modify",
"one",
"config",
"and",
"write",
"new",
"config",
"into",
"properties",
"file",
"."
] | train | https://github.com/xiaosunzhu/resource-utils/blob/4f2bf3f36df10195a978f122ed682ba1eb0462b5/src/main/java/net/sunyijun/resource/config/OneProperties.java#L227-L236 |
brettonw/Bag | src/main/java/com/brettonw/bag/Bag.java | Bag.getFloat | public Float getFloat (String key, Supplier<Float> notFound) {
"""
Retrieve a mapped element and return it as a Float.
@param key A string value used to index the element.
@param notFound A function to create a new Float if the requested key was not found
@return The element as a Float, or notFound if the element is not found.
"""
return getParsed (key, Float::new, notFound);
} | java | public Float getFloat (String key, Supplier<Float> notFound) {
return getParsed (key, Float::new, notFound);
} | [
"public",
"Float",
"getFloat",
"(",
"String",
"key",
",",
"Supplier",
"<",
"Float",
">",
"notFound",
")",
"{",
"return",
"getParsed",
"(",
"key",
",",
"Float",
"::",
"new",
",",
"notFound",
")",
";",
"}"
] | Retrieve a mapped element and return it as a Float.
@param key A string value used to index the element.
@param notFound A function to create a new Float if the requested key was not found
@return The element as a Float, or notFound if the element is not found. | [
"Retrieve",
"a",
"mapped",
"element",
"and",
"return",
"it",
"as",
"a",
"Float",
"."
] | train | https://github.com/brettonw/Bag/blob/25c0ff74893b6c9a2c61bf0f97189ab82e0b2f56/src/main/java/com/brettonw/bag/Bag.java#L250-L252 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.