repository_name
stringlengths 7
58
| func_path_in_repository
stringlengths 11
218
| func_name
stringlengths 4
140
| whole_func_string
stringlengths 153
5.32k
| language
stringclasses 1
value | func_code_string
stringlengths 72
4k
| func_code_tokens
sequencelengths 20
832
| func_documentation_string
stringlengths 61
2k
| func_documentation_tokens
sequencelengths 1
647
| split_name
stringclasses 1
value | func_code_url
stringlengths 102
339
|
---|---|---|---|---|---|---|---|---|---|---|
MenoData/Time4J | base/src/main/java/net/time4j/engine/AbstractMetric.java | AbstractMetric.compare | @Override
public int compare(U u1, U u2) {
"""
/*[deutsch]
<p>Vergleicht Zeiteinheiten absteigend nach ihrer Länge. </p>
@param u1 first time unit
@param u2 second time unit
@return negative, zero or positive if u1 is greater, equal to
or smaller than u2
"""
return Double.compare(u2.getLength(), u1.getLength()); // descending
} | java | @Override
public int compare(U u1, U u2) {
return Double.compare(u2.getLength(), u1.getLength()); // descending
} | [
"@",
"Override",
"public",
"int",
"compare",
"(",
"U",
"u1",
",",
"U",
"u2",
")",
"{",
"return",
"Double",
".",
"compare",
"(",
"u2",
".",
"getLength",
"(",
")",
",",
"u1",
".",
"getLength",
"(",
")",
")",
";",
"// descending",
"}"
] | /*[deutsch]
<p>Vergleicht Zeiteinheiten absteigend nach ihrer Länge. </p>
@param u1 first time unit
@param u2 second time unit
@return negative, zero or positive if u1 is greater, equal to
or smaller than u2 | [
"/",
"*",
"[",
"deutsch",
"]",
"<p",
">",
"Vergleicht",
"Zeiteinheiten",
"absteigend",
"nach",
"ihrer",
"Lä",
";",
"nge",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/MenoData/Time4J/blob/08b2eda6b2dbb140b92011cf7071bb087edd46a5/base/src/main/java/net/time4j/engine/AbstractMetric.java#L152-L157 |
lucee/Lucee | core/src/main/java/lucee/runtime/schedule/ScheduleTaskImpl.java | ScheduleTaskImpl.toURL | private static URL toURL(String url, int port) throws MalformedURLException {
"""
translate a urlString and a port definition to a URL Object
@param url URL String
@param port URL Port Definition
@return returns a URL Object
@throws MalformedURLException
"""
URL u = HTTPUtil.toURL(url, true);
if (port == -1) return u;
return new URL(u.getProtocol(), u.getHost(), port, u.getFile());
} | java | private static URL toURL(String url, int port) throws MalformedURLException {
URL u = HTTPUtil.toURL(url, true);
if (port == -1) return u;
return new URL(u.getProtocol(), u.getHost(), port, u.getFile());
} | [
"private",
"static",
"URL",
"toURL",
"(",
"String",
"url",
",",
"int",
"port",
")",
"throws",
"MalformedURLException",
"{",
"URL",
"u",
"=",
"HTTPUtil",
".",
"toURL",
"(",
"url",
",",
"true",
")",
";",
"if",
"(",
"port",
"==",
"-",
"1",
")",
"return",
"u",
";",
"return",
"new",
"URL",
"(",
"u",
".",
"getProtocol",
"(",
")",
",",
"u",
".",
"getHost",
"(",
")",
",",
"port",
",",
"u",
".",
"getFile",
"(",
")",
")",
";",
"}"
] | translate a urlString and a port definition to a URL Object
@param url URL String
@param port URL Port Definition
@return returns a URL Object
@throws MalformedURLException | [
"translate",
"a",
"urlString",
"and",
"a",
"port",
"definition",
"to",
"a",
"URL",
"Object"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/schedule/ScheduleTaskImpl.java#L169-L173 |
alibaba/canal | client-adapter/common/src/main/java/com/alibaba/otter/canal/client/adapter/config/bind/PropertySourcesPropertyResolver.java | PropertySourcesPropertyResolver.logKeyFound | protected void logKeyFound(String key, PropertySource<?> propertySource, Object value) {
"""
Log the given key as found in the given {@link PropertySource}, resulting in
the given value.
<p>
The default implementation writes a debug log message with key and source. As
of 4.3.3, this does not log the value anymore in order to avoid accidental
logging of sensitive settings. Subclasses may override this method to change
the log level and/or log message, including the property's value if desired.
@param key the key found
@param propertySource the {@code PropertySource} that the key has been found
in
@param value the corresponding value
@since 4.3.1
"""
if (logger.isDebugEnabled()) {
logger.debug("Found key '" + key + "' in PropertySource '" + propertySource.getName()
+ "' with value of type " + value.getClass().getSimpleName());
}
} | java | protected void logKeyFound(String key, PropertySource<?> propertySource, Object value) {
if (logger.isDebugEnabled()) {
logger.debug("Found key '" + key + "' in PropertySource '" + propertySource.getName()
+ "' with value of type " + value.getClass().getSimpleName());
}
} | [
"protected",
"void",
"logKeyFound",
"(",
"String",
"key",
",",
"PropertySource",
"<",
"?",
">",
"propertySource",
",",
"Object",
"value",
")",
"{",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"\"Found key '\"",
"+",
"key",
"+",
"\"' in PropertySource '\"",
"+",
"propertySource",
".",
"getName",
"(",
")",
"+",
"\"' with value of type \"",
"+",
"value",
".",
"getClass",
"(",
")",
".",
"getSimpleName",
"(",
")",
")",
";",
"}",
"}"
] | Log the given key as found in the given {@link PropertySource}, resulting in
the given value.
<p>
The default implementation writes a debug log message with key and source. As
of 4.3.3, this does not log the value anymore in order to avoid accidental
logging of sensitive settings. Subclasses may override this method to change
the log level and/or log message, including the property's value if desired.
@param key the key found
@param propertySource the {@code PropertySource} that the key has been found
in
@param value the corresponding value
@since 4.3.1 | [
"Log",
"the",
"given",
"key",
"as",
"found",
"in",
"the",
"given",
"{",
"@link",
"PropertySource",
"}",
"resulting",
"in",
"the",
"given",
"value",
".",
"<p",
">",
"The",
"default",
"implementation",
"writes",
"a",
"debug",
"log",
"message",
"with",
"key",
"and",
"source",
".",
"As",
"of",
"4",
".",
"3",
".",
"3",
"this",
"does",
"not",
"log",
"the",
"value",
"anymore",
"in",
"order",
"to",
"avoid",
"accidental",
"logging",
"of",
"sensitive",
"settings",
".",
"Subclasses",
"may",
"override",
"this",
"method",
"to",
"change",
"the",
"log",
"level",
"and",
"/",
"or",
"log",
"message",
"including",
"the",
"property",
"s",
"value",
"if",
"desired",
"."
] | train | https://github.com/alibaba/canal/blob/8f088cddc0755f4350c5aaae95c6e4002d90a40f/client-adapter/common/src/main/java/com/alibaba/otter/canal/client/adapter/config/bind/PropertySourcesPropertyResolver.java#L140-L145 |
betfair/cougar | cougar-codegen-plugin/src/main/java/com/betfair/cougar/codegen/FileUtil.java | FileUtil.resourceToFile | public static void resourceToFile(String resourceName, File dest, Class src) {
"""
Copy the given resource to the given file.
@param resourceName name of resource to copy
@param destination file
"""
InputStream is = null;
OutputStream os = null;
try {
is = src.getClassLoader().getResourceAsStream(resourceName);
if (is == null) {
throw new RuntimeException("Could not load resource: " + resourceName);
}
dest.getParentFile().mkdirs();
os = new FileOutputStream(dest);
IOUtils.copy(is, os);
} catch (Exception e) {
throw new RuntimeException("Error copying resource '" + resourceName + "' to file '"
+ dest.getPath() + "': "+ e, e);
}
finally {
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(os);
}
} | java | public static void resourceToFile(String resourceName, File dest, Class src) {
InputStream is = null;
OutputStream os = null;
try {
is = src.getClassLoader().getResourceAsStream(resourceName);
if (is == null) {
throw new RuntimeException("Could not load resource: " + resourceName);
}
dest.getParentFile().mkdirs();
os = new FileOutputStream(dest);
IOUtils.copy(is, os);
} catch (Exception e) {
throw new RuntimeException("Error copying resource '" + resourceName + "' to file '"
+ dest.getPath() + "': "+ e, e);
}
finally {
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(os);
}
} | [
"public",
"static",
"void",
"resourceToFile",
"(",
"String",
"resourceName",
",",
"File",
"dest",
",",
"Class",
"src",
")",
"{",
"InputStream",
"is",
"=",
"null",
";",
"OutputStream",
"os",
"=",
"null",
";",
"try",
"{",
"is",
"=",
"src",
".",
"getClassLoader",
"(",
")",
".",
"getResourceAsStream",
"(",
"resourceName",
")",
";",
"if",
"(",
"is",
"==",
"null",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Could not load resource: \"",
"+",
"resourceName",
")",
";",
"}",
"dest",
".",
"getParentFile",
"(",
")",
".",
"mkdirs",
"(",
")",
";",
"os",
"=",
"new",
"FileOutputStream",
"(",
"dest",
")",
";",
"IOUtils",
".",
"copy",
"(",
"is",
",",
"os",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Error copying resource '\"",
"+",
"resourceName",
"+",
"\"' to file '\"",
"+",
"dest",
".",
"getPath",
"(",
")",
"+",
"\"': \"",
"+",
"e",
",",
"e",
")",
";",
"}",
"finally",
"{",
"IOUtils",
".",
"closeQuietly",
"(",
"is",
")",
";",
"IOUtils",
".",
"closeQuietly",
"(",
"os",
")",
";",
"}",
"}"
] | Copy the given resource to the given file.
@param resourceName name of resource to copy
@param destination file | [
"Copy",
"the",
"given",
"resource",
"to",
"the",
"given",
"file",
"."
] | train | https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-codegen-plugin/src/main/java/com/betfair/cougar/codegen/FileUtil.java#L34-L56 |
softindex/datakernel | core-http/src/main/java/io/datakernel/http/HttpUtils.java | HttpUtils.urlEncode | public static String urlEncode(String string, String enc) {
"""
Translates a string into application/x-www-form-urlencoded format using a specific encoding scheme.
This method uses the supplied encoding scheme to obtain the bytes for unsafe characters
@param string string for encoding
@param enc new encoding
@return the translated String.
"""
try {
return URLEncoder.encode(string, enc);
} catch (UnsupportedEncodingException e) {
throw new IllegalArgumentException("Can't encode with supplied encoding: " + enc, e);
}
} | java | public static String urlEncode(String string, String enc) {
try {
return URLEncoder.encode(string, enc);
} catch (UnsupportedEncodingException e) {
throw new IllegalArgumentException("Can't encode with supplied encoding: " + enc, e);
}
} | [
"public",
"static",
"String",
"urlEncode",
"(",
"String",
"string",
",",
"String",
"enc",
")",
"{",
"try",
"{",
"return",
"URLEncoder",
".",
"encode",
"(",
"string",
",",
"enc",
")",
";",
"}",
"catch",
"(",
"UnsupportedEncodingException",
"e",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Can't encode with supplied encoding: \"",
"+",
"enc",
",",
"e",
")",
";",
"}",
"}"
] | Translates a string into application/x-www-form-urlencoded format using a specific encoding scheme.
This method uses the supplied encoding scheme to obtain the bytes for unsafe characters
@param string string for encoding
@param enc new encoding
@return the translated String. | [
"Translates",
"a",
"string",
"into",
"application",
"/",
"x",
"-",
"www",
"-",
"form",
"-",
"urlencoded",
"format",
"using",
"a",
"specific",
"encoding",
"scheme",
".",
"This",
"method",
"uses",
"the",
"supplied",
"encoding",
"scheme",
"to",
"obtain",
"the",
"bytes",
"for",
"unsafe",
"characters"
] | train | https://github.com/softindex/datakernel/blob/090ca1116416c14d463d49d275cb1daaafa69c56/core-http/src/main/java/io/datakernel/http/HttpUtils.java#L214-L220 |
greengerong/prerender-java | src/main/java/com/github/greengerong/PrerenderSeoService.java | PrerenderSeoService.responseEntity | private void responseEntity(String html, HttpServletResponse servletResponse)
throws IOException {
"""
Copy response body data (the entity) from the proxy to the servlet client.
"""
PrintWriter printWriter = servletResponse.getWriter();
try {
printWriter.write(html);
printWriter.flush();
} finally {
closeQuietly(printWriter);
}
} | java | private void responseEntity(String html, HttpServletResponse servletResponse)
throws IOException {
PrintWriter printWriter = servletResponse.getWriter();
try {
printWriter.write(html);
printWriter.flush();
} finally {
closeQuietly(printWriter);
}
} | [
"private",
"void",
"responseEntity",
"(",
"String",
"html",
",",
"HttpServletResponse",
"servletResponse",
")",
"throws",
"IOException",
"{",
"PrintWriter",
"printWriter",
"=",
"servletResponse",
".",
"getWriter",
"(",
")",
";",
"try",
"{",
"printWriter",
".",
"write",
"(",
"html",
")",
";",
"printWriter",
".",
"flush",
"(",
")",
";",
"}",
"finally",
"{",
"closeQuietly",
"(",
"printWriter",
")",
";",
"}",
"}"
] | Copy response body data (the entity) from the proxy to the servlet client. | [
"Copy",
"response",
"body",
"data",
"(",
"the",
"entity",
")",
"from",
"the",
"proxy",
"to",
"the",
"servlet",
"client",
"."
] | train | https://github.com/greengerong/prerender-java/blob/f7fc7a5e9adea8cf556c653a87bbac2cfcac3d06/src/main/java/com/github/greengerong/PrerenderSeoService.java#L256-L265 |
codeprimate-software/cp-elements | src/main/java/org/cp/elements/util/sort/SorterFactory.java | SorterFactory.createSorterElseDefault | public static <T extends Sorter> T createSorterElseDefault(final SortType type, final T defaultSorter) {
"""
Creates an instance of the Sorter interface implementing the sorting algorithm based on the SortType,
otherwise returns the provided default Sorter implementation if a Sorter based on the specified SortType
is not available.
@param <T> the Class type of the actual Sorter implementation based on the SortType.
@param type the type of sorting algorithm Sorter implementation to create.
@param defaultSorter the default Sorter implementation to use if a Sorter based on the specified SortType
is not available.
@return a Sorter implementation subclass that implements the sorting algorithm based on the SortType,
or the provided default Sorter implementation if the Sorter based on the SortType is not available.
@see #createSorter(SortType)
@see org.cp.elements.util.sort.Sorter
@see org.cp.elements.util.sort.SortType
"""
try {
return createSorter(type);
}
catch (IllegalArgumentException ignore) {
return defaultSorter;
}
} | java | public static <T extends Sorter> T createSorterElseDefault(final SortType type, final T defaultSorter) {
try {
return createSorter(type);
}
catch (IllegalArgumentException ignore) {
return defaultSorter;
}
} | [
"public",
"static",
"<",
"T",
"extends",
"Sorter",
">",
"T",
"createSorterElseDefault",
"(",
"final",
"SortType",
"type",
",",
"final",
"T",
"defaultSorter",
")",
"{",
"try",
"{",
"return",
"createSorter",
"(",
"type",
")",
";",
"}",
"catch",
"(",
"IllegalArgumentException",
"ignore",
")",
"{",
"return",
"defaultSorter",
";",
"}",
"}"
] | Creates an instance of the Sorter interface implementing the sorting algorithm based on the SortType,
otherwise returns the provided default Sorter implementation if a Sorter based on the specified SortType
is not available.
@param <T> the Class type of the actual Sorter implementation based on the SortType.
@param type the type of sorting algorithm Sorter implementation to create.
@param defaultSorter the default Sorter implementation to use if a Sorter based on the specified SortType
is not available.
@return a Sorter implementation subclass that implements the sorting algorithm based on the SortType,
or the provided default Sorter implementation if the Sorter based on the SortType is not available.
@see #createSorter(SortType)
@see org.cp.elements.util.sort.Sorter
@see org.cp.elements.util.sort.SortType | [
"Creates",
"an",
"instance",
"of",
"the",
"Sorter",
"interface",
"implementing",
"the",
"sorting",
"algorithm",
"based",
"on",
"the",
"SortType",
"otherwise",
"returns",
"the",
"provided",
"default",
"Sorter",
"implementation",
"if",
"a",
"Sorter",
"based",
"on",
"the",
"specified",
"SortType",
"is",
"not",
"available",
"."
] | train | https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/util/sort/SorterFactory.java#L97-L104 |
datumbox/datumbox-framework | datumbox-framework-core/src/main/java/com/datumbox/framework/core/common/dataobjects/Dataframe.java | Dataframe.dropXColumns | public void dropXColumns(Set<Object> columnSet) {
"""
Removes completely a list of columns from the dataset. The meta-data of
the Dataframe are updated. The method internally uses threads.
@param columnSet
"""
columnSet.retainAll(data.xDataTypes.keySet()); //keep only those columns that are already known to the Meta data of the Dataframe
if(columnSet.isEmpty()) {
return;
}
//remove all the columns from the Meta data
data.xDataTypes.keySet().removeAll(columnSet);
streamExecutor.forEach(StreamMethods.stream(entries(), true), e -> {
Integer rId = e.getKey();
Record r = e.getValue();
AssociativeArray xData = r.getX().copy();
boolean modified = xData.keySet().removeAll(columnSet);
if(modified) {
Record newR = new Record(xData, r.getY(), r.getYPredicted(), r.getYPredictedProbabilities());
//safe to call in this context. we already updated the meta when we modified the xDataTypes
_unsafe_set(rId, newR);
}
});
} | java | public void dropXColumns(Set<Object> columnSet) {
columnSet.retainAll(data.xDataTypes.keySet()); //keep only those columns that are already known to the Meta data of the Dataframe
if(columnSet.isEmpty()) {
return;
}
//remove all the columns from the Meta data
data.xDataTypes.keySet().removeAll(columnSet);
streamExecutor.forEach(StreamMethods.stream(entries(), true), e -> {
Integer rId = e.getKey();
Record r = e.getValue();
AssociativeArray xData = r.getX().copy();
boolean modified = xData.keySet().removeAll(columnSet);
if(modified) {
Record newR = new Record(xData, r.getY(), r.getYPredicted(), r.getYPredictedProbabilities());
//safe to call in this context. we already updated the meta when we modified the xDataTypes
_unsafe_set(rId, newR);
}
});
} | [
"public",
"void",
"dropXColumns",
"(",
"Set",
"<",
"Object",
">",
"columnSet",
")",
"{",
"columnSet",
".",
"retainAll",
"(",
"data",
".",
"xDataTypes",
".",
"keySet",
"(",
")",
")",
";",
"//keep only those columns that are already known to the Meta data of the Dataframe",
"if",
"(",
"columnSet",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
";",
"}",
"//remove all the columns from the Meta data",
"data",
".",
"xDataTypes",
".",
"keySet",
"(",
")",
".",
"removeAll",
"(",
"columnSet",
")",
";",
"streamExecutor",
".",
"forEach",
"(",
"StreamMethods",
".",
"stream",
"(",
"entries",
"(",
")",
",",
"true",
")",
",",
"e",
"->",
"{",
"Integer",
"rId",
"=",
"e",
".",
"getKey",
"(",
")",
";",
"Record",
"r",
"=",
"e",
".",
"getValue",
"(",
")",
";",
"AssociativeArray",
"xData",
"=",
"r",
".",
"getX",
"(",
")",
".",
"copy",
"(",
")",
";",
"boolean",
"modified",
"=",
"xData",
".",
"keySet",
"(",
")",
".",
"removeAll",
"(",
"columnSet",
")",
";",
"if",
"(",
"modified",
")",
"{",
"Record",
"newR",
"=",
"new",
"Record",
"(",
"xData",
",",
"r",
".",
"getY",
"(",
")",
",",
"r",
".",
"getYPredicted",
"(",
")",
",",
"r",
".",
"getYPredictedProbabilities",
"(",
")",
")",
";",
"//safe to call in this context. we already updated the meta when we modified the xDataTypes",
"_unsafe_set",
"(",
"rId",
",",
"newR",
")",
";",
"}",
"}",
")",
";",
"}"
] | Removes completely a list of columns from the dataset. The meta-data of
the Dataframe are updated. The method internally uses threads.
@param columnSet | [
"Removes",
"completely",
"a",
"list",
"of",
"columns",
"from",
"the",
"dataset",
".",
"The",
"meta",
"-",
"data",
"of",
"the",
"Dataframe",
"are",
"updated",
".",
"The",
"method",
"internally",
"uses",
"threads",
"."
] | train | https://github.com/datumbox/datumbox-framework/blob/909dff0476e80834f05ecdde0624dd2390e9b0ca/datumbox-framework-core/src/main/java/com/datumbox/framework/core/common/dataobjects/Dataframe.java#L701-L726 |
FasterXML/woodstox | src/main/java/com/ctc/wstx/sr/StreamScanner.java | StreamScanner.getIntEntity | protected EntityDecl getIntEntity(int ch, final char[] originalChars) {
"""
Returns an entity (possibly from cache) for the argument character using the encoded
representation in mInputBuffer[entityStartPos ... mInputPtr-1].
"""
String cacheKey = new String(originalChars);
IntEntity entity = mCachedEntities.get(cacheKey);
if (entity == null) {
String repl;
if (ch <= 0xFFFF) {
repl = Character.toString((char) ch);
} else {
StringBuffer sb = new StringBuffer(2);
ch -= 0x10000;
sb.append((char) ((ch >> 10) + 0xD800));
sb.append((char) ((ch & 0x3FF) + 0xDC00));
repl = sb.toString();
}
entity = IntEntity.create(new String(originalChars), repl);
mCachedEntities.put(cacheKey, entity);
}
return entity;
} | java | protected EntityDecl getIntEntity(int ch, final char[] originalChars)
{
String cacheKey = new String(originalChars);
IntEntity entity = mCachedEntities.get(cacheKey);
if (entity == null) {
String repl;
if (ch <= 0xFFFF) {
repl = Character.toString((char) ch);
} else {
StringBuffer sb = new StringBuffer(2);
ch -= 0x10000;
sb.append((char) ((ch >> 10) + 0xD800));
sb.append((char) ((ch & 0x3FF) + 0xDC00));
repl = sb.toString();
}
entity = IntEntity.create(new String(originalChars), repl);
mCachedEntities.put(cacheKey, entity);
}
return entity;
} | [
"protected",
"EntityDecl",
"getIntEntity",
"(",
"int",
"ch",
",",
"final",
"char",
"[",
"]",
"originalChars",
")",
"{",
"String",
"cacheKey",
"=",
"new",
"String",
"(",
"originalChars",
")",
";",
"IntEntity",
"entity",
"=",
"mCachedEntities",
".",
"get",
"(",
"cacheKey",
")",
";",
"if",
"(",
"entity",
"==",
"null",
")",
"{",
"String",
"repl",
";",
"if",
"(",
"ch",
"<=",
"0xFFFF",
")",
"{",
"repl",
"=",
"Character",
".",
"toString",
"(",
"(",
"char",
")",
"ch",
")",
";",
"}",
"else",
"{",
"StringBuffer",
"sb",
"=",
"new",
"StringBuffer",
"(",
"2",
")",
";",
"ch",
"-=",
"0x10000",
";",
"sb",
".",
"append",
"(",
"(",
"char",
")",
"(",
"(",
"ch",
">>",
"10",
")",
"+",
"0xD800",
")",
")",
";",
"sb",
".",
"append",
"(",
"(",
"char",
")",
"(",
"(",
"ch",
"&",
"0x3FF",
")",
"+",
"0xDC00",
")",
")",
";",
"repl",
"=",
"sb",
".",
"toString",
"(",
")",
";",
"}",
"entity",
"=",
"IntEntity",
".",
"create",
"(",
"new",
"String",
"(",
"originalChars",
")",
",",
"repl",
")",
";",
"mCachedEntities",
".",
"put",
"(",
"cacheKey",
",",
"entity",
")",
";",
"}",
"return",
"entity",
";",
"}"
] | Returns an entity (possibly from cache) for the argument character using the encoded
representation in mInputBuffer[entityStartPos ... mInputPtr-1]. | [
"Returns",
"an",
"entity",
"(",
"possibly",
"from",
"cache",
")",
"for",
"the",
"argument",
"character",
"using",
"the",
"encoded",
"representation",
"in",
"mInputBuffer",
"[",
"entityStartPos",
"...",
"mInputPtr",
"-",
"1",
"]",
"."
] | train | https://github.com/FasterXML/woodstox/blob/ffcaabdc06672d9564c48c25d601d029b7fd6548/src/main/java/com/ctc/wstx/sr/StreamScanner.java#L1588-L1608 |
paymill/paymill-java | src/main/java/com/paymill/services/SubscriptionService.java | SubscriptionService.changeOfferKeepCaptureDateNoRefund | public Subscription changeOfferKeepCaptureDateNoRefund( String subscription, Offer offer ) {
"""
Change the offer of a subscription.<br>
<br>
the plan will be changed immediately. The next_capture_at date will remain unchanged. No refund will be given<br>
<strong>IMPORTANT</strong><br>
Permitted up only until one day (24 hours) before the next charge date.<br>
@param subscription the subscription
@param offer the new offer
@return the updated subscription
"""
return changeOfferKeepCaptureDateNoRefund( new Subscription( subscription ), offer );
} | java | public Subscription changeOfferKeepCaptureDateNoRefund( String subscription, Offer offer ) {
return changeOfferKeepCaptureDateNoRefund( new Subscription( subscription ), offer );
} | [
"public",
"Subscription",
"changeOfferKeepCaptureDateNoRefund",
"(",
"String",
"subscription",
",",
"Offer",
"offer",
")",
"{",
"return",
"changeOfferKeepCaptureDateNoRefund",
"(",
"new",
"Subscription",
"(",
"subscription",
")",
",",
"offer",
")",
";",
"}"
] | Change the offer of a subscription.<br>
<br>
the plan will be changed immediately. The next_capture_at date will remain unchanged. No refund will be given<br>
<strong>IMPORTANT</strong><br>
Permitted up only until one day (24 hours) before the next charge date.<br>
@param subscription the subscription
@param offer the new offer
@return the updated subscription | [
"Change",
"the",
"offer",
"of",
"a",
"subscription",
".",
"<br",
">",
"<br",
">",
"the",
"plan",
"will",
"be",
"changed",
"immediately",
".",
"The",
"next_capture_at",
"date",
"will",
"remain",
"unchanged",
".",
"No",
"refund",
"will",
"be",
"given<br",
">",
"<strong",
">",
"IMPORTANT<",
"/",
"strong",
">",
"<br",
">",
"Permitted",
"up",
"only",
"until",
"one",
"day",
"(",
"24",
"hours",
")",
"before",
"the",
"next",
"charge",
"date",
".",
"<br",
">"
] | train | https://github.com/paymill/paymill-java/blob/17281a0d4376c76f1711af9f09bfc138c90ba65a/src/main/java/com/paymill/services/SubscriptionService.java#L486-L488 |
bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/BitcoinSerializer.java | BitcoinSerializer.makeInventoryMessage | @Override
public InventoryMessage makeInventoryMessage(byte[] payloadBytes, int length) throws ProtocolException {
"""
Make an inventory message from the payload. Extension point for alternative
serialization format support.
"""
return new InventoryMessage(params, payloadBytes, this, length);
} | java | @Override
public InventoryMessage makeInventoryMessage(byte[] payloadBytes, int length) throws ProtocolException {
return new InventoryMessage(params, payloadBytes, this, length);
} | [
"@",
"Override",
"public",
"InventoryMessage",
"makeInventoryMessage",
"(",
"byte",
"[",
"]",
"payloadBytes",
",",
"int",
"length",
")",
"throws",
"ProtocolException",
"{",
"return",
"new",
"InventoryMessage",
"(",
"params",
",",
"payloadBytes",
",",
"this",
",",
"length",
")",
";",
"}"
] | Make an inventory message from the payload. Extension point for alternative
serialization format support. | [
"Make",
"an",
"inventory",
"message",
"from",
"the",
"payload",
".",
"Extension",
"point",
"for",
"alternative",
"serialization",
"format",
"support",
"."
] | train | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/BitcoinSerializer.java#L299-L302 |
bluelinelabs/Conductor | conductor/src/main/java/com/bluelinelabs/conductor/changehandler/SharedElementTransitionChangeHandler.java | SharedElementTransitionChangeHandler.getExitTransitionCallback | @Nullable
public SharedElementCallback getExitTransitionCallback(@NonNull ViewGroup container, @Nullable View from, @Nullable View to, boolean isPush) {
"""
Should return a callback that can be used to customize transition behavior of the shared element transition for the "from" view.
"""
return null;
} | java | @Nullable
public SharedElementCallback getExitTransitionCallback(@NonNull ViewGroup container, @Nullable View from, @Nullable View to, boolean isPush) {
return null;
} | [
"@",
"Nullable",
"public",
"SharedElementCallback",
"getExitTransitionCallback",
"(",
"@",
"NonNull",
"ViewGroup",
"container",
",",
"@",
"Nullable",
"View",
"from",
",",
"@",
"Nullable",
"View",
"to",
",",
"boolean",
"isPush",
")",
"{",
"return",
"null",
";",
"}"
] | Should return a callback that can be used to customize transition behavior of the shared element transition for the "from" view. | [
"Should",
"return",
"a",
"callback",
"that",
"can",
"be",
"used",
"to",
"customize",
"transition",
"behavior",
"of",
"the",
"shared",
"element",
"transition",
"for",
"the",
"from",
"view",
"."
] | train | https://github.com/bluelinelabs/Conductor/blob/94c9121bb16f93b481954513a8e3905846829fb2/conductor/src/main/java/com/bluelinelabs/conductor/changehandler/SharedElementTransitionChangeHandler.java#L525-L528 |
opsmatters/newrelic-api | src/main/java/com/opsmatters/newrelic/api/services/HttpContext.java | HttpContext.POST | public <T> Optional<T> POST(String partialUrl, Object payload, GenericType<T> returnType) {
"""
Execute a POST call against the partial URL.
@param <T> The type parameter used for the return object
@param partialUrl The partial URL to build
@param payload The object to use for the POST
@param returnType The expected return type
@return The return type
"""
URI uri = buildUri(partialUrl);
return executePostRequest(uri, payload, returnType);
} | java | public <T> Optional<T> POST(String partialUrl, Object payload, GenericType<T> returnType)
{
URI uri = buildUri(partialUrl);
return executePostRequest(uri, payload, returnType);
} | [
"public",
"<",
"T",
">",
"Optional",
"<",
"T",
">",
"POST",
"(",
"String",
"partialUrl",
",",
"Object",
"payload",
",",
"GenericType",
"<",
"T",
">",
"returnType",
")",
"{",
"URI",
"uri",
"=",
"buildUri",
"(",
"partialUrl",
")",
";",
"return",
"executePostRequest",
"(",
"uri",
",",
"payload",
",",
"returnType",
")",
";",
"}"
] | Execute a POST call against the partial URL.
@param <T> The type parameter used for the return object
@param partialUrl The partial URL to build
@param payload The object to use for the POST
@param returnType The expected return type
@return The return type | [
"Execute",
"a",
"POST",
"call",
"against",
"the",
"partial",
"URL",
"."
] | train | https://github.com/opsmatters/newrelic-api/blob/5bc2ea62ec368db891e4fd5fe3dcdf529d086b5e/src/main/java/com/opsmatters/newrelic/api/services/HttpContext.java#L220-L224 |
wanglinsong/testharness | src/main/java/com/tascape/qa/th/comm/MySqlCommunication.java | MySqlCommunication.restoreTable | public void restoreTable(String tableName, String tempTableName) throws SQLException {
"""
Restores table content.
@param tableName table to be restored
@param tempTableName temporary table name
@throws SQLException for any issue
"""
LOG.debug("Restore table {} from {}", tableName, tempTableName);
try {
this.setForeignKeyCheckEnabled(false);
this.truncateTable(tableName);
final String sql = "INSERT INTO " + tableName + " SELECT * FROM " + tempTableName + ";";
this.executeUpdate(sql);
} finally {
this.setForeignKeyCheckEnabled(true);
}
} | java | public void restoreTable(String tableName, String tempTableName) throws SQLException {
LOG.debug("Restore table {} from {}", tableName, tempTableName);
try {
this.setForeignKeyCheckEnabled(false);
this.truncateTable(tableName);
final String sql = "INSERT INTO " + tableName + " SELECT * FROM " + tempTableName + ";";
this.executeUpdate(sql);
} finally {
this.setForeignKeyCheckEnabled(true);
}
} | [
"public",
"void",
"restoreTable",
"(",
"String",
"tableName",
",",
"String",
"tempTableName",
")",
"throws",
"SQLException",
"{",
"LOG",
".",
"debug",
"(",
"\"Restore table {} from {}\"",
",",
"tableName",
",",
"tempTableName",
")",
";",
"try",
"{",
"this",
".",
"setForeignKeyCheckEnabled",
"(",
"false",
")",
";",
"this",
".",
"truncateTable",
"(",
"tableName",
")",
";",
"final",
"String",
"sql",
"=",
"\"INSERT INTO \"",
"+",
"tableName",
"+",
"\" SELECT * FROM \"",
"+",
"tempTableName",
"+",
"\";\"",
";",
"this",
".",
"executeUpdate",
"(",
"sql",
")",
";",
"}",
"finally",
"{",
"this",
".",
"setForeignKeyCheckEnabled",
"(",
"true",
")",
";",
"}",
"}"
] | Restores table content.
@param tableName table to be restored
@param tempTableName temporary table name
@throws SQLException for any issue | [
"Restores",
"table",
"content",
"."
] | train | https://github.com/wanglinsong/testharness/blob/76f3e4546648e0720f6f87a58cb91a09cd36dfca/src/main/java/com/tascape/qa/th/comm/MySqlCommunication.java#L141-L151 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-vision/src/main/java/com/google/cloud/vision/v1/ProductSearchClient.java | ProductSearchClient.createProduct | public final Product createProduct(String parent, Product product, String productId) {
"""
Creates and returns a new product resource.
<p>Possible errors:
<p>* Returns INVALID_ARGUMENT if display_name is missing or longer than 4096 characters.
* Returns INVALID_ARGUMENT if description is longer than 4096 characters. * Returns
INVALID_ARGUMENT if product_category is missing or invalid.
<p>Sample code:
<pre><code>
try (ProductSearchClient productSearchClient = ProductSearchClient.create()) {
LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]");
Product product = Product.newBuilder().build();
String productId = "";
Product response = productSearchClient.createProduct(parent.toString(), product, productId);
}
</code></pre>
@param parent The project in which the Product should be created.
<p>Format is `projects/PROJECT_ID/locations/LOC_ID`.
@param product The product to create.
@param productId A user-supplied resource id for this Product. If set, the server will attempt
to use this value as the resource id. If it is already in use, an error is returned with
code ALREADY_EXISTS. Must be at most 128 characters long. It cannot contain the character
`/`.
@throws com.google.api.gax.rpc.ApiException if the remote call fails
"""
CreateProductRequest request =
CreateProductRequest.newBuilder()
.setParent(parent)
.setProduct(product)
.setProductId(productId)
.build();
return createProduct(request);
} | java | public final Product createProduct(String parent, Product product, String productId) {
CreateProductRequest request =
CreateProductRequest.newBuilder()
.setParent(parent)
.setProduct(product)
.setProductId(productId)
.build();
return createProduct(request);
} | [
"public",
"final",
"Product",
"createProduct",
"(",
"String",
"parent",
",",
"Product",
"product",
",",
"String",
"productId",
")",
"{",
"CreateProductRequest",
"request",
"=",
"CreateProductRequest",
".",
"newBuilder",
"(",
")",
".",
"setParent",
"(",
"parent",
")",
".",
"setProduct",
"(",
"product",
")",
".",
"setProductId",
"(",
"productId",
")",
".",
"build",
"(",
")",
";",
"return",
"createProduct",
"(",
"request",
")",
";",
"}"
] | Creates and returns a new product resource.
<p>Possible errors:
<p>* Returns INVALID_ARGUMENT if display_name is missing or longer than 4096 characters.
* Returns INVALID_ARGUMENT if description is longer than 4096 characters. * Returns
INVALID_ARGUMENT if product_category is missing or invalid.
<p>Sample code:
<pre><code>
try (ProductSearchClient productSearchClient = ProductSearchClient.create()) {
LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]");
Product product = Product.newBuilder().build();
String productId = "";
Product response = productSearchClient.createProduct(parent.toString(), product, productId);
}
</code></pre>
@param parent The project in which the Product should be created.
<p>Format is `projects/PROJECT_ID/locations/LOC_ID`.
@param product The product to create.
@param productId A user-supplied resource id for this Product. If set, the server will attempt
to use this value as the resource id. If it is already in use, an error is returned with
code ALREADY_EXISTS. Must be at most 128 characters long. It cannot contain the character
`/`.
@throws com.google.api.gax.rpc.ApiException if the remote call fails | [
"Creates",
"and",
"returns",
"a",
"new",
"product",
"resource",
"."
] | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-vision/src/main/java/com/google/cloud/vision/v1/ProductSearchClient.java#L457-L466 |
allengeorge/libraft | libraft-samples/kayvee/src/main/java/io/libraft/kayvee/resources/KeyResource.java | KeyResource.update | @PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public @Nullable KeyValue update(SetValue setValue) throws Exception {
"""
Perform a {@code SET} or {@code CAS} on the {@link KeyResource#key} represented by this resource.
<p/>
The rules for {@code SET} and {@code CAS} are
described in the KayVee README.md. Additional validation of
{@code setValue} is performed to ensure that its
fields meet the preconditions for these operations.
@param setValue valid instance of {@code SetValue} with fields set
appropriately for the invoked operation
@return new value associated with the {@link KeyResource#key} represented by this resource.
May be null if this key was deleted from replicated storage
@throws CannotSubmitCommandException if this server is not the
leader of the Raft cluster and cannot submit commands to the cluster
@throws Exception if this operation cannot be replicated to the Raft cluster. If an exception is
thrown this operation is in an <strong>unknown</strong> state, and should be retried
@see KayVeeCommand
"""
if (!setValue.hasNewValue() && !setValue.hasExpectedValue()) {
throw new IllegalArgumentException(String.format("key:%s - bad request: expectedValue and newValue not set", key));
}
if (setValue.hasExpectedValue()) {
return compareAndSet(setValue);
} else {
return set(setValue);
}
} | java | @PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public @Nullable KeyValue update(SetValue setValue) throws Exception {
if (!setValue.hasNewValue() && !setValue.hasExpectedValue()) {
throw new IllegalArgumentException(String.format("key:%s - bad request: expectedValue and newValue not set", key));
}
if (setValue.hasExpectedValue()) {
return compareAndSet(setValue);
} else {
return set(setValue);
}
} | [
"@",
"PUT",
"@",
"Consumes",
"(",
"MediaType",
".",
"APPLICATION_JSON",
")",
"@",
"Produces",
"(",
"MediaType",
".",
"APPLICATION_JSON",
")",
"public",
"@",
"Nullable",
"KeyValue",
"update",
"(",
"SetValue",
"setValue",
")",
"throws",
"Exception",
"{",
"if",
"(",
"!",
"setValue",
".",
"hasNewValue",
"(",
")",
"&&",
"!",
"setValue",
".",
"hasExpectedValue",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"String",
".",
"format",
"(",
"\"key:%s - bad request: expectedValue and newValue not set\"",
",",
"key",
")",
")",
";",
"}",
"if",
"(",
"setValue",
".",
"hasExpectedValue",
"(",
")",
")",
"{",
"return",
"compareAndSet",
"(",
"setValue",
")",
";",
"}",
"else",
"{",
"return",
"set",
"(",
"setValue",
")",
";",
"}",
"}"
] | Perform a {@code SET} or {@code CAS} on the {@link KeyResource#key} represented by this resource.
<p/>
The rules for {@code SET} and {@code CAS} are
described in the KayVee README.md. Additional validation of
{@code setValue} is performed to ensure that its
fields meet the preconditions for these operations.
@param setValue valid instance of {@code SetValue} with fields set
appropriately for the invoked operation
@return new value associated with the {@link KeyResource#key} represented by this resource.
May be null if this key was deleted from replicated storage
@throws CannotSubmitCommandException if this server is not the
leader of the Raft cluster and cannot submit commands to the cluster
@throws Exception if this operation cannot be replicated to the Raft cluster. If an exception is
thrown this operation is in an <strong>unknown</strong> state, and should be retried
@see KayVeeCommand | [
"Perform",
"a",
"{",
"@code",
"SET",
"}",
"or",
"{",
"@code",
"CAS",
"}",
"on",
"the",
"{",
"@link",
"KeyResource#key",
"}",
"represented",
"by",
"this",
"resource",
".",
"<p",
"/",
">",
"The",
"rules",
"for",
"{",
"@code",
"SET",
"}",
"and",
"{",
"@code",
"CAS",
"}",
"are",
"described",
"in",
"the",
"KayVee",
"README",
".",
"md",
".",
"Additional",
"validation",
"of",
"{",
"@code",
"setValue",
"}",
"is",
"performed",
"to",
"ensure",
"that",
"its",
"fields",
"meet",
"the",
"preconditions",
"for",
"these",
"operations",
"."
] | train | https://github.com/allengeorge/libraft/blob/00d68bb5e68d4020af59df3c8a9a14380108ac89/libraft-samples/kayvee/src/main/java/io/libraft/kayvee/resources/KeyResource.java#L149-L162 |
code4everything/util | src/main/java/com/zhazhapan/util/encryption/JavaEncrypt.java | JavaEncrypt.messageDigest | private static String messageDigest(String key, String string, int scale) throws NoSuchAlgorithmException {
"""
消息摘要算法,单向加密
@param key {@link String}
@param string {@link String}
@param scale {@link Integer}
@return {@link String}
@throws NoSuchAlgorithmException 异常
"""
MessageDigest md = MessageDigest.getInstance(key);
md.update(string.getBytes());
BigInteger bigInteger = new BigInteger(md.digest());
return bigInteger.toString(scale);
} | java | private static String messageDigest(String key, String string, int scale) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance(key);
md.update(string.getBytes());
BigInteger bigInteger = new BigInteger(md.digest());
return bigInteger.toString(scale);
} | [
"private",
"static",
"String",
"messageDigest",
"(",
"String",
"key",
",",
"String",
"string",
",",
"int",
"scale",
")",
"throws",
"NoSuchAlgorithmException",
"{",
"MessageDigest",
"md",
"=",
"MessageDigest",
".",
"getInstance",
"(",
"key",
")",
";",
"md",
".",
"update",
"(",
"string",
".",
"getBytes",
"(",
")",
")",
";",
"BigInteger",
"bigInteger",
"=",
"new",
"BigInteger",
"(",
"md",
".",
"digest",
"(",
")",
")",
";",
"return",
"bigInteger",
".",
"toString",
"(",
"scale",
")",
";",
"}"
] | 消息摘要算法,单向加密
@param key {@link String}
@param string {@link String}
@param scale {@link Integer}
@return {@link String}
@throws NoSuchAlgorithmException 异常 | [
"消息摘要算法,单向加密"
] | train | https://github.com/code4everything/util/blob/1fc9f0ead1108f4d7208ba7c000df4244f708418/src/main/java/com/zhazhapan/util/encryption/JavaEncrypt.java#L348-L353 |
microfocus-idol/java-configuration-impl | src/main/java/com/hp/autonomy/frontend/configuration/ConfigurationUtils.java | ConfigurationUtils.defaultValidate | public static <F extends ConfigurationComponent<F>> void defaultValidate(final F component, final String section) throws ConfigException {
"""
Calls {@link ConfigurationComponent#basicValidate(String)} on the supplied component if not null
@param component the nullable component
@param section the configuration section
@param <F> the component type
@throws ConfigException validation failure
@see SimpleComponent for basic usage
"""
try {
final Class<?> type = component.getClass();
final BeanInfo beanInfo = Introspector.getBeanInfo(type);
for (final PropertyDescriptor propertyDescriptor : beanInfo.getPropertyDescriptors()) {
if (ConfigurationComponent.class.isAssignableFrom(propertyDescriptor.getPropertyType())) {
@SuppressWarnings("rawtypes")
final ConfigurationComponent subComponent = (ConfigurationComponent) propertyDescriptor.getReadMethod().invoke(component);
basicValidate(subComponent, section);
}
}
} catch (final IntrospectionException | IllegalAccessException | InvocationTargetException e) {
throw new ConfigException("Error performing config bean introspection", e);
}
} | java | public static <F extends ConfigurationComponent<F>> void defaultValidate(final F component, final String section) throws ConfigException {
try {
final Class<?> type = component.getClass();
final BeanInfo beanInfo = Introspector.getBeanInfo(type);
for (final PropertyDescriptor propertyDescriptor : beanInfo.getPropertyDescriptors()) {
if (ConfigurationComponent.class.isAssignableFrom(propertyDescriptor.getPropertyType())) {
@SuppressWarnings("rawtypes")
final ConfigurationComponent subComponent = (ConfigurationComponent) propertyDescriptor.getReadMethod().invoke(component);
basicValidate(subComponent, section);
}
}
} catch (final IntrospectionException | IllegalAccessException | InvocationTargetException e) {
throw new ConfigException("Error performing config bean introspection", e);
}
} | [
"public",
"static",
"<",
"F",
"extends",
"ConfigurationComponent",
"<",
"F",
">",
">",
"void",
"defaultValidate",
"(",
"final",
"F",
"component",
",",
"final",
"String",
"section",
")",
"throws",
"ConfigException",
"{",
"try",
"{",
"final",
"Class",
"<",
"?",
">",
"type",
"=",
"component",
".",
"getClass",
"(",
")",
";",
"final",
"BeanInfo",
"beanInfo",
"=",
"Introspector",
".",
"getBeanInfo",
"(",
"type",
")",
";",
"for",
"(",
"final",
"PropertyDescriptor",
"propertyDescriptor",
":",
"beanInfo",
".",
"getPropertyDescriptors",
"(",
")",
")",
"{",
"if",
"(",
"ConfigurationComponent",
".",
"class",
".",
"isAssignableFrom",
"(",
"propertyDescriptor",
".",
"getPropertyType",
"(",
")",
")",
")",
"{",
"@",
"SuppressWarnings",
"(",
"\"rawtypes\"",
")",
"final",
"ConfigurationComponent",
"subComponent",
"=",
"(",
"ConfigurationComponent",
")",
"propertyDescriptor",
".",
"getReadMethod",
"(",
")",
".",
"invoke",
"(",
"component",
")",
";",
"basicValidate",
"(",
"subComponent",
",",
"section",
")",
";",
"}",
"}",
"}",
"catch",
"(",
"final",
"IntrospectionException",
"|",
"IllegalAccessException",
"|",
"InvocationTargetException",
"e",
")",
"{",
"throw",
"new",
"ConfigException",
"(",
"\"Error performing config bean introspection\"",
",",
"e",
")",
";",
"}",
"}"
] | Calls {@link ConfigurationComponent#basicValidate(String)} on the supplied component if not null
@param component the nullable component
@param section the configuration section
@param <F> the component type
@throws ConfigException validation failure
@see SimpleComponent for basic usage | [
"Calls",
"{",
"@link",
"ConfigurationComponent#basicValidate",
"(",
"String",
")",
"}",
"on",
"the",
"supplied",
"component",
"if",
"not",
"null"
] | train | https://github.com/microfocus-idol/java-configuration-impl/blob/cd9d744cacfaaae3c76cacc211e65742bbc7b00a/src/main/java/com/hp/autonomy/frontend/configuration/ConfigurationUtils.java#L113-L127 |
xcesco/kripton | kripton-processor/src/main/java/com/abubusoft/kripton/processor/bind/transform/ObjectBindTransform.java | ObjectBindTransform.generateParseOnJacksonAsString | @Override
public void generateParseOnJacksonAsString(BindTypeContext context, MethodSpec.Builder methodBuilder, String parserName, TypeName beanClass, String beanName, BindProperty property) {
"""
/* (non-Javadoc)
@see com.abubusoft.kripton.processor.bind.transform.BindTransform#generateParseOnJacksonAsString(com.abubusoft.kripton.processor.bind.BindTypeContext, com.squareup.javapoet.MethodSpec.Builder, java.lang.String, com.squareup.javapoet.TypeName, java.lang.String, com.abubusoft.kripton.processor.bind.model.BindProperty)
"""
// TODO QUA
// TypeName typeName = resolveTypeName(property.getParent(),
// property.getPropertyType().getTypeName());
TypeName typeName = property.getPropertyType().getTypeName();
String bindName = context.getBindMapperName(context, typeName);
if (property.isNullable()) {
methodBuilder.beginControlFlow("if ($L.currentToken()==$T.START_OBJECT || $L.currentToken()==$T.VALUE_STRING)", parserName, JsonToken.class, parserName, JsonToken.class);
}
methodBuilder.addStatement(setter(beanClass, beanName, property, "$L.parseOnJacksonAsString(jacksonParser)"), bindName);
if (property.isNullable()) {
methodBuilder.endControlFlow();
}
} | java | @Override
public void generateParseOnJacksonAsString(BindTypeContext context, MethodSpec.Builder methodBuilder, String parserName, TypeName beanClass, String beanName, BindProperty property) {
// TODO QUA
// TypeName typeName = resolveTypeName(property.getParent(),
// property.getPropertyType().getTypeName());
TypeName typeName = property.getPropertyType().getTypeName();
String bindName = context.getBindMapperName(context, typeName);
if (property.isNullable()) {
methodBuilder.beginControlFlow("if ($L.currentToken()==$T.START_OBJECT || $L.currentToken()==$T.VALUE_STRING)", parserName, JsonToken.class, parserName, JsonToken.class);
}
methodBuilder.addStatement(setter(beanClass, beanName, property, "$L.parseOnJacksonAsString(jacksonParser)"), bindName);
if (property.isNullable()) {
methodBuilder.endControlFlow();
}
} | [
"@",
"Override",
"public",
"void",
"generateParseOnJacksonAsString",
"(",
"BindTypeContext",
"context",
",",
"MethodSpec",
".",
"Builder",
"methodBuilder",
",",
"String",
"parserName",
",",
"TypeName",
"beanClass",
",",
"String",
"beanName",
",",
"BindProperty",
"property",
")",
"{",
"// TODO QUA",
"// TypeName typeName = resolveTypeName(property.getParent(),",
"// property.getPropertyType().getTypeName());",
"TypeName",
"typeName",
"=",
"property",
".",
"getPropertyType",
"(",
")",
".",
"getTypeName",
"(",
")",
";",
"String",
"bindName",
"=",
"context",
".",
"getBindMapperName",
"(",
"context",
",",
"typeName",
")",
";",
"if",
"(",
"property",
".",
"isNullable",
"(",
")",
")",
"{",
"methodBuilder",
".",
"beginControlFlow",
"(",
"\"if ($L.currentToken()==$T.START_OBJECT || $L.currentToken()==$T.VALUE_STRING)\"",
",",
"parserName",
",",
"JsonToken",
".",
"class",
",",
"parserName",
",",
"JsonToken",
".",
"class",
")",
";",
"}",
"methodBuilder",
".",
"addStatement",
"(",
"setter",
"(",
"beanClass",
",",
"beanName",
",",
"property",
",",
"\"$L.parseOnJacksonAsString(jacksonParser)\"",
")",
",",
"bindName",
")",
";",
"if",
"(",
"property",
".",
"isNullable",
"(",
")",
")",
"{",
"methodBuilder",
".",
"endControlFlow",
"(",
")",
";",
"}",
"}"
] | /* (non-Javadoc)
@see com.abubusoft.kripton.processor.bind.transform.BindTransform#generateParseOnJacksonAsString(com.abubusoft.kripton.processor.bind.BindTypeContext, com.squareup.javapoet.MethodSpec.Builder, java.lang.String, com.squareup.javapoet.TypeName, java.lang.String, com.abubusoft.kripton.processor.bind.model.BindProperty) | [
"/",
"*",
"(",
"non",
"-",
"Javadoc",
")"
] | train | https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/bind/transform/ObjectBindTransform.java#L179-L195 |
qiujiayu/AutoLoadCache | src/main/java/com/jarvis/cache/CacheHandler.java | CacheHandler.writeOnly | private Object writeOnly(CacheAopProxyChain pjp, Cache cache) throws Throwable {
"""
从数据源中获取最新数据,并写入缓存。注意:这里不使用“拿来主义”机制,是因为当前可能是更新数据的方法。
@param pjp CacheAopProxyChain
@param cache Cache注解
@return 最新数据
@throws Throwable 异常
"""
DataLoaderFactory factory = DataLoaderFactory.getInstance();
DataLoader dataLoader = factory.getDataLoader();
CacheWrapper<Object> cacheWrapper;
try {
cacheWrapper = dataLoader.init(pjp, cache, this).getData().getCacheWrapper();
} catch (Throwable e) {
throw e;
} finally {
factory.returnObject(dataLoader);
}
Object result = cacheWrapper.getCacheObject();
Object[] arguments = pjp.getArgs();
if (scriptParser.isCacheable(cache, pjp.getTarget(), arguments, result)) {
CacheKeyTO cacheKey = getCacheKey(pjp, cache, result);
// 注意:这里只能获取AutoloadTO,不能生成AutoloadTO
AutoLoadTO autoLoadTO = autoLoadHandler.getAutoLoadTO(cacheKey);
try {
writeCache(pjp, pjp.getArgs(), cache, cacheKey, cacheWrapper);
if (null != autoLoadTO) {
// 同步加载时间
autoLoadTO.setLastLoadTime(cacheWrapper.getLastLoadTime())
// 同步过期时间
.setExpire(cacheWrapper.getExpire());
}
} catch (Exception ex) {
log.error(ex.getMessage(), ex);
}
}
return result;
} | java | private Object writeOnly(CacheAopProxyChain pjp, Cache cache) throws Throwable {
DataLoaderFactory factory = DataLoaderFactory.getInstance();
DataLoader dataLoader = factory.getDataLoader();
CacheWrapper<Object> cacheWrapper;
try {
cacheWrapper = dataLoader.init(pjp, cache, this).getData().getCacheWrapper();
} catch (Throwable e) {
throw e;
} finally {
factory.returnObject(dataLoader);
}
Object result = cacheWrapper.getCacheObject();
Object[] arguments = pjp.getArgs();
if (scriptParser.isCacheable(cache, pjp.getTarget(), arguments, result)) {
CacheKeyTO cacheKey = getCacheKey(pjp, cache, result);
// 注意:这里只能获取AutoloadTO,不能生成AutoloadTO
AutoLoadTO autoLoadTO = autoLoadHandler.getAutoLoadTO(cacheKey);
try {
writeCache(pjp, pjp.getArgs(), cache, cacheKey, cacheWrapper);
if (null != autoLoadTO) {
// 同步加载时间
autoLoadTO.setLastLoadTime(cacheWrapper.getLastLoadTime())
// 同步过期时间
.setExpire(cacheWrapper.getExpire());
}
} catch (Exception ex) {
log.error(ex.getMessage(), ex);
}
}
return result;
} | [
"private",
"Object",
"writeOnly",
"(",
"CacheAopProxyChain",
"pjp",
",",
"Cache",
"cache",
")",
"throws",
"Throwable",
"{",
"DataLoaderFactory",
"factory",
"=",
"DataLoaderFactory",
".",
"getInstance",
"(",
")",
";",
"DataLoader",
"dataLoader",
"=",
"factory",
".",
"getDataLoader",
"(",
")",
";",
"CacheWrapper",
"<",
"Object",
">",
"cacheWrapper",
";",
"try",
"{",
"cacheWrapper",
"=",
"dataLoader",
".",
"init",
"(",
"pjp",
",",
"cache",
",",
"this",
")",
".",
"getData",
"(",
")",
".",
"getCacheWrapper",
"(",
")",
";",
"}",
"catch",
"(",
"Throwable",
"e",
")",
"{",
"throw",
"e",
";",
"}",
"finally",
"{",
"factory",
".",
"returnObject",
"(",
"dataLoader",
")",
";",
"}",
"Object",
"result",
"=",
"cacheWrapper",
".",
"getCacheObject",
"(",
")",
";",
"Object",
"[",
"]",
"arguments",
"=",
"pjp",
".",
"getArgs",
"(",
")",
";",
"if",
"(",
"scriptParser",
".",
"isCacheable",
"(",
"cache",
",",
"pjp",
".",
"getTarget",
"(",
")",
",",
"arguments",
",",
"result",
")",
")",
"{",
"CacheKeyTO",
"cacheKey",
"=",
"getCacheKey",
"(",
"pjp",
",",
"cache",
",",
"result",
")",
";",
"// 注意:这里只能获取AutoloadTO,不能生成AutoloadTO",
"AutoLoadTO",
"autoLoadTO",
"=",
"autoLoadHandler",
".",
"getAutoLoadTO",
"(",
"cacheKey",
")",
";",
"try",
"{",
"writeCache",
"(",
"pjp",
",",
"pjp",
".",
"getArgs",
"(",
")",
",",
"cache",
",",
"cacheKey",
",",
"cacheWrapper",
")",
";",
"if",
"(",
"null",
"!=",
"autoLoadTO",
")",
"{",
"// 同步加载时间",
"autoLoadTO",
".",
"setLastLoadTime",
"(",
"cacheWrapper",
".",
"getLastLoadTime",
"(",
")",
")",
"// 同步过期时间",
".",
"setExpire",
"(",
"cacheWrapper",
".",
"getExpire",
"(",
")",
")",
";",
"}",
"}",
"catch",
"(",
"Exception",
"ex",
")",
"{",
"log",
".",
"error",
"(",
"ex",
".",
"getMessage",
"(",
")",
",",
"ex",
")",
";",
"}",
"}",
"return",
"result",
";",
"}"
] | 从数据源中获取最新数据,并写入缓存。注意:这里不使用“拿来主义”机制,是因为当前可能是更新数据的方法。
@param pjp CacheAopProxyChain
@param cache Cache注解
@return 最新数据
@throws Throwable 异常 | [
"从数据源中获取最新数据,并写入缓存。注意:这里不使用“拿来主义”机制,是因为当前可能是更新数据的方法。"
] | train | https://github.com/qiujiayu/AutoLoadCache/blob/8121c146f1a420fa6d6832e849acadb547c13622/src/main/java/com/jarvis/cache/CacheHandler.java#L88-L118 |
TNG/JGiven | jgiven-core/src/main/java/com/tngtech/jgiven/attachment/Attachment.java | Attachment.fromBinaryInputStream | public static Attachment fromBinaryInputStream( InputStream inputStream, MediaType mediaType ) throws IOException {
"""
Creates an attachment from a binary input stream.
The content of the stream will be transformed into a Base64 encoded string
@throws IOException if an I/O error occurs
@throws java.lang.IllegalArgumentException if mediaType is not binary
"""
return fromBinaryBytes( ByteStreams.toByteArray( inputStream ), mediaType );
} | java | public static Attachment fromBinaryInputStream( InputStream inputStream, MediaType mediaType ) throws IOException {
return fromBinaryBytes( ByteStreams.toByteArray( inputStream ), mediaType );
} | [
"public",
"static",
"Attachment",
"fromBinaryInputStream",
"(",
"InputStream",
"inputStream",
",",
"MediaType",
"mediaType",
")",
"throws",
"IOException",
"{",
"return",
"fromBinaryBytes",
"(",
"ByteStreams",
".",
"toByteArray",
"(",
"inputStream",
")",
",",
"mediaType",
")",
";",
"}"
] | Creates an attachment from a binary input stream.
The content of the stream will be transformed into a Base64 encoded string
@throws IOException if an I/O error occurs
@throws java.lang.IllegalArgumentException if mediaType is not binary | [
"Creates",
"an",
"attachment",
"from",
"a",
"binary",
"input",
"stream",
".",
"The",
"content",
"of",
"the",
"stream",
"will",
"be",
"transformed",
"into",
"a",
"Base64",
"encoded",
"string"
] | train | https://github.com/TNG/JGiven/blob/1a69248fc6d7eb380cdc4542e3be273842889748/jgiven-core/src/main/java/com/tngtech/jgiven/attachment/Attachment.java#L176-L178 |
xcesco/kripton | kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/SqlBuilderHelper.java | SqlBuilderHelper.generateColumnCheckSet | public static String generateColumnCheckSet(TypeSpec.Builder builder, SQLiteModelMethod method, Set<String> columnNames) {
"""
check used columns.
@param builder
the builder
@param method
the method
@param columnNames
the column names
@return name of column name set
"""
String columnNameSet = method.contentProviderMethodName + "ColumnSet";
StringBuilder initBuilder = new StringBuilder();
String temp = "";
for (String item : columnNames) {
initBuilder.append(temp + "\"" + item + "\"");
temp = ", ";
}
FieldSpec.Builder fieldBuilder = FieldSpec.builder(ParameterizedTypeName.get(Set.class, String.class), columnNameSet, Modifier.STATIC, Modifier.PRIVATE, Modifier.FINAL);
fieldBuilder.initializer("$T.asSet($T.class, $L)", CollectionUtils.class, String.class, initBuilder.toString());
builder.addField(fieldBuilder.build());
return columnNameSet;
} | java | public static String generateColumnCheckSet(TypeSpec.Builder builder, SQLiteModelMethod method, Set<String> columnNames) {
String columnNameSet = method.contentProviderMethodName + "ColumnSet";
StringBuilder initBuilder = new StringBuilder();
String temp = "";
for (String item : columnNames) {
initBuilder.append(temp + "\"" + item + "\"");
temp = ", ";
}
FieldSpec.Builder fieldBuilder = FieldSpec.builder(ParameterizedTypeName.get(Set.class, String.class), columnNameSet, Modifier.STATIC, Modifier.PRIVATE, Modifier.FINAL);
fieldBuilder.initializer("$T.asSet($T.class, $L)", CollectionUtils.class, String.class, initBuilder.toString());
builder.addField(fieldBuilder.build());
return columnNameSet;
} | [
"public",
"static",
"String",
"generateColumnCheckSet",
"(",
"TypeSpec",
".",
"Builder",
"builder",
",",
"SQLiteModelMethod",
"method",
",",
"Set",
"<",
"String",
">",
"columnNames",
")",
"{",
"String",
"columnNameSet",
"=",
"method",
".",
"contentProviderMethodName",
"+",
"\"ColumnSet\"",
";",
"StringBuilder",
"initBuilder",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"String",
"temp",
"=",
"\"\"",
";",
"for",
"(",
"String",
"item",
":",
"columnNames",
")",
"{",
"initBuilder",
".",
"append",
"(",
"temp",
"+",
"\"\\\"\"",
"+",
"item",
"+",
"\"\\\"\"",
")",
";",
"temp",
"=",
"\", \"",
";",
"}",
"FieldSpec",
".",
"Builder",
"fieldBuilder",
"=",
"FieldSpec",
".",
"builder",
"(",
"ParameterizedTypeName",
".",
"get",
"(",
"Set",
".",
"class",
",",
"String",
".",
"class",
")",
",",
"columnNameSet",
",",
"Modifier",
".",
"STATIC",
",",
"Modifier",
".",
"PRIVATE",
",",
"Modifier",
".",
"FINAL",
")",
";",
"fieldBuilder",
".",
"initializer",
"(",
"\"$T.asSet($T.class, $L)\"",
",",
"CollectionUtils",
".",
"class",
",",
"String",
".",
"class",
",",
"initBuilder",
".",
"toString",
"(",
")",
")",
";",
"builder",
".",
"addField",
"(",
"fieldBuilder",
".",
"build",
"(",
")",
")",
";",
"return",
"columnNameSet",
";",
"}"
] | check used columns.
@param builder
the builder
@param method
the method
@param columnNames
the column names
@return name of column name set | [
"check",
"used",
"columns",
"."
] | train | https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/SqlBuilderHelper.java#L74-L90 |
spotbugs/spotbugs | spotbugs/src/gui/main/edu/umd/cs/findbugs/gui2/BugTreeModel.java | BugTreeModel.enumsThatExist | private @Nonnull List<SortableValue> enumsThatExist(BugAspects a) {
"""
/*
This contract has been changed to return a HashList of Stringpair, our
own data structure in which finding the index of an object in the list is
very fast
"""
List<Sortables> orderBeforeDivider = st.getOrderBeforeDivider();
if (orderBeforeDivider.size() == 0) {
List<SortableValue> result = Collections.emptyList();
assert false;
return result;
}
Sortables key;
if (a.size() == 0) {
key = orderBeforeDivider.get(0);
} else {
Sortables lastKey = a.last().key;
int index = orderBeforeDivider.indexOf(lastKey);
if (index + 1 < orderBeforeDivider.size()) {
key = orderBeforeDivider.get(index + 1);
} else {
key = lastKey;
}
}
String[] all = key.getAll(bugSet.query(a));
ArrayList<SortableValue> result = new ArrayList<>(all.length);
for (String i : all) {
result.add(new SortableValue(key, i));
}
return result;
} | java | private @Nonnull List<SortableValue> enumsThatExist(BugAspects a) {
List<Sortables> orderBeforeDivider = st.getOrderBeforeDivider();
if (orderBeforeDivider.size() == 0) {
List<SortableValue> result = Collections.emptyList();
assert false;
return result;
}
Sortables key;
if (a.size() == 0) {
key = orderBeforeDivider.get(0);
} else {
Sortables lastKey = a.last().key;
int index = orderBeforeDivider.indexOf(lastKey);
if (index + 1 < orderBeforeDivider.size()) {
key = orderBeforeDivider.get(index + 1);
} else {
key = lastKey;
}
}
String[] all = key.getAll(bugSet.query(a));
ArrayList<SortableValue> result = new ArrayList<>(all.length);
for (String i : all) {
result.add(new SortableValue(key, i));
}
return result;
} | [
"private",
"@",
"Nonnull",
"List",
"<",
"SortableValue",
">",
"enumsThatExist",
"(",
"BugAspects",
"a",
")",
"{",
"List",
"<",
"Sortables",
">",
"orderBeforeDivider",
"=",
"st",
".",
"getOrderBeforeDivider",
"(",
")",
";",
"if",
"(",
"orderBeforeDivider",
".",
"size",
"(",
")",
"==",
"0",
")",
"{",
"List",
"<",
"SortableValue",
">",
"result",
"=",
"Collections",
".",
"emptyList",
"(",
")",
";",
"assert",
"false",
";",
"return",
"result",
";",
"}",
"Sortables",
"key",
";",
"if",
"(",
"a",
".",
"size",
"(",
")",
"==",
"0",
")",
"{",
"key",
"=",
"orderBeforeDivider",
".",
"get",
"(",
"0",
")",
";",
"}",
"else",
"{",
"Sortables",
"lastKey",
"=",
"a",
".",
"last",
"(",
")",
".",
"key",
";",
"int",
"index",
"=",
"orderBeforeDivider",
".",
"indexOf",
"(",
"lastKey",
")",
";",
"if",
"(",
"index",
"+",
"1",
"<",
"orderBeforeDivider",
".",
"size",
"(",
")",
")",
"{",
"key",
"=",
"orderBeforeDivider",
".",
"get",
"(",
"index",
"+",
"1",
")",
";",
"}",
"else",
"{",
"key",
"=",
"lastKey",
";",
"}",
"}",
"String",
"[",
"]",
"all",
"=",
"key",
".",
"getAll",
"(",
"bugSet",
".",
"query",
"(",
"a",
")",
")",
";",
"ArrayList",
"<",
"SortableValue",
">",
"result",
"=",
"new",
"ArrayList",
"<>",
"(",
"all",
".",
"length",
")",
";",
"for",
"(",
"String",
"i",
":",
"all",
")",
"{",
"result",
".",
"add",
"(",
"new",
"SortableValue",
"(",
"key",
",",
"i",
")",
")",
";",
"}",
"return",
"result",
";",
"}"
] | /*
This contract has been changed to return a HashList of Stringpair, our
own data structure in which finding the index of an object in the list is
very fast | [
"/",
"*",
"This",
"contract",
"has",
"been",
"changed",
"to",
"return",
"a",
"HashList",
"of",
"Stringpair",
"our",
"own",
"data",
"structure",
"in",
"which",
"finding",
"the",
"index",
"of",
"an",
"object",
"in",
"the",
"list",
"is",
"very",
"fast"
] | train | https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/gui/main/edu/umd/cs/findbugs/gui2/BugTreeModel.java#L248-L276 |
codelibs/fess | src/main/java/org/codelibs/fess/mylasta/action/FessMessages.java | FessMessages.addErrorsInvalidHeaderForRequestFile | public FessMessages addErrorsInvalidHeaderForRequestFile(String property, String arg0) {
"""
Add the created action message for the key 'errors.invalid_header_for_request_file' with parameters.
<pre>
message: Invalid header: {0}
</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_invalid_header_for_request_file, arg0));
return this;
} | java | public FessMessages addErrorsInvalidHeaderForRequestFile(String property, String arg0) {
assertPropertyNotNull(property);
add(property, new UserMessage(ERRORS_invalid_header_for_request_file, arg0));
return this;
} | [
"public",
"FessMessages",
"addErrorsInvalidHeaderForRequestFile",
"(",
"String",
"property",
",",
"String",
"arg0",
")",
"{",
"assertPropertyNotNull",
"(",
"property",
")",
";",
"add",
"(",
"property",
",",
"new",
"UserMessage",
"(",
"ERRORS_invalid_header_for_request_file",
",",
"arg0",
")",
")",
";",
"return",
"this",
";",
"}"
] | Add the created action message for the key 'errors.invalid_header_for_request_file' with parameters.
<pre>
message: Invalid header: {0}
</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",
".",
"invalid_header_for_request_file",
"with",
"parameters",
".",
"<pre",
">",
"message",
":",
"Invalid",
"header",
":",
"{",
"0",
"}",
"<",
"/",
"pre",
">"
] | train | https://github.com/codelibs/fess/blob/e5e4b722549d32a4958dfd94965b21937bfe64cf/src/main/java/org/codelibs/fess/mylasta/action/FessMessages.java#L1965-L1969 |
networknt/light-4j | body/src/main/java/com/networknt/body/BodyHandler.java | BodyHandler.attachJsonBody | private void attachJsonBody(final HttpServerExchange exchange, String string) throws IOException {
"""
Method used to parse the body into a Map or a List and attach it into exchange
@param exchange exchange to be attached
@param string unparsed request body
@throws IOException
"""
Object body;
if (string != null) {
string = string.trim();
if (string.startsWith("{")) {
body = Config.getInstance().getMapper().readValue(string, new TypeReference<Map<String, Object>>() {
});
} else if (string.startsWith("[")) {
body = Config.getInstance().getMapper().readValue(string, new TypeReference<List<Object>>() {
});
} else {
// error here. The content type in head doesn't match the body.
setExchangeStatus(exchange, CONTENT_TYPE_MISMATCH, "application/json");
return;
}
exchange.putAttachment(REQUEST_BODY, body);
}
} | java | private void attachJsonBody(final HttpServerExchange exchange, String string) throws IOException {
Object body;
if (string != null) {
string = string.trim();
if (string.startsWith("{")) {
body = Config.getInstance().getMapper().readValue(string, new TypeReference<Map<String, Object>>() {
});
} else if (string.startsWith("[")) {
body = Config.getInstance().getMapper().readValue(string, new TypeReference<List<Object>>() {
});
} else {
// error here. The content type in head doesn't match the body.
setExchangeStatus(exchange, CONTENT_TYPE_MISMATCH, "application/json");
return;
}
exchange.putAttachment(REQUEST_BODY, body);
}
} | [
"private",
"void",
"attachJsonBody",
"(",
"final",
"HttpServerExchange",
"exchange",
",",
"String",
"string",
")",
"throws",
"IOException",
"{",
"Object",
"body",
";",
"if",
"(",
"string",
"!=",
"null",
")",
"{",
"string",
"=",
"string",
".",
"trim",
"(",
")",
";",
"if",
"(",
"string",
".",
"startsWith",
"(",
"\"{\"",
")",
")",
"{",
"body",
"=",
"Config",
".",
"getInstance",
"(",
")",
".",
"getMapper",
"(",
")",
".",
"readValue",
"(",
"string",
",",
"new",
"TypeReference",
"<",
"Map",
"<",
"String",
",",
"Object",
">",
">",
"(",
")",
"{",
"}",
")",
";",
"}",
"else",
"if",
"(",
"string",
".",
"startsWith",
"(",
"\"[\"",
")",
")",
"{",
"body",
"=",
"Config",
".",
"getInstance",
"(",
")",
".",
"getMapper",
"(",
")",
".",
"readValue",
"(",
"string",
",",
"new",
"TypeReference",
"<",
"List",
"<",
"Object",
">",
">",
"(",
")",
"{",
"}",
")",
";",
"}",
"else",
"{",
"// error here. The content type in head doesn't match the body.",
"setExchangeStatus",
"(",
"exchange",
",",
"CONTENT_TYPE_MISMATCH",
",",
"\"application/json\"",
")",
";",
"return",
";",
"}",
"exchange",
".",
"putAttachment",
"(",
"REQUEST_BODY",
",",
"body",
")",
";",
"}",
"}"
] | Method used to parse the body into a Map or a List and attach it into exchange
@param exchange exchange to be attached
@param string unparsed request body
@throws IOException | [
"Method",
"used",
"to",
"parse",
"the",
"body",
"into",
"a",
"Map",
"or",
"a",
"List",
"and",
"attach",
"it",
"into",
"exchange"
] | train | https://github.com/networknt/light-4j/blob/2a60257c60663684c8f6dc8b5ea3cf184e534db6/body/src/main/java/com/networknt/body/BodyHandler.java#L143-L160 |
BorderTech/wcomponents | wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/WDropdownOptionsExample.java | WDropdownOptionsExample.getDropDownControls | private WFieldSet getDropDownControls() {
"""
build the drop down controls.
@return a field set containing the dropdown controls.
"""
WFieldSet fieldSet = new WFieldSet("Drop down configuration");
WFieldLayout layout = new WFieldLayout();
layout.setLabelWidth(25);
fieldSet.add(layout);
rbsDDType.setButtonLayout(WRadioButtonSelect.LAYOUT_FLAT);
rbsDDType.setSelected(WDropdown.DropdownType.NATIVE);
rbsDDType.setFrameless(true);
layout.addField("Dropdown Type", rbsDDType);
nfWidth.setMinValue(0);
nfWidth.setDecimalPlaces(0);
layout.addField("Width", nfWidth);
layout.addField("ToolTip", tfToolTip);
layout.addField("Include null option", cbNullOption);
rgDefaultOption.setButtonLayout(WRadioButtonSelect.LAYOUT_COLUMNS);
rgDefaultOption.setButtonColumns(2);
rgDefaultOption.setSelected(NONE);
rgDefaultOption.setFrameless(true);
layout.addField("Default Option", rgDefaultOption);
layout.addField("Action on change", cbActionOnChange);
layout.addField("Ajax", cbAjax);
WField subField = layout.addField("Subordinate", cbSubordinate);
//.getLabel().setHint("Does not work with Dropdown Type COMBO");
layout.addField("Submit on change", cbSubmitOnChange);
layout.addField("Visible", cbVisible);
layout.addField("Disabled", cbDisabled);
// Apply Button
WButton apply = new WButton("Apply");
fieldSet.add(apply);
WSubordinateControl subSubControl = new WSubordinateControl();
Rule rule = new Rule();
subSubControl.addRule(rule);
rule.setCondition(new Equal(rbsDDType, WDropdown.DropdownType.COMBO));
rule.addActionOnTrue(new Disable(subField));
rule.addActionOnFalse(new Enable(subField));
fieldSet.add(subSubControl);
apply.setAction(new Action() {
@Override
public void execute(final ActionEvent event) {
applySettings();
}
});
return fieldSet;
} | java | private WFieldSet getDropDownControls() {
WFieldSet fieldSet = new WFieldSet("Drop down configuration");
WFieldLayout layout = new WFieldLayout();
layout.setLabelWidth(25);
fieldSet.add(layout);
rbsDDType.setButtonLayout(WRadioButtonSelect.LAYOUT_FLAT);
rbsDDType.setSelected(WDropdown.DropdownType.NATIVE);
rbsDDType.setFrameless(true);
layout.addField("Dropdown Type", rbsDDType);
nfWidth.setMinValue(0);
nfWidth.setDecimalPlaces(0);
layout.addField("Width", nfWidth);
layout.addField("ToolTip", tfToolTip);
layout.addField("Include null option", cbNullOption);
rgDefaultOption.setButtonLayout(WRadioButtonSelect.LAYOUT_COLUMNS);
rgDefaultOption.setButtonColumns(2);
rgDefaultOption.setSelected(NONE);
rgDefaultOption.setFrameless(true);
layout.addField("Default Option", rgDefaultOption);
layout.addField("Action on change", cbActionOnChange);
layout.addField("Ajax", cbAjax);
WField subField = layout.addField("Subordinate", cbSubordinate);
//.getLabel().setHint("Does not work with Dropdown Type COMBO");
layout.addField("Submit on change", cbSubmitOnChange);
layout.addField("Visible", cbVisible);
layout.addField("Disabled", cbDisabled);
// Apply Button
WButton apply = new WButton("Apply");
fieldSet.add(apply);
WSubordinateControl subSubControl = new WSubordinateControl();
Rule rule = new Rule();
subSubControl.addRule(rule);
rule.setCondition(new Equal(rbsDDType, WDropdown.DropdownType.COMBO));
rule.addActionOnTrue(new Disable(subField));
rule.addActionOnFalse(new Enable(subField));
fieldSet.add(subSubControl);
apply.setAction(new Action() {
@Override
public void execute(final ActionEvent event) {
applySettings();
}
});
return fieldSet;
} | [
"private",
"WFieldSet",
"getDropDownControls",
"(",
")",
"{",
"WFieldSet",
"fieldSet",
"=",
"new",
"WFieldSet",
"(",
"\"Drop down configuration\"",
")",
";",
"WFieldLayout",
"layout",
"=",
"new",
"WFieldLayout",
"(",
")",
";",
"layout",
".",
"setLabelWidth",
"(",
"25",
")",
";",
"fieldSet",
".",
"add",
"(",
"layout",
")",
";",
"rbsDDType",
".",
"setButtonLayout",
"(",
"WRadioButtonSelect",
".",
"LAYOUT_FLAT",
")",
";",
"rbsDDType",
".",
"setSelected",
"(",
"WDropdown",
".",
"DropdownType",
".",
"NATIVE",
")",
";",
"rbsDDType",
".",
"setFrameless",
"(",
"true",
")",
";",
"layout",
".",
"addField",
"(",
"\"Dropdown Type\"",
",",
"rbsDDType",
")",
";",
"nfWidth",
".",
"setMinValue",
"(",
"0",
")",
";",
"nfWidth",
".",
"setDecimalPlaces",
"(",
"0",
")",
";",
"layout",
".",
"addField",
"(",
"\"Width\"",
",",
"nfWidth",
")",
";",
"layout",
".",
"addField",
"(",
"\"ToolTip\"",
",",
"tfToolTip",
")",
";",
"layout",
".",
"addField",
"(",
"\"Include null option\"",
",",
"cbNullOption",
")",
";",
"rgDefaultOption",
".",
"setButtonLayout",
"(",
"WRadioButtonSelect",
".",
"LAYOUT_COLUMNS",
")",
";",
"rgDefaultOption",
".",
"setButtonColumns",
"(",
"2",
")",
";",
"rgDefaultOption",
".",
"setSelected",
"(",
"NONE",
")",
";",
"rgDefaultOption",
".",
"setFrameless",
"(",
"true",
")",
";",
"layout",
".",
"addField",
"(",
"\"Default Option\"",
",",
"rgDefaultOption",
")",
";",
"layout",
".",
"addField",
"(",
"\"Action on change\"",
",",
"cbActionOnChange",
")",
";",
"layout",
".",
"addField",
"(",
"\"Ajax\"",
",",
"cbAjax",
")",
";",
"WField",
"subField",
"=",
"layout",
".",
"addField",
"(",
"\"Subordinate\"",
",",
"cbSubordinate",
")",
";",
"//.getLabel().setHint(\"Does not work with Dropdown Type COMBO\");",
"layout",
".",
"addField",
"(",
"\"Submit on change\"",
",",
"cbSubmitOnChange",
")",
";",
"layout",
".",
"addField",
"(",
"\"Visible\"",
",",
"cbVisible",
")",
";",
"layout",
".",
"addField",
"(",
"\"Disabled\"",
",",
"cbDisabled",
")",
";",
"// Apply Button",
"WButton",
"apply",
"=",
"new",
"WButton",
"(",
"\"Apply\"",
")",
";",
"fieldSet",
".",
"add",
"(",
"apply",
")",
";",
"WSubordinateControl",
"subSubControl",
"=",
"new",
"WSubordinateControl",
"(",
")",
";",
"Rule",
"rule",
"=",
"new",
"Rule",
"(",
")",
";",
"subSubControl",
".",
"addRule",
"(",
"rule",
")",
";",
"rule",
".",
"setCondition",
"(",
"new",
"Equal",
"(",
"rbsDDType",
",",
"WDropdown",
".",
"DropdownType",
".",
"COMBO",
")",
")",
";",
"rule",
".",
"addActionOnTrue",
"(",
"new",
"Disable",
"(",
"subField",
")",
")",
";",
"rule",
".",
"addActionOnFalse",
"(",
"new",
"Enable",
"(",
"subField",
")",
")",
";",
"fieldSet",
".",
"add",
"(",
"subSubControl",
")",
";",
"apply",
".",
"setAction",
"(",
"new",
"Action",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"execute",
"(",
"final",
"ActionEvent",
"event",
")",
"{",
"applySettings",
"(",
")",
";",
"}",
"}",
")",
";",
"return",
"fieldSet",
";",
"}"
] | build the drop down controls.
@return a field set containing the dropdown controls. | [
"build",
"the",
"drop",
"down",
"controls",
"."
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/WDropdownOptionsExample.java#L161-L213 |
aspectran/aspectran | core/src/main/java/com/aspectran/core/util/ReflectionUtils.java | ReflectionUtils.getTypeDifferenceWeight | public static float getTypeDifferenceWeight(Class<?>[] paramTypes, Object[] destArgs) {
"""
Algorithm that judges the match between the declared parameter types of
a candidate method and a specific list of arguments that this method is
supposed to be invoked with.
@param paramTypes the parameter types to match
@param destArgs the arguments to match
@return the accumulated weight for all arguments
"""
if (paramTypes.length != destArgs.length) {
return Float.MAX_VALUE;
}
float weight = 0.0f;
for (int i = 0; i < paramTypes.length; i++) {
Class<?> srcClass = paramTypes[i];
Object destArg = destArgs[i];
weight += getTypeDifferenceWeight(srcClass, destArg);
if (weight == Float.MAX_VALUE) {
break;
}
}
return weight;
} | java | public static float getTypeDifferenceWeight(Class<?>[] paramTypes, Object[] destArgs) {
if (paramTypes.length != destArgs.length) {
return Float.MAX_VALUE;
}
float weight = 0.0f;
for (int i = 0; i < paramTypes.length; i++) {
Class<?> srcClass = paramTypes[i];
Object destArg = destArgs[i];
weight += getTypeDifferenceWeight(srcClass, destArg);
if (weight == Float.MAX_VALUE) {
break;
}
}
return weight;
} | [
"public",
"static",
"float",
"getTypeDifferenceWeight",
"(",
"Class",
"<",
"?",
">",
"[",
"]",
"paramTypes",
",",
"Object",
"[",
"]",
"destArgs",
")",
"{",
"if",
"(",
"paramTypes",
".",
"length",
"!=",
"destArgs",
".",
"length",
")",
"{",
"return",
"Float",
".",
"MAX_VALUE",
";",
"}",
"float",
"weight",
"=",
"0.0f",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"paramTypes",
".",
"length",
";",
"i",
"++",
")",
"{",
"Class",
"<",
"?",
">",
"srcClass",
"=",
"paramTypes",
"[",
"i",
"]",
";",
"Object",
"destArg",
"=",
"destArgs",
"[",
"i",
"]",
";",
"weight",
"+=",
"getTypeDifferenceWeight",
"(",
"srcClass",
",",
"destArg",
")",
";",
"if",
"(",
"weight",
"==",
"Float",
".",
"MAX_VALUE",
")",
"{",
"break",
";",
"}",
"}",
"return",
"weight",
";",
"}"
] | Algorithm that judges the match between the declared parameter types of
a candidate method and a specific list of arguments that this method is
supposed to be invoked with.
@param paramTypes the parameter types to match
@param destArgs the arguments to match
@return the accumulated weight for all arguments | [
"Algorithm",
"that",
"judges",
"the",
"match",
"between",
"the",
"declared",
"parameter",
"types",
"of",
"a",
"candidate",
"method",
"and",
"a",
"specific",
"list",
"of",
"arguments",
"that",
"this",
"method",
"is",
"supposed",
"to",
"be",
"invoked",
"with",
"."
] | train | https://github.com/aspectran/aspectran/blob/2d758a2a28b71ee85b42823c12dc44674d7f2c70/core/src/main/java/com/aspectran/core/util/ReflectionUtils.java#L93-L108 |
ManfredTremmel/gwt-commons-lang3 | src/main/java/org/apache/commons/lang3/StringUtils.java | StringUtils.appendIfMissingIgnoreCase | public static String appendIfMissingIgnoreCase(final String str, final CharSequence suffix, final CharSequence... suffixes) {
"""
Appends the suffix to the end of the string if the string does not
already end, case insensitive, with any of the suffixes.
<pre>
StringUtils.appendIfMissingIgnoreCase(null, null) = null
StringUtils.appendIfMissingIgnoreCase("abc", null) = "abc"
StringUtils.appendIfMissingIgnoreCase("", "xyz") = "xyz"
StringUtils.appendIfMissingIgnoreCase("abc", "xyz") = "abcxyz"
StringUtils.appendIfMissingIgnoreCase("abcxyz", "xyz") = "abcxyz"
StringUtils.appendIfMissingIgnoreCase("abcXYZ", "xyz") = "abcXYZ"
</pre>
<p>With additional suffixes,</p>
<pre>
StringUtils.appendIfMissingIgnoreCase(null, null, null) = null
StringUtils.appendIfMissingIgnoreCase("abc", null, null) = "abc"
StringUtils.appendIfMissingIgnoreCase("", "xyz", null) = "xyz"
StringUtils.appendIfMissingIgnoreCase("abc", "xyz", new CharSequence[]{null}) = "abcxyz"
StringUtils.appendIfMissingIgnoreCase("abc", "xyz", "") = "abc"
StringUtils.appendIfMissingIgnoreCase("abc", "xyz", "mno") = "axyz"
StringUtils.appendIfMissingIgnoreCase("abcxyz", "xyz", "mno") = "abcxyz"
StringUtils.appendIfMissingIgnoreCase("abcmno", "xyz", "mno") = "abcmno"
StringUtils.appendIfMissingIgnoreCase("abcXYZ", "xyz", "mno") = "abcXYZ"
StringUtils.appendIfMissingIgnoreCase("abcMNO", "xyz", "mno") = "abcMNO"
</pre>
@param str The string.
@param suffix The suffix to append to the end of the string.
@param suffixes Additional suffixes that are valid terminators.
@return A new String if suffix was appended, the same string otherwise.
@since 3.2
"""
return appendIfMissing(str, suffix, true, suffixes);
} | java | public static String appendIfMissingIgnoreCase(final String str, final CharSequence suffix, final CharSequence... suffixes) {
return appendIfMissing(str, suffix, true, suffixes);
} | [
"public",
"static",
"String",
"appendIfMissingIgnoreCase",
"(",
"final",
"String",
"str",
",",
"final",
"CharSequence",
"suffix",
",",
"final",
"CharSequence",
"...",
"suffixes",
")",
"{",
"return",
"appendIfMissing",
"(",
"str",
",",
"suffix",
",",
"true",
",",
"suffixes",
")",
";",
"}"
] | Appends the suffix to the end of the string if the string does not
already end, case insensitive, with any of the suffixes.
<pre>
StringUtils.appendIfMissingIgnoreCase(null, null) = null
StringUtils.appendIfMissingIgnoreCase("abc", null) = "abc"
StringUtils.appendIfMissingIgnoreCase("", "xyz") = "xyz"
StringUtils.appendIfMissingIgnoreCase("abc", "xyz") = "abcxyz"
StringUtils.appendIfMissingIgnoreCase("abcxyz", "xyz") = "abcxyz"
StringUtils.appendIfMissingIgnoreCase("abcXYZ", "xyz") = "abcXYZ"
</pre>
<p>With additional suffixes,</p>
<pre>
StringUtils.appendIfMissingIgnoreCase(null, null, null) = null
StringUtils.appendIfMissingIgnoreCase("abc", null, null) = "abc"
StringUtils.appendIfMissingIgnoreCase("", "xyz", null) = "xyz"
StringUtils.appendIfMissingIgnoreCase("abc", "xyz", new CharSequence[]{null}) = "abcxyz"
StringUtils.appendIfMissingIgnoreCase("abc", "xyz", "") = "abc"
StringUtils.appendIfMissingIgnoreCase("abc", "xyz", "mno") = "axyz"
StringUtils.appendIfMissingIgnoreCase("abcxyz", "xyz", "mno") = "abcxyz"
StringUtils.appendIfMissingIgnoreCase("abcmno", "xyz", "mno") = "abcmno"
StringUtils.appendIfMissingIgnoreCase("abcXYZ", "xyz", "mno") = "abcXYZ"
StringUtils.appendIfMissingIgnoreCase("abcMNO", "xyz", "mno") = "abcMNO"
</pre>
@param str The string.
@param suffix The suffix to append to the end of the string.
@param suffixes Additional suffixes that are valid terminators.
@return A new String if suffix was appended, the same string otherwise.
@since 3.2 | [
"Appends",
"the",
"suffix",
"to",
"the",
"end",
"of",
"the",
"string",
"if",
"the",
"string",
"does",
"not",
"already",
"end",
"case",
"insensitive",
"with",
"any",
"of",
"the",
"suffixes",
"."
] | train | https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/StringUtils.java#L8852-L8854 |
ops4j/org.ops4j.pax.exam2 | core/pax-exam-spi/src/main/java/org/ops4j/pax/exam/spi/war/FileFinder.java | FileFinder.findFile | public static File findFile(File rootDir, final String fileName) {
"""
Finds a file with the given name in the given root directory or any subdirectory. The files
and directories are scanned in alphabetical order, so the result is deterministic.
<p>
The method returns the first matching result, if any, and ignores all other matches.
@param rootDir
root directory
@param fileName
exact file name, without any wildcards
@return matching file, or null
"""
FilenameFilter filter = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.equals(fileName);
}
};
return findFile(rootDir, filter);
} | java | public static File findFile(File rootDir, final String fileName) {
FilenameFilter filter = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.equals(fileName);
}
};
return findFile(rootDir, filter);
} | [
"public",
"static",
"File",
"findFile",
"(",
"File",
"rootDir",
",",
"final",
"String",
"fileName",
")",
"{",
"FilenameFilter",
"filter",
"=",
"new",
"FilenameFilter",
"(",
")",
"{",
"@",
"Override",
"public",
"boolean",
"accept",
"(",
"File",
"dir",
",",
"String",
"name",
")",
"{",
"return",
"name",
".",
"equals",
"(",
"fileName",
")",
";",
"}",
"}",
";",
"return",
"findFile",
"(",
"rootDir",
",",
"filter",
")",
";",
"}"
] | Finds a file with the given name in the given root directory or any subdirectory. The files
and directories are scanned in alphabetical order, so the result is deterministic.
<p>
The method returns the first matching result, if any, and ignores all other matches.
@param rootDir
root directory
@param fileName
exact file name, without any wildcards
@return matching file, or null | [
"Finds",
"a",
"file",
"with",
"the",
"given",
"name",
"in",
"the",
"given",
"root",
"directory",
"or",
"any",
"subdirectory",
".",
"The",
"files",
"and",
"directories",
"are",
"scanned",
"in",
"alphabetical",
"order",
"so",
"the",
"result",
"is",
"deterministic",
".",
"<p",
">",
"The",
"method",
"returns",
"the",
"first",
"matching",
"result",
"if",
"any",
"and",
"ignores",
"all",
"other",
"matches",
"."
] | train | https://github.com/ops4j/org.ops4j.pax.exam2/blob/7f83796cbbb857123d8fc7fe817a7637218d5d77/core/pax-exam-spi/src/main/java/org/ops4j/pax/exam/spi/war/FileFinder.java#L60-L71 |
pravega/pravega | controller/src/main/java/io/pravega/controller/server/rpc/auth/StrongPasswordProcessor.java | StrongPasswordProcessor.checkPassword | public boolean checkPassword(String password, String encryptedPassword)
throws NoSuchAlgorithmException, InvalidKeySpecException {
"""
/*
@param password The incoming password.
@param encryptedPassword The stored password digest.
@return true if the password matches, false otherwise.
@throws NoSuchAlgorithmException encryption exceptions.
@throws InvalidKeySpecException encryption exceptions.
"""
String storedPassword = new String(fromHex(encryptedPassword));
String[] parts = storedPassword.split(":");
int iterations = Integer.parseInt(parts[0]);
byte[] salt = fromHex(parts[1]);
byte[] hash = fromHex(parts[2]);
PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, iterations, keyLength);
SecretKeyFactory skf = SecretKeyFactory.getInstance(keyAlgorythm);
byte[] testHash = skf.generateSecret(spec).getEncoded();
//This is time independent version of array comparison.
// This is done to ensure that time based attacks do not happen.
//Read more here for time based attacks in this context.
// https://security.stackexchange.com/questions/74547/timing-attack-against-hmac-in-authenticated-encryption
int diff = hash.length ^ testHash.length;
for (int i = 0; i < hash.length && i < testHash.length; i++) {
diff |= hash[i] ^ testHash[i];
}
return diff == 0;
} | java | public boolean checkPassword(String password, String encryptedPassword)
throws NoSuchAlgorithmException, InvalidKeySpecException {
String storedPassword = new String(fromHex(encryptedPassword));
String[] parts = storedPassword.split(":");
int iterations = Integer.parseInt(parts[0]);
byte[] salt = fromHex(parts[1]);
byte[] hash = fromHex(parts[2]);
PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, iterations, keyLength);
SecretKeyFactory skf = SecretKeyFactory.getInstance(keyAlgorythm);
byte[] testHash = skf.generateSecret(spec).getEncoded();
//This is time independent version of array comparison.
// This is done to ensure that time based attacks do not happen.
//Read more here for time based attacks in this context.
// https://security.stackexchange.com/questions/74547/timing-attack-against-hmac-in-authenticated-encryption
int diff = hash.length ^ testHash.length;
for (int i = 0; i < hash.length && i < testHash.length; i++) {
diff |= hash[i] ^ testHash[i];
}
return diff == 0;
} | [
"public",
"boolean",
"checkPassword",
"(",
"String",
"password",
",",
"String",
"encryptedPassword",
")",
"throws",
"NoSuchAlgorithmException",
",",
"InvalidKeySpecException",
"{",
"String",
"storedPassword",
"=",
"new",
"String",
"(",
"fromHex",
"(",
"encryptedPassword",
")",
")",
";",
"String",
"[",
"]",
"parts",
"=",
"storedPassword",
".",
"split",
"(",
"\":\"",
")",
";",
"int",
"iterations",
"=",
"Integer",
".",
"parseInt",
"(",
"parts",
"[",
"0",
"]",
")",
";",
"byte",
"[",
"]",
"salt",
"=",
"fromHex",
"(",
"parts",
"[",
"1",
"]",
")",
";",
"byte",
"[",
"]",
"hash",
"=",
"fromHex",
"(",
"parts",
"[",
"2",
"]",
")",
";",
"PBEKeySpec",
"spec",
"=",
"new",
"PBEKeySpec",
"(",
"password",
".",
"toCharArray",
"(",
")",
",",
"salt",
",",
"iterations",
",",
"keyLength",
")",
";",
"SecretKeyFactory",
"skf",
"=",
"SecretKeyFactory",
".",
"getInstance",
"(",
"keyAlgorythm",
")",
";",
"byte",
"[",
"]",
"testHash",
"=",
"skf",
".",
"generateSecret",
"(",
"spec",
")",
".",
"getEncoded",
"(",
")",
";",
"//This is time independent version of array comparison.",
"// This is done to ensure that time based attacks do not happen.",
"//Read more here for time based attacks in this context.",
"// https://security.stackexchange.com/questions/74547/timing-attack-against-hmac-in-authenticated-encryption",
"int",
"diff",
"=",
"hash",
".",
"length",
"^",
"testHash",
".",
"length",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"hash",
".",
"length",
"&&",
"i",
"<",
"testHash",
".",
"length",
";",
"i",
"++",
")",
"{",
"diff",
"|=",
"hash",
"[",
"i",
"]",
"^",
"testHash",
"[",
"i",
"]",
";",
"}",
"return",
"diff",
"==",
"0",
";",
"}"
] | /*
@param password The incoming password.
@param encryptedPassword The stored password digest.
@return true if the password matches, false otherwise.
@throws NoSuchAlgorithmException encryption exceptions.
@throws InvalidKeySpecException encryption exceptions. | [
"/",
"*"
] | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/controller/src/main/java/io/pravega/controller/server/rpc/auth/StrongPasswordProcessor.java#L51-L72 |
OpenLiberty/open-liberty | dev/com.ibm.ws.org.apache.jasper.el/src/org/apache/el/lang/ELSupport.java | ELSupport.coerceToBoolean | public static final Boolean coerceToBoolean(final ELContext ctx, final Object obj) {
"""
Convert an object to Boolean.
Null and empty string are false.
@param ctx the context in which this conversion is taking place
@param obj the object to convert
@return the Boolean value of the object
@throws ELException if object is not Boolean or String
"""
// previous el 2.2 implementation returned false if obj is null
// so pass in true for primitive to force the same behavior
return coerceToBoolean(ctx, obj, true);
} | java | public static final Boolean coerceToBoolean(final ELContext ctx, final Object obj) {
// previous el 2.2 implementation returned false if obj is null
// so pass in true for primitive to force the same behavior
return coerceToBoolean(ctx, obj, true);
} | [
"public",
"static",
"final",
"Boolean",
"coerceToBoolean",
"(",
"final",
"ELContext",
"ctx",
",",
"final",
"Object",
"obj",
")",
"{",
"// previous el 2.2 implementation returned false if obj is null",
"// so pass in true for primitive to force the same behavior",
"return",
"coerceToBoolean",
"(",
"ctx",
",",
"obj",
",",
"true",
")",
";",
"}"
] | Convert an object to Boolean.
Null and empty string are false.
@param ctx the context in which this conversion is taking place
@param obj the object to convert
@return the Boolean value of the object
@throws ELException if object is not Boolean or String | [
"Convert",
"an",
"object",
"to",
"Boolean",
".",
"Null",
"and",
"empty",
"string",
"are",
"false",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.org.apache.jasper.el/src/org/apache/el/lang/ELSupport.java#L312-L316 |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java | Bean.sendMessage | private void sendMessage(BeanMessageID type, Message message) {
"""
Send a message to Bean with a payload.
@param type The {@link com.punchthrough.bean.sdk.internal.BeanMessageID} for the message
@param message The message payload to send
"""
Buffer buffer = new Buffer();
buffer.writeByte((type.getRawValue() >> 8) & 0xff);
buffer.writeByte(type.getRawValue() & 0xff);
buffer.write(message.toPayload());
GattSerialMessage serialMessage = GattSerialMessage.fromPayload(buffer.readByteArray());
gattClient.getSerialProfile().sendMessage(serialMessage.getBuffer());
} | java | private void sendMessage(BeanMessageID type, Message message) {
Buffer buffer = new Buffer();
buffer.writeByte((type.getRawValue() >> 8) & 0xff);
buffer.writeByte(type.getRawValue() & 0xff);
buffer.write(message.toPayload());
GattSerialMessage serialMessage = GattSerialMessage.fromPayload(buffer.readByteArray());
gattClient.getSerialProfile().sendMessage(serialMessage.getBuffer());
} | [
"private",
"void",
"sendMessage",
"(",
"BeanMessageID",
"type",
",",
"Message",
"message",
")",
"{",
"Buffer",
"buffer",
"=",
"new",
"Buffer",
"(",
")",
";",
"buffer",
".",
"writeByte",
"(",
"(",
"type",
".",
"getRawValue",
"(",
")",
">>",
"8",
")",
"&",
"0xff",
")",
";",
"buffer",
".",
"writeByte",
"(",
"type",
".",
"getRawValue",
"(",
")",
"&",
"0xff",
")",
";",
"buffer",
".",
"write",
"(",
"message",
".",
"toPayload",
"(",
")",
")",
";",
"GattSerialMessage",
"serialMessage",
"=",
"GattSerialMessage",
".",
"fromPayload",
"(",
"buffer",
".",
"readByteArray",
"(",
")",
")",
";",
"gattClient",
".",
"getSerialProfile",
"(",
")",
".",
"sendMessage",
"(",
"serialMessage",
".",
"getBuffer",
"(",
")",
")",
";",
"}"
] | Send a message to Bean with a payload.
@param type The {@link com.punchthrough.bean.sdk.internal.BeanMessageID} for the message
@param message The message payload to send | [
"Send",
"a",
"message",
"to",
"Bean",
"with",
"a",
"payload",
"."
] | train | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java#L716-L723 |
wmdietl/jsr308-langtools | src/share/classes/com/sun/tools/doclets/formats/html/AbstractIndexWriter.java | AbstractIndexWriter.addComment | protected void addComment(ProgramElementDoc element, Content contentTree) {
"""
Add comment for each element in the index. If the element is deprecated
and it has a @deprecated tag, use that comment. Else if the containing
class for this element is deprecated, then add the word "Deprecated." at
the start and then print the normal comment.
@param element Index element
@param contentTree the content tree to which the comment will be added
"""
Tag[] tags;
Content span = HtmlTree.SPAN(HtmlStyle.deprecatedLabel, deprecatedPhrase);
HtmlTree div = new HtmlTree(HtmlTag.DIV);
div.addStyle(HtmlStyle.block);
if (Util.isDeprecated(element)) {
div.addContent(span);
if ((tags = element.tags("deprecated")).length > 0)
addInlineDeprecatedComment(element, tags[0], div);
contentTree.addContent(div);
} else {
ClassDoc cont = element.containingClass();
while (cont != null) {
if (Util.isDeprecated(cont)) {
div.addContent(span);
contentTree.addContent(div);
break;
}
cont = cont.containingClass();
}
addSummaryComment(element, contentTree);
}
} | java | protected void addComment(ProgramElementDoc element, Content contentTree) {
Tag[] tags;
Content span = HtmlTree.SPAN(HtmlStyle.deprecatedLabel, deprecatedPhrase);
HtmlTree div = new HtmlTree(HtmlTag.DIV);
div.addStyle(HtmlStyle.block);
if (Util.isDeprecated(element)) {
div.addContent(span);
if ((tags = element.tags("deprecated")).length > 0)
addInlineDeprecatedComment(element, tags[0], div);
contentTree.addContent(div);
} else {
ClassDoc cont = element.containingClass();
while (cont != null) {
if (Util.isDeprecated(cont)) {
div.addContent(span);
contentTree.addContent(div);
break;
}
cont = cont.containingClass();
}
addSummaryComment(element, contentTree);
}
} | [
"protected",
"void",
"addComment",
"(",
"ProgramElementDoc",
"element",
",",
"Content",
"contentTree",
")",
"{",
"Tag",
"[",
"]",
"tags",
";",
"Content",
"span",
"=",
"HtmlTree",
".",
"SPAN",
"(",
"HtmlStyle",
".",
"deprecatedLabel",
",",
"deprecatedPhrase",
")",
";",
"HtmlTree",
"div",
"=",
"new",
"HtmlTree",
"(",
"HtmlTag",
".",
"DIV",
")",
";",
"div",
".",
"addStyle",
"(",
"HtmlStyle",
".",
"block",
")",
";",
"if",
"(",
"Util",
".",
"isDeprecated",
"(",
"element",
")",
")",
"{",
"div",
".",
"addContent",
"(",
"span",
")",
";",
"if",
"(",
"(",
"tags",
"=",
"element",
".",
"tags",
"(",
"\"deprecated\"",
")",
")",
".",
"length",
">",
"0",
")",
"addInlineDeprecatedComment",
"(",
"element",
",",
"tags",
"[",
"0",
"]",
",",
"div",
")",
";",
"contentTree",
".",
"addContent",
"(",
"div",
")",
";",
"}",
"else",
"{",
"ClassDoc",
"cont",
"=",
"element",
".",
"containingClass",
"(",
")",
";",
"while",
"(",
"cont",
"!=",
"null",
")",
"{",
"if",
"(",
"Util",
".",
"isDeprecated",
"(",
"cont",
")",
")",
"{",
"div",
".",
"addContent",
"(",
"span",
")",
";",
"contentTree",
".",
"addContent",
"(",
"div",
")",
";",
"break",
";",
"}",
"cont",
"=",
"cont",
".",
"containingClass",
"(",
")",
";",
"}",
"addSummaryComment",
"(",
"element",
",",
"contentTree",
")",
";",
"}",
"}"
] | Add comment for each element in the index. If the element is deprecated
and it has a @deprecated tag, use that comment. Else if the containing
class for this element is deprecated, then add the word "Deprecated." at
the start and then print the normal comment.
@param element Index element
@param contentTree the content tree to which the comment will be added | [
"Add",
"comment",
"for",
"each",
"element",
"in",
"the",
"index",
".",
"If",
"the",
"element",
"is",
"deprecated",
"and",
"it",
"has",
"a",
"@deprecated",
"tag",
"use",
"that",
"comment",
".",
"Else",
"if",
"the",
"containing",
"class",
"for",
"this",
"element",
"is",
"deprecated",
"then",
"add",
"the",
"word",
"Deprecated",
".",
"at",
"the",
"start",
"and",
"then",
"print",
"the",
"normal",
"comment",
"."
] | train | https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/doclets/formats/html/AbstractIndexWriter.java#L199-L221 |
atomix/atomix | protocols/raft/src/main/java/io/atomix/protocols/raft/session/RaftSession.java | RaftSession.registerSequenceQuery | public void registerSequenceQuery(long sequence, Runnable query) {
"""
Registers a causal session query.
@param sequence The session sequence number at which to execute the query.
@param query The query to execute.
"""
// Add a query to be run once the session's sequence number reaches the given sequence number.
List<Runnable> queries = this.sequenceQueries.computeIfAbsent(sequence, v -> new LinkedList<Runnable>());
queries.add(query);
} | java | public void registerSequenceQuery(long sequence, Runnable query) {
// Add a query to be run once the session's sequence number reaches the given sequence number.
List<Runnable> queries = this.sequenceQueries.computeIfAbsent(sequence, v -> new LinkedList<Runnable>());
queries.add(query);
} | [
"public",
"void",
"registerSequenceQuery",
"(",
"long",
"sequence",
",",
"Runnable",
"query",
")",
"{",
"// Add a query to be run once the session's sequence number reaches the given sequence number.",
"List",
"<",
"Runnable",
">",
"queries",
"=",
"this",
".",
"sequenceQueries",
".",
"computeIfAbsent",
"(",
"sequence",
",",
"v",
"->",
"new",
"LinkedList",
"<",
"Runnable",
">",
"(",
")",
")",
";",
"queries",
".",
"add",
"(",
"query",
")",
";",
"}"
] | Registers a causal session query.
@param sequence The session sequence number at which to execute the query.
@param query The query to execute. | [
"Registers",
"a",
"causal",
"session",
"query",
"."
] | train | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/session/RaftSession.java#L305-L309 |
alipay/sofa-rpc | core/common/src/main/java/com/alipay/sofa/rpc/common/utils/CodecUtils.java | CodecUtils.hex2byte | public static byte[] hex2byte(String str) {
"""
hex string to byte[], such as "0001" -> [0,1]
@param str hex string
@return byte[]
"""
byte[] bytes = str.getBytes();
if ((bytes.length % 2) != 0) {
throw new IllegalArgumentException();
}
byte[] b2 = new byte[bytes.length / 2];
for (int n = 0; n < bytes.length; n += 2) {
String item = new String(bytes, n, 2);
b2[n / 2] = (byte) Integer.parseInt(item, 16);
}
return b2;
} | java | public static byte[] hex2byte(String str) {
byte[] bytes = str.getBytes();
if ((bytes.length % 2) != 0) {
throw new IllegalArgumentException();
}
byte[] b2 = new byte[bytes.length / 2];
for (int n = 0; n < bytes.length; n += 2) {
String item = new String(bytes, n, 2);
b2[n / 2] = (byte) Integer.parseInt(item, 16);
}
return b2;
} | [
"public",
"static",
"byte",
"[",
"]",
"hex2byte",
"(",
"String",
"str",
")",
"{",
"byte",
"[",
"]",
"bytes",
"=",
"str",
".",
"getBytes",
"(",
")",
";",
"if",
"(",
"(",
"bytes",
".",
"length",
"%",
"2",
")",
"!=",
"0",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
")",
";",
"}",
"byte",
"[",
"]",
"b2",
"=",
"new",
"byte",
"[",
"bytes",
".",
"length",
"/",
"2",
"]",
";",
"for",
"(",
"int",
"n",
"=",
"0",
";",
"n",
"<",
"bytes",
".",
"length",
";",
"n",
"+=",
"2",
")",
"{",
"String",
"item",
"=",
"new",
"String",
"(",
"bytes",
",",
"n",
",",
"2",
")",
";",
"b2",
"[",
"n",
"/",
"2",
"]",
"=",
"(",
"byte",
")",
"Integer",
".",
"parseInt",
"(",
"item",
",",
"16",
")",
";",
"}",
"return",
"b2",
";",
"}"
] | hex string to byte[], such as "0001" -> [0,1]
@param str hex string
@return byte[] | [
"hex",
"string",
"to",
"byte",
"[]",
"such",
"as",
"0001",
"-",
">",
"[",
"0",
"1",
"]"
] | train | https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/core/common/src/main/java/com/alipay/sofa/rpc/common/utils/CodecUtils.java#L249-L260 |
gallandarakhneorg/afc | advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/mapelement/MapComposedElement.java | MapComposedElement.addPoint | public int addPoint(double x, double y) {
"""
Add the specified point at the end of the last group.
@param x x coordinate
@param y y coordinate
@return the index of the new point in the element.
"""
int pointIndex;
if (this.pointCoordinates == null) {
this.pointCoordinates = new double[] {x, y};
this.partIndexes = null;
pointIndex = 0;
} else {
double[] pts = new double[this.pointCoordinates.length + 2];
System.arraycopy(this.pointCoordinates, 0, pts, 0, this.pointCoordinates.length);
pointIndex = pts.length - 2;
pts[pointIndex] = x;
pts[pointIndex + 1] = y;
this.pointCoordinates = pts;
pts = null;
pointIndex /= 2;
}
fireShapeChanged();
fireElementChanged();
return pointIndex;
} | java | public int addPoint(double x, double y) {
int pointIndex;
if (this.pointCoordinates == null) {
this.pointCoordinates = new double[] {x, y};
this.partIndexes = null;
pointIndex = 0;
} else {
double[] pts = new double[this.pointCoordinates.length + 2];
System.arraycopy(this.pointCoordinates, 0, pts, 0, this.pointCoordinates.length);
pointIndex = pts.length - 2;
pts[pointIndex] = x;
pts[pointIndex + 1] = y;
this.pointCoordinates = pts;
pts = null;
pointIndex /= 2;
}
fireShapeChanged();
fireElementChanged();
return pointIndex;
} | [
"public",
"int",
"addPoint",
"(",
"double",
"x",
",",
"double",
"y",
")",
"{",
"int",
"pointIndex",
";",
"if",
"(",
"this",
".",
"pointCoordinates",
"==",
"null",
")",
"{",
"this",
".",
"pointCoordinates",
"=",
"new",
"double",
"[",
"]",
"{",
"x",
",",
"y",
"}",
";",
"this",
".",
"partIndexes",
"=",
"null",
";",
"pointIndex",
"=",
"0",
";",
"}",
"else",
"{",
"double",
"[",
"]",
"pts",
"=",
"new",
"double",
"[",
"this",
".",
"pointCoordinates",
".",
"length",
"+",
"2",
"]",
";",
"System",
".",
"arraycopy",
"(",
"this",
".",
"pointCoordinates",
",",
"0",
",",
"pts",
",",
"0",
",",
"this",
".",
"pointCoordinates",
".",
"length",
")",
";",
"pointIndex",
"=",
"pts",
".",
"length",
"-",
"2",
";",
"pts",
"[",
"pointIndex",
"]",
"=",
"x",
";",
"pts",
"[",
"pointIndex",
"+",
"1",
"]",
"=",
"y",
";",
"this",
".",
"pointCoordinates",
"=",
"pts",
";",
"pts",
"=",
"null",
";",
"pointIndex",
"/=",
"2",
";",
"}",
"fireShapeChanged",
"(",
")",
";",
"fireElementChanged",
"(",
")",
";",
"return",
"pointIndex",
";",
"}"
] | Add the specified point at the end of the last group.
@param x x coordinate
@param y y coordinate
@return the index of the new point in the element. | [
"Add",
"the",
"specified",
"point",
"at",
"the",
"end",
"of",
"the",
"last",
"group",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/mapelement/MapComposedElement.java#L559-L582 |
pravega/pravega | controller/src/main/java/io/pravega/controller/store/stream/PersistentStreamBase.java | PersistentStreamBase.sealActiveTxn | private CompletableFuture<SimpleEntry<TxnStatus, Integer>> sealActiveTxn(final int epoch,
final UUID txId,
final boolean commit,
final Optional<Version> version) {
"""
Seal a transaction in OPEN/COMMITTING_TXN/ABORTING state. This method does CAS on the transaction VersionedMetadata node if
the transaction is in OPEN state, optionally checking version of transaction VersionedMetadata node, if required.
@param epoch transaction epoch.
@param txId transaction identifier.
@param commit boolean indicating whether to commit or abort the transaction.
@param version optional expected version of transaction node to validate before updating it.
@return a pair containing transaction status and its epoch.
"""
return getActiveTx(epoch, txId).thenCompose(data -> {
ActiveTxnRecord txnRecord = data.getObject();
Version dataVersion = version.orElseGet(data::getVersion);
TxnStatus status = txnRecord.getTxnStatus();
switch (status) {
case OPEN:
return sealActiveTx(epoch, txId, commit, txnRecord, dataVersion).thenApply(y ->
new SimpleEntry<>(commit ? TxnStatus.COMMITTING : TxnStatus.ABORTING, epoch));
case COMMITTING:
case COMMITTED:
if (commit) {
return CompletableFuture.completedFuture(new SimpleEntry<>(status, epoch));
} else {
throw StoreException.create(StoreException.Type.ILLEGAL_STATE,
"Stream: " + getName() + " Transaction: " + txId.toString() +
" State: " + status.name());
}
case ABORTING:
case ABORTED:
if (commit) {
throw StoreException.create(StoreException.Type.ILLEGAL_STATE,
"Stream: " + getName() + " Transaction: " + txId.toString() + " State: " +
status.name());
} else {
return CompletableFuture.completedFuture(new SimpleEntry<>(status, epoch));
}
default:
throw StoreException.create(StoreException.Type.DATA_NOT_FOUND,
"Stream: " + getName() + " Transaction: " + txId.toString());
}
});
} | java | private CompletableFuture<SimpleEntry<TxnStatus, Integer>> sealActiveTxn(final int epoch,
final UUID txId,
final boolean commit,
final Optional<Version> version) {
return getActiveTx(epoch, txId).thenCompose(data -> {
ActiveTxnRecord txnRecord = data.getObject();
Version dataVersion = version.orElseGet(data::getVersion);
TxnStatus status = txnRecord.getTxnStatus();
switch (status) {
case OPEN:
return sealActiveTx(epoch, txId, commit, txnRecord, dataVersion).thenApply(y ->
new SimpleEntry<>(commit ? TxnStatus.COMMITTING : TxnStatus.ABORTING, epoch));
case COMMITTING:
case COMMITTED:
if (commit) {
return CompletableFuture.completedFuture(new SimpleEntry<>(status, epoch));
} else {
throw StoreException.create(StoreException.Type.ILLEGAL_STATE,
"Stream: " + getName() + " Transaction: " + txId.toString() +
" State: " + status.name());
}
case ABORTING:
case ABORTED:
if (commit) {
throw StoreException.create(StoreException.Type.ILLEGAL_STATE,
"Stream: " + getName() + " Transaction: " + txId.toString() + " State: " +
status.name());
} else {
return CompletableFuture.completedFuture(new SimpleEntry<>(status, epoch));
}
default:
throw StoreException.create(StoreException.Type.DATA_NOT_FOUND,
"Stream: " + getName() + " Transaction: " + txId.toString());
}
});
} | [
"private",
"CompletableFuture",
"<",
"SimpleEntry",
"<",
"TxnStatus",
",",
"Integer",
">",
">",
"sealActiveTxn",
"(",
"final",
"int",
"epoch",
",",
"final",
"UUID",
"txId",
",",
"final",
"boolean",
"commit",
",",
"final",
"Optional",
"<",
"Version",
">",
"version",
")",
"{",
"return",
"getActiveTx",
"(",
"epoch",
",",
"txId",
")",
".",
"thenCompose",
"(",
"data",
"->",
"{",
"ActiveTxnRecord",
"txnRecord",
"=",
"data",
".",
"getObject",
"(",
")",
";",
"Version",
"dataVersion",
"=",
"version",
".",
"orElseGet",
"(",
"data",
"::",
"getVersion",
")",
";",
"TxnStatus",
"status",
"=",
"txnRecord",
".",
"getTxnStatus",
"(",
")",
";",
"switch",
"(",
"status",
")",
"{",
"case",
"OPEN",
":",
"return",
"sealActiveTx",
"(",
"epoch",
",",
"txId",
",",
"commit",
",",
"txnRecord",
",",
"dataVersion",
")",
".",
"thenApply",
"(",
"y",
"->",
"new",
"SimpleEntry",
"<>",
"(",
"commit",
"?",
"TxnStatus",
".",
"COMMITTING",
":",
"TxnStatus",
".",
"ABORTING",
",",
"epoch",
")",
")",
";",
"case",
"COMMITTING",
":",
"case",
"COMMITTED",
":",
"if",
"(",
"commit",
")",
"{",
"return",
"CompletableFuture",
".",
"completedFuture",
"(",
"new",
"SimpleEntry",
"<>",
"(",
"status",
",",
"epoch",
")",
")",
";",
"}",
"else",
"{",
"throw",
"StoreException",
".",
"create",
"(",
"StoreException",
".",
"Type",
".",
"ILLEGAL_STATE",
",",
"\"Stream: \"",
"+",
"getName",
"(",
")",
"+",
"\" Transaction: \"",
"+",
"txId",
".",
"toString",
"(",
")",
"+",
"\" State: \"",
"+",
"status",
".",
"name",
"(",
")",
")",
";",
"}",
"case",
"ABORTING",
":",
"case",
"ABORTED",
":",
"if",
"(",
"commit",
")",
"{",
"throw",
"StoreException",
".",
"create",
"(",
"StoreException",
".",
"Type",
".",
"ILLEGAL_STATE",
",",
"\"Stream: \"",
"+",
"getName",
"(",
")",
"+",
"\" Transaction: \"",
"+",
"txId",
".",
"toString",
"(",
")",
"+",
"\" State: \"",
"+",
"status",
".",
"name",
"(",
")",
")",
";",
"}",
"else",
"{",
"return",
"CompletableFuture",
".",
"completedFuture",
"(",
"new",
"SimpleEntry",
"<>",
"(",
"status",
",",
"epoch",
")",
")",
";",
"}",
"default",
":",
"throw",
"StoreException",
".",
"create",
"(",
"StoreException",
".",
"Type",
".",
"DATA_NOT_FOUND",
",",
"\"Stream: \"",
"+",
"getName",
"(",
")",
"+",
"\" Transaction: \"",
"+",
"txId",
".",
"toString",
"(",
")",
")",
";",
"}",
"}",
")",
";",
"}"
] | Seal a transaction in OPEN/COMMITTING_TXN/ABORTING state. This method does CAS on the transaction VersionedMetadata node if
the transaction is in OPEN state, optionally checking version of transaction VersionedMetadata node, if required.
@param epoch transaction epoch.
@param txId transaction identifier.
@param commit boolean indicating whether to commit or abort the transaction.
@param version optional expected version of transaction node to validate before updating it.
@return a pair containing transaction status and its epoch. | [
"Seal",
"a",
"transaction",
"in",
"OPEN",
"/",
"COMMITTING_TXN",
"/",
"ABORTING",
"state",
".",
"This",
"method",
"does",
"CAS",
"on",
"the",
"transaction",
"VersionedMetadata",
"node",
"if",
"the",
"transaction",
"is",
"in",
"OPEN",
"state",
"optionally",
"checking",
"version",
"of",
"transaction",
"VersionedMetadata",
"node",
"if",
"required",
"."
] | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/controller/src/main/java/io/pravega/controller/store/stream/PersistentStreamBase.java#L1106-L1141 |
craftercms/commons | utilities/src/main/java/org/craftercms/commons/zip/ZipUtils.java | ZipUtils.zipFiles | public static void zipFiles(List<File> files, File zipFile) throws IOException {
"""
Zips a collection of files to a destination zip file.
@param files A collection of files and directories
@param zipFile The path of the destination zip file
@throws FileNotFoundException
@throws IOException
"""
OutputStream os = new BufferedOutputStream(new FileOutputStream(zipFile));
try {
zipFiles(files, os);
} finally {
IOUtils.closeQuietly(os);
}
} | java | public static void zipFiles(List<File> files, File zipFile) throws IOException {
OutputStream os = new BufferedOutputStream(new FileOutputStream(zipFile));
try {
zipFiles(files, os);
} finally {
IOUtils.closeQuietly(os);
}
} | [
"public",
"static",
"void",
"zipFiles",
"(",
"List",
"<",
"File",
">",
"files",
",",
"File",
"zipFile",
")",
"throws",
"IOException",
"{",
"OutputStream",
"os",
"=",
"new",
"BufferedOutputStream",
"(",
"new",
"FileOutputStream",
"(",
"zipFile",
")",
")",
";",
"try",
"{",
"zipFiles",
"(",
"files",
",",
"os",
")",
";",
"}",
"finally",
"{",
"IOUtils",
".",
"closeQuietly",
"(",
"os",
")",
";",
"}",
"}"
] | Zips a collection of files to a destination zip file.
@param files A collection of files and directories
@param zipFile The path of the destination zip file
@throws FileNotFoundException
@throws IOException | [
"Zips",
"a",
"collection",
"of",
"files",
"to",
"a",
"destination",
"zip",
"file",
"."
] | train | https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/zip/ZipUtils.java#L75-L82 |
radkovo/CSSBox | src/main/java/org/fit/cssbox/layout/FloatList.java | FloatList.getNextY | public static int getNextY(FloatList fleft, FloatList fright, int y) {
"""
Finds the nearest higher Y coordinate in two float lists where the float widths are different from the given starting coordinate.
@param fleft left float list
@param fright right float list
@param y starting Y coordinate
@return the nearest higher Y coordinate or -1 when no further change exists
"""
int fy = y;
int nexty1 = fleft.getNextY(fy);
int nexty2 = fright.getNextY(fy);
if (nexty1 != -1 && nexty2 != -1)
fy = Math.min(nexty1, nexty2);
else if (nexty2 != -1)
fy = nexty2;
else if (nexty1 != -1)
fy = nexty1;
else
fy = -1;
return fy;
} | java | public static int getNextY(FloatList fleft, FloatList fright, int y)
{
int fy = y;
int nexty1 = fleft.getNextY(fy);
int nexty2 = fright.getNextY(fy);
if (nexty1 != -1 && nexty2 != -1)
fy = Math.min(nexty1, nexty2);
else if (nexty2 != -1)
fy = nexty2;
else if (nexty1 != -1)
fy = nexty1;
else
fy = -1;
return fy;
} | [
"public",
"static",
"int",
"getNextY",
"(",
"FloatList",
"fleft",
",",
"FloatList",
"fright",
",",
"int",
"y",
")",
"{",
"int",
"fy",
"=",
"y",
";",
"int",
"nexty1",
"=",
"fleft",
".",
"getNextY",
"(",
"fy",
")",
";",
"int",
"nexty2",
"=",
"fright",
".",
"getNextY",
"(",
"fy",
")",
";",
"if",
"(",
"nexty1",
"!=",
"-",
"1",
"&&",
"nexty2",
"!=",
"-",
"1",
")",
"fy",
"=",
"Math",
".",
"min",
"(",
"nexty1",
",",
"nexty2",
")",
";",
"else",
"if",
"(",
"nexty2",
"!=",
"-",
"1",
")",
"fy",
"=",
"nexty2",
";",
"else",
"if",
"(",
"nexty1",
"!=",
"-",
"1",
")",
"fy",
"=",
"nexty1",
";",
"else",
"fy",
"=",
"-",
"1",
";",
"return",
"fy",
";",
"}"
] | Finds the nearest higher Y coordinate in two float lists where the float widths are different from the given starting coordinate.
@param fleft left float list
@param fright right float list
@param y starting Y coordinate
@return the nearest higher Y coordinate or -1 when no further change exists | [
"Finds",
"the",
"nearest",
"higher",
"Y",
"coordinate",
"in",
"two",
"float",
"lists",
"where",
"the",
"float",
"widths",
"are",
"different",
"from",
"the",
"given",
"starting",
"coordinate",
"."
] | train | https://github.com/radkovo/CSSBox/blob/38aaf8f22d233d7b4dbc12a56cdbc72b447bc559/src/main/java/org/fit/cssbox/layout/FloatList.java#L192-L207 |
Impetus/Kundera | src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/thrift/ThriftClientFactory.java | ThriftClientFactory.getNewPool | private ConnectionPool getNewPool(String host, int port) {
"""
Gets the new pool.
@param host the host
@param port the port
@return the new pool
"""
CassandraHost cassandraHost = ((CassandraHostConfiguration) configuration).getCassandraHost(host, port);
hostPools.remove(cassandraHost);
if (cassandraHost.isRetryHost())
{
logger.warn("Scheduling node for future retry");
((CassandraRetryService) hostRetryService).add((CassandraHost) cassandraHost);
}
return getPoolUsingPolicy();
} | java | private ConnectionPool getNewPool(String host, int port)
{
CassandraHost cassandraHost = ((CassandraHostConfiguration) configuration).getCassandraHost(host, port);
hostPools.remove(cassandraHost);
if (cassandraHost.isRetryHost())
{
logger.warn("Scheduling node for future retry");
((CassandraRetryService) hostRetryService).add((CassandraHost) cassandraHost);
}
return getPoolUsingPolicy();
} | [
"private",
"ConnectionPool",
"getNewPool",
"(",
"String",
"host",
",",
"int",
"port",
")",
"{",
"CassandraHost",
"cassandraHost",
"=",
"(",
"(",
"CassandraHostConfiguration",
")",
"configuration",
")",
".",
"getCassandraHost",
"(",
"host",
",",
"port",
")",
";",
"hostPools",
".",
"remove",
"(",
"cassandraHost",
")",
";",
"if",
"(",
"cassandraHost",
".",
"isRetryHost",
"(",
")",
")",
"{",
"logger",
".",
"warn",
"(",
"\"Scheduling node for future retry\"",
")",
";",
"(",
"(",
"CassandraRetryService",
")",
"hostRetryService",
")",
".",
"add",
"(",
"(",
"CassandraHost",
")",
"cassandraHost",
")",
";",
"}",
"return",
"getPoolUsingPolicy",
"(",
")",
";",
"}"
] | Gets the new pool.
@param host the host
@param port the port
@return the new pool | [
"Gets",
"the",
"new",
"pool",
"."
] | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/thrift/ThriftClientFactory.java#L234-L246 |
javalite/activejdbc | javalite-common/src/main/java/org/javalite/common/Util.java | Util.readResource | public static String readResource(String resourceName, String charset) {
"""
Reads contents of resource fully into a string.
@param resourceName resource name.
@param charset name of supported charset
@return entire contents of resource as string.
"""
InputStream is = Util.class.getResourceAsStream(resourceName);
try {
return read(is, charset);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
closeQuietly(is);
}
} | java | public static String readResource(String resourceName, String charset) {
InputStream is = Util.class.getResourceAsStream(resourceName);
try {
return read(is, charset);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
closeQuietly(is);
}
} | [
"public",
"static",
"String",
"readResource",
"(",
"String",
"resourceName",
",",
"String",
"charset",
")",
"{",
"InputStream",
"is",
"=",
"Util",
".",
"class",
".",
"getResourceAsStream",
"(",
"resourceName",
")",
";",
"try",
"{",
"return",
"read",
"(",
"is",
",",
"charset",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"finally",
"{",
"closeQuietly",
"(",
"is",
")",
";",
"}",
"}"
] | Reads contents of resource fully into a string.
@param resourceName resource name.
@param charset name of supported charset
@return entire contents of resource as string. | [
"Reads",
"contents",
"of",
"resource",
"fully",
"into",
"a",
"string",
"."
] | train | https://github.com/javalite/activejdbc/blob/ffcf5457cace19622a8f71e856cbbbe9e7dd5fcc/javalite-common/src/main/java/org/javalite/common/Util.java#L67-L76 |
alipay/sofa-rpc | extension-impl/remoting-bolt/src/main/java/com/alipay/sofa/rpc/server/bolt/BoltServerProcessor.java | BoltServerProcessor.clientTimeoutWhenReceiveRequest | private SofaRpcException clientTimeoutWhenReceiveRequest(String appName, String serviceName, String remoteAddress) {
"""
客户端已经超时了(例如在队列里等待太久了),丢弃这个请求
@param appName 应用
@param serviceName 服务
@param remoteAddress 远程地址
@return 丢弃的异常
"""
String errorMsg = LogCodes.getLog(
LogCodes.ERROR_DISCARD_TIMEOUT_REQUEST, serviceName, remoteAddress);
if (LOGGER.isWarnEnabled(appName)) {
LOGGER.warnWithApp(appName, errorMsg);
}
return new SofaRpcException(RpcErrorType.SERVER_UNDECLARED_ERROR, errorMsg);
} | java | private SofaRpcException clientTimeoutWhenReceiveRequest(String appName, String serviceName, String remoteAddress) {
String errorMsg = LogCodes.getLog(
LogCodes.ERROR_DISCARD_TIMEOUT_REQUEST, serviceName, remoteAddress);
if (LOGGER.isWarnEnabled(appName)) {
LOGGER.warnWithApp(appName, errorMsg);
}
return new SofaRpcException(RpcErrorType.SERVER_UNDECLARED_ERROR, errorMsg);
} | [
"private",
"SofaRpcException",
"clientTimeoutWhenReceiveRequest",
"(",
"String",
"appName",
",",
"String",
"serviceName",
",",
"String",
"remoteAddress",
")",
"{",
"String",
"errorMsg",
"=",
"LogCodes",
".",
"getLog",
"(",
"LogCodes",
".",
"ERROR_DISCARD_TIMEOUT_REQUEST",
",",
"serviceName",
",",
"remoteAddress",
")",
";",
"if",
"(",
"LOGGER",
".",
"isWarnEnabled",
"(",
"appName",
")",
")",
"{",
"LOGGER",
".",
"warnWithApp",
"(",
"appName",
",",
"errorMsg",
")",
";",
"}",
"return",
"new",
"SofaRpcException",
"(",
"RpcErrorType",
".",
"SERVER_UNDECLARED_ERROR",
",",
"errorMsg",
")",
";",
"}"
] | 客户端已经超时了(例如在队列里等待太久了),丢弃这个请求
@param appName 应用
@param serviceName 服务
@param remoteAddress 远程地址
@return 丢弃的异常 | [
"客户端已经超时了(例如在队列里等待太久了),丢弃这个请求"
] | train | https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/extension-impl/remoting-bolt/src/main/java/com/alipay/sofa/rpc/server/bolt/BoltServerProcessor.java#L277-L284 |
icode/ameba | src/main/java/ameba/db/ebean/support/ModelResourceStructure.java | ModelResourceStructure.deleteMultipleModel | protected boolean deleteMultipleModel(Set<MODEL_ID> idCollection, boolean permanent) throws Exception {
"""
delete multiple Model
@param idCollection model id collection
@param permanent a boolean.
@return if true delete from physical device, if logical delete return false, response status 202
@throws java.lang.Exception if any.
"""
if (permanent) {
server.deleteAllPermanent(modelType, idCollection);
} else {
server.deleteAll(modelType, idCollection);
}
return permanent;
} | java | protected boolean deleteMultipleModel(Set<MODEL_ID> idCollection, boolean permanent) throws Exception {
if (permanent) {
server.deleteAllPermanent(modelType, idCollection);
} else {
server.deleteAll(modelType, idCollection);
}
return permanent;
} | [
"protected",
"boolean",
"deleteMultipleModel",
"(",
"Set",
"<",
"MODEL_ID",
">",
"idCollection",
",",
"boolean",
"permanent",
")",
"throws",
"Exception",
"{",
"if",
"(",
"permanent",
")",
"{",
"server",
".",
"deleteAllPermanent",
"(",
"modelType",
",",
"idCollection",
")",
";",
"}",
"else",
"{",
"server",
".",
"deleteAll",
"(",
"modelType",
",",
"idCollection",
")",
";",
"}",
"return",
"permanent",
";",
"}"
] | delete multiple Model
@param idCollection model id collection
@param permanent a boolean.
@return if true delete from physical device, if logical delete return false, response status 202
@throws java.lang.Exception if any. | [
"delete",
"multiple",
"Model"
] | train | https://github.com/icode/ameba/blob/9d4956e935898e41331b2745e400ef869cd265e0/src/main/java/ameba/db/ebean/support/ModelResourceStructure.java#L482-L489 |
raydac/java-binary-block-parser | jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPUtils.java | JBBPUtils.unpackInt | public static int unpackInt(final byte[] array, final JBBPIntCounter position) {
"""
Unpack an integer value from defined position in a byte array.
@param array the source byte array
@param position the position of the first byte of packed value
@return the unpacked value, the position will be increased
"""
final int code = array[position.getAndIncrement()] & 0xFF;
if (code < 0x80) {
return code;
}
final int result;
switch (code) {
case 0x80: {
result = ((array[position.getAndIncrement()] & 0xFF) << 8) | (array[position.getAndIncrement()] & 0xFF);
}
break;
case 0x81: {
result = ((array[position.getAndIncrement()] & 0xFF) << 24)
| ((array[position.getAndIncrement()] & 0xFF) << 16)
| ((array[position.getAndIncrement()] & 0xFF) << 8)
| (array[position.getAndIncrement()] & 0xFF);
}
break;
default:
throw new IllegalArgumentException("Unsupported packed integer prefix [0x" + Integer.toHexString(code).toUpperCase(Locale.ENGLISH) + ']');
}
return result;
} | java | public static int unpackInt(final byte[] array, final JBBPIntCounter position) {
final int code = array[position.getAndIncrement()] & 0xFF;
if (code < 0x80) {
return code;
}
final int result;
switch (code) {
case 0x80: {
result = ((array[position.getAndIncrement()] & 0xFF) << 8) | (array[position.getAndIncrement()] & 0xFF);
}
break;
case 0x81: {
result = ((array[position.getAndIncrement()] & 0xFF) << 24)
| ((array[position.getAndIncrement()] & 0xFF) << 16)
| ((array[position.getAndIncrement()] & 0xFF) << 8)
| (array[position.getAndIncrement()] & 0xFF);
}
break;
default:
throw new IllegalArgumentException("Unsupported packed integer prefix [0x" + Integer.toHexString(code).toUpperCase(Locale.ENGLISH) + ']');
}
return result;
} | [
"public",
"static",
"int",
"unpackInt",
"(",
"final",
"byte",
"[",
"]",
"array",
",",
"final",
"JBBPIntCounter",
"position",
")",
"{",
"final",
"int",
"code",
"=",
"array",
"[",
"position",
".",
"getAndIncrement",
"(",
")",
"]",
"&",
"0xFF",
";",
"if",
"(",
"code",
"<",
"0x80",
")",
"{",
"return",
"code",
";",
"}",
"final",
"int",
"result",
";",
"switch",
"(",
"code",
")",
"{",
"case",
"0x80",
":",
"{",
"result",
"=",
"(",
"(",
"array",
"[",
"position",
".",
"getAndIncrement",
"(",
")",
"]",
"&",
"0xFF",
")",
"<<",
"8",
")",
"|",
"(",
"array",
"[",
"position",
".",
"getAndIncrement",
"(",
")",
"]",
"&",
"0xFF",
")",
";",
"}",
"break",
";",
"case",
"0x81",
":",
"{",
"result",
"=",
"(",
"(",
"array",
"[",
"position",
".",
"getAndIncrement",
"(",
")",
"]",
"&",
"0xFF",
")",
"<<",
"24",
")",
"|",
"(",
"(",
"array",
"[",
"position",
".",
"getAndIncrement",
"(",
")",
"]",
"&",
"0xFF",
")",
"<<",
"16",
")",
"|",
"(",
"(",
"array",
"[",
"position",
".",
"getAndIncrement",
"(",
")",
"]",
"&",
"0xFF",
")",
"<<",
"8",
")",
"|",
"(",
"array",
"[",
"position",
".",
"getAndIncrement",
"(",
")",
"]",
"&",
"0xFF",
")",
";",
"}",
"break",
";",
"default",
":",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Unsupported packed integer prefix [0x\"",
"+",
"Integer",
".",
"toHexString",
"(",
"code",
")",
".",
"toUpperCase",
"(",
"Locale",
".",
"ENGLISH",
")",
"+",
"'",
"'",
")",
";",
"}",
"return",
"result",
";",
"}"
] | Unpack an integer value from defined position in a byte array.
@param array the source byte array
@param position the position of the first byte of packed value
@return the unpacked value, the position will be increased | [
"Unpack",
"an",
"integer",
"value",
"from",
"defined",
"position",
"in",
"a",
"byte",
"array",
"."
] | train | https://github.com/raydac/java-binary-block-parser/blob/6d98abcab01e0c72d525ebcc9e7b694f9ce49f5b/jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPUtils.java#L152-L175 |
line/armeria | tomcat/src/main/java/com/linecorp/armeria/server/tomcat/TomcatService.java | TomcatService.forConnector | public static TomcatService forConnector(String hostname, Connector connector) {
"""
Creates a new {@link TomcatService} from an existing Tomcat {@link Connector} instance.
If the specified {@link Connector} instance is not configured properly, the returned
{@link TomcatService} may respond with '503 Service Not Available' error.
@return a new {@link TomcatService}, which will not manage the provided {@link Connector} instance.
"""
requireNonNull(hostname, "hostname");
requireNonNull(connector, "connector");
return new UnmanagedTomcatService(hostname, connector);
} | java | public static TomcatService forConnector(String hostname, Connector connector) {
requireNonNull(hostname, "hostname");
requireNonNull(connector, "connector");
return new UnmanagedTomcatService(hostname, connector);
} | [
"public",
"static",
"TomcatService",
"forConnector",
"(",
"String",
"hostname",
",",
"Connector",
"connector",
")",
"{",
"requireNonNull",
"(",
"hostname",
",",
"\"hostname\"",
")",
";",
"requireNonNull",
"(",
"connector",
",",
"\"connector\"",
")",
";",
"return",
"new",
"UnmanagedTomcatService",
"(",
"hostname",
",",
"connector",
")",
";",
"}"
] | Creates a new {@link TomcatService} from an existing Tomcat {@link Connector} instance.
If the specified {@link Connector} instance is not configured properly, the returned
{@link TomcatService} may respond with '503 Service Not Available' error.
@return a new {@link TomcatService}, which will not manage the provided {@link Connector} instance. | [
"Creates",
"a",
"new",
"{",
"@link",
"TomcatService",
"}",
"from",
"an",
"existing",
"Tomcat",
"{",
"@link",
"Connector",
"}",
"instance",
".",
"If",
"the",
"specified",
"{",
"@link",
"Connector",
"}",
"instance",
"is",
"not",
"configured",
"properly",
"the",
"returned",
"{",
"@link",
"TomcatService",
"}",
"may",
"respond",
"with",
"503",
"Service",
"Not",
"Available",
"error",
"."
] | train | https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/tomcat/src/main/java/com/linecorp/armeria/server/tomcat/TomcatService.java#L212-L217 |
sdl/odata | odata_renderer/src/main/java/com/sdl/odata/renderer/atom/writer/AtomDataWriter.java | AtomDataWriter.marshallStructured | private void marshallStructured(final Object object, StructuredType structuredType)
throws ODataRenderException, XMLStreamException {
"""
Marshall an object that is of an OData structured type (entity type or complex type).
@param object The object to marshall. Can be {@code null}.
@param structuredType The structured type.
@throws ODataRenderException If an error occurs while rendering.
@throws XMLStreamException If an error occurs while rendering.
"""
LOG.trace("Start structured value of type: {}", structuredType);
if (object != null) {
visitProperties(entityDataModel, structuredType, property -> {
try {
if (!(property instanceof NavigationProperty)) {
marshallStructuralProperty(object, property);
}
} catch (XMLStreamException e) {
throw new ODataRenderException("Error while writing property: " + property.getName(), e);
}
});
} else {
LOG.trace("Structured value is null");
}
LOG.trace("End structured value of type: {}", structuredType);
} | java | private void marshallStructured(final Object object, StructuredType structuredType)
throws ODataRenderException, XMLStreamException {
LOG.trace("Start structured value of type: {}", structuredType);
if (object != null) {
visitProperties(entityDataModel, structuredType, property -> {
try {
if (!(property instanceof NavigationProperty)) {
marshallStructuralProperty(object, property);
}
} catch (XMLStreamException e) {
throw new ODataRenderException("Error while writing property: " + property.getName(), e);
}
});
} else {
LOG.trace("Structured value is null");
}
LOG.trace("End structured value of type: {}", structuredType);
} | [
"private",
"void",
"marshallStructured",
"(",
"final",
"Object",
"object",
",",
"StructuredType",
"structuredType",
")",
"throws",
"ODataRenderException",
",",
"XMLStreamException",
"{",
"LOG",
".",
"trace",
"(",
"\"Start structured value of type: {}\"",
",",
"structuredType",
")",
";",
"if",
"(",
"object",
"!=",
"null",
")",
"{",
"visitProperties",
"(",
"entityDataModel",
",",
"structuredType",
",",
"property",
"->",
"{",
"try",
"{",
"if",
"(",
"!",
"(",
"property",
"instanceof",
"NavigationProperty",
")",
")",
"{",
"marshallStructuralProperty",
"(",
"object",
",",
"property",
")",
";",
"}",
"}",
"catch",
"(",
"XMLStreamException",
"e",
")",
"{",
"throw",
"new",
"ODataRenderException",
"(",
"\"Error while writing property: \"",
"+",
"property",
".",
"getName",
"(",
")",
",",
"e",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"LOG",
".",
"trace",
"(",
"\"Structured value is null\"",
")",
";",
"}",
"LOG",
".",
"trace",
"(",
"\"End structured value of type: {}\"",
",",
"structuredType",
")",
";",
"}"
] | Marshall an object that is of an OData structured type (entity type or complex type).
@param object The object to marshall. Can be {@code null}.
@param structuredType The structured type.
@throws ODataRenderException If an error occurs while rendering.
@throws XMLStreamException If an error occurs while rendering. | [
"Marshall",
"an",
"object",
"that",
"is",
"of",
"an",
"OData",
"structured",
"type",
"(",
"entity",
"type",
"or",
"complex",
"type",
")",
"."
] | train | https://github.com/sdl/odata/blob/eb747d73e9af0f4e59a25b82ed656e526a7e2189/odata_renderer/src/main/java/com/sdl/odata/renderer/atom/writer/AtomDataWriter.java#L159-L179 |
beangle/beangle3 | commons/core/src/main/java/org/beangle/commons/collection/MapConverter.java | MapConverter.getLong | public Long getLong(Map<String, Object> data, String name) {
"""
<p>
getLong.
</p>
@param data a {@link java.util.Map} object.
@param name a {@link java.lang.String} object.
@return a {@link java.lang.Long} object.
"""
return get(data, name, Long.class);
} | java | public Long getLong(Map<String, Object> data, String name) {
return get(data, name, Long.class);
} | [
"public",
"Long",
"getLong",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"data",
",",
"String",
"name",
")",
"{",
"return",
"get",
"(",
"data",
",",
"name",
",",
"Long",
".",
"class",
")",
";",
"}"
] | <p>
getLong.
</p>
@param data a {@link java.util.Map} object.
@param name a {@link java.lang.String} object.
@return a {@link java.lang.Long} object. | [
"<p",
">",
"getLong",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/beangle/beangle3/blob/33df2873a5f38e28ac174a1d3b8144eb2f808e64/commons/core/src/main/java/org/beangle/commons/collection/MapConverter.java#L273-L275 |
astrapi69/jaulp-wicket | jaulp-wicket-base/src/main/java/de/alpharogroup/wicket/base/application/OnlineUsers.java | OnlineUsers.addOnline | public synchronized ID addOnline(final USER user, final ID sessionId) {
"""
Adds the user online.
@param user
the user
@param sessionId
the session id
@return the string
"""
sessionIdToUser.put(sessionId, user);
return usersOnline.put(user, sessionId);
} | java | public synchronized ID addOnline(final USER user, final ID sessionId)
{
sessionIdToUser.put(sessionId, user);
return usersOnline.put(user, sessionId);
} | [
"public",
"synchronized",
"ID",
"addOnline",
"(",
"final",
"USER",
"user",
",",
"final",
"ID",
"sessionId",
")",
"{",
"sessionIdToUser",
".",
"put",
"(",
"sessionId",
",",
"user",
")",
";",
"return",
"usersOnline",
".",
"put",
"(",
"user",
",",
"sessionId",
")",
";",
"}"
] | Adds the user online.
@param user
the user
@param sessionId
the session id
@return the string | [
"Adds",
"the",
"user",
"online",
"."
] | train | https://github.com/astrapi69/jaulp-wicket/blob/85d74368d00abd9bb97659b5794e38c0f8a013d4/jaulp-wicket-base/src/main/java/de/alpharogroup/wicket/base/application/OnlineUsers.java#L52-L56 |
depsypher/pngtastic | src/main/java/com/googlecode/pngtastic/core/processing/Base64.java | Base64.encodeFileToFile | public static void encodeFileToFile(String infile, String outfile) throws IOException {
"""
Reads <tt>infile</tt> and encodes it to <tt>outfile</tt>.
@param infile Input file
@param outfile Output file
@throws java.io.IOException if there is an error
@since 2.2
"""
String encoded = Base64.encodeFromFile(infile);
java.io.OutputStream out = null;
try {
out = new java.io.BufferedOutputStream(new FileOutputStream(outfile));
out.write(encoded.getBytes("US-ASCII")); // Strict, 7-bit output.
} catch (IOException e) {
throw e; // Catch and release to execute finally{}
} finally {
try {
if (out != null) {
out.close();
}
} catch (Exception ex) {
}
}
} | java | public static void encodeFileToFile(String infile, String outfile) throws IOException {
String encoded = Base64.encodeFromFile(infile);
java.io.OutputStream out = null;
try {
out = new java.io.BufferedOutputStream(new FileOutputStream(outfile));
out.write(encoded.getBytes("US-ASCII")); // Strict, 7-bit output.
} catch (IOException e) {
throw e; // Catch and release to execute finally{}
} finally {
try {
if (out != null) {
out.close();
}
} catch (Exception ex) {
}
}
} | [
"public",
"static",
"void",
"encodeFileToFile",
"(",
"String",
"infile",
",",
"String",
"outfile",
")",
"throws",
"IOException",
"{",
"String",
"encoded",
"=",
"Base64",
".",
"encodeFromFile",
"(",
"infile",
")",
";",
"java",
".",
"io",
".",
"OutputStream",
"out",
"=",
"null",
";",
"try",
"{",
"out",
"=",
"new",
"java",
".",
"io",
".",
"BufferedOutputStream",
"(",
"new",
"FileOutputStream",
"(",
"outfile",
")",
")",
";",
"out",
".",
"write",
"(",
"encoded",
".",
"getBytes",
"(",
"\"US-ASCII\"",
")",
")",
";",
"// Strict, 7-bit output.",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"e",
";",
"// Catch and release to execute finally{}",
"}",
"finally",
"{",
"try",
"{",
"if",
"(",
"out",
"!=",
"null",
")",
"{",
"out",
".",
"close",
"(",
")",
";",
"}",
"}",
"catch",
"(",
"Exception",
"ex",
")",
"{",
"}",
"}",
"}"
] | Reads <tt>infile</tt> and encodes it to <tt>outfile</tt>.
@param infile Input file
@param outfile Output file
@throws java.io.IOException if there is an error
@since 2.2 | [
"Reads",
"<tt",
">",
"infile<",
"/",
"tt",
">",
"and",
"encodes",
"it",
"to",
"<tt",
">",
"outfile<",
"/",
"tt",
">",
"."
] | train | https://github.com/depsypher/pngtastic/blob/13fd2a63dd8b2febd7041273889a1bba4f2a6a07/src/main/java/com/googlecode/pngtastic/core/processing/Base64.java#L1444-L1460 |
UrielCh/ovh-java-sdk | ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java | ApiOvhTelephony.billingAccount_portability_id_changeDate_POST | public void billingAccount_portability_id_changeDate_POST(String billingAccount, Long id, Date date) throws IOException {
"""
Ask to change the portability date
REST: POST /telephony/{billingAccount}/portability/{id}/changeDate
@param date [required] The proposed portability due date
@param billingAccount [required] The name of your billingAccount
@param id [required] The ID of the portability
"""
String qPath = "/telephony/{billingAccount}/portability/{id}/changeDate";
StringBuilder sb = path(qPath, billingAccount, id);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "date", date);
exec(qPath, "POST", sb.toString(), o);
} | java | public void billingAccount_portability_id_changeDate_POST(String billingAccount, Long id, Date date) throws IOException {
String qPath = "/telephony/{billingAccount}/portability/{id}/changeDate";
StringBuilder sb = path(qPath, billingAccount, id);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "date", date);
exec(qPath, "POST", sb.toString(), o);
} | [
"public",
"void",
"billingAccount_portability_id_changeDate_POST",
"(",
"String",
"billingAccount",
",",
"Long",
"id",
",",
"Date",
"date",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/telephony/{billingAccount}/portability/{id}/changeDate\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"billingAccount",
",",
"id",
")",
";",
"HashMap",
"<",
"String",
",",
"Object",
">",
"o",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Object",
">",
"(",
")",
";",
"addBody",
"(",
"o",
",",
"\"date\"",
",",
"date",
")",
";",
"exec",
"(",
"qPath",
",",
"\"POST\"",
",",
"sb",
".",
"toString",
"(",
")",
",",
"o",
")",
";",
"}"
] | Ask to change the portability date
REST: POST /telephony/{billingAccount}/portability/{id}/changeDate
@param date [required] The proposed portability due date
@param billingAccount [required] The name of your billingAccount
@param id [required] The ID of the portability | [
"Ask",
"to",
"change",
"the",
"portability",
"date"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java#L375-L381 |
ArcBees/gwtquery | gwtquery-core/src/main/java/com/google/gwt/query/client/plugins/events/EventsListener.java | EventsListener.dispatchEvent | public void dispatchEvent(Event event, String eventName) {
"""
Dispatch an event in this element but changing the type,
it's useful for special events.
"""
int typeInt = Event.getTypeInt(eventName);
Object[] handlerData = $(element).data(EVENT_DATA);
for (int i = 0, l = elementEvents.length(); i < l; i++) {
BindFunction listener = elementEvents.get(i);
String namespace = JsUtils.prop(event, "namespace");
boolean matchEV = listener != null && (listener.hasEventType(typeInt) || listener.isTypeOf(eventName));
boolean matchNS = matchEV && (isNullOrEmpty(namespace) || listener.nameSpace.equals(namespace));
if (matchEV && matchNS) {
if (!listener.fire(event, typeInt, eventName, handlerData)) {
event.stopPropagation();
event.preventDefault();
}
}
}
} | java | public void dispatchEvent(Event event, String eventName) {
int typeInt = Event.getTypeInt(eventName);
Object[] handlerData = $(element).data(EVENT_DATA);
for (int i = 0, l = elementEvents.length(); i < l; i++) {
BindFunction listener = elementEvents.get(i);
String namespace = JsUtils.prop(event, "namespace");
boolean matchEV = listener != null && (listener.hasEventType(typeInt) || listener.isTypeOf(eventName));
boolean matchNS = matchEV && (isNullOrEmpty(namespace) || listener.nameSpace.equals(namespace));
if (matchEV && matchNS) {
if (!listener.fire(event, typeInt, eventName, handlerData)) {
event.stopPropagation();
event.preventDefault();
}
}
}
} | [
"public",
"void",
"dispatchEvent",
"(",
"Event",
"event",
",",
"String",
"eventName",
")",
"{",
"int",
"typeInt",
"=",
"Event",
".",
"getTypeInt",
"(",
"eventName",
")",
";",
"Object",
"[",
"]",
"handlerData",
"=",
"$",
"(",
"element",
")",
".",
"data",
"(",
"EVENT_DATA",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
",",
"l",
"=",
"elementEvents",
".",
"length",
"(",
")",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"BindFunction",
"listener",
"=",
"elementEvents",
".",
"get",
"(",
"i",
")",
";",
"String",
"namespace",
"=",
"JsUtils",
".",
"prop",
"(",
"event",
",",
"\"namespace\"",
")",
";",
"boolean",
"matchEV",
"=",
"listener",
"!=",
"null",
"&&",
"(",
"listener",
".",
"hasEventType",
"(",
"typeInt",
")",
"||",
"listener",
".",
"isTypeOf",
"(",
"eventName",
")",
")",
";",
"boolean",
"matchNS",
"=",
"matchEV",
"&&",
"(",
"isNullOrEmpty",
"(",
"namespace",
")",
"||",
"listener",
".",
"nameSpace",
".",
"equals",
"(",
"namespace",
")",
")",
";",
"if",
"(",
"matchEV",
"&&",
"matchNS",
")",
"{",
"if",
"(",
"!",
"listener",
".",
"fire",
"(",
"event",
",",
"typeInt",
",",
"eventName",
",",
"handlerData",
")",
")",
"{",
"event",
".",
"stopPropagation",
"(",
")",
";",
"event",
".",
"preventDefault",
"(",
")",
";",
"}",
"}",
"}",
"}"
] | Dispatch an event in this element but changing the type,
it's useful for special events. | [
"Dispatch",
"an",
"event",
"in",
"this",
"element",
"but",
"changing",
"the",
"type",
"it",
"s",
"useful",
"for",
"special",
"events",
"."
] | train | https://github.com/ArcBees/gwtquery/blob/93e02bc8eb030081061c56134ebee1f585981107/gwtquery-core/src/main/java/com/google/gwt/query/client/plugins/events/EventsListener.java#L557-L572 |
PeterisP/LVTagger | src/main/java/edu/stanford/nlp/sequences/CoNLLDocumentReaderAndWriter.java | CoNLLDocumentReaderAndWriter.printAnswers | public void printAnswers(List<CoreLabel> doc, PrintWriter out) {
"""
Write a standard CoNLL format output file.
@param doc The document: A List of CoreLabel
@param out Where to send the answers to
"""
// boolean tagsMerged = flags.mergeTags;
// boolean useHead = flags.splitOnHead;
if ( ! "iob1".equalsIgnoreCase(flags.entitySubclassification)) {
deEndify(doc);
}
for (CoreLabel fl : doc) {
String word = fl.word();
if (word == BOUNDARY) { // Using == is okay, because it is set to constant
out.println();
} else {
String gold = fl.get(OriginalAnswerAnnotation.class);
if(gold == null) gold = "";
String guess = fl.get(AnswerAnnotation.class);
// System.err.println(fl.word() + "\t" + fl.get(AnswerAnnotation.class) + "\t" + fl.get(AnswerAnnotation.class));
String pos = fl.tag();
String chunk = (fl.get(ChunkAnnotation.class) == null ? "" : fl.get(ChunkAnnotation.class));
out.println(fl.word() + '\t' + pos + '\t' + chunk + '\t' +
gold + '\t' + guess);
}
}
} | java | public void printAnswers(List<CoreLabel> doc, PrintWriter out) {
// boolean tagsMerged = flags.mergeTags;
// boolean useHead = flags.splitOnHead;
if ( ! "iob1".equalsIgnoreCase(flags.entitySubclassification)) {
deEndify(doc);
}
for (CoreLabel fl : doc) {
String word = fl.word();
if (word == BOUNDARY) { // Using == is okay, because it is set to constant
out.println();
} else {
String gold = fl.get(OriginalAnswerAnnotation.class);
if(gold == null) gold = "";
String guess = fl.get(AnswerAnnotation.class);
// System.err.println(fl.word() + "\t" + fl.get(AnswerAnnotation.class) + "\t" + fl.get(AnswerAnnotation.class));
String pos = fl.tag();
String chunk = (fl.get(ChunkAnnotation.class) == null ? "" : fl.get(ChunkAnnotation.class));
out.println(fl.word() + '\t' + pos + '\t' + chunk + '\t' +
gold + '\t' + guess);
}
}
} | [
"public",
"void",
"printAnswers",
"(",
"List",
"<",
"CoreLabel",
">",
"doc",
",",
"PrintWriter",
"out",
")",
"{",
"// boolean tagsMerged = flags.mergeTags;\r",
"// boolean useHead = flags.splitOnHead;\r",
"if",
"(",
"!",
"\"iob1\"",
".",
"equalsIgnoreCase",
"(",
"flags",
".",
"entitySubclassification",
")",
")",
"{",
"deEndify",
"(",
"doc",
")",
";",
"}",
"for",
"(",
"CoreLabel",
"fl",
":",
"doc",
")",
"{",
"String",
"word",
"=",
"fl",
".",
"word",
"(",
")",
";",
"if",
"(",
"word",
"==",
"BOUNDARY",
")",
"{",
"// Using == is okay, because it is set to constant\r",
"out",
".",
"println",
"(",
")",
";",
"}",
"else",
"{",
"String",
"gold",
"=",
"fl",
".",
"get",
"(",
"OriginalAnswerAnnotation",
".",
"class",
")",
";",
"if",
"(",
"gold",
"==",
"null",
")",
"gold",
"=",
"\"\"",
";",
"String",
"guess",
"=",
"fl",
".",
"get",
"(",
"AnswerAnnotation",
".",
"class",
")",
";",
"// System.err.println(fl.word() + \"\\t\" + fl.get(AnswerAnnotation.class) + \"\\t\" + fl.get(AnswerAnnotation.class));\r",
"String",
"pos",
"=",
"fl",
".",
"tag",
"(",
")",
";",
"String",
"chunk",
"=",
"(",
"fl",
".",
"get",
"(",
"ChunkAnnotation",
".",
"class",
")",
"==",
"null",
"?",
"\"\"",
":",
"fl",
".",
"get",
"(",
"ChunkAnnotation",
".",
"class",
")",
")",
";",
"out",
".",
"println",
"(",
"fl",
".",
"word",
"(",
")",
"+",
"'",
"'",
"+",
"pos",
"+",
"'",
"'",
"+",
"chunk",
"+",
"'",
"'",
"+",
"gold",
"+",
"'",
"'",
"+",
"guess",
")",
";",
"}",
"}",
"}"
] | Write a standard CoNLL format output file.
@param doc The document: A List of CoreLabel
@param out Where to send the answers to | [
"Write",
"a",
"standard",
"CoNLL",
"format",
"output",
"file",
"."
] | train | https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/sequences/CoNLLDocumentReaderAndWriter.java#L337-L360 |
kuali/ojb-1.0.4 | src/java/org/apache/ojb/broker/util/ClassHelper.java | ClassHelper.newInstance | public static Object newInstance(Class target, Class type, Object arg) throws InstantiationException,
IllegalAccessException,
IllegalArgumentException,
InvocationTargetException,
NoSuchMethodException,
SecurityException {
"""
Returns a new instance of the given class using the constructor with the specified parameter.
@param target The class to instantiate
@param type The types of the single parameter of the constructor
@param arg The argument
@return The instance
"""
return newInstance(target, new Class[]{ type }, new Object[]{ arg });
} | java | public static Object newInstance(Class target, Class type, Object arg) throws InstantiationException,
IllegalAccessException,
IllegalArgumentException,
InvocationTargetException,
NoSuchMethodException,
SecurityException
{
return newInstance(target, new Class[]{ type }, new Object[]{ arg });
} | [
"public",
"static",
"Object",
"newInstance",
"(",
"Class",
"target",
",",
"Class",
"type",
",",
"Object",
"arg",
")",
"throws",
"InstantiationException",
",",
"IllegalAccessException",
",",
"IllegalArgumentException",
",",
"InvocationTargetException",
",",
"NoSuchMethodException",
",",
"SecurityException",
"{",
"return",
"newInstance",
"(",
"target",
",",
"new",
"Class",
"[",
"]",
"{",
"type",
"}",
",",
"new",
"Object",
"[",
"]",
"{",
"arg",
"}",
")",
";",
"}"
] | Returns a new instance of the given class using the constructor with the specified parameter.
@param target The class to instantiate
@param type The types of the single parameter of the constructor
@param arg The argument
@return The instance | [
"Returns",
"a",
"new",
"instance",
"of",
"the",
"given",
"class",
"using",
"the",
"constructor",
"with",
"the",
"specified",
"parameter",
"."
] | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/util/ClassHelper.java#L320-L328 |
ppiastucki/recast4j | detourcrowd/src/main/java/org/recast4j/detour/crowd/PathCorridor.java | PathCorridor.movePosition | public boolean movePosition(float[] npos, NavMeshQuery navquery, QueryFilter filter) {
"""
Moves the position from the current location to the desired location, adjusting the corridor as needed to reflect
the change.
Behavior:
- The movement is constrained to the surface of the navigation mesh. - The corridor is automatically adjusted
(shorted or lengthened) in order to remain valid. - The new position will be located in the adjusted corridor's
first polygon.
The expected use case is that the desired position will be 'near' the current corridor. What is considered 'near'
depends on local polygon density, query search extents, etc.
The resulting position will differ from the desired position if the desired position is not on the navigation
mesh, or it can't be reached using a local search.
@param npos
The desired new position. [(x, y, z)]
@param navquery
The query object used to build the corridor.
@param filter
The filter to apply to the operation.
"""
// Move along navmesh and update new position.
Result<MoveAlongSurfaceResult> masResult = navquery.moveAlongSurface(m_path.get(0), m_pos, npos, filter);
if (masResult.succeeded()) {
m_path = mergeCorridorStartMoved(m_path, masResult.result.getVisited());
// Adjust the position to stay on top of the navmesh.
vCopy(m_pos, masResult.result.getResultPos());
Result<Float> hr = navquery.getPolyHeight(m_path.get(0), masResult.result.getResultPos());
if (hr.succeeded()) {
m_pos[1] = hr.result;
}
return true;
}
return false;
} | java | public boolean movePosition(float[] npos, NavMeshQuery navquery, QueryFilter filter) {
// Move along navmesh and update new position.
Result<MoveAlongSurfaceResult> masResult = navquery.moveAlongSurface(m_path.get(0), m_pos, npos, filter);
if (masResult.succeeded()) {
m_path = mergeCorridorStartMoved(m_path, masResult.result.getVisited());
// Adjust the position to stay on top of the navmesh.
vCopy(m_pos, masResult.result.getResultPos());
Result<Float> hr = navquery.getPolyHeight(m_path.get(0), masResult.result.getResultPos());
if (hr.succeeded()) {
m_pos[1] = hr.result;
}
return true;
}
return false;
} | [
"public",
"boolean",
"movePosition",
"(",
"float",
"[",
"]",
"npos",
",",
"NavMeshQuery",
"navquery",
",",
"QueryFilter",
"filter",
")",
"{",
"// Move along navmesh and update new position.",
"Result",
"<",
"MoveAlongSurfaceResult",
">",
"masResult",
"=",
"navquery",
".",
"moveAlongSurface",
"(",
"m_path",
".",
"get",
"(",
"0",
")",
",",
"m_pos",
",",
"npos",
",",
"filter",
")",
";",
"if",
"(",
"masResult",
".",
"succeeded",
"(",
")",
")",
"{",
"m_path",
"=",
"mergeCorridorStartMoved",
"(",
"m_path",
",",
"masResult",
".",
"result",
".",
"getVisited",
"(",
")",
")",
";",
"// Adjust the position to stay on top of the navmesh.",
"vCopy",
"(",
"m_pos",
",",
"masResult",
".",
"result",
".",
"getResultPos",
"(",
")",
")",
";",
"Result",
"<",
"Float",
">",
"hr",
"=",
"navquery",
".",
"getPolyHeight",
"(",
"m_path",
".",
"get",
"(",
"0",
")",
",",
"masResult",
".",
"result",
".",
"getResultPos",
"(",
")",
")",
";",
"if",
"(",
"hr",
".",
"succeeded",
"(",
")",
")",
"{",
"m_pos",
"[",
"1",
"]",
"=",
"hr",
".",
"result",
";",
"}",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] | Moves the position from the current location to the desired location, adjusting the corridor as needed to reflect
the change.
Behavior:
- The movement is constrained to the surface of the navigation mesh. - The corridor is automatically adjusted
(shorted or lengthened) in order to remain valid. - The new position will be located in the adjusted corridor's
first polygon.
The expected use case is that the desired position will be 'near' the current corridor. What is considered 'near'
depends on local polygon density, query search extents, etc.
The resulting position will differ from the desired position if the desired position is not on the navigation
mesh, or it can't be reached using a local search.
@param npos
The desired new position. [(x, y, z)]
@param navquery
The query object used to build the corridor.
@param filter
The filter to apply to the operation. | [
"Moves",
"the",
"position",
"from",
"the",
"current",
"location",
"to",
"the",
"desired",
"location",
"adjusting",
"the",
"corridor",
"as",
"needed",
"to",
"reflect",
"the",
"change",
"."
] | train | https://github.com/ppiastucki/recast4j/blob/a414dc34f16b87c95fb4e0f46c28a7830d421788/detourcrowd/src/main/java/org/recast4j/detour/crowd/PathCorridor.java#L384-L398 |
kuali/ojb-1.0.4 | src/java/org/apache/ojb/broker/metadata/MetadataManager.java | MetadataManager.readDescriptorRepository | public DescriptorRepository readDescriptorRepository(String fileName) {
"""
Read ClassDescriptors from the given repository file.
@see #mergeDescriptorRepository
"""
try
{
RepositoryPersistor persistor = new RepositoryPersistor();
return persistor.readDescriptorRepository(fileName);
}
catch (Exception e)
{
throw new MetadataException("Can not read repository " + fileName, e);
}
} | java | public DescriptorRepository readDescriptorRepository(String fileName)
{
try
{
RepositoryPersistor persistor = new RepositoryPersistor();
return persistor.readDescriptorRepository(fileName);
}
catch (Exception e)
{
throw new MetadataException("Can not read repository " + fileName, e);
}
} | [
"public",
"DescriptorRepository",
"readDescriptorRepository",
"(",
"String",
"fileName",
")",
"{",
"try",
"{",
"RepositoryPersistor",
"persistor",
"=",
"new",
"RepositoryPersistor",
"(",
")",
";",
"return",
"persistor",
".",
"readDescriptorRepository",
"(",
"fileName",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"MetadataException",
"(",
"\"Can not read repository \"",
"+",
"fileName",
",",
"e",
")",
";",
"}",
"}"
] | Read ClassDescriptors from the given repository file.
@see #mergeDescriptorRepository | [
"Read",
"ClassDescriptors",
"from",
"the",
"given",
"repository",
"file",
"."
] | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/metadata/MetadataManager.java#L334-L345 |
b3dgs/lionengine | lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/transition/circuit/MapCircuitExtractor.java | MapCircuitExtractor.getCircuitType | private static CircuitType getCircuitType(String groupIn, Collection<String> neighborGroups) {
"""
Get the circuit type from one group to another.
@param groupIn The group in.
@param neighborGroups The neighbor groups.
@return The tile circuit.
"""
final boolean[] bits = new boolean[CircuitType.BITS];
int i = CircuitType.BITS - 1;
for (final String neighborGroup : neighborGroups)
{
bits[i] = groupIn.equals(neighborGroup);
i--;
}
return CircuitType.from(bits);
} | java | private static CircuitType getCircuitType(String groupIn, Collection<String> neighborGroups)
{
final boolean[] bits = new boolean[CircuitType.BITS];
int i = CircuitType.BITS - 1;
for (final String neighborGroup : neighborGroups)
{
bits[i] = groupIn.equals(neighborGroup);
i--;
}
return CircuitType.from(bits);
} | [
"private",
"static",
"CircuitType",
"getCircuitType",
"(",
"String",
"groupIn",
",",
"Collection",
"<",
"String",
">",
"neighborGroups",
")",
"{",
"final",
"boolean",
"[",
"]",
"bits",
"=",
"new",
"boolean",
"[",
"CircuitType",
".",
"BITS",
"]",
";",
"int",
"i",
"=",
"CircuitType",
".",
"BITS",
"-",
"1",
";",
"for",
"(",
"final",
"String",
"neighborGroup",
":",
"neighborGroups",
")",
"{",
"bits",
"[",
"i",
"]",
"=",
"groupIn",
".",
"equals",
"(",
"neighborGroup",
")",
";",
"i",
"--",
";",
"}",
"return",
"CircuitType",
".",
"from",
"(",
"bits",
")",
";",
"}"
] | Get the circuit type from one group to another.
@param groupIn The group in.
@param neighborGroups The neighbor groups.
@return The tile circuit. | [
"Get",
"the",
"circuit",
"type",
"from",
"one",
"group",
"to",
"another",
"."
] | train | https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/transition/circuit/MapCircuitExtractor.java#L75-L85 |
io7m/jaffirm | com.io7m.jaffirm.core/src/main/java/com/io7m/jaffirm/core/Postconditions.java | Postconditions.checkPostconditionL | public static long checkPostconditionL(
final long value,
final boolean condition,
final LongFunction<String> describer) {
"""
A {@code long} specialized version of {@link #checkPostcondition(Object,
Predicate, Function)}
@param condition The predicate
@param value The value
@param describer The describer of the predicate
@return value
@throws PostconditionViolationException If the predicate is false
"""
return innerCheckL(value, condition, describer);
} | java | public static long checkPostconditionL(
final long value,
final boolean condition,
final LongFunction<String> describer)
{
return innerCheckL(value, condition, describer);
} | [
"public",
"static",
"long",
"checkPostconditionL",
"(",
"final",
"long",
"value",
",",
"final",
"boolean",
"condition",
",",
"final",
"LongFunction",
"<",
"String",
">",
"describer",
")",
"{",
"return",
"innerCheckL",
"(",
"value",
",",
"condition",
",",
"describer",
")",
";",
"}"
] | A {@code long} specialized version of {@link #checkPostcondition(Object,
Predicate, Function)}
@param condition The predicate
@param value The value
@param describer The describer of the predicate
@return value
@throws PostconditionViolationException If the predicate is false | [
"A",
"{",
"@code",
"long",
"}",
"specialized",
"version",
"of",
"{",
"@link",
"#checkPostcondition",
"(",
"Object",
"Predicate",
"Function",
")",
"}"
] | train | https://github.com/io7m/jaffirm/blob/c97d246242d381e48832838737418cfe4cb57b4d/com.io7m.jaffirm.core/src/main/java/com/io7m/jaffirm/core/Postconditions.java#L476-L482 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/jca/GetInstance.java | GetInstance.getInstance | public static Instance getInstance(Service s, Class<?> clazz)
throws NoSuchAlgorithmException {
"""
/*
The two getInstance() methods below take a service. They are
intended for classes that cannot use the standard methods, e.g.
because they implement delayed provider selection like the
Signature class.
"""
Object instance = s.newInstance(null);
checkSuperClass(s, instance.getClass(), clazz);
return new Instance(s.getProvider(), instance);
} | java | public static Instance getInstance(Service s, Class<?> clazz)
throws NoSuchAlgorithmException {
Object instance = s.newInstance(null);
checkSuperClass(s, instance.getClass(), clazz);
return new Instance(s.getProvider(), instance);
} | [
"public",
"static",
"Instance",
"getInstance",
"(",
"Service",
"s",
",",
"Class",
"<",
"?",
">",
"clazz",
")",
"throws",
"NoSuchAlgorithmException",
"{",
"Object",
"instance",
"=",
"s",
".",
"newInstance",
"(",
"null",
")",
";",
"checkSuperClass",
"(",
"s",
",",
"instance",
".",
"getClass",
"(",
")",
",",
"clazz",
")",
";",
"return",
"new",
"Instance",
"(",
"s",
".",
"getProvider",
"(",
")",
",",
"instance",
")",
";",
"}"
] | /*
The two getInstance() methods below take a service. They are
intended for classes that cannot use the standard methods, e.g.
because they implement delayed provider selection like the
Signature class. | [
"/",
"*",
"The",
"two",
"getInstance",
"()",
"methods",
"below",
"take",
"a",
"service",
".",
"They",
"are",
"intended",
"for",
"classes",
"that",
"cannot",
"use",
"the",
"standard",
"methods",
"e",
".",
"g",
".",
"because",
"they",
"implement",
"delayed",
"provider",
"selection",
"like",
"the",
"Signature",
"class",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/jca/GetInstance.java#L234-L239 |
windup/windup | rules-java/api/src/main/java/org/jboss/windup/rules/apps/mavenize/FeatureBasedApiDependenciesDeducer.java | FeatureBasedApiDependenciesDeducer.addHardcodedRecognitionDependencies | private void addHardcodedRecognitionDependencies(ProjectModel projectModel, Pom modulePom) {
"""
This is, theoretically, slightly better than addDeploymentTypeBasedDependencies(),
but we don't have any of the has*() methods implemented yet, so it does nothing.
"""
// TODO: Create a mapping from API occurence in the module into use of
if (hasJpaEntities(projectModel))
modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_JPA_21));
if (hasJsf(projectModel))
modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_JSF));
if (hasJaxrs(projectModel))
modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_JAXRS_20));
} | java | private void addHardcodedRecognitionDependencies(ProjectModel projectModel, Pom modulePom)
{
// TODO: Create a mapping from API occurence in the module into use of
if (hasJpaEntities(projectModel))
modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_JPA_21));
if (hasJsf(projectModel))
modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_JSF));
if (hasJaxrs(projectModel))
modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_JAXRS_20));
} | [
"private",
"void",
"addHardcodedRecognitionDependencies",
"(",
"ProjectModel",
"projectModel",
",",
"Pom",
"modulePom",
")",
"{",
"// TODO: Create a mapping from API occurence in the module into use of",
"if",
"(",
"hasJpaEntities",
"(",
"projectModel",
")",
")",
"modulePom",
".",
"getDependencies",
"(",
")",
".",
"add",
"(",
"new",
"SimpleDependency",
"(",
"Dependency",
".",
"Role",
".",
"API",
",",
"ApiDependenciesData",
".",
"DEP_API_JPA_21",
")",
")",
";",
"if",
"(",
"hasJsf",
"(",
"projectModel",
")",
")",
"modulePom",
".",
"getDependencies",
"(",
")",
".",
"add",
"(",
"new",
"SimpleDependency",
"(",
"Dependency",
".",
"Role",
".",
"API",
",",
"ApiDependenciesData",
".",
"DEP_API_JSF",
")",
")",
";",
"if",
"(",
"hasJaxrs",
"(",
"projectModel",
")",
")",
"modulePom",
".",
"getDependencies",
"(",
")",
".",
"add",
"(",
"new",
"SimpleDependency",
"(",
"Dependency",
".",
"Role",
".",
"API",
",",
"ApiDependenciesData",
".",
"DEP_API_JAXRS_20",
")",
")",
";",
"}"
] | This is, theoretically, slightly better than addDeploymentTypeBasedDependencies(),
but we don't have any of the has*() methods implemented yet, so it does nothing. | [
"This",
"is",
"theoretically",
"slightly",
"better",
"than",
"addDeploymentTypeBasedDependencies",
"()",
"but",
"we",
"don",
"t",
"have",
"any",
"of",
"the",
"has",
"*",
"()",
"methods",
"implemented",
"yet",
"so",
"it",
"does",
"nothing",
"."
] | train | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/rules-java/api/src/main/java/org/jboss/windup/rules/apps/mavenize/FeatureBasedApiDependenciesDeducer.java#L79-L90 |
apache/flink | flink-libraries/flink-gelly/src/main/java/org/apache/flink/graph/AnalyticHelper.java | AnalyticHelper.addAccumulator | public <V, A extends Serializable> void addAccumulator(String name, Accumulator<V, A> accumulator) {
"""
Adds an accumulator by prepending the given name with a random string.
@param name The name of the accumulator
@param accumulator The accumulator
@param <V> Type of values that are added to the accumulator
@param <A> Type of the accumulator result as it will be reported to the client
"""
getRuntimeContext().addAccumulator(id + SEPARATOR + name, accumulator);
} | java | public <V, A extends Serializable> void addAccumulator(String name, Accumulator<V, A> accumulator) {
getRuntimeContext().addAccumulator(id + SEPARATOR + name, accumulator);
} | [
"public",
"<",
"V",
",",
"A",
"extends",
"Serializable",
">",
"void",
"addAccumulator",
"(",
"String",
"name",
",",
"Accumulator",
"<",
"V",
",",
"A",
">",
"accumulator",
")",
"{",
"getRuntimeContext",
"(",
")",
".",
"addAccumulator",
"(",
"id",
"+",
"SEPARATOR",
"+",
"name",
",",
"accumulator",
")",
";",
"}"
] | Adds an accumulator by prepending the given name with a random string.
@param name The name of the accumulator
@param accumulator The accumulator
@param <V> Type of values that are added to the accumulator
@param <A> Type of the accumulator result as it will be reported to the client | [
"Adds",
"an",
"accumulator",
"by",
"prepending",
"the",
"given",
"name",
"with",
"a",
"random",
"string",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-libraries/flink-gelly/src/main/java/org/apache/flink/graph/AnalyticHelper.java#L66-L68 |
foundation-runtime/service-directory | 1.1/sd-core/src/main/java/com/cisco/oss/foundation/directory/utils/ServiceInstanceUtils.java | ServiceInstanceUtils.validateMetadata | public static void validateMetadata(Map<String, String> metadata) throws ServiceException {
"""
Validate the ServiceInstance Metadata.
@param metadata
the service instance metadata map.
@throws ServiceException
"""
for ( String key : metadata.keySet()){
if (!validateRequiredField(key, metaKeyRegEx)){
throw new ServiceException(
ErrorCode.SERVICE_INSTANCE_METAKEY_FORMAT_ERROR,
ErrorCode.SERVICE_INSTANCE_METAKEY_FORMAT_ERROR.getMessageTemplate(),key
);
}
}
} | java | public static void validateMetadata(Map<String, String> metadata) throws ServiceException {
for ( String key : metadata.keySet()){
if (!validateRequiredField(key, metaKeyRegEx)){
throw new ServiceException(
ErrorCode.SERVICE_INSTANCE_METAKEY_FORMAT_ERROR,
ErrorCode.SERVICE_INSTANCE_METAKEY_FORMAT_ERROR.getMessageTemplate(),key
);
}
}
} | [
"public",
"static",
"void",
"validateMetadata",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"metadata",
")",
"throws",
"ServiceException",
"{",
"for",
"(",
"String",
"key",
":",
"metadata",
".",
"keySet",
"(",
")",
")",
"{",
"if",
"(",
"!",
"validateRequiredField",
"(",
"key",
",",
"metaKeyRegEx",
")",
")",
"{",
"throw",
"new",
"ServiceException",
"(",
"ErrorCode",
".",
"SERVICE_INSTANCE_METAKEY_FORMAT_ERROR",
",",
"ErrorCode",
".",
"SERVICE_INSTANCE_METAKEY_FORMAT_ERROR",
".",
"getMessageTemplate",
"(",
")",
",",
"key",
")",
";",
"}",
"}",
"}"
] | Validate the ServiceInstance Metadata.
@param metadata
the service instance metadata map.
@throws ServiceException | [
"Validate",
"the",
"ServiceInstance",
"Metadata",
"."
] | train | https://github.com/foundation-runtime/service-directory/blob/a7bdefe173dc99e75eff4a24e07e6407e62f2ed4/1.1/sd-core/src/main/java/com/cisco/oss/foundation/directory/utils/ServiceInstanceUtils.java#L194-L204 |
riversun/finbin | src/main/java/org/riversun/finbin/BinarySearcher.java | BinarySearcher.searchBytes | public List<Integer> searchBytes(byte[] srcBytes, byte[] searchBytes) {
"""
Search bytes in byte array returns indexes within this byte-array of all
occurrences of the specified(search bytes) byte array.
@param srcBytes
@param searchBytes
@return result index list
"""
final int startIdx = 0;
final int endIdx = srcBytes.length - 1;
return searchBytes(srcBytes, searchBytes, startIdx, endIdx);
} | java | public List<Integer> searchBytes(byte[] srcBytes, byte[] searchBytes) {
final int startIdx = 0;
final int endIdx = srcBytes.length - 1;
return searchBytes(srcBytes, searchBytes, startIdx, endIdx);
} | [
"public",
"List",
"<",
"Integer",
">",
"searchBytes",
"(",
"byte",
"[",
"]",
"srcBytes",
",",
"byte",
"[",
"]",
"searchBytes",
")",
"{",
"final",
"int",
"startIdx",
"=",
"0",
";",
"final",
"int",
"endIdx",
"=",
"srcBytes",
".",
"length",
"-",
"1",
";",
"return",
"searchBytes",
"(",
"srcBytes",
",",
"searchBytes",
",",
"startIdx",
",",
"endIdx",
")",
";",
"}"
] | Search bytes in byte array returns indexes within this byte-array of all
occurrences of the specified(search bytes) byte array.
@param srcBytes
@param searchBytes
@return result index list | [
"Search",
"bytes",
"in",
"byte",
"array",
"returns",
"indexes",
"within",
"this",
"byte",
"-",
"array",
"of",
"all",
"occurrences",
"of",
"the",
"specified",
"(",
"search",
"bytes",
")",
"byte",
"array",
"."
] | train | https://github.com/riversun/finbin/blob/d1db86a0d2966dcf47087340bbd0727a9d508b3e/src/main/java/org/riversun/finbin/BinarySearcher.java#L137-L141 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/impl/LocalQPConsumerKey.java | LocalQPConsumerKey.notifyReceiveAllowed | public void notifyReceiveAllowed(boolean isAllowed, DestinationHandler destinationBeingModified) {
"""
Method notifyReceiveAllowed
<p>Notify the consumerKeys consumerPoint about change of Receive Allowed state
@param isAllowed - New state of Receive Allowed for localization
"""
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "notifyReceiveAllowed", Boolean.valueOf(isAllowed));
if (consumerPoint.destinationMatches(destinationBeingModified, consumerDispatcher))
{
consumerPoint.notifyReceiveAllowed(isAllowed);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "notifyReceiveAllowed");
} | java | public void notifyReceiveAllowed(boolean isAllowed, DestinationHandler destinationBeingModified)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "notifyReceiveAllowed", Boolean.valueOf(isAllowed));
if (consumerPoint.destinationMatches(destinationBeingModified, consumerDispatcher))
{
consumerPoint.notifyReceiveAllowed(isAllowed);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "notifyReceiveAllowed");
} | [
"public",
"void",
"notifyReceiveAllowed",
"(",
"boolean",
"isAllowed",
",",
"DestinationHandler",
"destinationBeingModified",
")",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"SibTr",
".",
"entry",
"(",
"tc",
",",
"\"notifyReceiveAllowed\"",
",",
"Boolean",
".",
"valueOf",
"(",
"isAllowed",
")",
")",
";",
"if",
"(",
"consumerPoint",
".",
"destinationMatches",
"(",
"destinationBeingModified",
",",
"consumerDispatcher",
")",
")",
"{",
"consumerPoint",
".",
"notifyReceiveAllowed",
"(",
"isAllowed",
")",
";",
"}",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"SibTr",
".",
"exit",
"(",
"tc",
",",
"\"notifyReceiveAllowed\"",
")",
";",
"}"
] | Method notifyReceiveAllowed
<p>Notify the consumerKeys consumerPoint about change of Receive Allowed state
@param isAllowed - New state of Receive Allowed for localization | [
"Method",
"notifyReceiveAllowed",
"<p",
">",
"Notify",
"the",
"consumerKeys",
"consumerPoint",
"about",
"change",
"of",
"Receive",
"Allowed",
"state"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/impl/LocalQPConsumerKey.java#L638-L647 |
MenoData/Time4J | base/src/main/java/net/time4j/base/GregorianMath.java | GregorianMath.checkDate | public static void checkDate(
int year,
int month,
int dayOfMonth
) {
"""
/*[deutsch]
<p>Überprüft die Bereichsgrenzen der Datumswerte nach
den gregorianischen Kalenderregeln. </p>
@param year proleptic iso year [(-999999999) - 999999999]
@param month gregorian month (1-12)
@param dayOfMonth day of month (1-31)
@throws IllegalArgumentException if any argument is out of range
@see #isValid(int, int, int)
"""
if (year < MIN_YEAR || year > MAX_YEAR) {
throw new IllegalArgumentException(
"YEAR out of range: " + year);
} else if ((month < 1) || (month > 12)) {
throw new IllegalArgumentException(
"MONTH out of range: " + month);
} else if ((dayOfMonth < 1) || (dayOfMonth > 31)) {
throw new IllegalArgumentException(
"DAY_OF_MONTH out of range: " + dayOfMonth);
} else if (dayOfMonth > getLengthOfMonth(year, month)) {
throw new IllegalArgumentException(
"DAY_OF_MONTH exceeds month length in given year: "
+ toString(year, month, dayOfMonth));
}
} | java | public static void checkDate(
int year,
int month,
int dayOfMonth
) {
if (year < MIN_YEAR || year > MAX_YEAR) {
throw new IllegalArgumentException(
"YEAR out of range: " + year);
} else if ((month < 1) || (month > 12)) {
throw new IllegalArgumentException(
"MONTH out of range: " + month);
} else if ((dayOfMonth < 1) || (dayOfMonth > 31)) {
throw new IllegalArgumentException(
"DAY_OF_MONTH out of range: " + dayOfMonth);
} else if (dayOfMonth > getLengthOfMonth(year, month)) {
throw new IllegalArgumentException(
"DAY_OF_MONTH exceeds month length in given year: "
+ toString(year, month, dayOfMonth));
}
} | [
"public",
"static",
"void",
"checkDate",
"(",
"int",
"year",
",",
"int",
"month",
",",
"int",
"dayOfMonth",
")",
"{",
"if",
"(",
"year",
"<",
"MIN_YEAR",
"||",
"year",
">",
"MAX_YEAR",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"YEAR out of range: \"",
"+",
"year",
")",
";",
"}",
"else",
"if",
"(",
"(",
"month",
"<",
"1",
")",
"||",
"(",
"month",
">",
"12",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"MONTH out of range: \"",
"+",
"month",
")",
";",
"}",
"else",
"if",
"(",
"(",
"dayOfMonth",
"<",
"1",
")",
"||",
"(",
"dayOfMonth",
">",
"31",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"DAY_OF_MONTH out of range: \"",
"+",
"dayOfMonth",
")",
";",
"}",
"else",
"if",
"(",
"dayOfMonth",
">",
"getLengthOfMonth",
"(",
"year",
",",
"month",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"DAY_OF_MONTH exceeds month length in given year: \"",
"+",
"toString",
"(",
"year",
",",
"month",
",",
"dayOfMonth",
")",
")",
";",
"}",
"}"
] | /*[deutsch]
<p>Überprüft die Bereichsgrenzen der Datumswerte nach
den gregorianischen Kalenderregeln. </p>
@param year proleptic iso year [(-999999999) - 999999999]
@param month gregorian month (1-12)
@param dayOfMonth day of month (1-31)
@throws IllegalArgumentException if any argument is out of range
@see #isValid(int, int, int) | [
"/",
"*",
"[",
"deutsch",
"]",
"<p",
">",
"Ü",
";",
"berprü",
";",
"ft",
"die",
"Bereichsgrenzen",
"der",
"Datumswerte",
"nach",
"den",
"gregorianischen",
"Kalenderregeln",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/MenoData/Time4J/blob/08b2eda6b2dbb140b92011cf7071bb087edd46a5/base/src/main/java/net/time4j/base/GregorianMath.java#L195-L216 |
joniles/mpxj | src/main/java/net/sf/mpxj/primavera/PrimaveraXERFileReader.java | PrimaveraXERFileReader.processFile | private void processFile(InputStream is) throws MPXJException {
"""
Reads the XER file table and row structure ready for processing.
@param is input stream
@throws MPXJException
"""
int line = 1;
try
{
//
// Test the header and extract the separator. If this is successful,
// we reset the stream back as far as we can. The design of the
// BufferedInputStream class means that we can't get back to character
// zero, so the first record we will read will get "RMHDR" rather than
// "ERMHDR" in the first field position.
//
BufferedInputStream bis = new BufferedInputStream(is);
byte[] data = new byte[6];
data[0] = (byte) bis.read();
bis.mark(1024);
bis.read(data, 1, 5);
if (!new String(data).equals("ERMHDR"))
{
throw new MPXJException(MPXJException.INVALID_FILE);
}
bis.reset();
InputStreamReader reader = new InputStreamReader(bis, getCharset());
Tokenizer tk = new ReaderTokenizer(reader);
tk.setDelimiter('\t');
List<String> record = new ArrayList<String>();
while (tk.getType() != Tokenizer.TT_EOF)
{
readRecord(tk, record);
if (!record.isEmpty())
{
if (processRecord(record))
{
break;
}
}
++line;
}
}
catch (Exception ex)
{
throw new MPXJException(MPXJException.READ_ERROR + " (failed at line " + line + ")", ex);
}
} | java | private void processFile(InputStream is) throws MPXJException
{
int line = 1;
try
{
//
// Test the header and extract the separator. If this is successful,
// we reset the stream back as far as we can. The design of the
// BufferedInputStream class means that we can't get back to character
// zero, so the first record we will read will get "RMHDR" rather than
// "ERMHDR" in the first field position.
//
BufferedInputStream bis = new BufferedInputStream(is);
byte[] data = new byte[6];
data[0] = (byte) bis.read();
bis.mark(1024);
bis.read(data, 1, 5);
if (!new String(data).equals("ERMHDR"))
{
throw new MPXJException(MPXJException.INVALID_FILE);
}
bis.reset();
InputStreamReader reader = new InputStreamReader(bis, getCharset());
Tokenizer tk = new ReaderTokenizer(reader);
tk.setDelimiter('\t');
List<String> record = new ArrayList<String>();
while (tk.getType() != Tokenizer.TT_EOF)
{
readRecord(tk, record);
if (!record.isEmpty())
{
if (processRecord(record))
{
break;
}
}
++line;
}
}
catch (Exception ex)
{
throw new MPXJException(MPXJException.READ_ERROR + " (failed at line " + line + ")", ex);
}
} | [
"private",
"void",
"processFile",
"(",
"InputStream",
"is",
")",
"throws",
"MPXJException",
"{",
"int",
"line",
"=",
"1",
";",
"try",
"{",
"//",
"// Test the header and extract the separator. If this is successful,",
"// we reset the stream back as far as we can. The design of the",
"// BufferedInputStream class means that we can't get back to character",
"// zero, so the first record we will read will get \"RMHDR\" rather than",
"// \"ERMHDR\" in the first field position.",
"//",
"BufferedInputStream",
"bis",
"=",
"new",
"BufferedInputStream",
"(",
"is",
")",
";",
"byte",
"[",
"]",
"data",
"=",
"new",
"byte",
"[",
"6",
"]",
";",
"data",
"[",
"0",
"]",
"=",
"(",
"byte",
")",
"bis",
".",
"read",
"(",
")",
";",
"bis",
".",
"mark",
"(",
"1024",
")",
";",
"bis",
".",
"read",
"(",
"data",
",",
"1",
",",
"5",
")",
";",
"if",
"(",
"!",
"new",
"String",
"(",
"data",
")",
".",
"equals",
"(",
"\"ERMHDR\"",
")",
")",
"{",
"throw",
"new",
"MPXJException",
"(",
"MPXJException",
".",
"INVALID_FILE",
")",
";",
"}",
"bis",
".",
"reset",
"(",
")",
";",
"InputStreamReader",
"reader",
"=",
"new",
"InputStreamReader",
"(",
"bis",
",",
"getCharset",
"(",
")",
")",
";",
"Tokenizer",
"tk",
"=",
"new",
"ReaderTokenizer",
"(",
"reader",
")",
";",
"tk",
".",
"setDelimiter",
"(",
"'",
"'",
")",
";",
"List",
"<",
"String",
">",
"record",
"=",
"new",
"ArrayList",
"<",
"String",
">",
"(",
")",
";",
"while",
"(",
"tk",
".",
"getType",
"(",
")",
"!=",
"Tokenizer",
".",
"TT_EOF",
")",
"{",
"readRecord",
"(",
"tk",
",",
"record",
")",
";",
"if",
"(",
"!",
"record",
".",
"isEmpty",
"(",
")",
")",
"{",
"if",
"(",
"processRecord",
"(",
"record",
")",
")",
"{",
"break",
";",
"}",
"}",
"++",
"line",
";",
"}",
"}",
"catch",
"(",
"Exception",
"ex",
")",
"{",
"throw",
"new",
"MPXJException",
"(",
"MPXJException",
".",
"READ_ERROR",
"+",
"\" (failed at line \"",
"+",
"line",
"+",
"\")\"",
",",
"ex",
")",
";",
"}",
"}"
] | Reads the XER file table and row structure ready for processing.
@param is input stream
@throws MPXJException | [
"Reads",
"the",
"XER",
"file",
"table",
"and",
"row",
"structure",
"ready",
"for",
"processing",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/primavera/PrimaveraXERFileReader.java#L258-L307 |
javagl/ND | nd-tuples/src/main/java/de/javagl/nd/tuples/j/LongTuples.java | LongTuples.asList | public static List<Long> asList(final MutableLongTuple t) {
"""
Returns a <i>view</i> on the given tuple as a list that does not
allow <i>structural</i> modifications. Changes in the list will
write through to the given tuple. Changes in the backing tuple
will be visible in the returned list. The list will not permit
<code>null</code> elements.
@param t The tuple
@return The list
@throws NullPointerException If the given tuple is <code>null</code>
"""
if (t == null)
{
throw new NullPointerException("The tuple may not be null");
}
return new AbstractList<Long>()
{
@Override
public Long get(int index)
{
return t.get(index);
}
@Override
public int size()
{
return t.getSize();
}
@Override
public Long set(int index, Long element)
{
long oldValue = t.get(index);
t.set(index, element);
return oldValue;
}
};
} | java | public static List<Long> asList(final MutableLongTuple t)
{
if (t == null)
{
throw new NullPointerException("The tuple may not be null");
}
return new AbstractList<Long>()
{
@Override
public Long get(int index)
{
return t.get(index);
}
@Override
public int size()
{
return t.getSize();
}
@Override
public Long set(int index, Long element)
{
long oldValue = t.get(index);
t.set(index, element);
return oldValue;
}
};
} | [
"public",
"static",
"List",
"<",
"Long",
">",
"asList",
"(",
"final",
"MutableLongTuple",
"t",
")",
"{",
"if",
"(",
"t",
"==",
"null",
")",
"{",
"throw",
"new",
"NullPointerException",
"(",
"\"The tuple may not be null\"",
")",
";",
"}",
"return",
"new",
"AbstractList",
"<",
"Long",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"Long",
"get",
"(",
"int",
"index",
")",
"{",
"return",
"t",
".",
"get",
"(",
"index",
")",
";",
"}",
"@",
"Override",
"public",
"int",
"size",
"(",
")",
"{",
"return",
"t",
".",
"getSize",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"Long",
"set",
"(",
"int",
"index",
",",
"Long",
"element",
")",
"{",
"long",
"oldValue",
"=",
"t",
".",
"get",
"(",
"index",
")",
";",
"t",
".",
"set",
"(",
"index",
",",
"element",
")",
";",
"return",
"oldValue",
";",
"}",
"}",
";",
"}"
] | Returns a <i>view</i> on the given tuple as a list that does not
allow <i>structural</i> modifications. Changes in the list will
write through to the given tuple. Changes in the backing tuple
will be visible in the returned list. The list will not permit
<code>null</code> elements.
@param t The tuple
@return The list
@throws NullPointerException If the given tuple is <code>null</code> | [
"Returns",
"a",
"<i",
">",
"view<",
"/",
"i",
">",
"on",
"the",
"given",
"tuple",
"as",
"a",
"list",
"that",
"does",
"not",
"allow",
"<i",
">",
"structural<",
"/",
"i",
">",
"modifications",
".",
"Changes",
"in",
"the",
"list",
"will",
"write",
"through",
"to",
"the",
"given",
"tuple",
".",
"Changes",
"in",
"the",
"backing",
"tuple",
"will",
"be",
"visible",
"in",
"the",
"returned",
"list",
".",
"The",
"list",
"will",
"not",
"permit",
"<code",
">",
"null<",
"/",
"code",
">",
"elements",
"."
] | train | https://github.com/javagl/ND/blob/bcb655aaf5fc88af6194f73a27cca079186ff559/nd-tuples/src/main/java/de/javagl/nd/tuples/j/LongTuples.java#L315-L343 |
openengsb/openengsb | components/ekb/common/src/main/java/org/openengsb/core/ekb/common/EDBConverter.java | EDBConverter.fillEDBObjectWithEngineeringObjectInformation | private void fillEDBObjectWithEngineeringObjectInformation(EDBObject object, OpenEngSBModel model)
throws IllegalAccessException {
"""
Adds to the EDBObject special entries which mark that a model is referring to other models through
OpenEngSBForeignKey annotations
"""
if (!new AdvancedModelWrapper(model).isEngineeringObject()) {
return;
}
for (Field field : model.getClass().getDeclaredFields()) {
OpenEngSBForeignKey annotation = field.getAnnotation(OpenEngSBForeignKey.class);
if (annotation == null) {
continue;
}
String value = (String) FieldUtils.readField(field, model, true);
if (value == null) {
continue;
}
value = String.format("%s/%s", ContextHolder.get().getCurrentContextId(), value);
String key = getEOReferenceStringFromAnnotation(annotation);
object.put(key, new EDBObjectEntry(key, value, String.class));
}
} | java | private void fillEDBObjectWithEngineeringObjectInformation(EDBObject object, OpenEngSBModel model)
throws IllegalAccessException {
if (!new AdvancedModelWrapper(model).isEngineeringObject()) {
return;
}
for (Field field : model.getClass().getDeclaredFields()) {
OpenEngSBForeignKey annotation = field.getAnnotation(OpenEngSBForeignKey.class);
if (annotation == null) {
continue;
}
String value = (String) FieldUtils.readField(field, model, true);
if (value == null) {
continue;
}
value = String.format("%s/%s", ContextHolder.get().getCurrentContextId(), value);
String key = getEOReferenceStringFromAnnotation(annotation);
object.put(key, new EDBObjectEntry(key, value, String.class));
}
} | [
"private",
"void",
"fillEDBObjectWithEngineeringObjectInformation",
"(",
"EDBObject",
"object",
",",
"OpenEngSBModel",
"model",
")",
"throws",
"IllegalAccessException",
"{",
"if",
"(",
"!",
"new",
"AdvancedModelWrapper",
"(",
"model",
")",
".",
"isEngineeringObject",
"(",
")",
")",
"{",
"return",
";",
"}",
"for",
"(",
"Field",
"field",
":",
"model",
".",
"getClass",
"(",
")",
".",
"getDeclaredFields",
"(",
")",
")",
"{",
"OpenEngSBForeignKey",
"annotation",
"=",
"field",
".",
"getAnnotation",
"(",
"OpenEngSBForeignKey",
".",
"class",
")",
";",
"if",
"(",
"annotation",
"==",
"null",
")",
"{",
"continue",
";",
"}",
"String",
"value",
"=",
"(",
"String",
")",
"FieldUtils",
".",
"readField",
"(",
"field",
",",
"model",
",",
"true",
")",
";",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"continue",
";",
"}",
"value",
"=",
"String",
".",
"format",
"(",
"\"%s/%s\"",
",",
"ContextHolder",
".",
"get",
"(",
")",
".",
"getCurrentContextId",
"(",
")",
",",
"value",
")",
";",
"String",
"key",
"=",
"getEOReferenceStringFromAnnotation",
"(",
"annotation",
")",
";",
"object",
".",
"put",
"(",
"key",
",",
"new",
"EDBObjectEntry",
"(",
"key",
",",
"value",
",",
"String",
".",
"class",
")",
")",
";",
"}",
"}"
] | Adds to the EDBObject special entries which mark that a model is referring to other models through
OpenEngSBForeignKey annotations | [
"Adds",
"to",
"the",
"EDBObject",
"special",
"entries",
"which",
"mark",
"that",
"a",
"model",
"is",
"referring",
"to",
"other",
"models",
"through",
"OpenEngSBForeignKey",
"annotations"
] | train | https://github.com/openengsb/openengsb/blob/d39058000707f617cd405629f9bc7f17da7b414a/components/ekb/common/src/main/java/org/openengsb/core/ekb/common/EDBConverter.java#L465-L483 |
albfernandez/itext2 | src/main/java/com/lowagie/text/pdf/BidiOrder.java | BidiOrder.getReordering | public int[] getReordering(int[] linebreaks) {
"""
Return reordering array breaking lines at offsets in linebreaks.
<p>
The reordering array maps from a visual index to a logical index.
Lines are concatenated from left to right. So for example, the
fifth character from the left on the third line is
<pre> getReordering(linebreaks)[linebreaks[1] + 4]</pre>
(linebreaks[1] is the position after the last character of the
second line, which is also the index of the first character on the
third line, and adding four gets the fifth character from the left).
<p>
The linebreaks array must include at least one value.
The values must be in strictly increasing order (no duplicates)
between 1 and the length of the text, inclusive. The last value
must be the length of the text.
@param linebreaks the offsets at which to break the paragraph.
"""
validateLineBreaks(linebreaks, textLength);
byte[] levels = getLevels(linebreaks);
return computeMultilineReordering(levels, linebreaks);
} | java | public int[] getReordering(int[] linebreaks) {
validateLineBreaks(linebreaks, textLength);
byte[] levels = getLevels(linebreaks);
return computeMultilineReordering(levels, linebreaks);
} | [
"public",
"int",
"[",
"]",
"getReordering",
"(",
"int",
"[",
"]",
"linebreaks",
")",
"{",
"validateLineBreaks",
"(",
"linebreaks",
",",
"textLength",
")",
";",
"byte",
"[",
"]",
"levels",
"=",
"getLevels",
"(",
"linebreaks",
")",
";",
"return",
"computeMultilineReordering",
"(",
"levels",
",",
"linebreaks",
")",
";",
"}"
] | Return reordering array breaking lines at offsets in linebreaks.
<p>
The reordering array maps from a visual index to a logical index.
Lines are concatenated from left to right. So for example, the
fifth character from the left on the third line is
<pre> getReordering(linebreaks)[linebreaks[1] + 4]</pre>
(linebreaks[1] is the position after the last character of the
second line, which is also the index of the first character on the
third line, and adding four gets the fifth character from the left).
<p>
The linebreaks array must include at least one value.
The values must be in strictly increasing order (no duplicates)
between 1 and the length of the text, inclusive. The last value
must be the length of the text.
@param linebreaks the offsets at which to break the paragraph. | [
"Return",
"reordering",
"array",
"breaking",
"lines",
"at",
"offsets",
"in",
"linebreaks",
".",
"<p",
">",
"The",
"reordering",
"array",
"maps",
"from",
"a",
"visual",
"index",
"to",
"a",
"logical",
"index",
".",
"Lines",
"are",
"concatenated",
"from",
"left",
"to",
"right",
".",
"So",
"for",
"example",
"the",
"fifth",
"character",
"from",
"the",
"left",
"on",
"the",
"third",
"line",
"is",
"<pre",
">",
"getReordering",
"(",
"linebreaks",
")",
"[",
"linebreaks",
"[",
"1",
"]",
"+",
"4",
"]",
"<",
"/",
"pre",
">",
"(",
"linebreaks",
"[",
"1",
"]",
"is",
"the",
"position",
"after",
"the",
"last",
"character",
"of",
"the",
"second",
"line",
"which",
"is",
"also",
"the",
"index",
"of",
"the",
"first",
"character",
"on",
"the",
"third",
"line",
"and",
"adding",
"four",
"gets",
"the",
"fifth",
"character",
"from",
"the",
"left",
")",
".",
"<p",
">",
"The",
"linebreaks",
"array",
"must",
"include",
"at",
"least",
"one",
"value",
".",
"The",
"values",
"must",
"be",
"in",
"strictly",
"increasing",
"order",
"(",
"no",
"duplicates",
")",
"between",
"1",
"and",
"the",
"length",
"of",
"the",
"text",
"inclusive",
".",
"The",
"last",
"value",
"must",
"be",
"the",
"length",
"of",
"the",
"text",
"."
] | train | https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/BidiOrder.java#L910-L916 |
gsi-upm/BeastTool | beast-tool/src/main/java/es/upm/dit/gsi/beast/mock/jade/repositoryMock/RepositoryMockAgent.java | RepositoryMockAgent.setBelief | private void setBelief(String bName, Object value) {
"""
Modifies the belief referenced by bName parameter.
@param bName
- the name of the belief to update.
@param value
- the new value for the belief
"""
introspector.setBeliefValue(this.getLocalName(), bName, value, null);
} | java | private void setBelief(String bName, Object value) {
introspector.setBeliefValue(this.getLocalName(), bName, value, null);
} | [
"private",
"void",
"setBelief",
"(",
"String",
"bName",
",",
"Object",
"value",
")",
"{",
"introspector",
".",
"setBeliefValue",
"(",
"this",
".",
"getLocalName",
"(",
")",
",",
"bName",
",",
"value",
",",
"null",
")",
";",
"}"
] | Modifies the belief referenced by bName parameter.
@param bName
- the name of the belief to update.
@param value
- the new value for the belief | [
"Modifies",
"the",
"belief",
"referenced",
"by",
"bName",
"parameter",
"."
] | train | https://github.com/gsi-upm/BeastTool/blob/cc7fdc75cb818c5d60802aaf32c27829e0ca144c/beast-tool/src/main/java/es/upm/dit/gsi/beast/mock/jade/repositoryMock/RepositoryMockAgent.java#L138-L140 |
mirage-sql/mirage | src/main/java/com/miragesql/miragesql/util/MirageUtil.java | MirageUtil.getSqlContext | public static SqlContext getSqlContext(BeanDescFactory beanDescFactory, Object param) {
"""
Returns the {@link SqlContext} instance.
@param beanDescFactory the bean descriptor factory
@param param the parameter object
@return {@link SqlContext} instance
"""
SqlContext context = new SqlContextImpl();
if (param != null) {
BeanDesc beanDesc = beanDescFactory.getBeanDesc(param);
for (int i = 0; i < beanDesc.getPropertyDescSize(); i++) {
PropertyDesc pd = beanDesc.getPropertyDesc(i);
context.addArg(pd.getPropertyName(), pd.getValue(param), pd
.getPropertyType());
}
}
return context;
} | java | public static SqlContext getSqlContext(BeanDescFactory beanDescFactory, Object param) {
SqlContext context = new SqlContextImpl();
if (param != null) {
BeanDesc beanDesc = beanDescFactory.getBeanDesc(param);
for (int i = 0; i < beanDesc.getPropertyDescSize(); i++) {
PropertyDesc pd = beanDesc.getPropertyDesc(i);
context.addArg(pd.getPropertyName(), pd.getValue(param), pd
.getPropertyType());
}
}
return context;
} | [
"public",
"static",
"SqlContext",
"getSqlContext",
"(",
"BeanDescFactory",
"beanDescFactory",
",",
"Object",
"param",
")",
"{",
"SqlContext",
"context",
"=",
"new",
"SqlContextImpl",
"(",
")",
";",
"if",
"(",
"param",
"!=",
"null",
")",
"{",
"BeanDesc",
"beanDesc",
"=",
"beanDescFactory",
".",
"getBeanDesc",
"(",
"param",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"beanDesc",
".",
"getPropertyDescSize",
"(",
")",
";",
"i",
"++",
")",
"{",
"PropertyDesc",
"pd",
"=",
"beanDesc",
".",
"getPropertyDesc",
"(",
"i",
")",
";",
"context",
".",
"addArg",
"(",
"pd",
".",
"getPropertyName",
"(",
")",
",",
"pd",
".",
"getValue",
"(",
"param",
")",
",",
"pd",
".",
"getPropertyType",
"(",
")",
")",
";",
"}",
"}",
"return",
"context",
";",
"}"
] | Returns the {@link SqlContext} instance.
@param beanDescFactory the bean descriptor factory
@param param the parameter object
@return {@link SqlContext} instance | [
"Returns",
"the",
"{",
"@link",
"SqlContext",
"}",
"instance",
"."
] | train | https://github.com/mirage-sql/mirage/blob/29a44b7ad267b5a48bc250cd0ef7d74813d46889/src/main/java/com/miragesql/miragesql/util/MirageUtil.java#L52-L65 |
legsem/legstar-core2 | legstar-base/src/main/java/com/legstar/base/type/primitive/CobolDecimalType.java | CobolDecimalType.valueOf | @SuppressWarnings("unchecked")
public static <D extends Number> D valueOf(Class < D > clazz, String str) {
"""
Given a string representation of a numeric value, convert that to the
target java Number type.
<p/>
If the target is an integer type, we trim any fractional part.
@param clazz the java Number type
@param str the string representation of a numeric value
@return the java Number obtained from the input string
@throws NumberFormatException if umber cannot be derived from the input
string
"""
if (clazz.equals(Short.class)) {
return (D) Short.valueOf(intPart(str));
} else if (clazz.equals(Integer.class)) {
return (D) Integer.valueOf(intPart(str));
} else if (clazz.equals(Long.class)) {
return (D) Long.valueOf(intPart(str));
} else if (clazz.equals(BigDecimal.class)) {
return (D) new BigDecimal(str);
} else if (clazz.equals(BigInteger.class)) {
return (D) new BigInteger(intPart(str));
}
throw new IllegalArgumentException("Unsupported java type " + clazz);
} | java | @SuppressWarnings("unchecked")
public static <D extends Number> D valueOf(Class < D > clazz, String str) {
if (clazz.equals(Short.class)) {
return (D) Short.valueOf(intPart(str));
} else if (clazz.equals(Integer.class)) {
return (D) Integer.valueOf(intPart(str));
} else if (clazz.equals(Long.class)) {
return (D) Long.valueOf(intPart(str));
} else if (clazz.equals(BigDecimal.class)) {
return (D) new BigDecimal(str);
} else if (clazz.equals(BigInteger.class)) {
return (D) new BigInteger(intPart(str));
}
throw new IllegalArgumentException("Unsupported java type " + clazz);
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"<",
"D",
"extends",
"Number",
">",
"D",
"valueOf",
"(",
"Class",
"<",
"D",
">",
"clazz",
",",
"String",
"str",
")",
"{",
"if",
"(",
"clazz",
".",
"equals",
"(",
"Short",
".",
"class",
")",
")",
"{",
"return",
"(",
"D",
")",
"Short",
".",
"valueOf",
"(",
"intPart",
"(",
"str",
")",
")",
";",
"}",
"else",
"if",
"(",
"clazz",
".",
"equals",
"(",
"Integer",
".",
"class",
")",
")",
"{",
"return",
"(",
"D",
")",
"Integer",
".",
"valueOf",
"(",
"intPart",
"(",
"str",
")",
")",
";",
"}",
"else",
"if",
"(",
"clazz",
".",
"equals",
"(",
"Long",
".",
"class",
")",
")",
"{",
"return",
"(",
"D",
")",
"Long",
".",
"valueOf",
"(",
"intPart",
"(",
"str",
")",
")",
";",
"}",
"else",
"if",
"(",
"clazz",
".",
"equals",
"(",
"BigDecimal",
".",
"class",
")",
")",
"{",
"return",
"(",
"D",
")",
"new",
"BigDecimal",
"(",
"str",
")",
";",
"}",
"else",
"if",
"(",
"clazz",
".",
"equals",
"(",
"BigInteger",
".",
"class",
")",
")",
"{",
"return",
"(",
"D",
")",
"new",
"BigInteger",
"(",
"intPart",
"(",
"str",
")",
")",
";",
"}",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Unsupported java type \"",
"+",
"clazz",
")",
";",
"}"
] | Given a string representation of a numeric value, convert that to the
target java Number type.
<p/>
If the target is an integer type, we trim any fractional part.
@param clazz the java Number type
@param str the string representation of a numeric value
@return the java Number obtained from the input string
@throws NumberFormatException if umber cannot be derived from the input
string | [
"Given",
"a",
"string",
"representation",
"of",
"a",
"numeric",
"value",
"convert",
"that",
"to",
"the",
"target",
"java",
"Number",
"type",
".",
"<p",
"/",
">",
"If",
"the",
"target",
"is",
"an",
"integer",
"type",
"we",
"trim",
"any",
"fractional",
"part",
"."
] | train | https://github.com/legsem/legstar-core2/blob/f74d25d5b2b21a2ebaaaf2162b3fb7138dca40c6/legstar-base/src/main/java/com/legstar/base/type/primitive/CobolDecimalType.java#L193-L207 |
Azure/azure-sdk-for-java | sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/BackupLongTermRetentionVaultsInner.java | BackupLongTermRetentionVaultsInner.beginCreateOrUpdateAsync | public Observable<BackupLongTermRetentionVaultInner> beginCreateOrUpdateAsync(String resourceGroupName, String serverName, String recoveryServicesVaultResourceId) {
"""
Updates a server backup long term retention vault.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@param recoveryServicesVaultResourceId The azure recovery services vault resource id
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the BackupLongTermRetentionVaultInner object
"""
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, recoveryServicesVaultResourceId).map(new Func1<ServiceResponse<BackupLongTermRetentionVaultInner>, BackupLongTermRetentionVaultInner>() {
@Override
public BackupLongTermRetentionVaultInner call(ServiceResponse<BackupLongTermRetentionVaultInner> response) {
return response.body();
}
});
} | java | public Observable<BackupLongTermRetentionVaultInner> beginCreateOrUpdateAsync(String resourceGroupName, String serverName, String recoveryServicesVaultResourceId) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, recoveryServicesVaultResourceId).map(new Func1<ServiceResponse<BackupLongTermRetentionVaultInner>, BackupLongTermRetentionVaultInner>() {
@Override
public BackupLongTermRetentionVaultInner call(ServiceResponse<BackupLongTermRetentionVaultInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"BackupLongTermRetentionVaultInner",
">",
"beginCreateOrUpdateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"serverName",
",",
"String",
"recoveryServicesVaultResourceId",
")",
"{",
"return",
"beginCreateOrUpdateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"serverName",
",",
"recoveryServicesVaultResourceId",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"BackupLongTermRetentionVaultInner",
">",
",",
"BackupLongTermRetentionVaultInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"BackupLongTermRetentionVaultInner",
"call",
"(",
"ServiceResponse",
"<",
"BackupLongTermRetentionVaultInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Updates a server backup long term retention vault.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@param recoveryServicesVaultResourceId The azure recovery services vault resource id
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the BackupLongTermRetentionVaultInner object | [
"Updates",
"a",
"server",
"backup",
"long",
"term",
"retention",
"vault",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/BackupLongTermRetentionVaultsInner.java#L279-L286 |
line/armeria | core/src/main/java/com/linecorp/armeria/client/ClientFactoryBuilder.java | ClientFactoryBuilder.socketOption | @Deprecated
public <T> ClientFactoryBuilder socketOption(ChannelOption<T> option, T value) {
"""
Sets the options of sockets created by the {@link ClientFactory}.
@deprecated Use {@link #channelOption(ChannelOption, Object)}.
"""
return channelOption(option, value);
} | java | @Deprecated
public <T> ClientFactoryBuilder socketOption(ChannelOption<T> option, T value) {
return channelOption(option, value);
} | [
"@",
"Deprecated",
"public",
"<",
"T",
">",
"ClientFactoryBuilder",
"socketOption",
"(",
"ChannelOption",
"<",
"T",
">",
"option",
",",
"T",
"value",
")",
"{",
"return",
"channelOption",
"(",
"option",
",",
"value",
")",
";",
"}"
] | Sets the options of sockets created by the {@link ClientFactory}.
@deprecated Use {@link #channelOption(ChannelOption, Object)}. | [
"Sets",
"the",
"options",
"of",
"sockets",
"created",
"by",
"the",
"{",
"@link",
"ClientFactory",
"}",
"."
] | train | https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/core/src/main/java/com/linecorp/armeria/client/ClientFactoryBuilder.java#L161-L164 |
Jasig/uPortal | uPortal-url/src/main/java/org/apereo/portal/url/UrlStringBuilder.java | UrlStringBuilder.setParameter | public UrlStringBuilder setParameter(String name, String... values) {
"""
Sets a URL parameter, replacing any existing parameter with the same name.
@param name Parameter name, can not be null
@param values Values for the parameter, null is valid
@return this
"""
this.setParameter(name, values != null ? Arrays.asList(values) : null);
return this;
} | java | public UrlStringBuilder setParameter(String name, String... values) {
this.setParameter(name, values != null ? Arrays.asList(values) : null);
return this;
} | [
"public",
"UrlStringBuilder",
"setParameter",
"(",
"String",
"name",
",",
"String",
"...",
"values",
")",
"{",
"this",
".",
"setParameter",
"(",
"name",
",",
"values",
"!=",
"null",
"?",
"Arrays",
".",
"asList",
"(",
"values",
")",
":",
"null",
")",
";",
"return",
"this",
";",
"}"
] | Sets a URL parameter, replacing any existing parameter with the same name.
@param name Parameter name, can not be null
@param values Values for the parameter, null is valid
@return this | [
"Sets",
"a",
"URL",
"parameter",
"replacing",
"any",
"existing",
"parameter",
"with",
"the",
"same",
"name",
"."
] | train | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-url/src/main/java/org/apereo/portal/url/UrlStringBuilder.java#L116-L119 |
cdk/cdk | legacy/src/main/java/org/openscience/cdk/smsd/algorithm/rgraph/CDKMCS.java | CDKMCS.queryAdjacency | private static boolean queryAdjacency(IBond bondA1, IBond bondB1, IBond bondA2, IBond bondB2) {
"""
Determines if 2 bondA1 have 1 atom in common if second is atom query AtomContainer
@param atom1 first bondA1
@param bondB1 second bondA1
@return the symbol of the common atom or "" if
the 2 bonds have no common atom
"""
IAtom atom1 = null;
IAtom atom2 = null;
if (bondA1.contains(bondB1.getBegin())) {
atom1 = bondB1.getBegin();
} else if (bondA1.contains(bondB1.getEnd())) {
atom1 = bondB1.getEnd();
}
if (bondA2.contains(bondB2.getBegin())) {
atom2 = bondB2.getBegin();
} else if (bondA2.contains(bondB2.getEnd())) {
atom2 = bondB2.getEnd();
}
if (atom1 != null && atom2 != null) {
// well, this looks fishy: the atom2 is not always atom IQueryAtom !
return ((IQueryAtom) atom2).matches(atom1);
} else {
return atom1 == null && atom2 == null;
}
} | java | private static boolean queryAdjacency(IBond bondA1, IBond bondB1, IBond bondA2, IBond bondB2) {
IAtom atom1 = null;
IAtom atom2 = null;
if (bondA1.contains(bondB1.getBegin())) {
atom1 = bondB1.getBegin();
} else if (bondA1.contains(bondB1.getEnd())) {
atom1 = bondB1.getEnd();
}
if (bondA2.contains(bondB2.getBegin())) {
atom2 = bondB2.getBegin();
} else if (bondA2.contains(bondB2.getEnd())) {
atom2 = bondB2.getEnd();
}
if (atom1 != null && atom2 != null) {
// well, this looks fishy: the atom2 is not always atom IQueryAtom !
return ((IQueryAtom) atom2).matches(atom1);
} else {
return atom1 == null && atom2 == null;
}
} | [
"private",
"static",
"boolean",
"queryAdjacency",
"(",
"IBond",
"bondA1",
",",
"IBond",
"bondB1",
",",
"IBond",
"bondA2",
",",
"IBond",
"bondB2",
")",
"{",
"IAtom",
"atom1",
"=",
"null",
";",
"IAtom",
"atom2",
"=",
"null",
";",
"if",
"(",
"bondA1",
".",
"contains",
"(",
"bondB1",
".",
"getBegin",
"(",
")",
")",
")",
"{",
"atom1",
"=",
"bondB1",
".",
"getBegin",
"(",
")",
";",
"}",
"else",
"if",
"(",
"bondA1",
".",
"contains",
"(",
"bondB1",
".",
"getEnd",
"(",
")",
")",
")",
"{",
"atom1",
"=",
"bondB1",
".",
"getEnd",
"(",
")",
";",
"}",
"if",
"(",
"bondA2",
".",
"contains",
"(",
"bondB2",
".",
"getBegin",
"(",
")",
")",
")",
"{",
"atom2",
"=",
"bondB2",
".",
"getBegin",
"(",
")",
";",
"}",
"else",
"if",
"(",
"bondA2",
".",
"contains",
"(",
"bondB2",
".",
"getEnd",
"(",
")",
")",
")",
"{",
"atom2",
"=",
"bondB2",
".",
"getEnd",
"(",
")",
";",
"}",
"if",
"(",
"atom1",
"!=",
"null",
"&&",
"atom2",
"!=",
"null",
")",
"{",
"// well, this looks fishy: the atom2 is not always atom IQueryAtom !",
"return",
"(",
"(",
"IQueryAtom",
")",
"atom2",
")",
".",
"matches",
"(",
"atom1",
")",
";",
"}",
"else",
"{",
"return",
"atom1",
"==",
"null",
"&&",
"atom2",
"==",
"null",
";",
"}",
"}"
] | Determines if 2 bondA1 have 1 atom in common if second is atom query AtomContainer
@param atom1 first bondA1
@param bondB1 second bondA1
@return the symbol of the common atom or "" if
the 2 bonds have no common atom | [
"Determines",
"if",
"2",
"bondA1",
"have",
"1",
"atom",
"in",
"common",
"if",
"second",
"is",
"atom",
"query",
"AtomContainer"
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/legacy/src/main/java/org/openscience/cdk/smsd/algorithm/rgraph/CDKMCS.java#L940-L964 |
carewebframework/carewebframework-core | org.carewebframework.help-parent/org.carewebframework.help.ohj/src/main/java/org/carewebframework/help/ohj/HelpView.java | HelpView.initTopicTree | private void initTopicTree(HelpTopicNode htnParent, List<?> children) {
"""
Initialize the topic tree. Converts the Oracle help TopicTreeNode-based tree to a
HelpTopicNode-based tree.
@param htnParent Current help topic node.
@param children List of child nodes.
"""
if (children != null) {
for (Object node : children) {
TopicTreeNode ttnChild = (TopicTreeNode) node;
Topic topic = ttnChild.getTopic();
Target target = topic.getTarget();
String source = view.getBook().getBookTitle();
URL url = null;
try {
url = target == null ? null : target.getURL();
} catch (MalformedURLException e) {}
HelpTopic ht = new HelpTopic(url, topic.getLabel(), source);
HelpTopicNode htnChild = new HelpTopicNode(ht);
htnParent.addChild(htnChild);
initTopicTree(htnChild, ttnChild);
}
}
} | java | private void initTopicTree(HelpTopicNode htnParent, List<?> children) {
if (children != null) {
for (Object node : children) {
TopicTreeNode ttnChild = (TopicTreeNode) node;
Topic topic = ttnChild.getTopic();
Target target = topic.getTarget();
String source = view.getBook().getBookTitle();
URL url = null;
try {
url = target == null ? null : target.getURL();
} catch (MalformedURLException e) {}
HelpTopic ht = new HelpTopic(url, topic.getLabel(), source);
HelpTopicNode htnChild = new HelpTopicNode(ht);
htnParent.addChild(htnChild);
initTopicTree(htnChild, ttnChild);
}
}
} | [
"private",
"void",
"initTopicTree",
"(",
"HelpTopicNode",
"htnParent",
",",
"List",
"<",
"?",
">",
"children",
")",
"{",
"if",
"(",
"children",
"!=",
"null",
")",
"{",
"for",
"(",
"Object",
"node",
":",
"children",
")",
"{",
"TopicTreeNode",
"ttnChild",
"=",
"(",
"TopicTreeNode",
")",
"node",
";",
"Topic",
"topic",
"=",
"ttnChild",
".",
"getTopic",
"(",
")",
";",
"Target",
"target",
"=",
"topic",
".",
"getTarget",
"(",
")",
";",
"String",
"source",
"=",
"view",
".",
"getBook",
"(",
")",
".",
"getBookTitle",
"(",
")",
";",
"URL",
"url",
"=",
"null",
";",
"try",
"{",
"url",
"=",
"target",
"==",
"null",
"?",
"null",
":",
"target",
".",
"getURL",
"(",
")",
";",
"}",
"catch",
"(",
"MalformedURLException",
"e",
")",
"{",
"}",
"HelpTopic",
"ht",
"=",
"new",
"HelpTopic",
"(",
"url",
",",
"topic",
".",
"getLabel",
"(",
")",
",",
"source",
")",
";",
"HelpTopicNode",
"htnChild",
"=",
"new",
"HelpTopicNode",
"(",
"ht",
")",
";",
"htnParent",
".",
"addChild",
"(",
"htnChild",
")",
";",
"initTopicTree",
"(",
"htnChild",
",",
"ttnChild",
")",
";",
"}",
"}",
"}"
] | Initialize the topic tree. Converts the Oracle help TopicTreeNode-based tree to a
HelpTopicNode-based tree.
@param htnParent Current help topic node.
@param children List of child nodes. | [
"Initialize",
"the",
"topic",
"tree",
".",
"Converts",
"the",
"Oracle",
"help",
"TopicTreeNode",
"-",
"based",
"tree",
"to",
"a",
"HelpTopicNode",
"-",
"based",
"tree",
"."
] | train | https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.help-parent/org.carewebframework.help.ohj/src/main/java/org/carewebframework/help/ohj/HelpView.java#L117-L136 |
ModeShape/modeshape | modeshape-common/src/main/java/org/modeshape/common/util/Reflection.java | Reflection.findBestMethodOnTarget | public Method findBestMethodOnTarget( String methodName,
Object... arguments ) throws NoSuchMethodException, SecurityException {
"""
Find the best method on the target class that matches the signature specified with the specified name and the list of
arguments. This method first attempts to find the method with the specified arguments; if no such method is found, a
NoSuchMethodException is thrown.
<P>
This method is unable to find methods with signatures that include both primitive arguments <i>and</i> arguments that are
instances of <code>Number</code> or its subclasses.
@param methodName the name of the method that is to be invoked.
@param arguments the array of Object instances that correspond to the arguments passed to the method.
@return the Method object that references the method that satisfies the requirements, or null if no satisfactory method
could be found.
@throws NoSuchMethodException if a matching method is not found.
@throws SecurityException if access to the information is denied.
"""
Class<?>[] argumentClasses = buildArgumentClasses(arguments);
return findBestMethodWithSignature(methodName, argumentClasses);
} | java | public Method findBestMethodOnTarget( String methodName,
Object... arguments ) throws NoSuchMethodException, SecurityException {
Class<?>[] argumentClasses = buildArgumentClasses(arguments);
return findBestMethodWithSignature(methodName, argumentClasses);
} | [
"public",
"Method",
"findBestMethodOnTarget",
"(",
"String",
"methodName",
",",
"Object",
"...",
"arguments",
")",
"throws",
"NoSuchMethodException",
",",
"SecurityException",
"{",
"Class",
"<",
"?",
">",
"[",
"]",
"argumentClasses",
"=",
"buildArgumentClasses",
"(",
"arguments",
")",
";",
"return",
"findBestMethodWithSignature",
"(",
"methodName",
",",
"argumentClasses",
")",
";",
"}"
] | Find the best method on the target class that matches the signature specified with the specified name and the list of
arguments. This method first attempts to find the method with the specified arguments; if no such method is found, a
NoSuchMethodException is thrown.
<P>
This method is unable to find methods with signatures that include both primitive arguments <i>and</i> arguments that are
instances of <code>Number</code> or its subclasses.
@param methodName the name of the method that is to be invoked.
@param arguments the array of Object instances that correspond to the arguments passed to the method.
@return the Method object that references the method that satisfies the requirements, or null if no satisfactory method
could be found.
@throws NoSuchMethodException if a matching method is not found.
@throws SecurityException if access to the information is denied. | [
"Find",
"the",
"best",
"method",
"on",
"the",
"target",
"class",
"that",
"matches",
"the",
"signature",
"specified",
"with",
"the",
"specified",
"name",
"and",
"the",
"list",
"of",
"arguments",
".",
"This",
"method",
"first",
"attempts",
"to",
"find",
"the",
"method",
"with",
"the",
"specified",
"arguments",
";",
"if",
"no",
"such",
"method",
"is",
"found",
"a",
"NoSuchMethodException",
"is",
"thrown",
".",
"<P",
">",
"This",
"method",
"is",
"unable",
"to",
"find",
"methods",
"with",
"signatures",
"that",
"include",
"both",
"primitive",
"arguments",
"<i",
">",
"and<",
"/",
"i",
">",
"arguments",
"that",
"are",
"instances",
"of",
"<code",
">",
"Number<",
"/",
"code",
">",
"or",
"its",
"subclasses",
"."
] | train | https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-common/src/main/java/org/modeshape/common/util/Reflection.java#L674-L678 |
camunda/camunda-bpm-platform | engine/src/main/java/org/camunda/bpm/engine/impl/cmd/GetActivityInstanceCmd.java | GetActivityInstanceCmd.loadChildExecutionsFromCache | protected void loadChildExecutionsFromCache(ExecutionEntity execution, List<ExecutionEntity> childExecutions) {
"""
Loads all executions that are part of this process instance tree from the dbSqlSession cache.
(optionally querying the db if a child is not already loaded.
@param execution the current root execution (already contained in childExecutions)
@param childExecutions the list in which all child executions should be collected
"""
List<ExecutionEntity> childrenOfThisExecution = execution.getExecutions();
if(childrenOfThisExecution != null) {
childExecutions.addAll(childrenOfThisExecution);
for (ExecutionEntity child : childrenOfThisExecution) {
loadChildExecutionsFromCache(child, childExecutions);
}
}
} | java | protected void loadChildExecutionsFromCache(ExecutionEntity execution, List<ExecutionEntity> childExecutions) {
List<ExecutionEntity> childrenOfThisExecution = execution.getExecutions();
if(childrenOfThisExecution != null) {
childExecutions.addAll(childrenOfThisExecution);
for (ExecutionEntity child : childrenOfThisExecution) {
loadChildExecutionsFromCache(child, childExecutions);
}
}
} | [
"protected",
"void",
"loadChildExecutionsFromCache",
"(",
"ExecutionEntity",
"execution",
",",
"List",
"<",
"ExecutionEntity",
">",
"childExecutions",
")",
"{",
"List",
"<",
"ExecutionEntity",
">",
"childrenOfThisExecution",
"=",
"execution",
".",
"getExecutions",
"(",
")",
";",
"if",
"(",
"childrenOfThisExecution",
"!=",
"null",
")",
"{",
"childExecutions",
".",
"addAll",
"(",
"childrenOfThisExecution",
")",
";",
"for",
"(",
"ExecutionEntity",
"child",
":",
"childrenOfThisExecution",
")",
"{",
"loadChildExecutionsFromCache",
"(",
"child",
",",
"childExecutions",
")",
";",
"}",
"}",
"}"
] | Loads all executions that are part of this process instance tree from the dbSqlSession cache.
(optionally querying the db if a child is not already loaded.
@param execution the current root execution (already contained in childExecutions)
@param childExecutions the list in which all child executions should be collected | [
"Loads",
"all",
"executions",
"that",
"are",
"part",
"of",
"this",
"process",
"instance",
"tree",
"from",
"the",
"dbSqlSession",
"cache",
".",
"(",
"optionally",
"querying",
"the",
"db",
"if",
"a",
"child",
"is",
"not",
"already",
"loaded",
"."
] | train | https://github.com/camunda/camunda-bpm-platform/blob/1a464fc887ef3760e53d6f91b9e5b871a0d77cc0/engine/src/main/java/org/camunda/bpm/engine/impl/cmd/GetActivityInstanceCmd.java#L392-L400 |
artikcloud/artikcloud-java | src/main/java/cloud/artik/api/MonetizationApi.java | MonetizationApi.createPricingTiers | public DeviceTypePricingTier createPricingTiers(String dtid, DeviceTypePricingTier pricingTierInfo) throws ApiException {
"""
Define devicetype's pricing tiers.
Define devicetype's pricing tiers.
@param dtid DeviceType ID (required)
@param pricingTierInfo Pricing tier info (required)
@return DeviceTypePricingTier
@throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
"""
ApiResponse<DeviceTypePricingTier> resp = createPricingTiersWithHttpInfo(dtid, pricingTierInfo);
return resp.getData();
} | java | public DeviceTypePricingTier createPricingTiers(String dtid, DeviceTypePricingTier pricingTierInfo) throws ApiException {
ApiResponse<DeviceTypePricingTier> resp = createPricingTiersWithHttpInfo(dtid, pricingTierInfo);
return resp.getData();
} | [
"public",
"DeviceTypePricingTier",
"createPricingTiers",
"(",
"String",
"dtid",
",",
"DeviceTypePricingTier",
"pricingTierInfo",
")",
"throws",
"ApiException",
"{",
"ApiResponse",
"<",
"DeviceTypePricingTier",
">",
"resp",
"=",
"createPricingTiersWithHttpInfo",
"(",
"dtid",
",",
"pricingTierInfo",
")",
";",
"return",
"resp",
".",
"getData",
"(",
")",
";",
"}"
] | Define devicetype's pricing tiers.
Define devicetype's pricing tiers.
@param dtid DeviceType ID (required)
@param pricingTierInfo Pricing tier info (required)
@return DeviceTypePricingTier
@throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body | [
"Define",
"devicetype'",
";",
"s",
"pricing",
"tiers",
".",
"Define",
"devicetype'",
";",
"s",
"pricing",
"tiers",
"."
] | train | https://github.com/artikcloud/artikcloud-java/blob/412f447573e7796ab4f685c0bdd5eb76185a365c/src/main/java/cloud/artik/api/MonetizationApi.java#L135-L138 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/date/DateTime.java | DateTime.between | public String between(Date date, DateUnit unit, BetweenFormater.Level formatLevel) {
"""
计算相差时长
@param date 对比的日期
@param unit 单位 {@link DateUnit}
@param formatLevel 格式化级别
@return 相差时长
"""
return new DateBetween(this, date).toString(formatLevel);
} | java | public String between(Date date, DateUnit unit, BetweenFormater.Level formatLevel) {
return new DateBetween(this, date).toString(formatLevel);
} | [
"public",
"String",
"between",
"(",
"Date",
"date",
",",
"DateUnit",
"unit",
",",
"BetweenFormater",
".",
"Level",
"formatLevel",
")",
"{",
"return",
"new",
"DateBetween",
"(",
"this",
",",
"date",
")",
".",
"toString",
"(",
"formatLevel",
")",
";",
"}"
] | 计算相差时长
@param date 对比的日期
@param unit 单位 {@link DateUnit}
@param formatLevel 格式化级别
@return 相差时长 | [
"计算相差时长"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/date/DateTime.java#L609-L611 |
apereo/cas | core/cas-server-core-services-authentication/src/main/java/org/apereo/cas/authentication/principal/AbstractWebApplicationServiceResponseBuilder.java | AbstractWebApplicationServiceResponseBuilder.buildPost | protected Response buildPost(final WebApplicationService service, final Map<String, String> parameters) {
"""
Build post.
@param service the service
@param parameters the parameters
@return the response
"""
return DefaultResponse.getPostResponse(service.getOriginalUrl(), parameters);
} | java | protected Response buildPost(final WebApplicationService service, final Map<String, String> parameters) {
return DefaultResponse.getPostResponse(service.getOriginalUrl(), parameters);
} | [
"protected",
"Response",
"buildPost",
"(",
"final",
"WebApplicationService",
"service",
",",
"final",
"Map",
"<",
"String",
",",
"String",
">",
"parameters",
")",
"{",
"return",
"DefaultResponse",
".",
"getPostResponse",
"(",
"service",
".",
"getOriginalUrl",
"(",
")",
",",
"parameters",
")",
";",
"}"
] | Build post.
@param service the service
@param parameters the parameters
@return the response | [
"Build",
"post",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-services-authentication/src/main/java/org/apereo/cas/authentication/principal/AbstractWebApplicationServiceResponseBuilder.java#L66-L68 |
UrielCh/ovh-java-sdk | ovh-java-sdk-ipLoadbalancing/src/main/java/net/minidev/ovh/api/ApiOvhIpLoadbalancing.java | ApiOvhIpLoadbalancing.serviceName_udp_farm_farmId_server_POST | public OvhBackendUDPServer serviceName_udp_farm_farmId_server_POST(String serviceName, Long farmId, String address, String displayName, Long port, OvhBackendCustomerServerStatusEnum status) throws IOException {
"""
Add a server to an UDP Farm
REST: POST /ipLoadbalancing/{serviceName}/udp/farm/{farmId}/server
@param status [required] Enable or disable your server
@param address [required] Address of your server
@param port [required] Port attached to your server ([1..49151]). Inherited from farm if null
@param displayName [required] Human readable name for your server, this field is for you
@param serviceName [required] The internal name of your IP load balancing
@param farmId [required] Id of your farm
API beta
"""
String qPath = "/ipLoadbalancing/{serviceName}/udp/farm/{farmId}/server";
StringBuilder sb = path(qPath, serviceName, farmId);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "address", address);
addBody(o, "displayName", displayName);
addBody(o, "port", port);
addBody(o, "status", status);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhBackendUDPServer.class);
} | java | public OvhBackendUDPServer serviceName_udp_farm_farmId_server_POST(String serviceName, Long farmId, String address, String displayName, Long port, OvhBackendCustomerServerStatusEnum status) throws IOException {
String qPath = "/ipLoadbalancing/{serviceName}/udp/farm/{farmId}/server";
StringBuilder sb = path(qPath, serviceName, farmId);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "address", address);
addBody(o, "displayName", displayName);
addBody(o, "port", port);
addBody(o, "status", status);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhBackendUDPServer.class);
} | [
"public",
"OvhBackendUDPServer",
"serviceName_udp_farm_farmId_server_POST",
"(",
"String",
"serviceName",
",",
"Long",
"farmId",
",",
"String",
"address",
",",
"String",
"displayName",
",",
"Long",
"port",
",",
"OvhBackendCustomerServerStatusEnum",
"status",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/ipLoadbalancing/{serviceName}/udp/farm/{farmId}/server\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"serviceName",
",",
"farmId",
")",
";",
"HashMap",
"<",
"String",
",",
"Object",
">",
"o",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Object",
">",
"(",
")",
";",
"addBody",
"(",
"o",
",",
"\"address\"",
",",
"address",
")",
";",
"addBody",
"(",
"o",
",",
"\"displayName\"",
",",
"displayName",
")",
";",
"addBody",
"(",
"o",
",",
"\"port\"",
",",
"port",
")",
";",
"addBody",
"(",
"o",
",",
"\"status\"",
",",
"status",
")",
";",
"String",
"resp",
"=",
"exec",
"(",
"qPath",
",",
"\"POST\"",
",",
"sb",
".",
"toString",
"(",
")",
",",
"o",
")",
";",
"return",
"convertTo",
"(",
"resp",
",",
"OvhBackendUDPServer",
".",
"class",
")",
";",
"}"
] | Add a server to an UDP Farm
REST: POST /ipLoadbalancing/{serviceName}/udp/farm/{farmId}/server
@param status [required] Enable or disable your server
@param address [required] Address of your server
@param port [required] Port attached to your server ([1..49151]). Inherited from farm if null
@param displayName [required] Human readable name for your server, this field is for you
@param serviceName [required] The internal name of your IP load balancing
@param farmId [required] Id of your farm
API beta | [
"Add",
"a",
"server",
"to",
"an",
"UDP",
"Farm"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-ipLoadbalancing/src/main/java/net/minidev/ovh/api/ApiOvhIpLoadbalancing.java#L1016-L1026 |
GCRC/nunaliit | nunaliit2-dbSec/src/main/java/ca/carleton/gcrc/dbSec/FieldSelectorScoreSubString.java | FieldSelectorScoreSubString.getQueryString | public String getQueryString(TableSchema tableSchema, Phase phase) throws Exception {
"""
/*
least(
coalesce(
nullif(
position(lower(?) IN lower(title))
,0
)
,9999
)
,coalesce(
nullif(
position(lower(?) IN lower(notes))
,0
)
,9999
)
) AS score
coalesce - The COALESCE function returns the first of its arguments that
is not null. Null is returned only if all arguments are null.
nullif - The NULLIF function returns a null value if value1 and value2
are equal; otherwise it returns value1.
"""
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
boolean first = true;
for(String fieldName : fieldNames) {
if( first ) {
pw.print("least(coalesce(nullif(position(lower(?) IN lower(");
first = false;
} else {
pw.print(")),0),9999),coalesce(nullif(position(lower(?) IN lower(");
}
pw.print(fieldName);
}
pw.print(")),0),9999))");
if( Phase.SELECT == phase ) {
pw.print(" AS score");
}
pw.flush();
return sw.toString();
} | java | public String getQueryString(TableSchema tableSchema, Phase phase) throws Exception {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
boolean first = true;
for(String fieldName : fieldNames) {
if( first ) {
pw.print("least(coalesce(nullif(position(lower(?) IN lower(");
first = false;
} else {
pw.print(")),0),9999),coalesce(nullif(position(lower(?) IN lower(");
}
pw.print(fieldName);
}
pw.print(")),0),9999))");
if( Phase.SELECT == phase ) {
pw.print(" AS score");
}
pw.flush();
return sw.toString();
} | [
"public",
"String",
"getQueryString",
"(",
"TableSchema",
"tableSchema",
",",
"Phase",
"phase",
")",
"throws",
"Exception",
"{",
"StringWriter",
"sw",
"=",
"new",
"StringWriter",
"(",
")",
";",
"PrintWriter",
"pw",
"=",
"new",
"PrintWriter",
"(",
"sw",
")",
";",
"boolean",
"first",
"=",
"true",
";",
"for",
"(",
"String",
"fieldName",
":",
"fieldNames",
")",
"{",
"if",
"(",
"first",
")",
"{",
"pw",
".",
"print",
"(",
"\"least(coalesce(nullif(position(lower(?) IN lower(\"",
")",
";",
"first",
"=",
"false",
";",
"}",
"else",
"{",
"pw",
".",
"print",
"(",
"\")),0),9999),coalesce(nullif(position(lower(?) IN lower(\"",
")",
";",
"}",
"pw",
".",
"print",
"(",
"fieldName",
")",
";",
"}",
"pw",
".",
"print",
"(",
"\")),0),9999))\"",
")",
";",
"if",
"(",
"Phase",
".",
"SELECT",
"==",
"phase",
")",
"{",
"pw",
".",
"print",
"(",
"\" AS score\"",
")",
";",
"}",
"pw",
".",
"flush",
"(",
")",
";",
"return",
"sw",
".",
"toString",
"(",
")",
";",
"}"
] | /*
least(
coalesce(
nullif(
position(lower(?) IN lower(title))
,0
)
,9999
)
,coalesce(
nullif(
position(lower(?) IN lower(notes))
,0
)
,9999
)
) AS score
coalesce - The COALESCE function returns the first of its arguments that
is not null. Null is returned only if all arguments are null.
nullif - The NULLIF function returns a null value if value1 and value2
are equal; otherwise it returns value1. | [
"/",
"*",
"least",
"(",
"coalesce",
"(",
"nullif",
"(",
"position",
"(",
"lower",
"(",
"?",
")",
"IN",
"lower",
"(",
"title",
"))",
"0",
")",
"9999",
")",
"coalesce",
"(",
"nullif",
"(",
"position",
"(",
"lower",
"(",
"?",
")",
"IN",
"lower",
"(",
"notes",
"))",
"0",
")",
"9999",
")",
")",
"AS",
"score"
] | train | https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-dbSec/src/main/java/ca/carleton/gcrc/dbSec/FieldSelectorScoreSubString.java#L109-L128 |
graphql-java/graphql-java | src/main/java/graphql/language/NodeTraverser.java | NodeTraverser.postOrder | public Object postOrder(NodeVisitor nodeVisitor, Node root) {
"""
Version of {@link #postOrder(NodeVisitor, Collection)} with one root.
@param nodeVisitor the visitor of the nodes
@param root the root node
@return the accumulation result of this traversal
"""
return postOrder(nodeVisitor, Collections.singleton(root));
} | java | public Object postOrder(NodeVisitor nodeVisitor, Node root) {
return postOrder(nodeVisitor, Collections.singleton(root));
} | [
"public",
"Object",
"postOrder",
"(",
"NodeVisitor",
"nodeVisitor",
",",
"Node",
"root",
")",
"{",
"return",
"postOrder",
"(",
"nodeVisitor",
",",
"Collections",
".",
"singleton",
"(",
"root",
")",
")",
";",
"}"
] | Version of {@link #postOrder(NodeVisitor, Collection)} with one root.
@param nodeVisitor the visitor of the nodes
@param root the root node
@return the accumulation result of this traversal | [
"Version",
"of",
"{",
"@link",
"#postOrder",
"(",
"NodeVisitor",
"Collection",
")",
"}",
"with",
"one",
"root",
"."
] | train | https://github.com/graphql-java/graphql-java/blob/9214b6044317849388bd88a14b54fc1c18c9f29f/src/main/java/graphql/language/NodeTraverser.java#L128-L130 |
osglworks/java-tool | src/main/java/org/osgl/util/FastStr.java | FastStr.equalsIgnoreCase | public boolean equalsIgnoreCase(CharSequence x) {
"""
Wrapper of {@link String#equalsIgnoreCase(String)}
@param x the char sequence to be compared
@return {@code true} if the argument is not {@code null} and it
represents an equivalent {@code String} ignoring case; {@code
false} otherwise
"""
if (x == this) return true;
if (null == x || size() != x.length()) return false;
if (isEmpty() && x.length() == 0) return true;
return regionMatches(true, 0, x, 0, size());
} | java | public boolean equalsIgnoreCase(CharSequence x) {
if (x == this) return true;
if (null == x || size() != x.length()) return false;
if (isEmpty() && x.length() == 0) return true;
return regionMatches(true, 0, x, 0, size());
} | [
"public",
"boolean",
"equalsIgnoreCase",
"(",
"CharSequence",
"x",
")",
"{",
"if",
"(",
"x",
"==",
"this",
")",
"return",
"true",
";",
"if",
"(",
"null",
"==",
"x",
"||",
"size",
"(",
")",
"!=",
"x",
".",
"length",
"(",
")",
")",
"return",
"false",
";",
"if",
"(",
"isEmpty",
"(",
")",
"&&",
"x",
".",
"length",
"(",
")",
"==",
"0",
")",
"return",
"true",
";",
"return",
"regionMatches",
"(",
"true",
",",
"0",
",",
"x",
",",
"0",
",",
"size",
"(",
")",
")",
";",
"}"
] | Wrapper of {@link String#equalsIgnoreCase(String)}
@param x the char sequence to be compared
@return {@code true} if the argument is not {@code null} and it
represents an equivalent {@code String} ignoring case; {@code
false} otherwise | [
"Wrapper",
"of",
"{",
"@link",
"String#equalsIgnoreCase",
"(",
"String",
")",
"}"
] | train | https://github.com/osglworks/java-tool/blob/8b6eee2bccb067eb32e6a7bc4a4dfef7a7d9008b/src/main/java/org/osgl/util/FastStr.java#L739-L744 |
apache/flink | flink-core/src/main/java/org/apache/flink/util/NetUtils.java | NetUtils.hostAndPortToUrlString | public static String hostAndPortToUrlString(String host, int port) throws UnknownHostException {
"""
Normalizes and encodes a hostname and port to be included in URL.
In particular, this method makes sure that IPv6 address literals have the proper
formatting to be included in URLs.
@param host The address to be included in the URL.
@param port The port for the URL address.
@return The proper URL string encoded IP address and port.
@throws java.net.UnknownHostException Thrown, if the hostname cannot be translated into a URL.
"""
return ipAddressAndPortToUrlString(InetAddress.getByName(host), port);
} | java | public static String hostAndPortToUrlString(String host, int port) throws UnknownHostException {
return ipAddressAndPortToUrlString(InetAddress.getByName(host), port);
} | [
"public",
"static",
"String",
"hostAndPortToUrlString",
"(",
"String",
"host",
",",
"int",
"port",
")",
"throws",
"UnknownHostException",
"{",
"return",
"ipAddressAndPortToUrlString",
"(",
"InetAddress",
".",
"getByName",
"(",
"host",
")",
",",
"port",
")",
";",
"}"
] | Normalizes and encodes a hostname and port to be included in URL.
In particular, this method makes sure that IPv6 address literals have the proper
formatting to be included in URLs.
@param host The address to be included in the URL.
@param port The port for the URL address.
@return The proper URL string encoded IP address and port.
@throws java.net.UnknownHostException Thrown, if the hostname cannot be translated into a URL. | [
"Normalizes",
"and",
"encodes",
"a",
"hostname",
"and",
"port",
"to",
"be",
"included",
"in",
"URL",
".",
"In",
"particular",
"this",
"method",
"makes",
"sure",
"that",
"IPv6",
"address",
"literals",
"have",
"the",
"proper",
"formatting",
"to",
"be",
"included",
"in",
"URLs",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/util/NetUtils.java#L229-L231 |
groovy/groovy-core | src/main/org/codehaus/groovy/ast/decompiled/DecompiledClassNode.java | DecompiledClassNode.getFullModifiers | private static int getFullModifiers(ClassStub data, AsmReferenceResolver resolver) {
"""
Static inner classes don't have "static" part in their own modifiers. Their containing classes have to be inspected
whether they have an inner class with the same name that's static. '$' separator convention is used to search
for parent classes.
"""
String className = data.className;
int bound = className.length();
while (bound > 0) {
int idx = className.lastIndexOf('$', bound);
if (idx > 0) {
ClassNode outerClass = resolver.resolveClassNullable(className.substring(0, idx));
if (outerClass instanceof DecompiledClassNode) {
Integer outerModifiers = ((DecompiledClassNode) outerClass).classData.innerClassModifiers.get(className.substring(idx + 1));
if (outerModifiers != null) {
return data.accessModifiers | outerModifiers;
}
}
}
bound = idx - 1;
}
return data.accessModifiers;
} | java | private static int getFullModifiers(ClassStub data, AsmReferenceResolver resolver) {
String className = data.className;
int bound = className.length();
while (bound > 0) {
int idx = className.lastIndexOf('$', bound);
if (idx > 0) {
ClassNode outerClass = resolver.resolveClassNullable(className.substring(0, idx));
if (outerClass instanceof DecompiledClassNode) {
Integer outerModifiers = ((DecompiledClassNode) outerClass).classData.innerClassModifiers.get(className.substring(idx + 1));
if (outerModifiers != null) {
return data.accessModifiers | outerModifiers;
}
}
}
bound = idx - 1;
}
return data.accessModifiers;
} | [
"private",
"static",
"int",
"getFullModifiers",
"(",
"ClassStub",
"data",
",",
"AsmReferenceResolver",
"resolver",
")",
"{",
"String",
"className",
"=",
"data",
".",
"className",
";",
"int",
"bound",
"=",
"className",
".",
"length",
"(",
")",
";",
"while",
"(",
"bound",
">",
"0",
")",
"{",
"int",
"idx",
"=",
"className",
".",
"lastIndexOf",
"(",
"'",
"'",
",",
"bound",
")",
";",
"if",
"(",
"idx",
">",
"0",
")",
"{",
"ClassNode",
"outerClass",
"=",
"resolver",
".",
"resolveClassNullable",
"(",
"className",
".",
"substring",
"(",
"0",
",",
"idx",
")",
")",
";",
"if",
"(",
"outerClass",
"instanceof",
"DecompiledClassNode",
")",
"{",
"Integer",
"outerModifiers",
"=",
"(",
"(",
"DecompiledClassNode",
")",
"outerClass",
")",
".",
"classData",
".",
"innerClassModifiers",
".",
"get",
"(",
"className",
".",
"substring",
"(",
"idx",
"+",
"1",
")",
")",
";",
"if",
"(",
"outerModifiers",
"!=",
"null",
")",
"{",
"return",
"data",
".",
"accessModifiers",
"|",
"outerModifiers",
";",
"}",
"}",
"}",
"bound",
"=",
"idx",
"-",
"1",
";",
"}",
"return",
"data",
".",
"accessModifiers",
";",
"}"
] | Static inner classes don't have "static" part in their own modifiers. Their containing classes have to be inspected
whether they have an inner class with the same name that's static. '$' separator convention is used to search
for parent classes. | [
"Static",
"inner",
"classes",
"don",
"t",
"have",
"static",
"part",
"in",
"their",
"own",
"modifiers",
".",
"Their",
"containing",
"classes",
"have",
"to",
"be",
"inspected",
"whether",
"they",
"have",
"an",
"inner",
"class",
"with",
"the",
"same",
"name",
"that",
"s",
"static",
".",
"$",
"separator",
"convention",
"is",
"used",
"to",
"search",
"for",
"parent",
"classes",
"."
] | train | https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/ast/decompiled/DecompiledClassNode.java#L51-L68 |
j-easy/easy-batch | easybatch-extensions/easybatch-quartz/src/main/java/org/easybatch/extensions/quartz/JobScheduler.java | JobScheduler.isScheduled | public boolean isScheduled(final org.easybatch.core.job.Job job) throws JobSchedulerException {
"""
Check if the given job is scheduled.
@param job the job to check
@return true if the job is scheduled, false else
@throws JobSchedulerException thrown if an exception occurs while checking if the job is scheduled
"""
String jobName = job.getName();
try {
return scheduler.checkExists(TriggerKey.triggerKey(TRIGGER_NAME_PREFIX + jobName));
} catch (SchedulerException e) {
throw new JobSchedulerException(format("Unable to check if the job '%s' is scheduled", jobName), e);
}
} | java | public boolean isScheduled(final org.easybatch.core.job.Job job) throws JobSchedulerException {
String jobName = job.getName();
try {
return scheduler.checkExists(TriggerKey.triggerKey(TRIGGER_NAME_PREFIX + jobName));
} catch (SchedulerException e) {
throw new JobSchedulerException(format("Unable to check if the job '%s' is scheduled", jobName), e);
}
} | [
"public",
"boolean",
"isScheduled",
"(",
"final",
"org",
".",
"easybatch",
".",
"core",
".",
"job",
".",
"Job",
"job",
")",
"throws",
"JobSchedulerException",
"{",
"String",
"jobName",
"=",
"job",
".",
"getName",
"(",
")",
";",
"try",
"{",
"return",
"scheduler",
".",
"checkExists",
"(",
"TriggerKey",
".",
"triggerKey",
"(",
"TRIGGER_NAME_PREFIX",
"+",
"jobName",
")",
")",
";",
"}",
"catch",
"(",
"SchedulerException",
"e",
")",
"{",
"throw",
"new",
"JobSchedulerException",
"(",
"format",
"(",
"\"Unable to check if the job '%s' is scheduled\"",
",",
"jobName",
")",
",",
"e",
")",
";",
"}",
"}"
] | Check if the given job is scheduled.
@param job the job to check
@return true if the job is scheduled, false else
@throws JobSchedulerException thrown if an exception occurs while checking if the job is scheduled | [
"Check",
"if",
"the",
"given",
"job",
"is",
"scheduled",
"."
] | train | https://github.com/j-easy/easy-batch/blob/46286e1091dae1206674e2a30e0609c31feae36c/easybatch-extensions/easybatch-quartz/src/main/java/org/easybatch/extensions/quartz/JobScheduler.java#L365-L372 |
lunarray-org/common-event | src/main/java/org/lunarray/common/event/Bus.java | Bus.addListener | public <T> void addListener(final Listener<T> listener, final Object instance) {
"""
Adds a listener.
@param listener
The listener.
@param instance
The instance associated with this listener.
@param <T>
The listener event type.
"""
final ListenerInstancePair<T> pair = new ListenerInstancePair<T>(listener, instance);
this.listeners.add(pair);
final Type observableType = GenericsUtil.getEntityGenericType(listener.getClass(), 0, Listener.class);
final Class<?> observable = GenericsUtil.guessClazz(observableType);
if (!this.cachedListeners.containsKey(observable)) {
this.cachedListeners.put(observable, new LinkedList<ListenerInstancePair<?>>());
}
for (final Map.Entry<Class<?>, List<ListenerInstancePair<?>>> entry : this.cachedListeners.entrySet()) {
final Class<?> type = entry.getKey();
if (observable.isAssignableFrom(type)) {
entry.getValue().add(pair);
}
}
} | java | public <T> void addListener(final Listener<T> listener, final Object instance) {
final ListenerInstancePair<T> pair = new ListenerInstancePair<T>(listener, instance);
this.listeners.add(pair);
final Type observableType = GenericsUtil.getEntityGenericType(listener.getClass(), 0, Listener.class);
final Class<?> observable = GenericsUtil.guessClazz(observableType);
if (!this.cachedListeners.containsKey(observable)) {
this.cachedListeners.put(observable, new LinkedList<ListenerInstancePair<?>>());
}
for (final Map.Entry<Class<?>, List<ListenerInstancePair<?>>> entry : this.cachedListeners.entrySet()) {
final Class<?> type = entry.getKey();
if (observable.isAssignableFrom(type)) {
entry.getValue().add(pair);
}
}
} | [
"public",
"<",
"T",
">",
"void",
"addListener",
"(",
"final",
"Listener",
"<",
"T",
">",
"listener",
",",
"final",
"Object",
"instance",
")",
"{",
"final",
"ListenerInstancePair",
"<",
"T",
">",
"pair",
"=",
"new",
"ListenerInstancePair",
"<",
"T",
">",
"(",
"listener",
",",
"instance",
")",
";",
"this",
".",
"listeners",
".",
"add",
"(",
"pair",
")",
";",
"final",
"Type",
"observableType",
"=",
"GenericsUtil",
".",
"getEntityGenericType",
"(",
"listener",
".",
"getClass",
"(",
")",
",",
"0",
",",
"Listener",
".",
"class",
")",
";",
"final",
"Class",
"<",
"?",
">",
"observable",
"=",
"GenericsUtil",
".",
"guessClazz",
"(",
"observableType",
")",
";",
"if",
"(",
"!",
"this",
".",
"cachedListeners",
".",
"containsKey",
"(",
"observable",
")",
")",
"{",
"this",
".",
"cachedListeners",
".",
"put",
"(",
"observable",
",",
"new",
"LinkedList",
"<",
"ListenerInstancePair",
"<",
"?",
">",
">",
"(",
")",
")",
";",
"}",
"for",
"(",
"final",
"Map",
".",
"Entry",
"<",
"Class",
"<",
"?",
">",
",",
"List",
"<",
"ListenerInstancePair",
"<",
"?",
">",
">",
">",
"entry",
":",
"this",
".",
"cachedListeners",
".",
"entrySet",
"(",
")",
")",
"{",
"final",
"Class",
"<",
"?",
">",
"type",
"=",
"entry",
".",
"getKey",
"(",
")",
";",
"if",
"(",
"observable",
".",
"isAssignableFrom",
"(",
"type",
")",
")",
"{",
"entry",
".",
"getValue",
"(",
")",
".",
"add",
"(",
"pair",
")",
";",
"}",
"}",
"}"
] | Adds a listener.
@param listener
The listener.
@param instance
The instance associated with this listener.
@param <T>
The listener event type. | [
"Adds",
"a",
"listener",
"."
] | train | https://github.com/lunarray-org/common-event/blob/a92102546d136d5f4270cfe8dbd69e4188a46202/src/main/java/org/lunarray/common/event/Bus.java#L70-L84 |
op4j/op4j | src/main/java/org/op4j/Op.java | Op.onArray | public static <T> Level0ArrayOperator<Boolean[],Boolean> onArray(final boolean[] target) {
"""
<p>
Creates an <i>operation expression</i> on the specified target object.
</p>
@param target the target object on which the expression will execute
@return an operator, ready for chaining
"""
return onArrayOf(Types.BOOLEAN, ArrayUtils.toObject(target));
} | java | public static <T> Level0ArrayOperator<Boolean[],Boolean> onArray(final boolean[] target) {
return onArrayOf(Types.BOOLEAN, ArrayUtils.toObject(target));
} | [
"public",
"static",
"<",
"T",
">",
"Level0ArrayOperator",
"<",
"Boolean",
"[",
"]",
",",
"Boolean",
">",
"onArray",
"(",
"final",
"boolean",
"[",
"]",
"target",
")",
"{",
"return",
"onArrayOf",
"(",
"Types",
".",
"BOOLEAN",
",",
"ArrayUtils",
".",
"toObject",
"(",
"target",
")",
")",
";",
"}"
] | <p>
Creates an <i>operation expression</i> on the specified target object.
</p>
@param target the target object on which the expression will execute
@return an operator, ready for chaining | [
"<p",
">",
"Creates",
"an",
"<i",
">",
"operation",
"expression<",
"/",
"i",
">",
"on",
"the",
"specified",
"target",
"object",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/op4j/op4j/blob/b577596dfe462089d3dd169666defc6de7ad289a/src/main/java/org/op4j/Op.java#L650-L652 |
rundeck/rundeck | core/src/main/java/com/dtolabs/rundeck/core/storage/StorageTreeFactory.java | StorageTreeFactory.expandConfig | private Map<String, String> expandConfig(Map<String, String> map) {
"""
Expand embedded framework property references in the map values
@param map map
@return expanded map
"""
return expandAllProperties(map, getPropertyLookup().getPropertiesMap());
} | java | private Map<String, String> expandConfig(Map<String, String> map) {
return expandAllProperties(map, getPropertyLookup().getPropertiesMap());
} | [
"private",
"Map",
"<",
"String",
",",
"String",
">",
"expandConfig",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"map",
")",
"{",
"return",
"expandAllProperties",
"(",
"map",
",",
"getPropertyLookup",
"(",
")",
".",
"getPropertiesMap",
"(",
")",
")",
";",
"}"
] | Expand embedded framework property references in the map values
@param map map
@return expanded map | [
"Expand",
"embedded",
"framework",
"property",
"references",
"in",
"the",
"map",
"values"
] | train | https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/storage/StorageTreeFactory.java#L313-L315 |
f2prateek/dart | henson/src/main/java/dart/henson/Bundler.java | Bundler.put | public Bundler put(String key, String[] value) {
"""
Inserts a String array value into the mapping of the underlying Bundle, replacing any existing
value for the given key. Either key or value may be null.
@param key a String, or null
@param value a String array object, or null
@return this bundler instance to chain method calls
"""
delegate.putStringArray(key, value);
return this;
} | java | public Bundler put(String key, String[] value) {
delegate.putStringArray(key, value);
return this;
} | [
"public",
"Bundler",
"put",
"(",
"String",
"key",
",",
"String",
"[",
"]",
"value",
")",
"{",
"delegate",
".",
"putStringArray",
"(",
"key",
",",
"value",
")",
";",
"return",
"this",
";",
"}"
] | Inserts a String array value into the mapping of the underlying Bundle, replacing any existing
value for the given key. Either key or value may be null.
@param key a String, or null
@param value a String array object, or null
@return this bundler instance to chain method calls | [
"Inserts",
"a",
"String",
"array",
"value",
"into",
"the",
"mapping",
"of",
"the",
"underlying",
"Bundle",
"replacing",
"any",
"existing",
"value",
"for",
"the",
"given",
"key",
".",
"Either",
"key",
"or",
"value",
"may",
"be",
"null",
"."
] | train | https://github.com/f2prateek/dart/blob/7163b1b148e5141817975ae7dad99d58a8589aeb/henson/src/main/java/dart/henson/Bundler.java#L179-L182 |
otto-de/edison-microservice | edison-jobs/src/main/java/de/otto/edison/jobs/definition/DefaultJobDefinition.java | DefaultJobDefinition.fixedDelayJobDefinition | public static DefaultJobDefinition fixedDelayJobDefinition(final String jobType,
final String jobName,
final String description,
final Duration fixedDelay,
final int restarts,
final Optional<Duration> maxAge) {
"""
Create a JobDefinition that is using fixed delays specify, when and how often the job should be triggered.
@param jobType The type of the Job
@param jobName A human readable name of the Job
@param description A human readable description of the Job.
@param fixedDelay The delay duration between to executions of the Job
@param restarts The number of restarts if the job failed because of errors or exceptions
@param maxAge Optional maximum age of a job. When the job is not run for longer than this duration,
a warning is displayed on the status page
@return JobDefinition
"""
return new DefaultJobDefinition(jobType, jobName, description, maxAge, Optional.of(fixedDelay), Optional.empty(), restarts, 0, Optional.empty());
} | java | public static DefaultJobDefinition fixedDelayJobDefinition(final String jobType,
final String jobName,
final String description,
final Duration fixedDelay,
final int restarts,
final Optional<Duration> maxAge) {
return new DefaultJobDefinition(jobType, jobName, description, maxAge, Optional.of(fixedDelay), Optional.empty(), restarts, 0, Optional.empty());
} | [
"public",
"static",
"DefaultJobDefinition",
"fixedDelayJobDefinition",
"(",
"final",
"String",
"jobType",
",",
"final",
"String",
"jobName",
",",
"final",
"String",
"description",
",",
"final",
"Duration",
"fixedDelay",
",",
"final",
"int",
"restarts",
",",
"final",
"Optional",
"<",
"Duration",
">",
"maxAge",
")",
"{",
"return",
"new",
"DefaultJobDefinition",
"(",
"jobType",
",",
"jobName",
",",
"description",
",",
"maxAge",
",",
"Optional",
".",
"of",
"(",
"fixedDelay",
")",
",",
"Optional",
".",
"empty",
"(",
")",
",",
"restarts",
",",
"0",
",",
"Optional",
".",
"empty",
"(",
")",
")",
";",
"}"
] | Create a JobDefinition that is using fixed delays specify, when and how often the job should be triggered.
@param jobType The type of the Job
@param jobName A human readable name of the Job
@param description A human readable description of the Job.
@param fixedDelay The delay duration between to executions of the Job
@param restarts The number of restarts if the job failed because of errors or exceptions
@param maxAge Optional maximum age of a job. When the job is not run for longer than this duration,
a warning is displayed on the status page
@return JobDefinition | [
"Create",
"a",
"JobDefinition",
"that",
"is",
"using",
"fixed",
"delays",
"specify",
"when",
"and",
"how",
"often",
"the",
"job",
"should",
"be",
"triggered",
"."
] | train | https://github.com/otto-de/edison-microservice/blob/89ecf0a0dee40977f004370b0b474a36c699e8a2/edison-jobs/src/main/java/de/otto/edison/jobs/definition/DefaultJobDefinition.java#L106-L113 |
kuali/ojb-1.0.4 | src/java/org/apache/ojb/broker/accesslayer/sql/SqlQueryStatement.java | SqlQueryStatement.ensureColumns | protected void ensureColumns(List columns, List existingColumns) {
"""
Builds the Join for columns if they are not found among the existingColumns.
@param columns the list of columns represented by Criteria.Field to ensure
@param existingColumns the list of column names (String) that are already appended
"""
if (columns == null || columns.isEmpty())
{
return;
}
Iterator iter = columns.iterator();
while (iter.hasNext())
{
FieldHelper cf = (FieldHelper) iter.next();
if (!existingColumns.contains(cf.name))
{
getAttributeInfo(cf.name, false, null, getQuery().getPathClasses());
}
}
} | java | protected void ensureColumns(List columns, List existingColumns)
{
if (columns == null || columns.isEmpty())
{
return;
}
Iterator iter = columns.iterator();
while (iter.hasNext())
{
FieldHelper cf = (FieldHelper) iter.next();
if (!existingColumns.contains(cf.name))
{
getAttributeInfo(cf.name, false, null, getQuery().getPathClasses());
}
}
} | [
"protected",
"void",
"ensureColumns",
"(",
"List",
"columns",
",",
"List",
"existingColumns",
")",
"{",
"if",
"(",
"columns",
"==",
"null",
"||",
"columns",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
";",
"}",
"Iterator",
"iter",
"=",
"columns",
".",
"iterator",
"(",
")",
";",
"while",
"(",
"iter",
".",
"hasNext",
"(",
")",
")",
"{",
"FieldHelper",
"cf",
"=",
"(",
"FieldHelper",
")",
"iter",
".",
"next",
"(",
")",
";",
"if",
"(",
"!",
"existingColumns",
".",
"contains",
"(",
"cf",
".",
"name",
")",
")",
"{",
"getAttributeInfo",
"(",
"cf",
".",
"name",
",",
"false",
",",
"null",
",",
"getQuery",
"(",
")",
".",
"getPathClasses",
"(",
")",
")",
";",
"}",
"}",
"}"
] | Builds the Join for columns if they are not found among the existingColumns.
@param columns the list of columns represented by Criteria.Field to ensure
@param existingColumns the list of column names (String) that are already appended | [
"Builds",
"the",
"Join",
"for",
"columns",
"if",
"they",
"are",
"not",
"found",
"among",
"the",
"existingColumns",
"."
] | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/accesslayer/sql/SqlQueryStatement.java#L480-L497 |
facebookarchive/hadoop-20 | src/core/org/apache/hadoop/util/ProcfsBasedProcessTree.java | ProcfsBasedProcessTree.assertAndDestroyProcessGroup | public static void assertAndDestroyProcessGroup(String pgrpId, long interval,
boolean inBackground)
throws IOException {
"""
Make sure that the given pid is a process group leader and then
destroy the process group.
@param pgrpId Process group id of to-be-killed-processes
@param interval The time to wait before sending SIGKILL
after sending SIGTERM
@param inBackground Process is to be killed in the back ground with
a separate thread
"""
// Make sure that the pid given is a process group leader
if (!checkPidPgrpidForMatch(pgrpId, PROCFS)) {
throw new IOException("Process with PID " + pgrpId +
" is not a process group leader.");
}
destroyProcessGroup(pgrpId, interval, inBackground);
} | java | public static void assertAndDestroyProcessGroup(String pgrpId, long interval,
boolean inBackground)
throws IOException {
// Make sure that the pid given is a process group leader
if (!checkPidPgrpidForMatch(pgrpId, PROCFS)) {
throw new IOException("Process with PID " + pgrpId +
" is not a process group leader.");
}
destroyProcessGroup(pgrpId, interval, inBackground);
} | [
"public",
"static",
"void",
"assertAndDestroyProcessGroup",
"(",
"String",
"pgrpId",
",",
"long",
"interval",
",",
"boolean",
"inBackground",
")",
"throws",
"IOException",
"{",
"// Make sure that the pid given is a process group leader",
"if",
"(",
"!",
"checkPidPgrpidForMatch",
"(",
"pgrpId",
",",
"PROCFS",
")",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"Process with PID \"",
"+",
"pgrpId",
"+",
"\" is not a process group leader.\"",
")",
";",
"}",
"destroyProcessGroup",
"(",
"pgrpId",
",",
"interval",
",",
"inBackground",
")",
";",
"}"
] | Make sure that the given pid is a process group leader and then
destroy the process group.
@param pgrpId Process group id of to-be-killed-processes
@param interval The time to wait before sending SIGKILL
after sending SIGTERM
@param inBackground Process is to be killed in the back ground with
a separate thread | [
"Make",
"sure",
"that",
"the",
"given",
"pid",
"is",
"a",
"process",
"group",
"leader",
"and",
"then",
"destroy",
"the",
"process",
"group",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/util/ProcfsBasedProcessTree.java#L299-L308 |
unbescape/unbescape | src/main/java/org/unbescape/csv/CsvEscape.java | CsvEscape.escapeCsv | public static void escapeCsv(final String text, final Writer writer)
throws IOException {
"""
<p>
Perform a CSV <strong>escape</strong> operation on a <tt>String</tt> input, writing results to
a <tt>Writer</tt>.
</p>
<p>
This method is <strong>thread-safe</strong>.
</p>
@param text the <tt>String</tt> to be escaped.
@param writer the <tt>java.io.Writer</tt> to which the escaped result will be written. Nothing will
be written at all to this writer if input is <tt>null</tt>.
@throws IOException if an input/output exception occurs
@since 1.1.2
"""
if (writer == null) {
throw new IllegalArgumentException("Argument 'writer' cannot be null");
}
CsvEscapeUtil.escape(new InternalStringReader(text), writer);
} | java | public static void escapeCsv(final String text, final Writer writer)
throws IOException {
if (writer == null) {
throw new IllegalArgumentException("Argument 'writer' cannot be null");
}
CsvEscapeUtil.escape(new InternalStringReader(text), writer);
} | [
"public",
"static",
"void",
"escapeCsv",
"(",
"final",
"String",
"text",
",",
"final",
"Writer",
"writer",
")",
"throws",
"IOException",
"{",
"if",
"(",
"writer",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Argument 'writer' cannot be null\"",
")",
";",
"}",
"CsvEscapeUtil",
".",
"escape",
"(",
"new",
"InternalStringReader",
"(",
"text",
")",
",",
"writer",
")",
";",
"}"
] | <p>
Perform a CSV <strong>escape</strong> operation on a <tt>String</tt> input, writing results to
a <tt>Writer</tt>.
</p>
<p>
This method is <strong>thread-safe</strong>.
</p>
@param text the <tt>String</tt> to be escaped.
@param writer the <tt>java.io.Writer</tt> to which the escaped result will be written. Nothing will
be written at all to this writer if input is <tt>null</tt>.
@throws IOException if an input/output exception occurs
@since 1.1.2 | [
"<p",
">",
"Perform",
"a",
"CSV",
"<strong",
">",
"escape<",
"/",
"strong",
">",
"operation",
"on",
"a",
"<tt",
">",
"String<",
"/",
"tt",
">",
"input",
"writing",
"results",
"to",
"a",
"<tt",
">",
"Writer<",
"/",
"tt",
">",
".",
"<",
"/",
"p",
">",
"<p",
">",
"This",
"method",
"is",
"<strong",
">",
"thread",
"-",
"safe<",
"/",
"strong",
">",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/unbescape/unbescape/blob/ec5435fb3508c2eed25d8165dc27ded2602cae13/src/main/java/org/unbescape/csv/CsvEscape.java#L157-L165 |
alkacon/opencms-core | src-modules/org/opencms/workplace/commons/CmsLock.java | CmsLock.performDialogOperation | @Override
protected boolean performDialogOperation() throws CmsException {
"""
Performs the lock/unlock/steal lock operation.<p>
@return true, if the operation was performed, otherwise false
@throws CmsException if operation is not successful
"""
//on multi resource operation display "please wait" screen
if (isMultiOperation() && !DIALOG_WAIT.equals(getParamAction())) {
return false;
}
// determine action to perform (lock, unlock, change lock)
int dialogAction = getDialogAction(getCms());
// now perform the operation on the resource(s)
Iterator<String> i = getResourceList().iterator();
while (i.hasNext()) {
String resName = i.next();
try {
performSingleResourceOperation(resName, dialogAction);
} catch (CmsException e) {
// collect exceptions to create a detailed output
addMultiOperationException(e);
}
}
// generate the error message for exception
String message;
if (dialogAction == TYPE_LOCK) {
message = Messages.ERR_LOCK_MULTI_0;
} else {
message = Messages.ERR_UNLOCK_MULTI_0;
}
checkMultiOperationException(Messages.get(), message);
return true;
} | java | @Override
protected boolean performDialogOperation() throws CmsException {
//on multi resource operation display "please wait" screen
if (isMultiOperation() && !DIALOG_WAIT.equals(getParamAction())) {
return false;
}
// determine action to perform (lock, unlock, change lock)
int dialogAction = getDialogAction(getCms());
// now perform the operation on the resource(s)
Iterator<String> i = getResourceList().iterator();
while (i.hasNext()) {
String resName = i.next();
try {
performSingleResourceOperation(resName, dialogAction);
} catch (CmsException e) {
// collect exceptions to create a detailed output
addMultiOperationException(e);
}
}
// generate the error message for exception
String message;
if (dialogAction == TYPE_LOCK) {
message = Messages.ERR_LOCK_MULTI_0;
} else {
message = Messages.ERR_UNLOCK_MULTI_0;
}
checkMultiOperationException(Messages.get(), message);
return true;
} | [
"@",
"Override",
"protected",
"boolean",
"performDialogOperation",
"(",
")",
"throws",
"CmsException",
"{",
"//on multi resource operation display \"please wait\" screen",
"if",
"(",
"isMultiOperation",
"(",
")",
"&&",
"!",
"DIALOG_WAIT",
".",
"equals",
"(",
"getParamAction",
"(",
")",
")",
")",
"{",
"return",
"false",
";",
"}",
"// determine action to perform (lock, unlock, change lock)",
"int",
"dialogAction",
"=",
"getDialogAction",
"(",
"getCms",
"(",
")",
")",
";",
"// now perform the operation on the resource(s)",
"Iterator",
"<",
"String",
">",
"i",
"=",
"getResourceList",
"(",
")",
".",
"iterator",
"(",
")",
";",
"while",
"(",
"i",
".",
"hasNext",
"(",
")",
")",
"{",
"String",
"resName",
"=",
"i",
".",
"next",
"(",
")",
";",
"try",
"{",
"performSingleResourceOperation",
"(",
"resName",
",",
"dialogAction",
")",
";",
"}",
"catch",
"(",
"CmsException",
"e",
")",
"{",
"// collect exceptions to create a detailed output",
"addMultiOperationException",
"(",
"e",
")",
";",
"}",
"}",
"// generate the error message for exception",
"String",
"message",
";",
"if",
"(",
"dialogAction",
"==",
"TYPE_LOCK",
")",
"{",
"message",
"=",
"Messages",
".",
"ERR_LOCK_MULTI_0",
";",
"}",
"else",
"{",
"message",
"=",
"Messages",
".",
"ERR_UNLOCK_MULTI_0",
";",
"}",
"checkMultiOperationException",
"(",
"Messages",
".",
"get",
"(",
")",
",",
"message",
")",
";",
"return",
"true",
";",
"}"
] | Performs the lock/unlock/steal lock operation.<p>
@return true, if the operation was performed, otherwise false
@throws CmsException if operation is not successful | [
"Performs",
"the",
"lock",
"/",
"unlock",
"/",
"steal",
"lock",
"operation",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/commons/CmsLock.java#L935-L966 |
kite-sdk/kite | kite-data/kite-data-core/src/main/java/org/kitesdk/data/spi/SchemaUtil.java | SchemaUtil.keySchema | public static Schema keySchema(Schema schema, PartitionStrategy strategy) {
"""
Creates a {@link Schema} for the keys of a {@link PartitionStrategy} based
on an entity {@code Schema}.
<p>
The partition strategy and schema are assumed to be compatible and this
will result in NullPointerExceptions if they are not.
@param schema an entity schema {@code Schema}
@param strategy a {@code PartitionStrategy}
@return a {@code Schema} for the storage keys of the partition strategy
"""
List<Schema.Field> partitionFields = new ArrayList<Schema.Field>();
for (FieldPartitioner<?, ?> fp : Accessor.getDefault().getFieldPartitioners(strategy)) {
partitionFields.add(partitionField(fp, schema));
}
Schema keySchema = Schema.createRecord(
schema.getName() + "KeySchema", null, null, false);
keySchema.setFields(partitionFields);
return keySchema;
} | java | public static Schema keySchema(Schema schema, PartitionStrategy strategy) {
List<Schema.Field> partitionFields = new ArrayList<Schema.Field>();
for (FieldPartitioner<?, ?> fp : Accessor.getDefault().getFieldPartitioners(strategy)) {
partitionFields.add(partitionField(fp, schema));
}
Schema keySchema = Schema.createRecord(
schema.getName() + "KeySchema", null, null, false);
keySchema.setFields(partitionFields);
return keySchema;
} | [
"public",
"static",
"Schema",
"keySchema",
"(",
"Schema",
"schema",
",",
"PartitionStrategy",
"strategy",
")",
"{",
"List",
"<",
"Schema",
".",
"Field",
">",
"partitionFields",
"=",
"new",
"ArrayList",
"<",
"Schema",
".",
"Field",
">",
"(",
")",
";",
"for",
"(",
"FieldPartitioner",
"<",
"?",
",",
"?",
">",
"fp",
":",
"Accessor",
".",
"getDefault",
"(",
")",
".",
"getFieldPartitioners",
"(",
"strategy",
")",
")",
"{",
"partitionFields",
".",
"add",
"(",
"partitionField",
"(",
"fp",
",",
"schema",
")",
")",
";",
"}",
"Schema",
"keySchema",
"=",
"Schema",
".",
"createRecord",
"(",
"schema",
".",
"getName",
"(",
")",
"+",
"\"KeySchema\"",
",",
"null",
",",
"null",
",",
"false",
")",
";",
"keySchema",
".",
"setFields",
"(",
"partitionFields",
")",
";",
"return",
"keySchema",
";",
"}"
] | Creates a {@link Schema} for the keys of a {@link PartitionStrategy} based
on an entity {@code Schema}.
<p>
The partition strategy and schema are assumed to be compatible and this
will result in NullPointerExceptions if they are not.
@param schema an entity schema {@code Schema}
@param strategy a {@code PartitionStrategy}
@return a {@code Schema} for the storage keys of the partition strategy | [
"Creates",
"a",
"{",
"@link",
"Schema",
"}",
"for",
"the",
"keys",
"of",
"a",
"{",
"@link",
"PartitionStrategy",
"}",
"based",
"on",
"an",
"entity",
"{",
"@code",
"Schema",
"}",
".",
"<p",
">",
"The",
"partition",
"strategy",
"and",
"schema",
"are",
"assumed",
"to",
"be",
"compatible",
"and",
"this",
"will",
"result",
"in",
"NullPointerExceptions",
"if",
"they",
"are",
"not",
"."
] | train | https://github.com/kite-sdk/kite/blob/72bfb4b1a881af85808cd7f14bc3e15160a1e811/kite-data/kite-data-core/src/main/java/org/kitesdk/data/spi/SchemaUtil.java#L272-L281 |
EdwardRaff/JSAT | JSAT/src/jsat/utils/IntPriorityQueue.java | IntPriorityQueue.swapHeapValues | private void swapHeapValues(int i, int j) {
"""
Swaps the values stored in the heap for the given indices
@param i the first index to be swapped
@param j the second index to be swapped
"""
if(fastValueRemove == Mode.HASH)
{
valueIndexMap.put(heap[i], j);
valueIndexMap.put(heap[j], i);
}
else if(fastValueRemove == Mode.BOUNDED)
{
//Already in the array, so just need to set
valueIndexStore[heap[i]] = j;
valueIndexStore[heap[j]] = i;
}
int tmp = heap[i];
heap[i] = heap[j];
heap[j] = tmp;
} | java | private void swapHeapValues(int i, int j)
{
if(fastValueRemove == Mode.HASH)
{
valueIndexMap.put(heap[i], j);
valueIndexMap.put(heap[j], i);
}
else if(fastValueRemove == Mode.BOUNDED)
{
//Already in the array, so just need to set
valueIndexStore[heap[i]] = j;
valueIndexStore[heap[j]] = i;
}
int tmp = heap[i];
heap[i] = heap[j];
heap[j] = tmp;
} | [
"private",
"void",
"swapHeapValues",
"(",
"int",
"i",
",",
"int",
"j",
")",
"{",
"if",
"(",
"fastValueRemove",
"==",
"Mode",
".",
"HASH",
")",
"{",
"valueIndexMap",
".",
"put",
"(",
"heap",
"[",
"i",
"]",
",",
"j",
")",
";",
"valueIndexMap",
".",
"put",
"(",
"heap",
"[",
"j",
"]",
",",
"i",
")",
";",
"}",
"else",
"if",
"(",
"fastValueRemove",
"==",
"Mode",
".",
"BOUNDED",
")",
"{",
"//Already in the array, so just need to set",
"valueIndexStore",
"[",
"heap",
"[",
"i",
"]",
"]",
"=",
"j",
";",
"valueIndexStore",
"[",
"heap",
"[",
"j",
"]",
"]",
"=",
"i",
";",
"}",
"int",
"tmp",
"=",
"heap",
"[",
"i",
"]",
";",
"heap",
"[",
"i",
"]",
"=",
"heap",
"[",
"j",
"]",
";",
"heap",
"[",
"j",
"]",
"=",
"tmp",
";",
"}"
] | Swaps the values stored in the heap for the given indices
@param i the first index to be swapped
@param j the second index to be swapped | [
"Swaps",
"the",
"values",
"stored",
"in",
"the",
"heap",
"for",
"the",
"given",
"indices"
] | train | https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/utils/IntPriorityQueue.java#L288-L304 |
Azure/azure-sdk-for-java | notificationhubs/resource-manager/v2016_03_01/src/main/java/com/microsoft/azure/management/notificationhubs/v2016_03_01/implementation/NotificationHubsInner.java | NotificationHubsInner.checkAvailability | public CheckAvailabilityResultInner checkAvailability(String resourceGroupName, String namespaceName, CheckAvailabilityParameters parameters) {
"""
Checks the availability of the given notificationHub in a namespace.
@param resourceGroupName The name of the resource group.
@param namespaceName The namespace name.
@param parameters The notificationHub name.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the CheckAvailabilityResultInner object if successful.
"""
return checkAvailabilityWithServiceResponseAsync(resourceGroupName, namespaceName, parameters).toBlocking().single().body();
} | java | public CheckAvailabilityResultInner checkAvailability(String resourceGroupName, String namespaceName, CheckAvailabilityParameters parameters) {
return checkAvailabilityWithServiceResponseAsync(resourceGroupName, namespaceName, parameters).toBlocking().single().body();
} | [
"public",
"CheckAvailabilityResultInner",
"checkAvailability",
"(",
"String",
"resourceGroupName",
",",
"String",
"namespaceName",
",",
"CheckAvailabilityParameters",
"parameters",
")",
"{",
"return",
"checkAvailabilityWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"namespaceName",
",",
"parameters",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
"body",
"(",
")",
";",
"}"
] | Checks the availability of the given notificationHub in a namespace.
@param resourceGroupName The name of the resource group.
@param namespaceName The namespace name.
@param parameters The notificationHub name.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the CheckAvailabilityResultInner object if successful. | [
"Checks",
"the",
"availability",
"of",
"the",
"given",
"notificationHub",
"in",
"a",
"namespace",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/notificationhubs/resource-manager/v2016_03_01/src/main/java/com/microsoft/azure/management/notificationhubs/v2016_03_01/implementation/NotificationHubsInner.java#L138-L140 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.