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
|
---|---|---|---|---|---|---|---|---|---|---|
Stratio/bdt | src/main/java/com/stratio/qa/specs/CommonG.java | CommonG.asYaml | public String asYaml(String jsonStringFile) throws JsonProcessingException, IOException, FileNotFoundException {
"""
Method to convert one json to yaml file - backup&restore functionality
<p>
File will be placed on path /target/test-classes
"""
InputStream stream = getClass().getClassLoader().getResourceAsStream(jsonStringFile);
Writer writer = new StringWriter();
char[] buffer = new char[1024];
Reader reader;
if (stream == null) {
this.getLogger().error("File does not exist: {}", jsonStringFile);
throw new FileNotFoundException("ERR! File not found: " + jsonStringFile);
}
try {
reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} catch (Exception readerexception) {
this.getLogger().error(readerexception.getMessage());
} finally {
try {
stream.close();
} catch (Exception closeException) {
this.getLogger().error(closeException.getMessage());
}
}
String text = writer.toString();
String std = text.replace("\r", "").replace("\n", ""); // make sure we have unix style text regardless of the input
// parse JSON
JsonNode jsonNodeTree = new ObjectMapper().readTree(std);
// save it as YAML
String jsonAsYaml = new YAMLMapper().writeValueAsString(jsonNodeTree);
return jsonAsYaml;
} | java | public String asYaml(String jsonStringFile) throws JsonProcessingException, IOException, FileNotFoundException {
InputStream stream = getClass().getClassLoader().getResourceAsStream(jsonStringFile);
Writer writer = new StringWriter();
char[] buffer = new char[1024];
Reader reader;
if (stream == null) {
this.getLogger().error("File does not exist: {}", jsonStringFile);
throw new FileNotFoundException("ERR! File not found: " + jsonStringFile);
}
try {
reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} catch (Exception readerexception) {
this.getLogger().error(readerexception.getMessage());
} finally {
try {
stream.close();
} catch (Exception closeException) {
this.getLogger().error(closeException.getMessage());
}
}
String text = writer.toString();
String std = text.replace("\r", "").replace("\n", ""); // make sure we have unix style text regardless of the input
// parse JSON
JsonNode jsonNodeTree = new ObjectMapper().readTree(std);
// save it as YAML
String jsonAsYaml = new YAMLMapper().writeValueAsString(jsonNodeTree);
return jsonAsYaml;
} | [
"public",
"String",
"asYaml",
"(",
"String",
"jsonStringFile",
")",
"throws",
"JsonProcessingException",
",",
"IOException",
",",
"FileNotFoundException",
"{",
"InputStream",
"stream",
"=",
"getClass",
"(",
")",
".",
"getClassLoader",
"(",
")",
".",
"getResourceAsStream",
"(",
"jsonStringFile",
")",
";",
"Writer",
"writer",
"=",
"new",
"StringWriter",
"(",
")",
";",
"char",
"[",
"]",
"buffer",
"=",
"new",
"char",
"[",
"1024",
"]",
";",
"Reader",
"reader",
";",
"if",
"(",
"stream",
"==",
"null",
")",
"{",
"this",
".",
"getLogger",
"(",
")",
".",
"error",
"(",
"\"File does not exist: {}\"",
",",
"jsonStringFile",
")",
";",
"throw",
"new",
"FileNotFoundException",
"(",
"\"ERR! File not found: \"",
"+",
"jsonStringFile",
")",
";",
"}",
"try",
"{",
"reader",
"=",
"new",
"BufferedReader",
"(",
"new",
"InputStreamReader",
"(",
"stream",
",",
"\"UTF-8\"",
")",
")",
";",
"int",
"n",
";",
"while",
"(",
"(",
"n",
"=",
"reader",
".",
"read",
"(",
"buffer",
")",
")",
"!=",
"-",
"1",
")",
"{",
"writer",
".",
"write",
"(",
"buffer",
",",
"0",
",",
"n",
")",
";",
"}",
"}",
"catch",
"(",
"Exception",
"readerexception",
")",
"{",
"this",
".",
"getLogger",
"(",
")",
".",
"error",
"(",
"readerexception",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"finally",
"{",
"try",
"{",
"stream",
".",
"close",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"closeException",
")",
"{",
"this",
".",
"getLogger",
"(",
")",
".",
"error",
"(",
"closeException",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"}",
"String",
"text",
"=",
"writer",
".",
"toString",
"(",
")",
";",
"String",
"std",
"=",
"text",
".",
"replace",
"(",
"\"\\r\"",
",",
"\"\"",
")",
".",
"replace",
"(",
"\"\\n\"",
",",
"\"\"",
")",
";",
"// make sure we have unix style text regardless of the input",
"// parse JSON",
"JsonNode",
"jsonNodeTree",
"=",
"new",
"ObjectMapper",
"(",
")",
".",
"readTree",
"(",
"std",
")",
";",
"// save it as YAML",
"String",
"jsonAsYaml",
"=",
"new",
"YAMLMapper",
"(",
")",
".",
"writeValueAsString",
"(",
"jsonNodeTree",
")",
";",
"return",
"jsonAsYaml",
";",
"}"
] | Method to convert one json to yaml file - backup&restore functionality
<p>
File will be placed on path /target/test-classes | [
"Method",
"to",
"convert",
"one",
"json",
"to",
"yaml",
"file",
"-",
"backup&restore",
"functionality",
"<p",
">",
"File",
"will",
"be",
"placed",
"on",
"path",
"/",
"target",
"/",
"test",
"-",
"classes"
] | train | https://github.com/Stratio/bdt/blob/55324d19e7497764ad3dd7139923e13eb9841d75/src/main/java/com/stratio/qa/specs/CommonG.java#L2068-L2105 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/concurrent/locks/LockSupport.java | LockSupport.parkUntil | public static void parkUntil(Object blocker, long deadline) {
"""
Disables the current thread for thread scheduling purposes, until
the specified deadline, unless the permit is available.
<p>If the permit is available then it is consumed and the call
returns immediately; otherwise the current thread becomes disabled
for thread scheduling purposes and lies dormant until one of four
things happens:
<ul>
<li>Some other thread invokes {@link #unpark unpark} with the
current thread as the target; or
<li>Some other thread {@linkplain Thread#interrupt interrupts} the
current thread; or
<li>The specified deadline passes; or
<li>The call spuriously (that is, for no reason) returns.
</ul>
<p>This method does <em>not</em> report which of these caused the
method to return. Callers should re-check the conditions which caused
the thread to park in the first place. Callers may also determine,
for example, the interrupt status of the thread, or the current time
upon return.
@param blocker the synchronization object responsible for this
thread parking
@param deadline the absolute time, in milliseconds from the Epoch,
to wait until
@since 1.6
"""
Thread t = Thread.currentThread();
setBlocker(t, blocker);
U.park(true, deadline);
setBlocker(t, null);
} | java | public static void parkUntil(Object blocker, long deadline) {
Thread t = Thread.currentThread();
setBlocker(t, blocker);
U.park(true, deadline);
setBlocker(t, null);
} | [
"public",
"static",
"void",
"parkUntil",
"(",
"Object",
"blocker",
",",
"long",
"deadline",
")",
"{",
"Thread",
"t",
"=",
"Thread",
".",
"currentThread",
"(",
")",
";",
"setBlocker",
"(",
"t",
",",
"blocker",
")",
";",
"U",
".",
"park",
"(",
"true",
",",
"deadline",
")",
";",
"setBlocker",
"(",
"t",
",",
"null",
")",
";",
"}"
] | Disables the current thread for thread scheduling purposes, until
the specified deadline, unless the permit is available.
<p>If the permit is available then it is consumed and the call
returns immediately; otherwise the current thread becomes disabled
for thread scheduling purposes and lies dormant until one of four
things happens:
<ul>
<li>Some other thread invokes {@link #unpark unpark} with the
current thread as the target; or
<li>Some other thread {@linkplain Thread#interrupt interrupts} the
current thread; or
<li>The specified deadline passes; or
<li>The call spuriously (that is, for no reason) returns.
</ul>
<p>This method does <em>not</em> report which of these caused the
method to return. Callers should re-check the conditions which caused
the thread to park in the first place. Callers may also determine,
for example, the interrupt status of the thread, or the current time
upon return.
@param blocker the synchronization object responsible for this
thread parking
@param deadline the absolute time, in milliseconds from the Epoch,
to wait until
@since 1.6 | [
"Disables",
"the",
"current",
"thread",
"for",
"thread",
"scheduling",
"purposes",
"until",
"the",
"specified",
"deadline",
"unless",
"the",
"permit",
"is",
"available",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/concurrent/locks/LockSupport.java#L271-L276 |
Azure/azure-sdk-for-java | keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java | KeyVaultClientBaseImpl.unwrapKey | public KeyOperationResult unwrapKey(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) {
"""
Unwraps a symmetric key using the specified key that was initially used for wrapping that key.
The UNWRAP operation supports decryption of a symmetric key using the target key encryption key. This operation is the reverse of the WRAP operation. The UNWRAP operation applies to asymmetric and symmetric keys stored in Azure Key Vault since it uses the private portion of the key. This operation requires the keys/unwrapKey permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param keyName The name of the key.
@param keyVersion The version of the key.
@param algorithm algorithm identifier. Possible values include: 'RSA-OAEP', 'RSA-OAEP-256', 'RSA1_5'
@param value the Base64Url value
@throws IllegalArgumentException thrown if parameters fail the validation
@throws KeyVaultErrorException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the KeyOperationResult object if successful.
"""
return unwrapKeyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value).toBlocking().single().body();
} | java | public KeyOperationResult unwrapKey(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) {
return unwrapKeyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value).toBlocking().single().body();
} | [
"public",
"KeyOperationResult",
"unwrapKey",
"(",
"String",
"vaultBaseUrl",
",",
"String",
"keyName",
",",
"String",
"keyVersion",
",",
"JsonWebKeyEncryptionAlgorithm",
"algorithm",
",",
"byte",
"[",
"]",
"value",
")",
"{",
"return",
"unwrapKeyWithServiceResponseAsync",
"(",
"vaultBaseUrl",
",",
"keyName",
",",
"keyVersion",
",",
"algorithm",
",",
"value",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
"body",
"(",
")",
";",
"}"
] | Unwraps a symmetric key using the specified key that was initially used for wrapping that key.
The UNWRAP operation supports decryption of a symmetric key using the target key encryption key. This operation is the reverse of the WRAP operation. The UNWRAP operation applies to asymmetric and symmetric keys stored in Azure Key Vault since it uses the private portion of the key. This operation requires the keys/unwrapKey permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param keyName The name of the key.
@param keyVersion The version of the key.
@param algorithm algorithm identifier. Possible values include: 'RSA-OAEP', 'RSA-OAEP-256', 'RSA1_5'
@param value the Base64Url value
@throws IllegalArgumentException thrown if parameters fail the validation
@throws KeyVaultErrorException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the KeyOperationResult object if successful. | [
"Unwraps",
"a",
"symmetric",
"key",
"using",
"the",
"specified",
"key",
"that",
"was",
"initially",
"used",
"for",
"wrapping",
"that",
"key",
".",
"The",
"UNWRAP",
"operation",
"supports",
"decryption",
"of",
"a",
"symmetric",
"key",
"using",
"the",
"target",
"key",
"encryption",
"key",
".",
"This",
"operation",
"is",
"the",
"reverse",
"of",
"the",
"WRAP",
"operation",
".",
"The",
"UNWRAP",
"operation",
"applies",
"to",
"asymmetric",
"and",
"symmetric",
"keys",
"stored",
"in",
"Azure",
"Key",
"Vault",
"since",
"it",
"uses",
"the",
"private",
"portion",
"of",
"the",
"key",
".",
"This",
"operation",
"requires",
"the",
"keys",
"/",
"unwrapKey",
"permission",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L2714-L2716 |
ManfredTremmel/gwt-commons-lang3 | src/main/java/org/apache/commons/lang3/StringUtils.java | StringUtils.getJaroWinklerDistance | @Deprecated
public static double getJaroWinklerDistance(final CharSequence first, final CharSequence second) {
"""
<p>Find the Jaro Winkler Distance which indicates the similarity score between two Strings.</p>
<p>The Jaro measure is the weighted sum of percentage of matched characters from each file and transposed characters.
Winkler increased this measure for matching initial characters.</p>
<p>This implementation is based on the Jaro Winkler similarity algorithm
from <a href="http://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance">http://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance</a>.</p>
<pre>
StringUtils.getJaroWinklerDistance(null, null) = IllegalArgumentException
StringUtils.getJaroWinklerDistance("","") = 0.0
StringUtils.getJaroWinklerDistance("","a") = 0.0
StringUtils.getJaroWinklerDistance("aaapppp", "") = 0.0
StringUtils.getJaroWinklerDistance("frog", "fog") = 0.93
StringUtils.getJaroWinklerDistance("fly", "ant") = 0.0
StringUtils.getJaroWinklerDistance("elephant", "hippo") = 0.44
StringUtils.getJaroWinklerDistance("hippo", "elephant") = 0.44
StringUtils.getJaroWinklerDistance("hippo", "zzzzzzzz") = 0.0
StringUtils.getJaroWinklerDistance("hello", "hallo") = 0.88
StringUtils.getJaroWinklerDistance("ABC Corporation", "ABC Corp") = 0.93
StringUtils.getJaroWinklerDistance("D N H Enterprises Inc", "D & H Enterprises, Inc.") = 0.95
StringUtils.getJaroWinklerDistance("My Gym Children's Fitness Center", "My Gym. Childrens Fitness") = 0.92
StringUtils.getJaroWinklerDistance("PENNSYLVANIA", "PENNCISYLVNIA") = 0.88
</pre>
@param first the first String, must not be null
@param second the second String, must not be null
@return result distance
@throws IllegalArgumentException if either String input {@code null}
@since 3.3
@deprecated as of 3.6, use commons-text
<a href="https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/similarity/JaroWinklerDistance.html">
JaroWinklerDistance</a> instead
"""
final double DEFAULT_SCALING_FACTOR = 0.1;
if (first == null || second == null) {
throw new IllegalArgumentException("Strings must not be null");
}
final int[] mtp = matches(first, second);
final double m = mtp[0];
if (m == 0) {
return 0D;
}
final double j = ((m / first.length() + m / second.length() + (m - mtp[1]) / m)) / 3;
final double jw = j < 0.7D ? j : j + Math.min(DEFAULT_SCALING_FACTOR, 1D / mtp[3]) * mtp[2] * (1D - j);
return Math.round(jw * 100.0D) / 100.0D;
} | java | @Deprecated
public static double getJaroWinklerDistance(final CharSequence first, final CharSequence second) {
final double DEFAULT_SCALING_FACTOR = 0.1;
if (first == null || second == null) {
throw new IllegalArgumentException("Strings must not be null");
}
final int[] mtp = matches(first, second);
final double m = mtp[0];
if (m == 0) {
return 0D;
}
final double j = ((m / first.length() + m / second.length() + (m - mtp[1]) / m)) / 3;
final double jw = j < 0.7D ? j : j + Math.min(DEFAULT_SCALING_FACTOR, 1D / mtp[3]) * mtp[2] * (1D - j);
return Math.round(jw * 100.0D) / 100.0D;
} | [
"@",
"Deprecated",
"public",
"static",
"double",
"getJaroWinklerDistance",
"(",
"final",
"CharSequence",
"first",
",",
"final",
"CharSequence",
"second",
")",
"{",
"final",
"double",
"DEFAULT_SCALING_FACTOR",
"=",
"0.1",
";",
"if",
"(",
"first",
"==",
"null",
"||",
"second",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Strings must not be null\"",
")",
";",
"}",
"final",
"int",
"[",
"]",
"mtp",
"=",
"matches",
"(",
"first",
",",
"second",
")",
";",
"final",
"double",
"m",
"=",
"mtp",
"[",
"0",
"]",
";",
"if",
"(",
"m",
"==",
"0",
")",
"{",
"return",
"0D",
";",
"}",
"final",
"double",
"j",
"=",
"(",
"(",
"m",
"/",
"first",
".",
"length",
"(",
")",
"+",
"m",
"/",
"second",
".",
"length",
"(",
")",
"+",
"(",
"m",
"-",
"mtp",
"[",
"1",
"]",
")",
"/",
"m",
")",
")",
"/",
"3",
";",
"final",
"double",
"jw",
"=",
"j",
"<",
"0.7D",
"?",
"j",
":",
"j",
"+",
"Math",
".",
"min",
"(",
"DEFAULT_SCALING_FACTOR",
",",
"1D",
"/",
"mtp",
"[",
"3",
"]",
")",
"*",
"mtp",
"[",
"2",
"]",
"*",
"(",
"1D",
"-",
"j",
")",
";",
"return",
"Math",
".",
"round",
"(",
"jw",
"*",
"100.0D",
")",
"/",
"100.0D",
";",
"}"
] | <p>Find the Jaro Winkler Distance which indicates the similarity score between two Strings.</p>
<p>The Jaro measure is the weighted sum of percentage of matched characters from each file and transposed characters.
Winkler increased this measure for matching initial characters.</p>
<p>This implementation is based on the Jaro Winkler similarity algorithm
from <a href="http://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance">http://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance</a>.</p>
<pre>
StringUtils.getJaroWinklerDistance(null, null) = IllegalArgumentException
StringUtils.getJaroWinklerDistance("","") = 0.0
StringUtils.getJaroWinklerDistance("","a") = 0.0
StringUtils.getJaroWinklerDistance("aaapppp", "") = 0.0
StringUtils.getJaroWinklerDistance("frog", "fog") = 0.93
StringUtils.getJaroWinklerDistance("fly", "ant") = 0.0
StringUtils.getJaroWinklerDistance("elephant", "hippo") = 0.44
StringUtils.getJaroWinklerDistance("hippo", "elephant") = 0.44
StringUtils.getJaroWinklerDistance("hippo", "zzzzzzzz") = 0.0
StringUtils.getJaroWinklerDistance("hello", "hallo") = 0.88
StringUtils.getJaroWinklerDistance("ABC Corporation", "ABC Corp") = 0.93
StringUtils.getJaroWinklerDistance("D N H Enterprises Inc", "D & H Enterprises, Inc.") = 0.95
StringUtils.getJaroWinklerDistance("My Gym Children's Fitness Center", "My Gym. Childrens Fitness") = 0.92
StringUtils.getJaroWinklerDistance("PENNSYLVANIA", "PENNCISYLVNIA") = 0.88
</pre>
@param first the first String, must not be null
@param second the second String, must not be null
@return result distance
@throws IllegalArgumentException if either String input {@code null}
@since 3.3
@deprecated as of 3.6, use commons-text
<a href="https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/similarity/JaroWinklerDistance.html">
JaroWinklerDistance</a> instead | [
"<p",
">",
"Find",
"the",
"Jaro",
"Winkler",
"Distance",
"which",
"indicates",
"the",
"similarity",
"score",
"between",
"two",
"Strings",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/StringUtils.java#L8303-L8319 |
mebigfatguy/fb-contrib | src/main/java/com/mebigfatguy/fbcontrib/detect/OverlyConcreteParameter.java | OverlyConcreteParameter.methodIsSpecial | private static boolean methodIsSpecial(String methodName, String methodSig) {
"""
determines whether the method is a baked in special method of the jdk
@param methodName the method name to check
@param methodSig the parameter signature of the method to check
@return if it is a well known baked in method
"""
return SignatureBuilder.SIG_READ_OBJECT.equals(methodName + methodSig);
} | java | private static boolean methodIsSpecial(String methodName, String methodSig) {
return SignatureBuilder.SIG_READ_OBJECT.equals(methodName + methodSig);
} | [
"private",
"static",
"boolean",
"methodIsSpecial",
"(",
"String",
"methodName",
",",
"String",
"methodSig",
")",
"{",
"return",
"SignatureBuilder",
".",
"SIG_READ_OBJECT",
".",
"equals",
"(",
"methodName",
"+",
"methodSig",
")",
";",
"}"
] | determines whether the method is a baked in special method of the jdk
@param methodName the method name to check
@param methodSig the parameter signature of the method to check
@return if it is a well known baked in method | [
"determines",
"whether",
"the",
"method",
"is",
"a",
"baked",
"in",
"special",
"method",
"of",
"the",
"jdk"
] | train | https://github.com/mebigfatguy/fb-contrib/blob/3b5203196f627b399fbcea3c2ab2b1f4e56cc7b8/src/main/java/com/mebigfatguy/fbcontrib/detect/OverlyConcreteParameter.java#L357-L359 |
powermock/powermock | powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java | PowerMock.expectNew | public static synchronized <T> IExpectationSetters<T> expectNew(Class<T> type, Class<?>[] parameterTypes,
Object... arguments) throws Exception {
"""
Allows specifying expectations on new invocations. For example you might
want to throw an exception or return a mock. Note that you must replay
the class when using this method since this behavior is part of the class
mock.
<p/>
Use this method when you need to specify parameter types for the
constructor when PowerMock cannot determine which constructor to use
automatically. In most cases you should use
{@link #expectNew(Class, Object...)} instead.
"""
return doExpectNew(type, new DefaultMockStrategy(), parameterTypes, arguments);
} | java | public static synchronized <T> IExpectationSetters<T> expectNew(Class<T> type, Class<?>[] parameterTypes,
Object... arguments) throws Exception {
return doExpectNew(type, new DefaultMockStrategy(), parameterTypes, arguments);
} | [
"public",
"static",
"synchronized",
"<",
"T",
">",
"IExpectationSetters",
"<",
"T",
">",
"expectNew",
"(",
"Class",
"<",
"T",
">",
"type",
",",
"Class",
"<",
"?",
">",
"[",
"]",
"parameterTypes",
",",
"Object",
"...",
"arguments",
")",
"throws",
"Exception",
"{",
"return",
"doExpectNew",
"(",
"type",
",",
"new",
"DefaultMockStrategy",
"(",
")",
",",
"parameterTypes",
",",
"arguments",
")",
";",
"}"
] | Allows specifying expectations on new invocations. For example you might
want to throw an exception or return a mock. Note that you must replay
the class when using this method since this behavior is part of the class
mock.
<p/>
Use this method when you need to specify parameter types for the
constructor when PowerMock cannot determine which constructor to use
automatically. In most cases you should use
{@link #expectNew(Class, Object...)} instead. | [
"Allows",
"specifying",
"expectations",
"on",
"new",
"invocations",
".",
"For",
"example",
"you",
"might",
"want",
"to",
"throw",
"an",
"exception",
"or",
"return",
"a",
"mock",
".",
"Note",
"that",
"you",
"must",
"replay",
"the",
"class",
"when",
"using",
"this",
"method",
"since",
"this",
"behavior",
"is",
"part",
"of",
"the",
"class",
"mock",
".",
"<p",
"/",
">",
"Use",
"this",
"method",
"when",
"you",
"need",
"to",
"specify",
"parameter",
"types",
"for",
"the",
"constructor",
"when",
"PowerMock",
"cannot",
"determine",
"which",
"constructor",
"to",
"use",
"automatically",
".",
"In",
"most",
"cases",
"you",
"should",
"use",
"{"
] | train | https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java#L1615-L1618 |
xcesco/kripton | kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/grammars/jql/JQLBuilder.java | JQLBuilder.isInSet | private static boolean isInSet(String value, Set<JQLPlaceHolder> parametersUsedInWhereConditions) {
"""
Checks if is in set.
@param value
the value
@param parametersUsedInWhereConditions
the parameters used in where conditions
@return true, if is in set
"""
for (JQLPlaceHolder ph : parametersUsedInWhereConditions) {
if (ph.value.equals(value))
return true;
}
return false;
} | java | private static boolean isInSet(String value, Set<JQLPlaceHolder> parametersUsedInWhereConditions) {
for (JQLPlaceHolder ph : parametersUsedInWhereConditions) {
if (ph.value.equals(value))
return true;
}
return false;
} | [
"private",
"static",
"boolean",
"isInSet",
"(",
"String",
"value",
",",
"Set",
"<",
"JQLPlaceHolder",
">",
"parametersUsedInWhereConditions",
")",
"{",
"for",
"(",
"JQLPlaceHolder",
"ph",
":",
"parametersUsedInWhereConditions",
")",
"{",
"if",
"(",
"ph",
".",
"value",
".",
"equals",
"(",
"value",
")",
")",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] | Checks if is in set.
@param value
the value
@param parametersUsedInWhereConditions
the parameters used in where conditions
@return true, if is in set | [
"Checks",
"if",
"is",
"in",
"set",
"."
] | train | https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/grammars/jql/JQLBuilder.java#L876-L882 |
NordicSemiconductor/Android-DFU-Library | dfu/src/main/java/no/nordicsemi/android/dfu/DfuServiceListenerHelper.java | DfuServiceListenerHelper.unregisterProgressListener | public static void unregisterProgressListener(@NonNull final Context context, @NonNull final DfuProgressListener listener) {
"""
Unregisters the previously registered progress listener.
@param context the application context.
@param listener the listener to unregister.
"""
if (mProgressBroadcastReceiver != null) {
final boolean empty = mProgressBroadcastReceiver.removeProgressListener(listener);
if (empty) {
LocalBroadcastManager.getInstance(context).unregisterReceiver(mProgressBroadcastReceiver);
mProgressBroadcastReceiver = null;
}
}
} | java | public static void unregisterProgressListener(@NonNull final Context context, @NonNull final DfuProgressListener listener) {
if (mProgressBroadcastReceiver != null) {
final boolean empty = mProgressBroadcastReceiver.removeProgressListener(listener);
if (empty) {
LocalBroadcastManager.getInstance(context).unregisterReceiver(mProgressBroadcastReceiver);
mProgressBroadcastReceiver = null;
}
}
} | [
"public",
"static",
"void",
"unregisterProgressListener",
"(",
"@",
"NonNull",
"final",
"Context",
"context",
",",
"@",
"NonNull",
"final",
"DfuProgressListener",
"listener",
")",
"{",
"if",
"(",
"mProgressBroadcastReceiver",
"!=",
"null",
")",
"{",
"final",
"boolean",
"empty",
"=",
"mProgressBroadcastReceiver",
".",
"removeProgressListener",
"(",
"listener",
")",
";",
"if",
"(",
"empty",
")",
"{",
"LocalBroadcastManager",
".",
"getInstance",
"(",
"context",
")",
".",
"unregisterReceiver",
"(",
"mProgressBroadcastReceiver",
")",
";",
"mProgressBroadcastReceiver",
"=",
"null",
";",
"}",
"}",
"}"
] | Unregisters the previously registered progress listener.
@param context the application context.
@param listener the listener to unregister. | [
"Unregisters",
"the",
"previously",
"registered",
"progress",
"listener",
"."
] | train | https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/DfuServiceListenerHelper.java#L324-L333 |
aws/aws-sdk-java | aws-java-sdk-greengrass/src/main/java/com/amazonaws/services/greengrass/model/GetSubscriptionDefinitionResult.java | GetSubscriptionDefinitionResult.withTags | public GetSubscriptionDefinitionResult withTags(java.util.Map<String, String> tags) {
"""
The tags for the definition.
@param tags
The tags for the definition.
@return Returns a reference to this object so that method calls can be chained together.
"""
setTags(tags);
return this;
} | java | public GetSubscriptionDefinitionResult withTags(java.util.Map<String, String> tags) {
setTags(tags);
return this;
} | [
"public",
"GetSubscriptionDefinitionResult",
"withTags",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"tags",
")",
"{",
"setTags",
"(",
"tags",
")",
";",
"return",
"this",
";",
"}"
] | The tags for the definition.
@param tags
The tags for the definition.
@return Returns a reference to this object so that method calls can be chained together. | [
"The",
"tags",
"for",
"the",
"definition",
"."
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-greengrass/src/main/java/com/amazonaws/services/greengrass/model/GetSubscriptionDefinitionResult.java#L310-L313 |
raydac/java-binary-block-parser | jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPDslBuilder.java | JBBPDslBuilder.Bits | public JBBPDslBuilder Bits(final String name, final String bitLenExpression) {
"""
Add named bit field which length calculated by expression.
@param name name of the field, if null then anonymous one
@param bitLenExpression expression to calculate number of bits, must not be null
@return the builder instance, must not be null
"""
final Item item = new Item(BinType.BIT, name, this.byteOrder);
item.bitLenExpression = assertExpressionChars(bitLenExpression);
this.addItem(item);
return this;
} | java | public JBBPDslBuilder Bits(final String name, final String bitLenExpression) {
final Item item = new Item(BinType.BIT, name, this.byteOrder);
item.bitLenExpression = assertExpressionChars(bitLenExpression);
this.addItem(item);
return this;
} | [
"public",
"JBBPDslBuilder",
"Bits",
"(",
"final",
"String",
"name",
",",
"final",
"String",
"bitLenExpression",
")",
"{",
"final",
"Item",
"item",
"=",
"new",
"Item",
"(",
"BinType",
".",
"BIT",
",",
"name",
",",
"this",
".",
"byteOrder",
")",
";",
"item",
".",
"bitLenExpression",
"=",
"assertExpressionChars",
"(",
"bitLenExpression",
")",
";",
"this",
".",
"addItem",
"(",
"item",
")",
";",
"return",
"this",
";",
"}"
] | Add named bit field which length calculated by expression.
@param name name of the field, if null then anonymous one
@param bitLenExpression expression to calculate number of bits, must not be null
@return the builder instance, must not be null | [
"Add",
"named",
"bit",
"field",
"which",
"length",
"calculated",
"by",
"expression",
"."
] | train | https://github.com/raydac/java-binary-block-parser/blob/6d98abcab01e0c72d525ebcc9e7b694f9ce49f5b/jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPDslBuilder.java#L650-L655 |
Swagger2Markup/swagger2markup | src/main/java/io/github/swagger2markup/internal/document/PathsDocument.java | PathsDocument.buildOperation | private void buildOperation(MarkupDocBuilder markupDocBuilder, PathOperation operation, Swagger2MarkupConfig config) {
"""
Builds a path operation depending on generation mode.
@param operation operation
"""
if (config.isSeparatedOperationsEnabled()) {
MarkupDocBuilder pathDocBuilder = copyMarkupDocBuilder(markupDocBuilder);
applyPathOperationComponent(pathDocBuilder, operation);
java.nio.file.Path operationFile = context.getOutputPath().resolve(operationDocumentNameResolver.apply(operation));
pathDocBuilder.writeToFileWithoutExtension(operationFile, StandardCharsets.UTF_8);
if (logger.isDebugEnabled()) {
logger.debug("Separate operation file produced : '{}'", operationFile);
}
buildOperationRef(markupDocBuilder, operation);
} else {
applyPathOperationComponent(markupDocBuilder, operation);
}
if (logger.isDebugEnabled()) {
logger.debug("Operation processed : '{}' (normalized id = '{}')", operation, normalizeName(operation.getId()));
}
} | java | private void buildOperation(MarkupDocBuilder markupDocBuilder, PathOperation operation, Swagger2MarkupConfig config) {
if (config.isSeparatedOperationsEnabled()) {
MarkupDocBuilder pathDocBuilder = copyMarkupDocBuilder(markupDocBuilder);
applyPathOperationComponent(pathDocBuilder, operation);
java.nio.file.Path operationFile = context.getOutputPath().resolve(operationDocumentNameResolver.apply(operation));
pathDocBuilder.writeToFileWithoutExtension(operationFile, StandardCharsets.UTF_8);
if (logger.isDebugEnabled()) {
logger.debug("Separate operation file produced : '{}'", operationFile);
}
buildOperationRef(markupDocBuilder, operation);
} else {
applyPathOperationComponent(markupDocBuilder, operation);
}
if (logger.isDebugEnabled()) {
logger.debug("Operation processed : '{}' (normalized id = '{}')", operation, normalizeName(operation.getId()));
}
} | [
"private",
"void",
"buildOperation",
"(",
"MarkupDocBuilder",
"markupDocBuilder",
",",
"PathOperation",
"operation",
",",
"Swagger2MarkupConfig",
"config",
")",
"{",
"if",
"(",
"config",
".",
"isSeparatedOperationsEnabled",
"(",
")",
")",
"{",
"MarkupDocBuilder",
"pathDocBuilder",
"=",
"copyMarkupDocBuilder",
"(",
"markupDocBuilder",
")",
";",
"applyPathOperationComponent",
"(",
"pathDocBuilder",
",",
"operation",
")",
";",
"java",
".",
"nio",
".",
"file",
".",
"Path",
"operationFile",
"=",
"context",
".",
"getOutputPath",
"(",
")",
".",
"resolve",
"(",
"operationDocumentNameResolver",
".",
"apply",
"(",
"operation",
")",
")",
";",
"pathDocBuilder",
".",
"writeToFileWithoutExtension",
"(",
"operationFile",
",",
"StandardCharsets",
".",
"UTF_8",
")",
";",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"\"Separate operation file produced : '{}'\"",
",",
"operationFile",
")",
";",
"}",
"buildOperationRef",
"(",
"markupDocBuilder",
",",
"operation",
")",
";",
"}",
"else",
"{",
"applyPathOperationComponent",
"(",
"markupDocBuilder",
",",
"operation",
")",
";",
"}",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"\"Operation processed : '{}' (normalized id = '{}')\"",
",",
"operation",
",",
"normalizeName",
"(",
"operation",
".",
"getId",
"(",
")",
")",
")",
";",
"}",
"}"
] | Builds a path operation depending on generation mode.
@param operation operation | [
"Builds",
"a",
"path",
"operation",
"depending",
"on",
"generation",
"mode",
"."
] | train | https://github.com/Swagger2Markup/swagger2markup/blob/da83465f19a2f8a0f1fba873b5762bca8587896b/src/main/java/io/github/swagger2markup/internal/document/PathsDocument.java#L207-L225 |
google/identity-toolkit-java-client | src/main/java/com/google/identitytoolkit/GitkitClient.java | GitkitClient.getOobResponse | public OobResponse getOobResponse(HttpServletRequest req, String gitkitToken)
throws GitkitServerException {
"""
Gets out-of-band response. Used by oob endpoint for ResetPassword and ChangeEmail operation.
The web site needs to send user an email containing the oobUrl in the response. The user needs
to click the oobUrl to finish the operation.
@param req http request for the oob endpoint
@param gitkitToken Gitkit token of authenticated user, required for ChangeEmail operation
@return the oob response.
@throws GitkitServerException
"""
try {
String action = req.getParameter("action");
if ("resetPassword".equals(action)) {
String oobLink = buildOobLink(buildPasswordResetRequest(req), action);
return new OobResponse(
req.getParameter("email"),
null,
oobLink,
OobAction.RESET_PASSWORD);
} else if ("changeEmail".equals(action)) {
if (gitkitToken == null) {
return new OobResponse("login is required");
} else {
String oobLink = buildOobLink(buildChangeEmailRequest(req, gitkitToken), action);
return new OobResponse(
req.getParameter("oldEmail"),
req.getParameter("newEmail"),
oobLink,
OobAction.CHANGE_EMAIL);
}
} else {
return new OobResponse("unknown request");
}
} catch (GitkitClientException e) {
return new OobResponse(e.getMessage());
}
} | java | public OobResponse getOobResponse(HttpServletRequest req, String gitkitToken)
throws GitkitServerException {
try {
String action = req.getParameter("action");
if ("resetPassword".equals(action)) {
String oobLink = buildOobLink(buildPasswordResetRequest(req), action);
return new OobResponse(
req.getParameter("email"),
null,
oobLink,
OobAction.RESET_PASSWORD);
} else if ("changeEmail".equals(action)) {
if (gitkitToken == null) {
return new OobResponse("login is required");
} else {
String oobLink = buildOobLink(buildChangeEmailRequest(req, gitkitToken), action);
return new OobResponse(
req.getParameter("oldEmail"),
req.getParameter("newEmail"),
oobLink,
OobAction.CHANGE_EMAIL);
}
} else {
return new OobResponse("unknown request");
}
} catch (GitkitClientException e) {
return new OobResponse(e.getMessage());
}
} | [
"public",
"OobResponse",
"getOobResponse",
"(",
"HttpServletRequest",
"req",
",",
"String",
"gitkitToken",
")",
"throws",
"GitkitServerException",
"{",
"try",
"{",
"String",
"action",
"=",
"req",
".",
"getParameter",
"(",
"\"action\"",
")",
";",
"if",
"(",
"\"resetPassword\"",
".",
"equals",
"(",
"action",
")",
")",
"{",
"String",
"oobLink",
"=",
"buildOobLink",
"(",
"buildPasswordResetRequest",
"(",
"req",
")",
",",
"action",
")",
";",
"return",
"new",
"OobResponse",
"(",
"req",
".",
"getParameter",
"(",
"\"email\"",
")",
",",
"null",
",",
"oobLink",
",",
"OobAction",
".",
"RESET_PASSWORD",
")",
";",
"}",
"else",
"if",
"(",
"\"changeEmail\"",
".",
"equals",
"(",
"action",
")",
")",
"{",
"if",
"(",
"gitkitToken",
"==",
"null",
")",
"{",
"return",
"new",
"OobResponse",
"(",
"\"login is required\"",
")",
";",
"}",
"else",
"{",
"String",
"oobLink",
"=",
"buildOobLink",
"(",
"buildChangeEmailRequest",
"(",
"req",
",",
"gitkitToken",
")",
",",
"action",
")",
";",
"return",
"new",
"OobResponse",
"(",
"req",
".",
"getParameter",
"(",
"\"oldEmail\"",
")",
",",
"req",
".",
"getParameter",
"(",
"\"newEmail\"",
")",
",",
"oobLink",
",",
"OobAction",
".",
"CHANGE_EMAIL",
")",
";",
"}",
"}",
"else",
"{",
"return",
"new",
"OobResponse",
"(",
"\"unknown request\"",
")",
";",
"}",
"}",
"catch",
"(",
"GitkitClientException",
"e",
")",
"{",
"return",
"new",
"OobResponse",
"(",
"e",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"}"
] | Gets out-of-band response. Used by oob endpoint for ResetPassword and ChangeEmail operation.
The web site needs to send user an email containing the oobUrl in the response. The user needs
to click the oobUrl to finish the operation.
@param req http request for the oob endpoint
@param gitkitToken Gitkit token of authenticated user, required for ChangeEmail operation
@return the oob response.
@throws GitkitServerException | [
"Gets",
"out",
"-",
"of",
"-",
"band",
"response",
".",
"Used",
"by",
"oob",
"endpoint",
"for",
"ResetPassword",
"and",
"ChangeEmail",
"operation",
".",
"The",
"web",
"site",
"needs",
"to",
"send",
"user",
"an",
"email",
"containing",
"the",
"oobUrl",
"in",
"the",
"response",
".",
"The",
"user",
"needs",
"to",
"click",
"the",
"oobUrl",
"to",
"finish",
"the",
"operation",
"."
] | train | https://github.com/google/identity-toolkit-java-client/blob/61dda1aabbd541ad5e431e840fd266bfca5f8a4a/src/main/java/com/google/identitytoolkit/GitkitClient.java#L460-L488 |
looly/hutool | hutool-db/src/main/java/cn/hutool/db/AbstractDb.java | AbstractDb.find | public <T> T find(Entity where, RsHandler<T> rsh, String... fields) throws SQLException {
"""
查询,返回所有字段<br>
查询条件为多个key value对表示,默认key = value,如果使用其它条件可以使用:where.put("key", " > 1"),value也可以传Condition对象,key被忽略
@param <T> 需要处理成的结果对象类型
@param where 条件实体类(包含表名)
@param rsh 结果集处理对象
@param fields 字段列表,可变长参数如果无值表示查询全部字段
@return 结果对象
@throws SQLException SQL执行异常
"""
return find(CollectionUtil.newArrayList(fields), where, rsh);
} | java | public <T> T find(Entity where, RsHandler<T> rsh, String... fields) throws SQLException {
return find(CollectionUtil.newArrayList(fields), where, rsh);
} | [
"public",
"<",
"T",
">",
"T",
"find",
"(",
"Entity",
"where",
",",
"RsHandler",
"<",
"T",
">",
"rsh",
",",
"String",
"...",
"fields",
")",
"throws",
"SQLException",
"{",
"return",
"find",
"(",
"CollectionUtil",
".",
"newArrayList",
"(",
"fields",
")",
",",
"where",
",",
"rsh",
")",
";",
"}"
] | 查询,返回所有字段<br>
查询条件为多个key value对表示,默认key = value,如果使用其它条件可以使用:where.put("key", " > 1"),value也可以传Condition对象,key被忽略
@param <T> 需要处理成的结果对象类型
@param where 条件实体类(包含表名)
@param rsh 结果集处理对象
@param fields 字段列表,可变长参数如果无值表示查询全部字段
@return 结果对象
@throws SQLException SQL执行异常 | [
"查询,返回所有字段<br",
">",
"查询条件为多个key",
"value对表示,默认key",
"=",
"value,如果使用其它条件可以使用:where",
".",
"put",
"(",
"key",
">",
";",
"1",
")",
",value也可以传Condition对象,key被忽略"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-db/src/main/java/cn/hutool/db/AbstractDb.java#L478-L480 |
lessthanoptimal/BoofCV | main/boofcv-ip/src/main/java/boofcv/alg/transform/ii/DerivativeIntegralImage.java | DerivativeIntegralImage.kernelHaarX | public static IntegralKernel kernelHaarX( int r , IntegralKernel ret) {
"""
Creates a kernel for the Haar wavelet "centered" around the target pixel.
@param r Radius of the box. width is 2*r
@return Kernel for a Haar x-axis wavelet.
"""
if( ret == null )
ret = new IntegralKernel(2);
ret.blocks[0].set(-r, -r, 0, r);
ret.blocks[1].set(0,-r,r,r);
ret.scales[0] = -1;
ret.scales[1] = 1;
return ret;
} | java | public static IntegralKernel kernelHaarX( int r , IntegralKernel ret) {
if( ret == null )
ret = new IntegralKernel(2);
ret.blocks[0].set(-r, -r, 0, r);
ret.blocks[1].set(0,-r,r,r);
ret.scales[0] = -1;
ret.scales[1] = 1;
return ret;
} | [
"public",
"static",
"IntegralKernel",
"kernelHaarX",
"(",
"int",
"r",
",",
"IntegralKernel",
"ret",
")",
"{",
"if",
"(",
"ret",
"==",
"null",
")",
"ret",
"=",
"new",
"IntegralKernel",
"(",
"2",
")",
";",
"ret",
".",
"blocks",
"[",
"0",
"]",
".",
"set",
"(",
"-",
"r",
",",
"-",
"r",
",",
"0",
",",
"r",
")",
";",
"ret",
".",
"blocks",
"[",
"1",
"]",
".",
"set",
"(",
"0",
",",
"-",
"r",
",",
"r",
",",
"r",
")",
";",
"ret",
".",
"scales",
"[",
"0",
"]",
"=",
"-",
"1",
";",
"ret",
".",
"scales",
"[",
"1",
"]",
"=",
"1",
";",
"return",
"ret",
";",
"}"
] | Creates a kernel for the Haar wavelet "centered" around the target pixel.
@param r Radius of the box. width is 2*r
@return Kernel for a Haar x-axis wavelet. | [
"Creates",
"a",
"kernel",
"for",
"the",
"Haar",
"wavelet",
"centered",
"around",
"the",
"target",
"pixel",
"."
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/alg/transform/ii/DerivativeIntegralImage.java#L72-L82 |
apache/incubator-gobblin | gobblin-utility/src/main/java/org/apache/gobblin/util/ForkOperatorUtils.java | ForkOperatorUtils.getPropertyNameForBranch | public static String getPropertyNameForBranch(String key, int numBranches, int branchId) {
"""
Get a new property key from an original one with branch index (if applicable).
@param key property key
@param numBranches number of branches (non-negative)
@param branchId branch id (non-negative)
@return a new property key
"""
Preconditions.checkArgument(numBranches >= 0, "The number of branches is expected to be non-negative");
Preconditions.checkArgument(branchId >= 0, "The branchId is expected to be non-negative");
return numBranches > 1 ? key + "." + branchId : key;
} | java | public static String getPropertyNameForBranch(String key, int numBranches, int branchId) {
Preconditions.checkArgument(numBranches >= 0, "The number of branches is expected to be non-negative");
Preconditions.checkArgument(branchId >= 0, "The branchId is expected to be non-negative");
return numBranches > 1 ? key + "." + branchId : key;
} | [
"public",
"static",
"String",
"getPropertyNameForBranch",
"(",
"String",
"key",
",",
"int",
"numBranches",
",",
"int",
"branchId",
")",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"numBranches",
">=",
"0",
",",
"\"The number of branches is expected to be non-negative\"",
")",
";",
"Preconditions",
".",
"checkArgument",
"(",
"branchId",
">=",
"0",
",",
"\"The branchId is expected to be non-negative\"",
")",
";",
"return",
"numBranches",
">",
"1",
"?",
"key",
"+",
"\".\"",
"+",
"branchId",
":",
"key",
";",
"}"
] | Get a new property key from an original one with branch index (if applicable).
@param key property key
@param numBranches number of branches (non-negative)
@param branchId branch id (non-negative)
@return a new property key | [
"Get",
"a",
"new",
"property",
"key",
"from",
"an",
"original",
"one",
"with",
"branch",
"index",
"(",
"if",
"applicable",
")",
"."
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/ForkOperatorUtils.java#L45-L49 |
PeterisP/LVTagger | src/main/java/edu/stanford/nlp/trees/GrammaticalRelation.java | GrammaticalRelation.valueOf | public static GrammaticalRelation valueOf(Language language, String s) {
"""
Convert from a String representation of a GrammaticalRelation to a
GrammaticalRelation. Where possible, you should avoid using this
method and simply work with true GrammaticalRelations rather than
String representations. Correct behavior of this method depends
on the underlying data structure resources used being kept in sync
with the toString() and equals() methods. However, there is really
no choice but to use this method when storing GrammaticalRelations
to text files and then reading them back in, so this method is not
deprecated.
@param s The String representation of a GrammaticalRelation
@return The grammatical relation represented by this String
"""
GrammaticalRelation reln = (stringsToRelations.get(language) != null ? valueOf(s, stringsToRelations.get(language).values()) : null);
if (reln == null) {
// TODO this breaks the hierarchical structure of the classes,
// but it makes English relations that much likelier to work.
reln = EnglishGrammaticalRelations.valueOf(s);
}
if (reln == null) {
// the block below fails when 'specific' includes underscores.
// this is possible on weird web text, which generates relations such as prep______
/*
String[] names = s.split("_");
String specific = names.length > 1? names[1] : null;
reln = new GrammaticalRelation(language, names[0], null, null, null, specific);
*/
String name;
String specific;
int underscorePosition = s.indexOf('_');
if (underscorePosition > 0) {
name = s.substring(0, underscorePosition);
specific = s.substring(underscorePosition + 1);
} else {
name = s;
specific = null;
}
reln = new GrammaticalRelation(language, name, null, null, null, specific);
}
return reln;
} | java | public static GrammaticalRelation valueOf(Language language, String s) {
GrammaticalRelation reln = (stringsToRelations.get(language) != null ? valueOf(s, stringsToRelations.get(language).values()) : null);
if (reln == null) {
// TODO this breaks the hierarchical structure of the classes,
// but it makes English relations that much likelier to work.
reln = EnglishGrammaticalRelations.valueOf(s);
}
if (reln == null) {
// the block below fails when 'specific' includes underscores.
// this is possible on weird web text, which generates relations such as prep______
/*
String[] names = s.split("_");
String specific = names.length > 1? names[1] : null;
reln = new GrammaticalRelation(language, names[0], null, null, null, specific);
*/
String name;
String specific;
int underscorePosition = s.indexOf('_');
if (underscorePosition > 0) {
name = s.substring(0, underscorePosition);
specific = s.substring(underscorePosition + 1);
} else {
name = s;
specific = null;
}
reln = new GrammaticalRelation(language, name, null, null, null, specific);
}
return reln;
} | [
"public",
"static",
"GrammaticalRelation",
"valueOf",
"(",
"Language",
"language",
",",
"String",
"s",
")",
"{",
"GrammaticalRelation",
"reln",
"=",
"(",
"stringsToRelations",
".",
"get",
"(",
"language",
")",
"!=",
"null",
"?",
"valueOf",
"(",
"s",
",",
"stringsToRelations",
".",
"get",
"(",
"language",
")",
".",
"values",
"(",
")",
")",
":",
"null",
")",
";",
"if",
"(",
"reln",
"==",
"null",
")",
"{",
"// TODO this breaks the hierarchical structure of the classes,\r",
"// but it makes English relations that much likelier to work.\r",
"reln",
"=",
"EnglishGrammaticalRelations",
".",
"valueOf",
"(",
"s",
")",
";",
"}",
"if",
"(",
"reln",
"==",
"null",
")",
"{",
"// the block below fails when 'specific' includes underscores.\r",
"// this is possible on weird web text, which generates relations such as prep______\r",
"/*\r\n String[] names = s.split(\"_\");\r\n String specific = names.length > 1? names[1] : null;\r\n reln = new GrammaticalRelation(language, names[0], null, null, null, specific);\r\n */",
"String",
"name",
";",
"String",
"specific",
";",
"int",
"underscorePosition",
"=",
"s",
".",
"indexOf",
"(",
"'",
"'",
")",
";",
"if",
"(",
"underscorePosition",
">",
"0",
")",
"{",
"name",
"=",
"s",
".",
"substring",
"(",
"0",
",",
"underscorePosition",
")",
";",
"specific",
"=",
"s",
".",
"substring",
"(",
"underscorePosition",
"+",
"1",
")",
";",
"}",
"else",
"{",
"name",
"=",
"s",
";",
"specific",
"=",
"null",
";",
"}",
"reln",
"=",
"new",
"GrammaticalRelation",
"(",
"language",
",",
"name",
",",
"null",
",",
"null",
",",
"null",
",",
"specific",
")",
";",
"}",
"return",
"reln",
";",
"}"
] | Convert from a String representation of a GrammaticalRelation to a
GrammaticalRelation. Where possible, you should avoid using this
method and simply work with true GrammaticalRelations rather than
String representations. Correct behavior of this method depends
on the underlying data structure resources used being kept in sync
with the toString() and equals() methods. However, there is really
no choice but to use this method when storing GrammaticalRelations
to text files and then reading them back in, so this method is not
deprecated.
@param s The String representation of a GrammaticalRelation
@return The grammatical relation represented by this String | [
"Convert",
"from",
"a",
"String",
"representation",
"of",
"a",
"GrammaticalRelation",
"to",
"a",
"GrammaticalRelation",
".",
"Where",
"possible",
"you",
"should",
"avoid",
"using",
"this",
"method",
"and",
"simply",
"work",
"with",
"true",
"GrammaticalRelations",
"rather",
"than",
"String",
"representations",
".",
"Correct",
"behavior",
"of",
"this",
"method",
"depends",
"on",
"the",
"underlying",
"data",
"structure",
"resources",
"used",
"being",
"kept",
"in",
"sync",
"with",
"the",
"toString",
"()",
"and",
"equals",
"()",
"methods",
".",
"However",
"there",
"is",
"really",
"no",
"choice",
"but",
"to",
"use",
"this",
"method",
"when",
"storing",
"GrammaticalRelations",
"to",
"text",
"files",
"and",
"then",
"reading",
"them",
"back",
"in",
"so",
"this",
"method",
"is",
"not",
"deprecated",
"."
] | train | https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/trees/GrammaticalRelation.java#L176-L205 |
lessthanoptimal/BoofCV | main/boofcv-feature/src/main/java/boofcv/alg/flow/DenseFlowPyramidBase.java | DenseFlowPyramidBase.warpImageTaylor | protected void warpImageTaylor(GrayF32 before, GrayF32 flowX , GrayF32 flowY , GrayF32 after) {
"""
Takes the flow from the previous lower resolution layer and uses it to initialize the flow
in the current layer. Adjusts for change in image scale.
"""
interp.setBorder(FactoryImageBorder.single(before.getImageType().getImageClass(), BorderType.EXTENDED));
interp.setImage(before);
for( int y = 0; y < before.height; y++ ) {
int pixelIndex = y*before.width;
for (int x = 0; x < before.width; x++, pixelIndex++ ) {
float u = flowX.data[pixelIndex];
float v = flowY.data[pixelIndex];
float wx = x + u;
float wy = y + v;
after.data[pixelIndex] = interp.get(wx, wy);
}
}
} | java | protected void warpImageTaylor(GrayF32 before, GrayF32 flowX , GrayF32 flowY , GrayF32 after) {
interp.setBorder(FactoryImageBorder.single(before.getImageType().getImageClass(), BorderType.EXTENDED));
interp.setImage(before);
for( int y = 0; y < before.height; y++ ) {
int pixelIndex = y*before.width;
for (int x = 0; x < before.width; x++, pixelIndex++ ) {
float u = flowX.data[pixelIndex];
float v = flowY.data[pixelIndex];
float wx = x + u;
float wy = y + v;
after.data[pixelIndex] = interp.get(wx, wy);
}
}
} | [
"protected",
"void",
"warpImageTaylor",
"(",
"GrayF32",
"before",
",",
"GrayF32",
"flowX",
",",
"GrayF32",
"flowY",
",",
"GrayF32",
"after",
")",
"{",
"interp",
".",
"setBorder",
"(",
"FactoryImageBorder",
".",
"single",
"(",
"before",
".",
"getImageType",
"(",
")",
".",
"getImageClass",
"(",
")",
",",
"BorderType",
".",
"EXTENDED",
")",
")",
";",
"interp",
".",
"setImage",
"(",
"before",
")",
";",
"for",
"(",
"int",
"y",
"=",
"0",
";",
"y",
"<",
"before",
".",
"height",
";",
"y",
"++",
")",
"{",
"int",
"pixelIndex",
"=",
"y",
"*",
"before",
".",
"width",
";",
"for",
"(",
"int",
"x",
"=",
"0",
";",
"x",
"<",
"before",
".",
"width",
";",
"x",
"++",
",",
"pixelIndex",
"++",
")",
"{",
"float",
"u",
"=",
"flowX",
".",
"data",
"[",
"pixelIndex",
"]",
";",
"float",
"v",
"=",
"flowY",
".",
"data",
"[",
"pixelIndex",
"]",
";",
"float",
"wx",
"=",
"x",
"+",
"u",
";",
"float",
"wy",
"=",
"y",
"+",
"v",
";",
"after",
".",
"data",
"[",
"pixelIndex",
"]",
"=",
"interp",
".",
"get",
"(",
"wx",
",",
"wy",
")",
";",
"}",
"}",
"}"
] | Takes the flow from the previous lower resolution layer and uses it to initialize the flow
in the current layer. Adjusts for change in image scale. | [
"Takes",
"the",
"flow",
"from",
"the",
"previous",
"lower",
"resolution",
"layer",
"and",
"uses",
"it",
"to",
"initialize",
"the",
"flow",
"in",
"the",
"current",
"layer",
".",
"Adjusts",
"for",
"change",
"in",
"image",
"scale",
"."
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/flow/DenseFlowPyramidBase.java#L122-L138 |
Azure/azure-sdk-for-java | iothub/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/iothub/v2018_04_01/implementation/IotHubResourcesInner.java | IotHubResourcesInner.listEventHubConsumerGroupsAsync | public Observable<Page<EventHubConsumerGroupInfoInner>> listEventHubConsumerGroupsAsync(final String resourceGroupName, final String resourceName, final String eventHubEndpointName) {
"""
Get a list of the consumer groups in the Event Hub-compatible device-to-cloud endpoint in an IoT hub.
Get a list of the consumer groups in the Event Hub-compatible device-to-cloud endpoint in an IoT hub.
@param resourceGroupName The name of the resource group that contains the IoT hub.
@param resourceName The name of the IoT hub.
@param eventHubEndpointName The name of the Event Hub-compatible endpoint.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<EventHubConsumerGroupInfoInner> object
"""
return listEventHubConsumerGroupsWithServiceResponseAsync(resourceGroupName, resourceName, eventHubEndpointName)
.map(new Func1<ServiceResponse<Page<EventHubConsumerGroupInfoInner>>, Page<EventHubConsumerGroupInfoInner>>() {
@Override
public Page<EventHubConsumerGroupInfoInner> call(ServiceResponse<Page<EventHubConsumerGroupInfoInner>> response) {
return response.body();
}
});
} | java | public Observable<Page<EventHubConsumerGroupInfoInner>> listEventHubConsumerGroupsAsync(final String resourceGroupName, final String resourceName, final String eventHubEndpointName) {
return listEventHubConsumerGroupsWithServiceResponseAsync(resourceGroupName, resourceName, eventHubEndpointName)
.map(new Func1<ServiceResponse<Page<EventHubConsumerGroupInfoInner>>, Page<EventHubConsumerGroupInfoInner>>() {
@Override
public Page<EventHubConsumerGroupInfoInner> call(ServiceResponse<Page<EventHubConsumerGroupInfoInner>> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Page",
"<",
"EventHubConsumerGroupInfoInner",
">",
">",
"listEventHubConsumerGroupsAsync",
"(",
"final",
"String",
"resourceGroupName",
",",
"final",
"String",
"resourceName",
",",
"final",
"String",
"eventHubEndpointName",
")",
"{",
"return",
"listEventHubConsumerGroupsWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"resourceName",
",",
"eventHubEndpointName",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"EventHubConsumerGroupInfoInner",
">",
">",
",",
"Page",
"<",
"EventHubConsumerGroupInfoInner",
">",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"Page",
"<",
"EventHubConsumerGroupInfoInner",
">",
"call",
"(",
"ServiceResponse",
"<",
"Page",
"<",
"EventHubConsumerGroupInfoInner",
">",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Get a list of the consumer groups in the Event Hub-compatible device-to-cloud endpoint in an IoT hub.
Get a list of the consumer groups in the Event Hub-compatible device-to-cloud endpoint in an IoT hub.
@param resourceGroupName The name of the resource group that contains the IoT hub.
@param resourceName The name of the IoT hub.
@param eventHubEndpointName The name of the Event Hub-compatible endpoint.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<EventHubConsumerGroupInfoInner> object | [
"Get",
"a",
"list",
"of",
"the",
"consumer",
"groups",
"in",
"the",
"Event",
"Hub",
"-",
"compatible",
"device",
"-",
"to",
"-",
"cloud",
"endpoint",
"in",
"an",
"IoT",
"hub",
".",
"Get",
"a",
"list",
"of",
"the",
"consumer",
"groups",
"in",
"the",
"Event",
"Hub",
"-",
"compatible",
"device",
"-",
"to",
"-",
"cloud",
"endpoint",
"in",
"an",
"IoT",
"hub",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/iothub/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/iothub/v2018_04_01/implementation/IotHubResourcesInner.java#L1676-L1684 |
alkacon/opencms-core | src/org/opencms/main/CmsShellCommands.java | CmsShellCommands.addUserToRole | public void addUserToRole(String user, String role) throws CmsException {
"""
Add the user to the given role.<p>
@param user name of the user
@param role name of the role, for example 'EDITOR'
@throws CmsException if something goes wrong
"""
OpenCms.getRoleManager().addUserToRole(m_cms, CmsRole.valueOfRoleName(role), user);
} | java | public void addUserToRole(String user, String role) throws CmsException {
OpenCms.getRoleManager().addUserToRole(m_cms, CmsRole.valueOfRoleName(role), user);
} | [
"public",
"void",
"addUserToRole",
"(",
"String",
"user",
",",
"String",
"role",
")",
"throws",
"CmsException",
"{",
"OpenCms",
".",
"getRoleManager",
"(",
")",
".",
"addUserToRole",
"(",
"m_cms",
",",
"CmsRole",
".",
"valueOfRoleName",
"(",
"role",
")",
",",
"user",
")",
";",
"}"
] | Add the user to the given role.<p>
@param user name of the user
@param role name of the role, for example 'EDITOR'
@throws CmsException if something goes wrong | [
"Add",
"the",
"user",
"to",
"the",
"given",
"role",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/main/CmsShellCommands.java#L175-L178 |
BlueBrain/bluima | modules/bluima_typesystem/src/main/java/de/julielab/jules/types/DBInfo.java | DBInfo.setAcList | public void setAcList(int i, String v) {
"""
indexed setter for acList - sets an indexed value - A list of accession numbers for this DB, C
@generated
@param i index in the array to set
@param v value to set into the array
"""
if (DBInfo_Type.featOkTst && ((DBInfo_Type)jcasType).casFeat_acList == null)
jcasType.jcas.throwFeatMissing("acList", "de.julielab.jules.types.DBInfo");
jcasType.jcas.checkArrayBounds(jcasType.ll_cas.ll_getRefValue(addr, ((DBInfo_Type)jcasType).casFeatCode_acList), i);
jcasType.ll_cas.ll_setStringArrayValue(jcasType.ll_cas.ll_getRefValue(addr, ((DBInfo_Type)jcasType).casFeatCode_acList), i, v);} | java | public void setAcList(int i, String v) {
if (DBInfo_Type.featOkTst && ((DBInfo_Type)jcasType).casFeat_acList == null)
jcasType.jcas.throwFeatMissing("acList", "de.julielab.jules.types.DBInfo");
jcasType.jcas.checkArrayBounds(jcasType.ll_cas.ll_getRefValue(addr, ((DBInfo_Type)jcasType).casFeatCode_acList), i);
jcasType.ll_cas.ll_setStringArrayValue(jcasType.ll_cas.ll_getRefValue(addr, ((DBInfo_Type)jcasType).casFeatCode_acList), i, v);} | [
"public",
"void",
"setAcList",
"(",
"int",
"i",
",",
"String",
"v",
")",
"{",
"if",
"(",
"DBInfo_Type",
".",
"featOkTst",
"&&",
"(",
"(",
"DBInfo_Type",
")",
"jcasType",
")",
".",
"casFeat_acList",
"==",
"null",
")",
"jcasType",
".",
"jcas",
".",
"throwFeatMissing",
"(",
"\"acList\"",
",",
"\"de.julielab.jules.types.DBInfo\"",
")",
";",
"jcasType",
".",
"jcas",
".",
"checkArrayBounds",
"(",
"jcasType",
".",
"ll_cas",
".",
"ll_getRefValue",
"(",
"addr",
",",
"(",
"(",
"DBInfo_Type",
")",
"jcasType",
")",
".",
"casFeatCode_acList",
")",
",",
"i",
")",
";",
"jcasType",
".",
"ll_cas",
".",
"ll_setStringArrayValue",
"(",
"jcasType",
".",
"ll_cas",
".",
"ll_getRefValue",
"(",
"addr",
",",
"(",
"(",
"DBInfo_Type",
")",
"jcasType",
")",
".",
"casFeatCode_acList",
")",
",",
"i",
",",
"v",
")",
";",
"}"
] | indexed setter for acList - sets an indexed value - A list of accession numbers for this DB, C
@generated
@param i index in the array to set
@param v value to set into the array | [
"indexed",
"setter",
"for",
"acList",
"-",
"sets",
"an",
"indexed",
"value",
"-",
"A",
"list",
"of",
"accession",
"numbers",
"for",
"this",
"DB",
"C"
] | train | https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_typesystem/src/main/java/de/julielab/jules/types/DBInfo.java#L138-L142 |
Azure/azure-sdk-for-java | batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/PoolsImpl.java | PoolsImpl.deleteAsync | public Observable<Void> deleteAsync(String poolId) {
"""
Deletes a pool from the specified account.
When you request that a pool be deleted, the following actions occur: the pool state is set to deleting; any ongoing resize operation on the pool are stopped; the Batch service starts resizing the pool to zero nodes; any tasks running on existing nodes are terminated and requeued (as if a resize pool operation had been requested with the default requeue option); finally, the pool is removed from the system. Because running tasks are requeued, the user can rerun these tasks by updating their job to target a different pool. The tasks can then run on the new pool. If you want to override the requeue behavior, then you should call resize pool explicitly to shrink the pool to zero size before deleting the pool. If you call an Update, Patch or Delete API on a pool in the deleting state, it will fail with HTTP status code 409 with error code PoolBeingDeleted.
@param poolId The ID of the pool to delete.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceResponseWithHeaders} object if successful.
"""
return deleteWithServiceResponseAsync(poolId).map(new Func1<ServiceResponseWithHeaders<Void, PoolDeleteHeaders>, Void>() {
@Override
public Void call(ServiceResponseWithHeaders<Void, PoolDeleteHeaders> response) {
return response.body();
}
});
} | java | public Observable<Void> deleteAsync(String poolId) {
return deleteWithServiceResponseAsync(poolId).map(new Func1<ServiceResponseWithHeaders<Void, PoolDeleteHeaders>, Void>() {
@Override
public Void call(ServiceResponseWithHeaders<Void, PoolDeleteHeaders> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Void",
">",
"deleteAsync",
"(",
"String",
"poolId",
")",
"{",
"return",
"deleteWithServiceResponseAsync",
"(",
"poolId",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponseWithHeaders",
"<",
"Void",
",",
"PoolDeleteHeaders",
">",
",",
"Void",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"Void",
"call",
"(",
"ServiceResponseWithHeaders",
"<",
"Void",
",",
"PoolDeleteHeaders",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Deletes a pool from the specified account.
When you request that a pool be deleted, the following actions occur: the pool state is set to deleting; any ongoing resize operation on the pool are stopped; the Batch service starts resizing the pool to zero nodes; any tasks running on existing nodes are terminated and requeued (as if a resize pool operation had been requested with the default requeue option); finally, the pool is removed from the system. Because running tasks are requeued, the user can rerun these tasks by updating their job to target a different pool. The tasks can then run on the new pool. If you want to override the requeue behavior, then you should call resize pool explicitly to shrink the pool to zero size before deleting the pool. If you call an Update, Patch or Delete API on a pool in the deleting state, it will fail with HTTP status code 409 with error code PoolBeingDeleted.
@param poolId The ID of the pool to delete.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceResponseWithHeaders} object if successful. | [
"Deletes",
"a",
"pool",
"from",
"the",
"specified",
"account",
".",
"When",
"you",
"request",
"that",
"a",
"pool",
"be",
"deleted",
"the",
"following",
"actions",
"occur",
":",
"the",
"pool",
"state",
"is",
"set",
"to",
"deleting",
";",
"any",
"ongoing",
"resize",
"operation",
"on",
"the",
"pool",
"are",
"stopped",
";",
"the",
"Batch",
"service",
"starts",
"resizing",
"the",
"pool",
"to",
"zero",
"nodes",
";",
"any",
"tasks",
"running",
"on",
"existing",
"nodes",
"are",
"terminated",
"and",
"requeued",
"(",
"as",
"if",
"a",
"resize",
"pool",
"operation",
"had",
"been",
"requested",
"with",
"the",
"default",
"requeue",
"option",
")",
";",
"finally",
"the",
"pool",
"is",
"removed",
"from",
"the",
"system",
".",
"Because",
"running",
"tasks",
"are",
"requeued",
"the",
"user",
"can",
"rerun",
"these",
"tasks",
"by",
"updating",
"their",
"job",
"to",
"target",
"a",
"different",
"pool",
".",
"The",
"tasks",
"can",
"then",
"run",
"on",
"the",
"new",
"pool",
".",
"If",
"you",
"want",
"to",
"override",
"the",
"requeue",
"behavior",
"then",
"you",
"should",
"call",
"resize",
"pool",
"explicitly",
"to",
"shrink",
"the",
"pool",
"to",
"zero",
"size",
"before",
"deleting",
"the",
"pool",
".",
"If",
"you",
"call",
"an",
"Update",
"Patch",
"or",
"Delete",
"API",
"on",
"a",
"pool",
"in",
"the",
"deleting",
"state",
"it",
"will",
"fail",
"with",
"HTTP",
"status",
"code",
"409",
"with",
"error",
"code",
"PoolBeingDeleted",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/PoolsImpl.java#L1171-L1178 |
alkacon/opencms-core | src/org/opencms/file/collectors/A_CmsResourceCollector.java | A_CmsResourceCollector.getCreateInFolder | protected String getCreateInFolder(CmsObject cms, String param) throws CmsException {
"""
Returns the link to create a new XML content item in the folder pointed to by the parameter.<p>
@param cms the current CmsObject
@param param the folder name to use
@return the link to create a new XML content item in the folder
@throws CmsException if something goes wrong
"""
return getCreateInFolder(cms, new CmsCollectorData(param));
} | java | protected String getCreateInFolder(CmsObject cms, String param) throws CmsException {
return getCreateInFolder(cms, new CmsCollectorData(param));
} | [
"protected",
"String",
"getCreateInFolder",
"(",
"CmsObject",
"cms",
",",
"String",
"param",
")",
"throws",
"CmsException",
"{",
"return",
"getCreateInFolder",
"(",
"cms",
",",
"new",
"CmsCollectorData",
"(",
"param",
")",
")",
";",
"}"
] | Returns the link to create a new XML content item in the folder pointed to by the parameter.<p>
@param cms the current CmsObject
@param param the folder name to use
@return the link to create a new XML content item in the folder
@throws CmsException if something goes wrong | [
"Returns",
"the",
"link",
"to",
"create",
"a",
"new",
"XML",
"content",
"item",
"in",
"the",
"folder",
"pointed",
"to",
"by",
"the",
"parameter",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/file/collectors/A_CmsResourceCollector.java#L398-L401 |
jmxtrans/jmxtrans | jmxtrans-core/src/main/java/com/googlecode/jmxtrans/model/output/Settings.java | Settings.getIntegerSetting | public static Integer getIntegerSetting(Map<String, Object> settings, String key, Integer defaultVal) {
"""
Gets an Integer value for the key, returning the default value given if
not specified or not a valid numeric value.
@param settings
@param key the key to get the Integer setting for
@param defaultVal the default value to return if the setting was not specified
or was not coercible to an Integer value
@return the Integer value for the setting
"""
final Object value = settings.get(key);
if (value == null) {
return defaultVal;
}
if (value instanceof Number) {
return ((Number) value).intValue();
}
if (value instanceof String) {
try {
return Integer.parseInt((String) value);
} catch (NumberFormatException e) {
return defaultVal;
}
}
return defaultVal;
} | java | public static Integer getIntegerSetting(Map<String, Object> settings, String key, Integer defaultVal) {
final Object value = settings.get(key);
if (value == null) {
return defaultVal;
}
if (value instanceof Number) {
return ((Number) value).intValue();
}
if (value instanceof String) {
try {
return Integer.parseInt((String) value);
} catch (NumberFormatException e) {
return defaultVal;
}
}
return defaultVal;
} | [
"public",
"static",
"Integer",
"getIntegerSetting",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"settings",
",",
"String",
"key",
",",
"Integer",
"defaultVal",
")",
"{",
"final",
"Object",
"value",
"=",
"settings",
".",
"get",
"(",
"key",
")",
";",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"return",
"defaultVal",
";",
"}",
"if",
"(",
"value",
"instanceof",
"Number",
")",
"{",
"return",
"(",
"(",
"Number",
")",
"value",
")",
".",
"intValue",
"(",
")",
";",
"}",
"if",
"(",
"value",
"instanceof",
"String",
")",
"{",
"try",
"{",
"return",
"Integer",
".",
"parseInt",
"(",
"(",
"String",
")",
"value",
")",
";",
"}",
"catch",
"(",
"NumberFormatException",
"e",
")",
"{",
"return",
"defaultVal",
";",
"}",
"}",
"return",
"defaultVal",
";",
"}"
] | Gets an Integer value for the key, returning the default value given if
not specified or not a valid numeric value.
@param settings
@param key the key to get the Integer setting for
@param defaultVal the default value to return if the setting was not specified
or was not coercible to an Integer value
@return the Integer value for the setting | [
"Gets",
"an",
"Integer",
"value",
"for",
"the",
"key",
"returning",
"the",
"default",
"value",
"given",
"if",
"not",
"specified",
"or",
"not",
"a",
"valid",
"numeric",
"value",
"."
] | train | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-core/src/main/java/com/googlecode/jmxtrans/model/output/Settings.java#L88-L105 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/mfp/impl/JsJmsMessageFactoryImpl.java | JsJmsMessageFactoryImpl.createInboundJmsMessage | final JsJmsMessage createInboundJmsMessage(JsMsgObject jmo, int messageType) {
"""
Create an instance of the appropriate sub-class, e.g. JsJmsTextMessage
if the inbound message is actually a JMS Text Message, for the
given JMO.
@return JsJmsMessage A JsJmsMessage of the appropriate subtype
"""
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())SibTr.entry(tc, "createInboundJmsMessage " + messageType );
JsJmsMessage jmsMessage = null;
switch (messageType) {
case JmsBodyType.BYTES_INT:
jmsMessage = new JsJmsBytesMessageImpl(jmo);
break;
case JmsBodyType.MAP_INT:
jmsMessage = new JsJmsMapMessageImpl(jmo);
break;
case JmsBodyType.OBJECT_INT:
jmsMessage = new JsJmsObjectMessageImpl(jmo);
break;
case JmsBodyType.STREAM_INT:
jmsMessage = new JsJmsStreamMessageImpl(jmo);
break;
case JmsBodyType.TEXT_INT:
jmsMessage = new JsJmsTextMessageImpl(jmo);
break;
default:
jmsMessage = new JsJmsMessageImpl(jmo);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())SibTr.exit(tc, "createInboundJmsMessage");
return jmsMessage;
} | java | final JsJmsMessage createInboundJmsMessage(JsMsgObject jmo, int messageType) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())SibTr.entry(tc, "createInboundJmsMessage " + messageType );
JsJmsMessage jmsMessage = null;
switch (messageType) {
case JmsBodyType.BYTES_INT:
jmsMessage = new JsJmsBytesMessageImpl(jmo);
break;
case JmsBodyType.MAP_INT:
jmsMessage = new JsJmsMapMessageImpl(jmo);
break;
case JmsBodyType.OBJECT_INT:
jmsMessage = new JsJmsObjectMessageImpl(jmo);
break;
case JmsBodyType.STREAM_INT:
jmsMessage = new JsJmsStreamMessageImpl(jmo);
break;
case JmsBodyType.TEXT_INT:
jmsMessage = new JsJmsTextMessageImpl(jmo);
break;
default:
jmsMessage = new JsJmsMessageImpl(jmo);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())SibTr.exit(tc, "createInboundJmsMessage");
return jmsMessage;
} | [
"final",
"JsJmsMessage",
"createInboundJmsMessage",
"(",
"JsMsgObject",
"jmo",
",",
"int",
"messageType",
")",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"SibTr",
".",
"entry",
"(",
"tc",
",",
"\"createInboundJmsMessage \"",
"+",
"messageType",
")",
";",
"JsJmsMessage",
"jmsMessage",
"=",
"null",
";",
"switch",
"(",
"messageType",
")",
"{",
"case",
"JmsBodyType",
".",
"BYTES_INT",
":",
"jmsMessage",
"=",
"new",
"JsJmsBytesMessageImpl",
"(",
"jmo",
")",
";",
"break",
";",
"case",
"JmsBodyType",
".",
"MAP_INT",
":",
"jmsMessage",
"=",
"new",
"JsJmsMapMessageImpl",
"(",
"jmo",
")",
";",
"break",
";",
"case",
"JmsBodyType",
".",
"OBJECT_INT",
":",
"jmsMessage",
"=",
"new",
"JsJmsObjectMessageImpl",
"(",
"jmo",
")",
";",
"break",
";",
"case",
"JmsBodyType",
".",
"STREAM_INT",
":",
"jmsMessage",
"=",
"new",
"JsJmsStreamMessageImpl",
"(",
"jmo",
")",
";",
"break",
";",
"case",
"JmsBodyType",
".",
"TEXT_INT",
":",
"jmsMessage",
"=",
"new",
"JsJmsTextMessageImpl",
"(",
"jmo",
")",
";",
"break",
";",
"default",
":",
"jmsMessage",
"=",
"new",
"JsJmsMessageImpl",
"(",
"jmo",
")",
";",
"}",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"SibTr",
".",
"exit",
"(",
"tc",
",",
"\"createInboundJmsMessage\"",
")",
";",
"return",
"jmsMessage",
";",
"}"
] | Create an instance of the appropriate sub-class, e.g. JsJmsTextMessage
if the inbound message is actually a JMS Text Message, for the
given JMO.
@return JsJmsMessage A JsJmsMessage of the appropriate subtype | [
"Create",
"an",
"instance",
"of",
"the",
"appropriate",
"sub",
"-",
"class",
"e",
".",
"g",
".",
"JsJmsTextMessage",
"if",
"the",
"inbound",
"message",
"is",
"actually",
"a",
"JMS",
"Text",
"Message",
"for",
"the",
"given",
"JMO",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/mfp/impl/JsJmsMessageFactoryImpl.java#L180-L214 |
lessthanoptimal/ddogleg | src/org/ddogleg/clustering/FactoryClustering.java | FactoryClustering.gaussianMixtureModelEM_F64 | public static ExpectationMaximizationGmm_F64 gaussianMixtureModelEM_F64(
int maxIterations, int maxConverge , double convergeTol) {
"""
<p>
High level interface for creating GMM cluster. If more flexibility is needed (e.g. custom seeds)
then create and instance of {@link ExpectationMaximizationGmm_F64} directly
</p>
<p>WARNING: DEVELOPMENTAL AND IS LIKELY TO FAIL HORRIBLY</p>
@param maxIterations Maximum number of iterations it will perform.
@param maxConverge Maximum iterations allowed before convergence. Re-seeded if it doesn't converge.
@param convergeTol Distance based convergence tolerance. Try 1e-8
@return ExpectationMaximizationGmm_F64
"""
StandardKMeans_F64 kmeans = kMeans_F64(null,maxIterations,maxConverge,convergeTol);
SeedFromKMeans_F64 seeds = new SeedFromKMeans_F64(kmeans);
return new ExpectationMaximizationGmm_F64(maxIterations,convergeTol,seeds);
} | java | public static ExpectationMaximizationGmm_F64 gaussianMixtureModelEM_F64(
int maxIterations, int maxConverge , double convergeTol) {
StandardKMeans_F64 kmeans = kMeans_F64(null,maxIterations,maxConverge,convergeTol);
SeedFromKMeans_F64 seeds = new SeedFromKMeans_F64(kmeans);
return new ExpectationMaximizationGmm_F64(maxIterations,convergeTol,seeds);
} | [
"public",
"static",
"ExpectationMaximizationGmm_F64",
"gaussianMixtureModelEM_F64",
"(",
"int",
"maxIterations",
",",
"int",
"maxConverge",
",",
"double",
"convergeTol",
")",
"{",
"StandardKMeans_F64",
"kmeans",
"=",
"kMeans_F64",
"(",
"null",
",",
"maxIterations",
",",
"maxConverge",
",",
"convergeTol",
")",
";",
"SeedFromKMeans_F64",
"seeds",
"=",
"new",
"SeedFromKMeans_F64",
"(",
"kmeans",
")",
";",
"return",
"new",
"ExpectationMaximizationGmm_F64",
"(",
"maxIterations",
",",
"convergeTol",
",",
"seeds",
")",
";",
"}"
] | <p>
High level interface for creating GMM cluster. If more flexibility is needed (e.g. custom seeds)
then create and instance of {@link ExpectationMaximizationGmm_F64} directly
</p>
<p>WARNING: DEVELOPMENTAL AND IS LIKELY TO FAIL HORRIBLY</p>
@param maxIterations Maximum number of iterations it will perform.
@param maxConverge Maximum iterations allowed before convergence. Re-seeded if it doesn't converge.
@param convergeTol Distance based convergence tolerance. Try 1e-8
@return ExpectationMaximizationGmm_F64 | [
"<p",
">",
"High",
"level",
"interface",
"for",
"creating",
"GMM",
"cluster",
".",
"If",
"more",
"flexibility",
"is",
"needed",
"(",
"e",
".",
"g",
".",
"custom",
"seeds",
")",
"then",
"create",
"and",
"instance",
"of",
"{",
"@link",
"ExpectationMaximizationGmm_F64",
"}",
"directly",
"<",
"/",
"p",
">"
] | train | https://github.com/lessthanoptimal/ddogleg/blob/3786bf448ba23d0e04962dd08c34fa68de276029/src/org/ddogleg/clustering/FactoryClustering.java#L48-L55 |
cdk/cdk | descriptor/qsarmolecular/src/main/java/org/openscience/cdk/qsar/descriptors/molecular/XLogPDescriptor.java | XLogPDescriptor.getCarbonsCount | private int getCarbonsCount(IAtomContainer ac, IAtom atom) {
"""
Gets the carbonsCount attribute of the XLogPDescriptor object.
@param ac Description of the Parameter
@param atom Description of the Parameter
@return The carbonsCount value
"""
List<IAtom> neighbours = ac.getConnectedAtomsList(atom);
int ccounter = 0;
for (IAtom neighbour : neighbours) {
if (neighbour.getSymbol().equals("C")) {
if (!neighbour.getFlag(CDKConstants.ISAROMATIC)) {
ccounter += 1;
}
}
}
return ccounter;
} | java | private int getCarbonsCount(IAtomContainer ac, IAtom atom) {
List<IAtom> neighbours = ac.getConnectedAtomsList(atom);
int ccounter = 0;
for (IAtom neighbour : neighbours) {
if (neighbour.getSymbol().equals("C")) {
if (!neighbour.getFlag(CDKConstants.ISAROMATIC)) {
ccounter += 1;
}
}
}
return ccounter;
} | [
"private",
"int",
"getCarbonsCount",
"(",
"IAtomContainer",
"ac",
",",
"IAtom",
"atom",
")",
"{",
"List",
"<",
"IAtom",
">",
"neighbours",
"=",
"ac",
".",
"getConnectedAtomsList",
"(",
"atom",
")",
";",
"int",
"ccounter",
"=",
"0",
";",
"for",
"(",
"IAtom",
"neighbour",
":",
"neighbours",
")",
"{",
"if",
"(",
"neighbour",
".",
"getSymbol",
"(",
")",
".",
"equals",
"(",
"\"C\"",
")",
")",
"{",
"if",
"(",
"!",
"neighbour",
".",
"getFlag",
"(",
"CDKConstants",
".",
"ISAROMATIC",
")",
")",
"{",
"ccounter",
"+=",
"1",
";",
"}",
"}",
"}",
"return",
"ccounter",
";",
"}"
] | Gets the carbonsCount attribute of the XLogPDescriptor object.
@param ac Description of the Parameter
@param atom Description of the Parameter
@return The carbonsCount value | [
"Gets",
"the",
"carbonsCount",
"attribute",
"of",
"the",
"XLogPDescriptor",
"object",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/descriptor/qsarmolecular/src/main/java/org/openscience/cdk/qsar/descriptors/molecular/XLogPDescriptor.java#L1092-L1103 |
facebookarchive/hadoop-20 | src/contrib/raid/src/java/org/apache/hadoop/raid/RaidHistogram.java | RaidHistogram.put | public synchronized void put(String path, long value, String taskId) {
"""
/*
If value is RECOVERY_FAIL, we consider it as recovery failure
"""
Point p;
int last = windowNum - 1;
if (value == RECOVERY_FAIL) {
p = new Point(value, path, System.currentTimeMillis(), taskId);
AtomicInteger counter = failedRecoveredFiles.get(path);
if (counter == null) {
counter = new AtomicInteger(0);
failedRecoveredFiles.put(path, counter);
}
if (counter.incrementAndGet() == 1) {
totalFailedPaths.get(last).incrementAndGet();
}
} else {
value /= dividend;
p = new Point(value, path, System.currentTimeMillis(), taskId);
CounterArray counters = histo.get(value);
if (counters == null) {
counters = new CounterArray(windowNum);
histo.put(value, counters);
}
counters.incrementAndGet(last);
totalPoints.incrementAndGet(last);
}
points.add(p);
InjectionHandler.processEvent(InjectionEvent.RAID_SEND_RECOVERY_TIME, this, path,
value, taskId);
} | java | public synchronized void put(String path, long value, String taskId) {
Point p;
int last = windowNum - 1;
if (value == RECOVERY_FAIL) {
p = new Point(value, path, System.currentTimeMillis(), taskId);
AtomicInteger counter = failedRecoveredFiles.get(path);
if (counter == null) {
counter = new AtomicInteger(0);
failedRecoveredFiles.put(path, counter);
}
if (counter.incrementAndGet() == 1) {
totalFailedPaths.get(last).incrementAndGet();
}
} else {
value /= dividend;
p = new Point(value, path, System.currentTimeMillis(), taskId);
CounterArray counters = histo.get(value);
if (counters == null) {
counters = new CounterArray(windowNum);
histo.put(value, counters);
}
counters.incrementAndGet(last);
totalPoints.incrementAndGet(last);
}
points.add(p);
InjectionHandler.processEvent(InjectionEvent.RAID_SEND_RECOVERY_TIME, this, path,
value, taskId);
} | [
"public",
"synchronized",
"void",
"put",
"(",
"String",
"path",
",",
"long",
"value",
",",
"String",
"taskId",
")",
"{",
"Point",
"p",
";",
"int",
"last",
"=",
"windowNum",
"-",
"1",
";",
"if",
"(",
"value",
"==",
"RECOVERY_FAIL",
")",
"{",
"p",
"=",
"new",
"Point",
"(",
"value",
",",
"path",
",",
"System",
".",
"currentTimeMillis",
"(",
")",
",",
"taskId",
")",
";",
"AtomicInteger",
"counter",
"=",
"failedRecoveredFiles",
".",
"get",
"(",
"path",
")",
";",
"if",
"(",
"counter",
"==",
"null",
")",
"{",
"counter",
"=",
"new",
"AtomicInteger",
"(",
"0",
")",
";",
"failedRecoveredFiles",
".",
"put",
"(",
"path",
",",
"counter",
")",
";",
"}",
"if",
"(",
"counter",
".",
"incrementAndGet",
"(",
")",
"==",
"1",
")",
"{",
"totalFailedPaths",
".",
"get",
"(",
"last",
")",
".",
"incrementAndGet",
"(",
")",
";",
"}",
"}",
"else",
"{",
"value",
"/=",
"dividend",
";",
"p",
"=",
"new",
"Point",
"(",
"value",
",",
"path",
",",
"System",
".",
"currentTimeMillis",
"(",
")",
",",
"taskId",
")",
";",
"CounterArray",
"counters",
"=",
"histo",
".",
"get",
"(",
"value",
")",
";",
"if",
"(",
"counters",
"==",
"null",
")",
"{",
"counters",
"=",
"new",
"CounterArray",
"(",
"windowNum",
")",
";",
"histo",
".",
"put",
"(",
"value",
",",
"counters",
")",
";",
"}",
"counters",
".",
"incrementAndGet",
"(",
"last",
")",
";",
"totalPoints",
".",
"incrementAndGet",
"(",
"last",
")",
";",
"}",
"points",
".",
"add",
"(",
"p",
")",
";",
"InjectionHandler",
".",
"processEvent",
"(",
"InjectionEvent",
".",
"RAID_SEND_RECOVERY_TIME",
",",
"this",
",",
"path",
",",
"value",
",",
"taskId",
")",
";",
"}"
] | /*
If value is RECOVERY_FAIL, we consider it as recovery failure | [
"/",
"*",
"If",
"value",
"is",
"RECOVERY_FAIL",
"we",
"consider",
"it",
"as",
"recovery",
"failure"
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/raid/src/java/org/apache/hadoop/raid/RaidHistogram.java#L183-L210 |
Whiley/WhileyCompiler | src/main/java/wyc/io/WhileyFileParser.java | WhileyFileParser.parseFunctionOrMethodType | private Type parseFunctionOrMethodType(boolean isFunction, EnclosingScope scope) {
"""
Parse a function or method type, which is of the form:
<pre>
FunctionType ::= "function" [Type (',' Type)* ] "->" Type
MethodType ::= "method" [Type (',' Type)* ] "->" Type
</pre>
At the moment, it is required that parameters for a function or method
type are enclosed in braces. In principle, we would like to relax this.
However, this is difficult to make work because there is not way to
invoke a function or method without using braces.
@return
"""
int start = index;
Tuple<Identifier> lifetimes;
Tuple<Identifier> captures;
if (isFunction) {
match(Function);
captures = new Tuple<>();
lifetimes = new Tuple<>();
} else {
match(Method);
captures = parseOptionalCapturedLifetimes(scope);
scope = scope.newEnclosingScope();
lifetimes = parseOptionalLifetimeParameters(scope);
}
// First, parse the parameter type(s).
Tuple<Type> paramTypes = parseParameterTypes(scope);
Tuple<Type> returnTypes = new Tuple<>();
// Second, parse the right arrow.
if (isFunction) {
// Functions require a return type (since otherwise they are just
// nops)
match(MinusGreater);
// Third, parse the return types.
returnTypes = parseOptionalParameterTypes(scope);
} else if (tryAndMatch(true, MinusGreater) != null) {
// Methods have an optional return type
// Third, parse the return type
returnTypes = parseOptionalParameterTypes(scope);
}
// Done
Type type;
if (isFunction) {
type = new Type.Function(paramTypes, returnTypes);
} else {
type = new Type.Method(paramTypes, returnTypes, captures, lifetimes);
}
return annotateSourceLocation(type,start);
} | java | private Type parseFunctionOrMethodType(boolean isFunction, EnclosingScope scope) {
int start = index;
Tuple<Identifier> lifetimes;
Tuple<Identifier> captures;
if (isFunction) {
match(Function);
captures = new Tuple<>();
lifetimes = new Tuple<>();
} else {
match(Method);
captures = parseOptionalCapturedLifetimes(scope);
scope = scope.newEnclosingScope();
lifetimes = parseOptionalLifetimeParameters(scope);
}
// First, parse the parameter type(s).
Tuple<Type> paramTypes = parseParameterTypes(scope);
Tuple<Type> returnTypes = new Tuple<>();
// Second, parse the right arrow.
if (isFunction) {
// Functions require a return type (since otherwise they are just
// nops)
match(MinusGreater);
// Third, parse the return types.
returnTypes = parseOptionalParameterTypes(scope);
} else if (tryAndMatch(true, MinusGreater) != null) {
// Methods have an optional return type
// Third, parse the return type
returnTypes = parseOptionalParameterTypes(scope);
}
// Done
Type type;
if (isFunction) {
type = new Type.Function(paramTypes, returnTypes);
} else {
type = new Type.Method(paramTypes, returnTypes, captures, lifetimes);
}
return annotateSourceLocation(type,start);
} | [
"private",
"Type",
"parseFunctionOrMethodType",
"(",
"boolean",
"isFunction",
",",
"EnclosingScope",
"scope",
")",
"{",
"int",
"start",
"=",
"index",
";",
"Tuple",
"<",
"Identifier",
">",
"lifetimes",
";",
"Tuple",
"<",
"Identifier",
">",
"captures",
";",
"if",
"(",
"isFunction",
")",
"{",
"match",
"(",
"Function",
")",
";",
"captures",
"=",
"new",
"Tuple",
"<>",
"(",
")",
";",
"lifetimes",
"=",
"new",
"Tuple",
"<>",
"(",
")",
";",
"}",
"else",
"{",
"match",
"(",
"Method",
")",
";",
"captures",
"=",
"parseOptionalCapturedLifetimes",
"(",
"scope",
")",
";",
"scope",
"=",
"scope",
".",
"newEnclosingScope",
"(",
")",
";",
"lifetimes",
"=",
"parseOptionalLifetimeParameters",
"(",
"scope",
")",
";",
"}",
"// First, parse the parameter type(s).",
"Tuple",
"<",
"Type",
">",
"paramTypes",
"=",
"parseParameterTypes",
"(",
"scope",
")",
";",
"Tuple",
"<",
"Type",
">",
"returnTypes",
"=",
"new",
"Tuple",
"<>",
"(",
")",
";",
"// Second, parse the right arrow.",
"if",
"(",
"isFunction",
")",
"{",
"// Functions require a return type (since otherwise they are just",
"// nops)",
"match",
"(",
"MinusGreater",
")",
";",
"// Third, parse the return types.",
"returnTypes",
"=",
"parseOptionalParameterTypes",
"(",
"scope",
")",
";",
"}",
"else",
"if",
"(",
"tryAndMatch",
"(",
"true",
",",
"MinusGreater",
")",
"!=",
"null",
")",
"{",
"// Methods have an optional return type",
"// Third, parse the return type",
"returnTypes",
"=",
"parseOptionalParameterTypes",
"(",
"scope",
")",
";",
"}",
"// Done",
"Type",
"type",
";",
"if",
"(",
"isFunction",
")",
"{",
"type",
"=",
"new",
"Type",
".",
"Function",
"(",
"paramTypes",
",",
"returnTypes",
")",
";",
"}",
"else",
"{",
"type",
"=",
"new",
"Type",
".",
"Method",
"(",
"paramTypes",
",",
"returnTypes",
",",
"captures",
",",
"lifetimes",
")",
";",
"}",
"return",
"annotateSourceLocation",
"(",
"type",
",",
"start",
")",
";",
"}"
] | Parse a function or method type, which is of the form:
<pre>
FunctionType ::= "function" [Type (',' Type)* ] "->" Type
MethodType ::= "method" [Type (',' Type)* ] "->" Type
</pre>
At the moment, it is required that parameters for a function or method
type are enclosed in braces. In principle, we would like to relax this.
However, this is difficult to make work because there is not way to
invoke a function or method without using braces.
@return | [
"Parse",
"a",
"function",
"or",
"method",
"type",
"which",
"is",
"of",
"the",
"form",
":"
] | train | https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyc/io/WhileyFileParser.java#L3837-L3875 |
hazelcast/hazelcast | hazelcast/src/main/java/com/hazelcast/query/impl/Numbers.java | Numbers.equalLongAndDouble | @SuppressWarnings("checkstyle:magicnumber")
public static boolean equalLongAndDouble(long l, double d) {
"""
Checks the provided long and double values for equality.
<p>
The method fully avoids magnitude and precision losses while performing
the equality check, e.g. {@code (double) Long.MAX_VALUE} is not equal to
{@code Long.MAX_VALUE - 1}.
@param l the long value to check the equality of.
@param d the double value to check the equality of.
@return {@code true} if the provided values are equal, {@code false}
otherwise.
"""
// see compareLongWithDouble for more details on what is going on here
if (d > -0x1p53 && d < +0x1p53) {
return equalDoubles((double) l, d);
}
if (d <= -0x1p63) {
return false;
}
if (d >= +0x1p63) {
return false;
}
if (Double.isNaN(d)) {
return false;
}
return l == (long) d;
} | java | @SuppressWarnings("checkstyle:magicnumber")
public static boolean equalLongAndDouble(long l, double d) {
// see compareLongWithDouble for more details on what is going on here
if (d > -0x1p53 && d < +0x1p53) {
return equalDoubles((double) l, d);
}
if (d <= -0x1p63) {
return false;
}
if (d >= +0x1p63) {
return false;
}
if (Double.isNaN(d)) {
return false;
}
return l == (long) d;
} | [
"@",
"SuppressWarnings",
"(",
"\"checkstyle:magicnumber\"",
")",
"public",
"static",
"boolean",
"equalLongAndDouble",
"(",
"long",
"l",
",",
"double",
"d",
")",
"{",
"// see compareLongWithDouble for more details on what is going on here",
"if",
"(",
"d",
">",
"-",
"0x1",
"p53",
"&&",
"d",
"<",
"+",
"0x1",
"p53",
")",
"{",
"return",
"equalDoubles",
"(",
"(",
"double",
")",
"l",
",",
"d",
")",
";",
"}",
"if",
"(",
"d",
"<=",
"-",
"0x1",
"p63",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"d",
">=",
"+",
"0x1",
"p63",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"Double",
".",
"isNaN",
"(",
"d",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"l",
"==",
"(",
"long",
")",
"d",
";",
"}"
] | Checks the provided long and double values for equality.
<p>
The method fully avoids magnitude and precision losses while performing
the equality check, e.g. {@code (double) Long.MAX_VALUE} is not equal to
{@code Long.MAX_VALUE - 1}.
@param l the long value to check the equality of.
@param d the double value to check the equality of.
@return {@code true} if the provided values are equal, {@code false}
otherwise. | [
"Checks",
"the",
"provided",
"long",
"and",
"double",
"values",
"for",
"equality",
".",
"<p",
">",
"The",
"method",
"fully",
"avoids",
"magnitude",
"and",
"precision",
"losses",
"while",
"performing",
"the",
"equality",
"check",
"e",
".",
"g",
".",
"{",
"@code",
"(",
"double",
")",
"Long",
".",
"MAX_VALUE",
"}",
"is",
"not",
"equal",
"to",
"{",
"@code",
"Long",
".",
"MAX_VALUE",
"-",
"1",
"}",
"."
] | train | https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/query/impl/Numbers.java#L286-L307 |
codeprimate-software/cp-elements | src/main/java/org/cp/elements/util/PropertiesUtils.java | PropertiesUtils.singletonProperties | public static Properties singletonProperties(String propertyName, String propertyValue) {
"""
Factory method to construct a Singleton {@link Properties} object, a {@link Properties} instance containing
only a single property and value.
@param propertyName name of the property.
@param propertyValue value of the property.
@return a Singleton {@link Properties} instance.
@see java.util.Properties
"""
Properties singleProperty = new Properties();
singleProperty.setProperty(propertyName, propertyValue);
return singleProperty;
} | java | public static Properties singletonProperties(String propertyName, String propertyValue) {
Properties singleProperty = new Properties();
singleProperty.setProperty(propertyName, propertyValue);
return singleProperty;
} | [
"public",
"static",
"Properties",
"singletonProperties",
"(",
"String",
"propertyName",
",",
"String",
"propertyValue",
")",
"{",
"Properties",
"singleProperty",
"=",
"new",
"Properties",
"(",
")",
";",
"singleProperty",
".",
"setProperty",
"(",
"propertyName",
",",
"propertyValue",
")",
";",
"return",
"singleProperty",
";",
"}"
] | Factory method to construct a Singleton {@link Properties} object, a {@link Properties} instance containing
only a single property and value.
@param propertyName name of the property.
@param propertyValue value of the property.
@return a Singleton {@link Properties} instance.
@see java.util.Properties | [
"Factory",
"method",
"to",
"construct",
"a",
"Singleton",
"{",
"@link",
"Properties",
"}",
"object",
"a",
"{",
"@link",
"Properties",
"}",
"instance",
"containing",
"only",
"a",
"single",
"property",
"and",
"value",
"."
] | train | https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/util/PropertiesUtils.java#L40-L44 |
Drivemode/TypefaceHelper | TypefaceHelper/src/main/java/com/drivemode/android/typeface/TypefaceHelper.java | TypefaceHelper.setTypeface | public View setTypeface(Context context, @LayoutRes int layoutRes, ViewGroup parent, String typefaceName, int style) {
"""
Set the typeface to the all text views belong to the view group.
@param context the context.
@param layoutRes the layout resource id.
@param parent the parent view group to attach the layout.
@param typefaceName typeface name.
@param style the typeface style.
@return the view.
"""
ViewGroup view = (ViewGroup) LayoutInflater.from(context).inflate(layoutRes, parent);
setTypeface(view, typefaceName, style);
return view;
} | java | public View setTypeface(Context context, @LayoutRes int layoutRes, ViewGroup parent, String typefaceName, int style) {
ViewGroup view = (ViewGroup) LayoutInflater.from(context).inflate(layoutRes, parent);
setTypeface(view, typefaceName, style);
return view;
} | [
"public",
"View",
"setTypeface",
"(",
"Context",
"context",
",",
"@",
"LayoutRes",
"int",
"layoutRes",
",",
"ViewGroup",
"parent",
",",
"String",
"typefaceName",
",",
"int",
"style",
")",
"{",
"ViewGroup",
"view",
"=",
"(",
"ViewGroup",
")",
"LayoutInflater",
".",
"from",
"(",
"context",
")",
".",
"inflate",
"(",
"layoutRes",
",",
"parent",
")",
";",
"setTypeface",
"(",
"view",
",",
"typefaceName",
",",
"style",
")",
";",
"return",
"view",
";",
"}"
] | Set the typeface to the all text views belong to the view group.
@param context the context.
@param layoutRes the layout resource id.
@param parent the parent view group to attach the layout.
@param typefaceName typeface name.
@param style the typeface style.
@return the view. | [
"Set",
"the",
"typeface",
"to",
"the",
"all",
"text",
"views",
"belong",
"to",
"the",
"view",
"group",
"."
] | train | https://github.com/Drivemode/TypefaceHelper/blob/86bef9ce16b9626b7076559e846db1b9f043c008/TypefaceHelper/src/main/java/com/drivemode/android/typeface/TypefaceHelper.java#L290-L294 |
raydac/java-comment-preprocessor | jcp/src/main/java/com/igormaznitsa/meta/common/utils/Assertions.java | Assertions.assertAmong | @SafeVarargs
@Nullable
public static <T> T assertAmong(@Nullable T obj, @MayContainNull @Nonnull final T... list) {
"""
Check that object is presented among provided elements and replace the object by equal element from the list.
@param <T> type of object
@param obj object to be checked
@param list list of elements for checking
@return equal element provided in the list
@throws AssertionError if object is not found among defined ones
@since 1.0.2
"""
if (obj == null) {
for (final T i : assertNotNull(list)) {
if (i == null) {
return i;
}
}
} else {
final int objHash = obj.hashCode();
for (final T i : assertNotNull(list)) {
if (obj == i || (i != null && objHash == i.hashCode() && obj.equals(i))) {
return i;
}
}
}
final AssertionError error = new AssertionError("Object is not found among elements");
MetaErrorListeners.fireError("Asserion error", error);
throw error;
} | java | @SafeVarargs
@Nullable
public static <T> T assertAmong(@Nullable T obj, @MayContainNull @Nonnull final T... list) {
if (obj == null) {
for (final T i : assertNotNull(list)) {
if (i == null) {
return i;
}
}
} else {
final int objHash = obj.hashCode();
for (final T i : assertNotNull(list)) {
if (obj == i || (i != null && objHash == i.hashCode() && obj.equals(i))) {
return i;
}
}
}
final AssertionError error = new AssertionError("Object is not found among elements");
MetaErrorListeners.fireError("Asserion error", error);
throw error;
} | [
"@",
"SafeVarargs",
"@",
"Nullable",
"public",
"static",
"<",
"T",
">",
"T",
"assertAmong",
"(",
"@",
"Nullable",
"T",
"obj",
",",
"@",
"MayContainNull",
"@",
"Nonnull",
"final",
"T",
"...",
"list",
")",
"{",
"if",
"(",
"obj",
"==",
"null",
")",
"{",
"for",
"(",
"final",
"T",
"i",
":",
"assertNotNull",
"(",
"list",
")",
")",
"{",
"if",
"(",
"i",
"==",
"null",
")",
"{",
"return",
"i",
";",
"}",
"}",
"}",
"else",
"{",
"final",
"int",
"objHash",
"=",
"obj",
".",
"hashCode",
"(",
")",
";",
"for",
"(",
"final",
"T",
"i",
":",
"assertNotNull",
"(",
"list",
")",
")",
"{",
"if",
"(",
"obj",
"==",
"i",
"||",
"(",
"i",
"!=",
"null",
"&&",
"objHash",
"==",
"i",
".",
"hashCode",
"(",
")",
"&&",
"obj",
".",
"equals",
"(",
"i",
")",
")",
")",
"{",
"return",
"i",
";",
"}",
"}",
"}",
"final",
"AssertionError",
"error",
"=",
"new",
"AssertionError",
"(",
"\"Object is not found among elements\"",
")",
";",
"MetaErrorListeners",
".",
"fireError",
"(",
"\"Asserion error\"",
",",
"error",
")",
";",
"throw",
"error",
";",
"}"
] | Check that object is presented among provided elements and replace the object by equal element from the list.
@param <T> type of object
@param obj object to be checked
@param list list of elements for checking
@return equal element provided in the list
@throws AssertionError if object is not found among defined ones
@since 1.0.2 | [
"Check",
"that",
"object",
"is",
"presented",
"among",
"provided",
"elements",
"and",
"replace",
"the",
"object",
"by",
"equal",
"element",
"from",
"the",
"list",
"."
] | train | https://github.com/raydac/java-comment-preprocessor/blob/83ac87b575ac084914d77695a8c8673de3b8300c/jcp/src/main/java/com/igormaznitsa/meta/common/utils/Assertions.java#L259-L279 |
kopihao/peasy-recyclerview | peasy-recyclerview/src/main/java/com/kopirealm/peasyrecyclerview/PeasyViewHolder.java | PeasyViewHolder.GetViewHolder | public static <VH extends PeasyViewHolder> VH GetViewHolder(PeasyViewHolder vh, Class<VH> cls) {
"""
Help to cast provided PeasyViewHolder to its child class instance
@param vh PeasyViewHolder Parent Class
@param cls Class of PeasyViewHolder
@param <VH> PeasyViewHolder Child Class
@return VH as Child Class Instance
"""
return cls.cast(vh);
} | java | public static <VH extends PeasyViewHolder> VH GetViewHolder(PeasyViewHolder vh, Class<VH> cls) {
return cls.cast(vh);
} | [
"public",
"static",
"<",
"VH",
"extends",
"PeasyViewHolder",
">",
"VH",
"GetViewHolder",
"(",
"PeasyViewHolder",
"vh",
",",
"Class",
"<",
"VH",
">",
"cls",
")",
"{",
"return",
"cls",
".",
"cast",
"(",
"vh",
")",
";",
"}"
] | Help to cast provided PeasyViewHolder to its child class instance
@param vh PeasyViewHolder Parent Class
@param cls Class of PeasyViewHolder
@param <VH> PeasyViewHolder Child Class
@return VH as Child Class Instance | [
"Help",
"to",
"cast",
"provided",
"PeasyViewHolder",
"to",
"its",
"child",
"class",
"instance"
] | train | https://github.com/kopihao/peasy-recyclerview/blob/a26071849e5d5b5b1febe685f205558b49908f87/peasy-recyclerview/src/main/java/com/kopirealm/peasyrecyclerview/PeasyViewHolder.java#L37-L39 |
querydsl/querydsl | querydsl-core/src/main/java/com/querydsl/core/types/dsl/PathBuilder.java | PathBuilder.get | public BooleanPath get(BooleanPath path) {
"""
Create a new Boolean typed path
@param path existing path
@return property path
"""
BooleanPath newPath = getBoolean(toString(path));
return addMetadataOf(newPath, path);
} | java | public BooleanPath get(BooleanPath path) {
BooleanPath newPath = getBoolean(toString(path));
return addMetadataOf(newPath, path);
} | [
"public",
"BooleanPath",
"get",
"(",
"BooleanPath",
"path",
")",
"{",
"BooleanPath",
"newPath",
"=",
"getBoolean",
"(",
"toString",
"(",
"path",
")",
")",
";",
"return",
"addMetadataOf",
"(",
"newPath",
",",
"path",
")",
";",
"}"
] | Create a new Boolean typed path
@param path existing path
@return property path | [
"Create",
"a",
"new",
"Boolean",
"typed",
"path"
] | train | https://github.com/querydsl/querydsl/blob/2bf234caf78549813a1e0f44d9c30ecc5ef734e3/querydsl-core/src/main/java/com/querydsl/core/types/dsl/PathBuilder.java#L183-L186 |
SahaginOrg/sahagin-java | src/main/java/org/sahagin/share/yaml/YamlUtils.java | YamlUtils.getIntValue | public static Integer getIntValue(Map<String, Object> yamlObject, String key, boolean allowsEmpty)
throws YamlConvertException {
"""
if allowsEmpty, returns null for the case no key entry or null value
"""
Object obj = getObjectValue(yamlObject, key, allowsEmpty);
if (obj == null && allowsEmpty) {
return null;
}
String objStr;
if (obj == null) {
objStr = null;
} else {
objStr = obj.toString();
}
try {
return new Integer(objStr);
} catch (NumberFormatException e) {
throw new YamlConvertException(String.format(MSG_VALUE_NOT_INT, key, objStr));
}
} | java | public static Integer getIntValue(Map<String, Object> yamlObject, String key, boolean allowsEmpty)
throws YamlConvertException {
Object obj = getObjectValue(yamlObject, key, allowsEmpty);
if (obj == null && allowsEmpty) {
return null;
}
String objStr;
if (obj == null) {
objStr = null;
} else {
objStr = obj.toString();
}
try {
return new Integer(objStr);
} catch (NumberFormatException e) {
throw new YamlConvertException(String.format(MSG_VALUE_NOT_INT, key, objStr));
}
} | [
"public",
"static",
"Integer",
"getIntValue",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"yamlObject",
",",
"String",
"key",
",",
"boolean",
"allowsEmpty",
")",
"throws",
"YamlConvertException",
"{",
"Object",
"obj",
"=",
"getObjectValue",
"(",
"yamlObject",
",",
"key",
",",
"allowsEmpty",
")",
";",
"if",
"(",
"obj",
"==",
"null",
"&&",
"allowsEmpty",
")",
"{",
"return",
"null",
";",
"}",
"String",
"objStr",
";",
"if",
"(",
"obj",
"==",
"null",
")",
"{",
"objStr",
"=",
"null",
";",
"}",
"else",
"{",
"objStr",
"=",
"obj",
".",
"toString",
"(",
")",
";",
"}",
"try",
"{",
"return",
"new",
"Integer",
"(",
"objStr",
")",
";",
"}",
"catch",
"(",
"NumberFormatException",
"e",
")",
"{",
"throw",
"new",
"YamlConvertException",
"(",
"String",
".",
"format",
"(",
"MSG_VALUE_NOT_INT",
",",
"key",
",",
"objStr",
")",
")",
";",
"}",
"}"
] | if allowsEmpty, returns null for the case no key entry or null value | [
"if",
"allowsEmpty",
"returns",
"null",
"for",
"the",
"case",
"no",
"key",
"entry",
"or",
"null",
"value"
] | train | https://github.com/SahaginOrg/sahagin-java/blob/7ace428adebe3466ceb5826bc9681f8e3d52be68/src/main/java/org/sahagin/share/yaml/YamlUtils.java#L111-L128 |
GoogleCloudPlatform/bigdata-interop | gcs/src/main/java/com/google/cloud/hadoop/fs/gcs/GoogleHadoopFileSystemBase.java | GoogleHadoopFileSystemBase.initializeDelegationTokenSupport | private void initializeDelegationTokenSupport(Configuration config, URI path) throws IOException {
"""
Initialize the delegation token support for this filesystem.
@param config The filesystem configuration
@param path The filesystem path
@throws IOException
"""
logger.atFine().log("GHFS.initializeDelegationTokenSupport");
// Load delegation token binding, if support is configured
GcsDelegationTokens dts = new GcsDelegationTokens();
Text service = new Text(getScheme() + "://" + path.getAuthority());
dts.bindToFileSystem(this, service);
try {
dts.init(config);
delegationTokens = dts;
if (delegationTokens.isBoundToDT()) {
logger.atFine().log(
"GHFS.initializeDelegationTokenSupport: Using existing delegation token.");
}
} catch (IllegalStateException e) {
logger.atInfo().log("GHFS.initializeDelegationTokenSupport: %s", e.getMessage());
}
} | java | private void initializeDelegationTokenSupport(Configuration config, URI path) throws IOException {
logger.atFine().log("GHFS.initializeDelegationTokenSupport");
// Load delegation token binding, if support is configured
GcsDelegationTokens dts = new GcsDelegationTokens();
Text service = new Text(getScheme() + "://" + path.getAuthority());
dts.bindToFileSystem(this, service);
try {
dts.init(config);
delegationTokens = dts;
if (delegationTokens.isBoundToDT()) {
logger.atFine().log(
"GHFS.initializeDelegationTokenSupport: Using existing delegation token.");
}
} catch (IllegalStateException e) {
logger.atInfo().log("GHFS.initializeDelegationTokenSupport: %s", e.getMessage());
}
} | [
"private",
"void",
"initializeDelegationTokenSupport",
"(",
"Configuration",
"config",
",",
"URI",
"path",
")",
"throws",
"IOException",
"{",
"logger",
".",
"atFine",
"(",
")",
".",
"log",
"(",
"\"GHFS.initializeDelegationTokenSupport\"",
")",
";",
"// Load delegation token binding, if support is configured",
"GcsDelegationTokens",
"dts",
"=",
"new",
"GcsDelegationTokens",
"(",
")",
";",
"Text",
"service",
"=",
"new",
"Text",
"(",
"getScheme",
"(",
")",
"+",
"\"://\"",
"+",
"path",
".",
"getAuthority",
"(",
")",
")",
";",
"dts",
".",
"bindToFileSystem",
"(",
"this",
",",
"service",
")",
";",
"try",
"{",
"dts",
".",
"init",
"(",
"config",
")",
";",
"delegationTokens",
"=",
"dts",
";",
"if",
"(",
"delegationTokens",
".",
"isBoundToDT",
"(",
")",
")",
"{",
"logger",
".",
"atFine",
"(",
")",
".",
"log",
"(",
"\"GHFS.initializeDelegationTokenSupport: Using existing delegation token.\"",
")",
";",
"}",
"}",
"catch",
"(",
"IllegalStateException",
"e",
")",
"{",
"logger",
".",
"atInfo",
"(",
")",
".",
"log",
"(",
"\"GHFS.initializeDelegationTokenSupport: %s\"",
",",
"e",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"}"
] | Initialize the delegation token support for this filesystem.
@param config The filesystem configuration
@param path The filesystem path
@throws IOException | [
"Initialize",
"the",
"delegation",
"token",
"support",
"for",
"this",
"filesystem",
"."
] | train | https://github.com/GoogleCloudPlatform/bigdata-interop/blob/918d91c80a63e36046edb28972a5c65d3326a858/gcs/src/main/java/com/google/cloud/hadoop/fs/gcs/GoogleHadoopFileSystemBase.java#L638-L654 |
mikepenz/MaterialDrawer | library/src/main/java/com/mikepenz/materialdrawer/DrawerUtils.java | DrawerUtils.processDrawerLayoutParams | public static DrawerLayout.LayoutParams processDrawerLayoutParams(DrawerBuilder drawer, DrawerLayout.LayoutParams params) {
"""
helper to extend the layoutParams of the drawer
@param params
@return
"""
if (params != null) {
if (drawer.mDrawerGravity != null && (drawer.mDrawerGravity == Gravity.RIGHT || drawer.mDrawerGravity == Gravity.END)) {
params.rightMargin = 0;
if (Build.VERSION.SDK_INT >= 17) {
params.setMarginEnd(0);
}
params.leftMargin = drawer.mActivity.getResources().getDimensionPixelSize(R.dimen.material_drawer_margin);
if (Build.VERSION.SDK_INT >= 17) {
params.setMarginEnd(drawer.mActivity.getResources().getDimensionPixelSize(R.dimen.material_drawer_margin));
}
}
if (drawer.mDrawerWidth > -1) {
params.width = drawer.mDrawerWidth;
} else {
params.width = DrawerUIUtils.getOptimalDrawerWidth(drawer.mActivity);
}
}
return params;
} | java | public static DrawerLayout.LayoutParams processDrawerLayoutParams(DrawerBuilder drawer, DrawerLayout.LayoutParams params) {
if (params != null) {
if (drawer.mDrawerGravity != null && (drawer.mDrawerGravity == Gravity.RIGHT || drawer.mDrawerGravity == Gravity.END)) {
params.rightMargin = 0;
if (Build.VERSION.SDK_INT >= 17) {
params.setMarginEnd(0);
}
params.leftMargin = drawer.mActivity.getResources().getDimensionPixelSize(R.dimen.material_drawer_margin);
if (Build.VERSION.SDK_INT >= 17) {
params.setMarginEnd(drawer.mActivity.getResources().getDimensionPixelSize(R.dimen.material_drawer_margin));
}
}
if (drawer.mDrawerWidth > -1) {
params.width = drawer.mDrawerWidth;
} else {
params.width = DrawerUIUtils.getOptimalDrawerWidth(drawer.mActivity);
}
}
return params;
} | [
"public",
"static",
"DrawerLayout",
".",
"LayoutParams",
"processDrawerLayoutParams",
"(",
"DrawerBuilder",
"drawer",
",",
"DrawerLayout",
".",
"LayoutParams",
"params",
")",
"{",
"if",
"(",
"params",
"!=",
"null",
")",
"{",
"if",
"(",
"drawer",
".",
"mDrawerGravity",
"!=",
"null",
"&&",
"(",
"drawer",
".",
"mDrawerGravity",
"==",
"Gravity",
".",
"RIGHT",
"||",
"drawer",
".",
"mDrawerGravity",
"==",
"Gravity",
".",
"END",
")",
")",
"{",
"params",
".",
"rightMargin",
"=",
"0",
";",
"if",
"(",
"Build",
".",
"VERSION",
".",
"SDK_INT",
">=",
"17",
")",
"{",
"params",
".",
"setMarginEnd",
"(",
"0",
")",
";",
"}",
"params",
".",
"leftMargin",
"=",
"drawer",
".",
"mActivity",
".",
"getResources",
"(",
")",
".",
"getDimensionPixelSize",
"(",
"R",
".",
"dimen",
".",
"material_drawer_margin",
")",
";",
"if",
"(",
"Build",
".",
"VERSION",
".",
"SDK_INT",
">=",
"17",
")",
"{",
"params",
".",
"setMarginEnd",
"(",
"drawer",
".",
"mActivity",
".",
"getResources",
"(",
")",
".",
"getDimensionPixelSize",
"(",
"R",
".",
"dimen",
".",
"material_drawer_margin",
")",
")",
";",
"}",
"}",
"if",
"(",
"drawer",
".",
"mDrawerWidth",
">",
"-",
"1",
")",
"{",
"params",
".",
"width",
"=",
"drawer",
".",
"mDrawerWidth",
";",
"}",
"else",
"{",
"params",
".",
"width",
"=",
"DrawerUIUtils",
".",
"getOptimalDrawerWidth",
"(",
"drawer",
".",
"mActivity",
")",
";",
"}",
"}",
"return",
"params",
";",
"}"
] | helper to extend the layoutParams of the drawer
@param params
@return | [
"helper",
"to",
"extend",
"the",
"layoutParams",
"of",
"the",
"drawer"
] | train | https://github.com/mikepenz/MaterialDrawer/blob/f4fb31635767edead0a01cee7b7588942b89d8d9/library/src/main/java/com/mikepenz/materialdrawer/DrawerUtils.java#L424-L446 |
josueeduardo/snappy | plugin-parent/snappy-maven-plugin/src/main/java/io/joshworks/snappy/maven/tools/JarWriter.java | JarWriter.writeEntries | public void writeEntries(JarFile jarFile) throws IOException {
"""
Write all entries from the specified jar file.
@param jarFile the source jar file
@throws IOException if the entries cannot be written
"""
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
ZipHeaderPeekInputStream inputStream = new ZipHeaderPeekInputStream(
jarFile.getInputStream(entry));
try {
if (inputStream.hasZipHeader() && entry.getMethod() != ZipEntry.STORED) {
new CrcAndSize(inputStream).setupStoredEntry(entry);
inputStream.close();
inputStream = new ZipHeaderPeekInputStream(
jarFile.getInputStream(entry));
}
EntryWriter entryWriter = new InputStreamEntryWriter(inputStream, true);
writeEntry(entry, entryWriter);
} finally {
inputStream.close();
}
}
} | java | public void writeEntries(JarFile jarFile) throws IOException {
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
ZipHeaderPeekInputStream inputStream = new ZipHeaderPeekInputStream(
jarFile.getInputStream(entry));
try {
if (inputStream.hasZipHeader() && entry.getMethod() != ZipEntry.STORED) {
new CrcAndSize(inputStream).setupStoredEntry(entry);
inputStream.close();
inputStream = new ZipHeaderPeekInputStream(
jarFile.getInputStream(entry));
}
EntryWriter entryWriter = new InputStreamEntryWriter(inputStream, true);
writeEntry(entry, entryWriter);
} finally {
inputStream.close();
}
}
} | [
"public",
"void",
"writeEntries",
"(",
"JarFile",
"jarFile",
")",
"throws",
"IOException",
"{",
"Enumeration",
"<",
"JarEntry",
">",
"entries",
"=",
"jarFile",
".",
"entries",
"(",
")",
";",
"while",
"(",
"entries",
".",
"hasMoreElements",
"(",
")",
")",
"{",
"JarEntry",
"entry",
"=",
"entries",
".",
"nextElement",
"(",
")",
";",
"ZipHeaderPeekInputStream",
"inputStream",
"=",
"new",
"ZipHeaderPeekInputStream",
"(",
"jarFile",
".",
"getInputStream",
"(",
"entry",
")",
")",
";",
"try",
"{",
"if",
"(",
"inputStream",
".",
"hasZipHeader",
"(",
")",
"&&",
"entry",
".",
"getMethod",
"(",
")",
"!=",
"ZipEntry",
".",
"STORED",
")",
"{",
"new",
"CrcAndSize",
"(",
"inputStream",
")",
".",
"setupStoredEntry",
"(",
"entry",
")",
";",
"inputStream",
".",
"close",
"(",
")",
";",
"inputStream",
"=",
"new",
"ZipHeaderPeekInputStream",
"(",
"jarFile",
".",
"getInputStream",
"(",
"entry",
")",
")",
";",
"}",
"EntryWriter",
"entryWriter",
"=",
"new",
"InputStreamEntryWriter",
"(",
"inputStream",
",",
"true",
")",
";",
"writeEntry",
"(",
"entry",
",",
"entryWriter",
")",
";",
"}",
"finally",
"{",
"inputStream",
".",
"close",
"(",
")",
";",
"}",
"}",
"}"
] | Write all entries from the specified jar file.
@param jarFile the source jar file
@throws IOException if the entries cannot be written | [
"Write",
"all",
"entries",
"from",
"the",
"specified",
"jar",
"file",
"."
] | train | https://github.com/josueeduardo/snappy/blob/d95a9e811eda3c24a5e53086369208819884fa49/plugin-parent/snappy-maven-plugin/src/main/java/io/joshworks/snappy/maven/tools/JarWriter.java#L125-L144 |
OpenLiberty/open-liberty | dev/com.ibm.ws.org.apache.cxf.cxf.rt.frontend.jaxrs.3.2/src/org/apache/cxf/jaxrs/provider/ProviderFactory.java | ProviderFactory.putTypes | private static void putTypes(Class<?> cls, Class<?> expectedCls, Class<?> commonBaseCls, Type[] types) {
"""
Add a new expected class and Type[] to the Map of Maps. If there is only one expected class
for a given class, then we will use a Collections.singletonMap(). Otherwise we will convert to a
ConcurrentHashMap. This reduces overhead when there is only one expected Class.
@param cls
@param expectedCls
@param types
"""
poll();
genericInterfacesCache.put(new ClassesKey(referenceQueue, cls, expectedCls, commonBaseCls), types);
} | java | private static void putTypes(Class<?> cls, Class<?> expectedCls, Class<?> commonBaseCls, Type[] types) {
poll();
genericInterfacesCache.put(new ClassesKey(referenceQueue, cls, expectedCls, commonBaseCls), types);
} | [
"private",
"static",
"void",
"putTypes",
"(",
"Class",
"<",
"?",
">",
"cls",
",",
"Class",
"<",
"?",
">",
"expectedCls",
",",
"Class",
"<",
"?",
">",
"commonBaseCls",
",",
"Type",
"[",
"]",
"types",
")",
"{",
"poll",
"(",
")",
";",
"genericInterfacesCache",
".",
"put",
"(",
"new",
"ClassesKey",
"(",
"referenceQueue",
",",
"cls",
",",
"expectedCls",
",",
"commonBaseCls",
")",
",",
"types",
")",
";",
"}"
] | Add a new expected class and Type[] to the Map of Maps. If there is only one expected class
for a given class, then we will use a Collections.singletonMap(). Otherwise we will convert to a
ConcurrentHashMap. This reduces overhead when there is only one expected Class.
@param cls
@param expectedCls
@param types | [
"Add",
"a",
"new",
"expected",
"class",
"and",
"Type",
"[]",
"to",
"the",
"Map",
"of",
"Maps",
".",
"If",
"there",
"is",
"only",
"one",
"expected",
"class",
"for",
"a",
"given",
"class",
"then",
"we",
"will",
"use",
"a",
"Collections",
".",
"singletonMap",
"()",
".",
"Otherwise",
"we",
"will",
"convert",
"to",
"a",
"ConcurrentHashMap",
".",
"This",
"reduces",
"overhead",
"when",
"there",
"is",
"only",
"one",
"expected",
"Class",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.org.apache.cxf.cxf.rt.frontend.jaxrs.3.2/src/org/apache/cxf/jaxrs/provider/ProviderFactory.java#L1939-L1942 |
OpenLiberty/open-liberty | dev/com.ibm.ws.kernel.boot.core/src/com/ibm/ws/kernel/provisioning/ContentBasedLocalBundleRepository.java | ContentBasedLocalBundleRepository.includeBaseLocation | @Override
protected synchronized void includeBaseLocation(String baseLocation) {
"""
This method scans the provided location under the install dir. It looks at all the jar files in that directory
and provided the file isn't in the cache it'll read the manifest and add it into memory.
@param baseLocation the directory in the install to scan.
"""
_locations.add(baseLocation);
// only do the processing if the cache has been read.
if (_cacheRead) {
File[] files = new File(_installDir, baseLocation).listFiles(new FileFilter() {
@Override
public boolean accept(File arg0) {
// select files only if they end .jar and they aren't in the cache already.
return arg0.getName().endsWith(".jar") && !!!_bundleLocations.contains(arg0);
}
});
if (files != null) {
for (File f : files) {
BundleInfo bInfo;
try {
bInfo = new BundleInfo(f, baseLocation);
if (bInfo.symbolicName != null) {
_dirty = true;
addToCache(bInfo);
}
} catch (IOException e) {
}
}
}
}
} | java | @Override
protected synchronized void includeBaseLocation(String baseLocation) {
_locations.add(baseLocation);
// only do the processing if the cache has been read.
if (_cacheRead) {
File[] files = new File(_installDir, baseLocation).listFiles(new FileFilter() {
@Override
public boolean accept(File arg0) {
// select files only if they end .jar and they aren't in the cache already.
return arg0.getName().endsWith(".jar") && !!!_bundleLocations.contains(arg0);
}
});
if (files != null) {
for (File f : files) {
BundleInfo bInfo;
try {
bInfo = new BundleInfo(f, baseLocation);
if (bInfo.symbolicName != null) {
_dirty = true;
addToCache(bInfo);
}
} catch (IOException e) {
}
}
}
}
} | [
"@",
"Override",
"protected",
"synchronized",
"void",
"includeBaseLocation",
"(",
"String",
"baseLocation",
")",
"{",
"_locations",
".",
"add",
"(",
"baseLocation",
")",
";",
"// only do the processing if the cache has been read.",
"if",
"(",
"_cacheRead",
")",
"{",
"File",
"[",
"]",
"files",
"=",
"new",
"File",
"(",
"_installDir",
",",
"baseLocation",
")",
".",
"listFiles",
"(",
"new",
"FileFilter",
"(",
")",
"{",
"@",
"Override",
"public",
"boolean",
"accept",
"(",
"File",
"arg0",
")",
"{",
"// select files only if they end .jar and they aren't in the cache already.",
"return",
"arg0",
".",
"getName",
"(",
")",
".",
"endsWith",
"(",
"\".jar\"",
")",
"&&",
"!",
"!",
"!",
"_bundleLocations",
".",
"contains",
"(",
"arg0",
")",
";",
"}",
"}",
")",
";",
"if",
"(",
"files",
"!=",
"null",
")",
"{",
"for",
"(",
"File",
"f",
":",
"files",
")",
"{",
"BundleInfo",
"bInfo",
";",
"try",
"{",
"bInfo",
"=",
"new",
"BundleInfo",
"(",
"f",
",",
"baseLocation",
")",
";",
"if",
"(",
"bInfo",
".",
"symbolicName",
"!=",
"null",
")",
"{",
"_dirty",
"=",
"true",
";",
"addToCache",
"(",
"bInfo",
")",
";",
"}",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"}",
"}",
"}",
"}",
"}"
] | This method scans the provided location under the install dir. It looks at all the jar files in that directory
and provided the file isn't in the cache it'll read the manifest and add it into memory.
@param baseLocation the directory in the install to scan. | [
"This",
"method",
"scans",
"the",
"provided",
"location",
"under",
"the",
"install",
"dir",
".",
"It",
"looks",
"at",
"all",
"the",
"jar",
"files",
"in",
"that",
"directory",
"and",
"provided",
"the",
"file",
"isn",
"t",
"in",
"the",
"cache",
"it",
"ll",
"read",
"the",
"manifest",
"and",
"add",
"it",
"into",
"memory",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.kernel.boot.core/src/com/ibm/ws/kernel/provisioning/ContentBasedLocalBundleRepository.java#L357-L385 |
arquillian/arquillian-algeron | common/git/src/main/java/org/arquillian/algeron/git/GitOperations.java | GitOperations.createTag | public Ref createTag(Git git, String name) {
"""
Creates a tag.
@param git
instance.
@param name
of the tag.
@return Ref created to tag.
"""
try {
return git.tag()
.setName(name)
.call();
} catch (GitAPIException e) {
throw new IllegalStateException(e);
}
} | java | public Ref createTag(Git git, String name) {
try {
return git.tag()
.setName(name)
.call();
} catch (GitAPIException e) {
throw new IllegalStateException(e);
}
} | [
"public",
"Ref",
"createTag",
"(",
"Git",
"git",
",",
"String",
"name",
")",
"{",
"try",
"{",
"return",
"git",
".",
"tag",
"(",
")",
".",
"setName",
"(",
"name",
")",
".",
"call",
"(",
")",
";",
"}",
"catch",
"(",
"GitAPIException",
"e",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"e",
")",
";",
"}",
"}"
] | Creates a tag.
@param git
instance.
@param name
of the tag.
@return Ref created to tag. | [
"Creates",
"a",
"tag",
"."
] | train | https://github.com/arquillian/arquillian-algeron/blob/ec79372defdafe99ab2f7bb696f1c1eabdbbacb6/common/git/src/main/java/org/arquillian/algeron/git/GitOperations.java#L329-L337 |
apache/incubator-heron | heron/packing/src/java/org/apache/heron/packing/roundrobin/RoundRobinPacking.java | RoundRobinPacking.getRoundRobinAllocation | private Map<Integer, List<InstanceId>> getRoundRobinAllocation(
int numContainer, Map<String, Integer> parallelismMap) {
"""
Get the instances' allocation basing on round robin algorithm
@return containerId -> list of InstanceId belonging to this container
"""
Map<Integer, List<InstanceId>> allocation = new HashMap<>();
int totalInstance = TopologyUtils.getTotalInstance(parallelismMap);
if (numContainer < 1) {
throw new RuntimeException(String.format("Invlaid number of container: %d", numContainer));
} else if (numContainer > totalInstance) {
throw new RuntimeException(
String.format("More containers (%d) allocated than instances (%d).",
numContainer, totalInstance));
}
for (int i = 1; i <= numContainer; ++i) {
allocation.put(i, new ArrayList<>());
}
int index = 1;
int globalTaskIndex = 1;
// To ensure we spread out the big instances first
// Only sorting by RAM here because only RAM can be explicitly capped by JVM processes
List<String> sortedInstances = getSortedRAMComponents(parallelismMap.keySet()).stream()
.map(ResourceRequirement::getComponentName).collect(Collectors.toList());
for (String component : sortedInstances) {
int numInstance = parallelismMap.get(component);
for (int i = 0; i < numInstance; ++i) {
allocation.get(index).add(new InstanceId(component, globalTaskIndex, i));
index = (index == numContainer) ? 1 : index + 1;
globalTaskIndex++;
}
}
return allocation;
} | java | private Map<Integer, List<InstanceId>> getRoundRobinAllocation(
int numContainer, Map<String, Integer> parallelismMap) {
Map<Integer, List<InstanceId>> allocation = new HashMap<>();
int totalInstance = TopologyUtils.getTotalInstance(parallelismMap);
if (numContainer < 1) {
throw new RuntimeException(String.format("Invlaid number of container: %d", numContainer));
} else if (numContainer > totalInstance) {
throw new RuntimeException(
String.format("More containers (%d) allocated than instances (%d).",
numContainer, totalInstance));
}
for (int i = 1; i <= numContainer; ++i) {
allocation.put(i, new ArrayList<>());
}
int index = 1;
int globalTaskIndex = 1;
// To ensure we spread out the big instances first
// Only sorting by RAM here because only RAM can be explicitly capped by JVM processes
List<String> sortedInstances = getSortedRAMComponents(parallelismMap.keySet()).stream()
.map(ResourceRequirement::getComponentName).collect(Collectors.toList());
for (String component : sortedInstances) {
int numInstance = parallelismMap.get(component);
for (int i = 0; i < numInstance; ++i) {
allocation.get(index).add(new InstanceId(component, globalTaskIndex, i));
index = (index == numContainer) ? 1 : index + 1;
globalTaskIndex++;
}
}
return allocation;
} | [
"private",
"Map",
"<",
"Integer",
",",
"List",
"<",
"InstanceId",
">",
">",
"getRoundRobinAllocation",
"(",
"int",
"numContainer",
",",
"Map",
"<",
"String",
",",
"Integer",
">",
"parallelismMap",
")",
"{",
"Map",
"<",
"Integer",
",",
"List",
"<",
"InstanceId",
">",
">",
"allocation",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"int",
"totalInstance",
"=",
"TopologyUtils",
".",
"getTotalInstance",
"(",
"parallelismMap",
")",
";",
"if",
"(",
"numContainer",
"<",
"1",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"String",
".",
"format",
"(",
"\"Invlaid number of container: %d\"",
",",
"numContainer",
")",
")",
";",
"}",
"else",
"if",
"(",
"numContainer",
">",
"totalInstance",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"String",
".",
"format",
"(",
"\"More containers (%d) allocated than instances (%d).\"",
",",
"numContainer",
",",
"totalInstance",
")",
")",
";",
"}",
"for",
"(",
"int",
"i",
"=",
"1",
";",
"i",
"<=",
"numContainer",
";",
"++",
"i",
")",
"{",
"allocation",
".",
"put",
"(",
"i",
",",
"new",
"ArrayList",
"<>",
"(",
")",
")",
";",
"}",
"int",
"index",
"=",
"1",
";",
"int",
"globalTaskIndex",
"=",
"1",
";",
"// To ensure we spread out the big instances first",
"// Only sorting by RAM here because only RAM can be explicitly capped by JVM processes",
"List",
"<",
"String",
">",
"sortedInstances",
"=",
"getSortedRAMComponents",
"(",
"parallelismMap",
".",
"keySet",
"(",
")",
")",
".",
"stream",
"(",
")",
".",
"map",
"(",
"ResourceRequirement",
"::",
"getComponentName",
")",
".",
"collect",
"(",
"Collectors",
".",
"toList",
"(",
")",
")",
";",
"for",
"(",
"String",
"component",
":",
"sortedInstances",
")",
"{",
"int",
"numInstance",
"=",
"parallelismMap",
".",
"get",
"(",
"component",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"numInstance",
";",
"++",
"i",
")",
"{",
"allocation",
".",
"get",
"(",
"index",
")",
".",
"add",
"(",
"new",
"InstanceId",
"(",
"component",
",",
"globalTaskIndex",
",",
"i",
")",
")",
";",
"index",
"=",
"(",
"index",
"==",
"numContainer",
")",
"?",
"1",
":",
"index",
"+",
"1",
";",
"globalTaskIndex",
"++",
";",
"}",
"}",
"return",
"allocation",
";",
"}"
] | Get the instances' allocation basing on round robin algorithm
@return containerId -> list of InstanceId belonging to this container | [
"Get",
"the",
"instances",
"allocation",
"basing",
"on",
"round",
"robin",
"algorithm"
] | train | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/packing/src/java/org/apache/heron/packing/roundrobin/RoundRobinPacking.java#L363-L395 |
neo4j/neo4j-java-driver | driver/src/main/java/org/neo4j/driver/internal/util/CertificateTool.java | CertificateTool.saveX509Cert | public static void saveX509Cert( Certificate[] certs, File certFile ) throws GeneralSecurityException, IOException {
"""
Save a list of certificates into a file
@param certs
@param certFile
@throws GeneralSecurityException
@throws IOException
"""
try ( BufferedWriter writer = new BufferedWriter( new FileWriter( certFile ) ) )
{
for ( Certificate cert : certs )
{
String certStr = Base64.getEncoder().encodeToString( cert.getEncoded() ).replaceAll( "(.{64})", "$1\n" );
writer.write( BEGIN_CERT );
writer.newLine();
writer.write( certStr );
writer.newLine();
writer.write( END_CERT );
writer.newLine();
}
}
} | java | public static void saveX509Cert( Certificate[] certs, File certFile ) throws GeneralSecurityException, IOException
{
try ( BufferedWriter writer = new BufferedWriter( new FileWriter( certFile ) ) )
{
for ( Certificate cert : certs )
{
String certStr = Base64.getEncoder().encodeToString( cert.getEncoded() ).replaceAll( "(.{64})", "$1\n" );
writer.write( BEGIN_CERT );
writer.newLine();
writer.write( certStr );
writer.newLine();
writer.write( END_CERT );
writer.newLine();
}
}
} | [
"public",
"static",
"void",
"saveX509Cert",
"(",
"Certificate",
"[",
"]",
"certs",
",",
"File",
"certFile",
")",
"throws",
"GeneralSecurityException",
",",
"IOException",
"{",
"try",
"(",
"BufferedWriter",
"writer",
"=",
"new",
"BufferedWriter",
"(",
"new",
"FileWriter",
"(",
"certFile",
")",
")",
")",
"{",
"for",
"(",
"Certificate",
"cert",
":",
"certs",
")",
"{",
"String",
"certStr",
"=",
"Base64",
".",
"getEncoder",
"(",
")",
".",
"encodeToString",
"(",
"cert",
".",
"getEncoded",
"(",
")",
")",
".",
"replaceAll",
"(",
"\"(.{64})\"",
",",
"\"$1\\n\"",
")",
";",
"writer",
".",
"write",
"(",
"BEGIN_CERT",
")",
";",
"writer",
".",
"newLine",
"(",
")",
";",
"writer",
".",
"write",
"(",
"certStr",
")",
";",
"writer",
".",
"newLine",
"(",
")",
";",
"writer",
".",
"write",
"(",
"END_CERT",
")",
";",
"writer",
".",
"newLine",
"(",
")",
";",
"}",
"}",
"}"
] | Save a list of certificates into a file
@param certs
@param certFile
@throws GeneralSecurityException
@throws IOException | [
"Save",
"a",
"list",
"of",
"certificates",
"into",
"a",
"file"
] | train | https://github.com/neo4j/neo4j-java-driver/blob/8dad6c48251fa1ab7017e72d9998a24fa2337a22/driver/src/main/java/org/neo4j/driver/internal/util/CertificateTool.java#L85-L103 |
coursera/courier | generator-api/src/main/java/org/coursera/courier/lang/DocEscaping.java | DocEscaping.stringToDocComment | public static String stringToDocComment(String doc, DocCommentStyle style) {
"""
Returns a doc comment, as a string of source, for the given documentation string
and deprecated property.
@param doc provides the schemadoc for the symbol, if any. May be null.
@return an escaped schemadoc string.
"""
if (doc == null || doc.trim().isEmpty()) return "";
String commentNewline = (style == DocCommentStyle.ASTRISK_MARGIN) ? "\n * " : "\n";
String schemadoc = wrap(escape(doc)).replaceAll("\\n", commentNewline);
StringBuilder builder = new StringBuilder();
builder.append("/**\n");
if (style == DocCommentStyle.ASTRISK_MARGIN) builder.append(" * ");
builder.append(schemadoc).append("\n");
if (style == DocCommentStyle.ASTRISK_MARGIN) builder.append(" ");
builder.append("*/");
return builder.toString();
} | java | public static String stringToDocComment(String doc, DocCommentStyle style) {
if (doc == null || doc.trim().isEmpty()) return "";
String commentNewline = (style == DocCommentStyle.ASTRISK_MARGIN) ? "\n * " : "\n";
String schemadoc = wrap(escape(doc)).replaceAll("\\n", commentNewline);
StringBuilder builder = new StringBuilder();
builder.append("/**\n");
if (style == DocCommentStyle.ASTRISK_MARGIN) builder.append(" * ");
builder.append(schemadoc).append("\n");
if (style == DocCommentStyle.ASTRISK_MARGIN) builder.append(" ");
builder.append("*/");
return builder.toString();
} | [
"public",
"static",
"String",
"stringToDocComment",
"(",
"String",
"doc",
",",
"DocCommentStyle",
"style",
")",
"{",
"if",
"(",
"doc",
"==",
"null",
"||",
"doc",
".",
"trim",
"(",
")",
".",
"isEmpty",
"(",
")",
")",
"return",
"\"\"",
";",
"String",
"commentNewline",
"=",
"(",
"style",
"==",
"DocCommentStyle",
".",
"ASTRISK_MARGIN",
")",
"?",
"\"\\n * \"",
":",
"\"\\n\"",
";",
"String",
"schemadoc",
"=",
"wrap",
"(",
"escape",
"(",
"doc",
")",
")",
".",
"replaceAll",
"(",
"\"\\\\n\"",
",",
"commentNewline",
")",
";",
"StringBuilder",
"builder",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"builder",
".",
"append",
"(",
"\"/**\\n\"",
")",
";",
"if",
"(",
"style",
"==",
"DocCommentStyle",
".",
"ASTRISK_MARGIN",
")",
"builder",
".",
"append",
"(",
"\" * \"",
")",
";",
"builder",
".",
"append",
"(",
"schemadoc",
")",
".",
"append",
"(",
"\"\\n\"",
")",
";",
"if",
"(",
"style",
"==",
"DocCommentStyle",
".",
"ASTRISK_MARGIN",
")",
"builder",
".",
"append",
"(",
"\" \"",
")",
";",
"builder",
".",
"append",
"(",
"\"*/\"",
")",
";",
"return",
"builder",
".",
"toString",
"(",
")",
";",
"}"
] | Returns a doc comment, as a string of source, for the given documentation string
and deprecated property.
@param doc provides the schemadoc for the symbol, if any. May be null.
@return an escaped schemadoc string. | [
"Returns",
"a",
"doc",
"comment",
"as",
"a",
"string",
"of",
"source",
"for",
"the",
"given",
"documentation",
"string",
"and",
"deprecated",
"property",
"."
] | train | https://github.com/coursera/courier/blob/749674fa7ee33804ad11b6c8ecb560f455cb4c22/generator-api/src/main/java/org/coursera/courier/lang/DocEscaping.java#L30-L42 |
lightblueseas/vintage-time | src/main/java/de/alpharogroup/date/CalculateDateExtensions.java | CalculateDateExtensions.addHours | public static Date addHours(final Date date, final int addHours) {
"""
Adds hours to the given Date object and returns it. Note: you can add negative values too for
get date in past.
@param date
The Date object to add the hours.
@param addHours
The days to add.
@return The resulted Date object.
"""
final Calendar dateOnCalendar = Calendar.getInstance();
dateOnCalendar.setTime(date);
dateOnCalendar.add(Calendar.HOUR, addHours);
return dateOnCalendar.getTime();
} | java | public static Date addHours(final Date date, final int addHours)
{
final Calendar dateOnCalendar = Calendar.getInstance();
dateOnCalendar.setTime(date);
dateOnCalendar.add(Calendar.HOUR, addHours);
return dateOnCalendar.getTime();
} | [
"public",
"static",
"Date",
"addHours",
"(",
"final",
"Date",
"date",
",",
"final",
"int",
"addHours",
")",
"{",
"final",
"Calendar",
"dateOnCalendar",
"=",
"Calendar",
".",
"getInstance",
"(",
")",
";",
"dateOnCalendar",
".",
"setTime",
"(",
"date",
")",
";",
"dateOnCalendar",
".",
"add",
"(",
"Calendar",
".",
"HOUR",
",",
"addHours",
")",
";",
"return",
"dateOnCalendar",
".",
"getTime",
"(",
")",
";",
"}"
] | Adds hours to the given Date object and returns it. Note: you can add negative values too for
get date in past.
@param date
The Date object to add the hours.
@param addHours
The days to add.
@return The resulted Date object. | [
"Adds",
"hours",
"to",
"the",
"given",
"Date",
"object",
"and",
"returns",
"it",
".",
"Note",
":",
"you",
"can",
"add",
"negative",
"values",
"too",
"for",
"get",
"date",
"in",
"past",
"."
] | train | https://github.com/lightblueseas/vintage-time/blob/fbf201e679d9f9b92e7b5771f3eea1413cc2e113/src/main/java/de/alpharogroup/date/CalculateDateExtensions.java#L74-L80 |
lisicnu/droidUtil | src/main/java/com/github/lisicnu/libDroid/util/StringUtils.java | StringUtils.combine | public static String combine(String str1, String str2, String separator) {
"""
e.g. str1= "aaaa/", str2= "/bbb" ,separator="/" will return "aaaa/bbb"
@param str1
@param str2
@param separator
@return
"""
if (separator == null || separator.isEmpty()) {
return str1 == null ? str2 : str1.concat(str2);
}
if (str1 == null)
str1 = "";
if (str2 == null)
str2 = "";
StringBuilder builder = new StringBuilder();
if (str1.endsWith(separator)) {
builder.append(str1.substring(0, str1.length() - separator.length()));
} else {
builder.append(str1);
}
builder.append(separator);
if (str2.startsWith(separator)) {
builder.append(str2.substring(separator.length()));
} else {
builder.append(str2);
}
return builder.toString();
} | java | public static String combine(String str1, String str2, String separator) {
if (separator == null || separator.isEmpty()) {
return str1 == null ? str2 : str1.concat(str2);
}
if (str1 == null)
str1 = "";
if (str2 == null)
str2 = "";
StringBuilder builder = new StringBuilder();
if (str1.endsWith(separator)) {
builder.append(str1.substring(0, str1.length() - separator.length()));
} else {
builder.append(str1);
}
builder.append(separator);
if (str2.startsWith(separator)) {
builder.append(str2.substring(separator.length()));
} else {
builder.append(str2);
}
return builder.toString();
} | [
"public",
"static",
"String",
"combine",
"(",
"String",
"str1",
",",
"String",
"str2",
",",
"String",
"separator",
")",
"{",
"if",
"(",
"separator",
"==",
"null",
"||",
"separator",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"str1",
"==",
"null",
"?",
"str2",
":",
"str1",
".",
"concat",
"(",
"str2",
")",
";",
"}",
"if",
"(",
"str1",
"==",
"null",
")",
"str1",
"=",
"\"\"",
";",
"if",
"(",
"str2",
"==",
"null",
")",
"str2",
"=",
"\"\"",
";",
"StringBuilder",
"builder",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"if",
"(",
"str1",
".",
"endsWith",
"(",
"separator",
")",
")",
"{",
"builder",
".",
"append",
"(",
"str1",
".",
"substring",
"(",
"0",
",",
"str1",
".",
"length",
"(",
")",
"-",
"separator",
".",
"length",
"(",
")",
")",
")",
";",
"}",
"else",
"{",
"builder",
".",
"append",
"(",
"str1",
")",
";",
"}",
"builder",
".",
"append",
"(",
"separator",
")",
";",
"if",
"(",
"str2",
".",
"startsWith",
"(",
"separator",
")",
")",
"{",
"builder",
".",
"append",
"(",
"str2",
".",
"substring",
"(",
"separator",
".",
"length",
"(",
")",
")",
")",
";",
"}",
"else",
"{",
"builder",
".",
"append",
"(",
"str2",
")",
";",
"}",
"return",
"builder",
".",
"toString",
"(",
")",
";",
"}"
] | e.g. str1= "aaaa/", str2= "/bbb" ,separator="/" will return "aaaa/bbb"
@param str1
@param str2
@param separator
@return | [
"e",
".",
"g",
".",
"str1",
"=",
"aaaa",
"/",
"str2",
"=",
"/",
"bbb",
"separator",
"=",
"/",
"will",
"return",
"aaaa",
"/",
"bbb"
] | train | https://github.com/lisicnu/droidUtil/blob/e4d6cf3e3f60e5efb5a75672607ded94d1725519/src/main/java/com/github/lisicnu/libDroid/util/StringUtils.java#L149-L174 |
threerings/narya | core/src/main/java/com/threerings/crowd/server/PlaceRegistry.java | PlaceRegistry.createPlace | public PlaceManager createPlace (PlaceConfig config, List<PlaceManagerDelegate> delegates)
throws InstantiationException, InvocationException {
"""
Creates and registers a new place manager along with the place object to be managed. The
registry takes care of tracking the creation of the object and informing the manager when it
is created.
@param config the configuration object for the place to be created. The {@link PlaceManager}
derived class that should be instantiated to manage the place will be determined from the
config object.
@param delegates a list of {@link PlaceManagerDelegate} instances to be registered with the
manager prior to it being initialized and started up. <em>Note:</em> these delegates will
have dependencies injected into them prior to registering them with the manager.
@return a reference to the place manager, which will have been configured with its place
object and started up (via a call to {@link PlaceManager#startup}.
@exception InstantiationException thrown if an error occurs trying to instantiate and
initialize the place manager.
@exception InvocationException thrown if the place manager returns failure from the call to
{@link PlaceManager#checkPermissions}. The error string returned by that call will be
provided as in the exception.
"""
return createPlace(config, delegates, null);
} | java | public PlaceManager createPlace (PlaceConfig config, List<PlaceManagerDelegate> delegates)
throws InstantiationException, InvocationException
{
return createPlace(config, delegates, null);
} | [
"public",
"PlaceManager",
"createPlace",
"(",
"PlaceConfig",
"config",
",",
"List",
"<",
"PlaceManagerDelegate",
">",
"delegates",
")",
"throws",
"InstantiationException",
",",
"InvocationException",
"{",
"return",
"createPlace",
"(",
"config",
",",
"delegates",
",",
"null",
")",
";",
"}"
] | Creates and registers a new place manager along with the place object to be managed. The
registry takes care of tracking the creation of the object and informing the manager when it
is created.
@param config the configuration object for the place to be created. The {@link PlaceManager}
derived class that should be instantiated to manage the place will be determined from the
config object.
@param delegates a list of {@link PlaceManagerDelegate} instances to be registered with the
manager prior to it being initialized and started up. <em>Note:</em> these delegates will
have dependencies injected into them prior to registering them with the manager.
@return a reference to the place manager, which will have been configured with its place
object and started up (via a call to {@link PlaceManager#startup}.
@exception InstantiationException thrown if an error occurs trying to instantiate and
initialize the place manager.
@exception InvocationException thrown if the place manager returns failure from the call to
{@link PlaceManager#checkPermissions}. The error string returned by that call will be
provided as in the exception. | [
"Creates",
"and",
"registers",
"a",
"new",
"place",
"manager",
"along",
"with",
"the",
"place",
"object",
"to",
"be",
"managed",
".",
"The",
"registry",
"takes",
"care",
"of",
"tracking",
"the",
"creation",
"of",
"the",
"object",
"and",
"informing",
"the",
"manager",
"when",
"it",
"is",
"created",
"."
] | train | https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/crowd/server/PlaceRegistry.java#L109-L113 |
Stratio/bdt | src/main/java/com/stratio/qa/specs/DatabaseSpec.java | DatabaseSpec.assertValuesOfTable | @Then("^a Cassandra keyspace '(.+?)' contains a table '(.+?)' with values:$")
public void assertValuesOfTable(String keyspace, String tableName, DataTable data) throws InterruptedException {
"""
Checks if a cassandra table contains the values of a DataTable.
@param keyspace
@param tableName
@param data
@throws InterruptedException
"""
// USE of Keyspace
commonspec.getCassandraClient().useKeyspace(keyspace);
// Obtain the types and column names of the datatable
// to return in a hashmap,
Map<String, String> dataTableColumns = extractColumnNamesAndTypes(data.raw().get(0));
// check if the table has columns
String query = "SELECT * FROM " + tableName + " LIMIT 1;";
com.datastax.driver.core.ResultSet res = commonspec.getCassandraClient().executeQuery(query);
equalsColumns(res.getColumnDefinitions(), dataTableColumns);
//receiving the string from the select with the columns
// that belong to the dataTable
List<String> selectQueries = giveQueriesList(data, tableName, columnNames(data.raw().get(0)));
//Check the data of cassandra with different queries
int index = 1;
for (String execQuery : selectQueries) {
res = commonspec.getCassandraClient().executeQuery(execQuery);
List<Row> resAsList = res.all();
assertThat(resAsList.size()).as("The query " + execQuery + " not return any result on Cassandra").isGreaterThan(0);
assertThat(resAsList.get(0).toString()
.substring(VALUE_SUBSTRING)).as("The resultSet is not as expected").isEqualTo(data.raw().get(index).toString().replace("'", ""));
index++;
}
} | java | @Then("^a Cassandra keyspace '(.+?)' contains a table '(.+?)' with values:$")
public void assertValuesOfTable(String keyspace, String tableName, DataTable data) throws InterruptedException {
// USE of Keyspace
commonspec.getCassandraClient().useKeyspace(keyspace);
// Obtain the types and column names of the datatable
// to return in a hashmap,
Map<String, String> dataTableColumns = extractColumnNamesAndTypes(data.raw().get(0));
// check if the table has columns
String query = "SELECT * FROM " + tableName + " LIMIT 1;";
com.datastax.driver.core.ResultSet res = commonspec.getCassandraClient().executeQuery(query);
equalsColumns(res.getColumnDefinitions(), dataTableColumns);
//receiving the string from the select with the columns
// that belong to the dataTable
List<String> selectQueries = giveQueriesList(data, tableName, columnNames(data.raw().get(0)));
//Check the data of cassandra with different queries
int index = 1;
for (String execQuery : selectQueries) {
res = commonspec.getCassandraClient().executeQuery(execQuery);
List<Row> resAsList = res.all();
assertThat(resAsList.size()).as("The query " + execQuery + " not return any result on Cassandra").isGreaterThan(0);
assertThat(resAsList.get(0).toString()
.substring(VALUE_SUBSTRING)).as("The resultSet is not as expected").isEqualTo(data.raw().get(index).toString().replace("'", ""));
index++;
}
} | [
"@",
"Then",
"(",
"\"^a Cassandra keyspace '(.+?)' contains a table '(.+?)' with values:$\"",
")",
"public",
"void",
"assertValuesOfTable",
"(",
"String",
"keyspace",
",",
"String",
"tableName",
",",
"DataTable",
"data",
")",
"throws",
"InterruptedException",
"{",
"// USE of Keyspace",
"commonspec",
".",
"getCassandraClient",
"(",
")",
".",
"useKeyspace",
"(",
"keyspace",
")",
";",
"// Obtain the types and column names of the datatable",
"// to return in a hashmap,",
"Map",
"<",
"String",
",",
"String",
">",
"dataTableColumns",
"=",
"extractColumnNamesAndTypes",
"(",
"data",
".",
"raw",
"(",
")",
".",
"get",
"(",
"0",
")",
")",
";",
"// check if the table has columns",
"String",
"query",
"=",
"\"SELECT * FROM \"",
"+",
"tableName",
"+",
"\" LIMIT 1;\"",
";",
"com",
".",
"datastax",
".",
"driver",
".",
"core",
".",
"ResultSet",
"res",
"=",
"commonspec",
".",
"getCassandraClient",
"(",
")",
".",
"executeQuery",
"(",
"query",
")",
";",
"equalsColumns",
"(",
"res",
".",
"getColumnDefinitions",
"(",
")",
",",
"dataTableColumns",
")",
";",
"//receiving the string from the select with the columns",
"// that belong to the dataTable",
"List",
"<",
"String",
">",
"selectQueries",
"=",
"giveQueriesList",
"(",
"data",
",",
"tableName",
",",
"columnNames",
"(",
"data",
".",
"raw",
"(",
")",
".",
"get",
"(",
"0",
")",
")",
")",
";",
"//Check the data of cassandra with different queries",
"int",
"index",
"=",
"1",
";",
"for",
"(",
"String",
"execQuery",
":",
"selectQueries",
")",
"{",
"res",
"=",
"commonspec",
".",
"getCassandraClient",
"(",
")",
".",
"executeQuery",
"(",
"execQuery",
")",
";",
"List",
"<",
"Row",
">",
"resAsList",
"=",
"res",
".",
"all",
"(",
")",
";",
"assertThat",
"(",
"resAsList",
".",
"size",
"(",
")",
")",
".",
"as",
"(",
"\"The query \"",
"+",
"execQuery",
"+",
"\" not return any result on Cassandra\"",
")",
".",
"isGreaterThan",
"(",
"0",
")",
";",
"assertThat",
"(",
"resAsList",
".",
"get",
"(",
"0",
")",
".",
"toString",
"(",
")",
".",
"substring",
"(",
"VALUE_SUBSTRING",
")",
")",
".",
"as",
"(",
"\"The resultSet is not as expected\"",
")",
".",
"isEqualTo",
"(",
"data",
".",
"raw",
"(",
")",
".",
"get",
"(",
"index",
")",
".",
"toString",
"(",
")",
".",
"replace",
"(",
"\"'\"",
",",
"\"\"",
")",
")",
";",
"index",
"++",
";",
"}",
"}"
] | Checks if a cassandra table contains the values of a DataTable.
@param keyspace
@param tableName
@param data
@throws InterruptedException | [
"Checks",
"if",
"a",
"cassandra",
"table",
"contains",
"the",
"values",
"of",
"a",
"DataTable",
"."
] | train | https://github.com/Stratio/bdt/blob/55324d19e7497764ad3dd7139923e13eb9841d75/src/main/java/com/stratio/qa/specs/DatabaseSpec.java#L696-L720 |
Kurento/kurento-module-creator | src/main/java/com/github/zafarkhaja/semver/VersionParser.java | VersionParser.parseValidSemVer | private Version parseValidSemVer() {
"""
Parses the {@literal <valid semver>} non-terminal.
<pre>
{@literal
<valid semver> ::= <version core>
| <version core> "-" <pre-release>
| <version core> "+" <build>
| <version core> "-" <pre-release> "+" <build>
}
</pre>
@return a valid version object
"""
NormalVersion normal = parseVersionCore();
MetadataVersion preRelease = MetadataVersion.NULL;
MetadataVersion build = MetadataVersion.NULL;
Character next = consumeNextCharacter(CharType.HYPHEN, CharType.PLUS, CharType.EOL);
if (CharType.HYPHEN.isMatchedBy(next)) {
preRelease = parsePreRelease();
next = consumeNextCharacter(CharType.PLUS, CharType.EOL);
if (CharType.PLUS.isMatchedBy(next)) {
build = parseBuild();
}
} else if (CharType.PLUS.isMatchedBy(next)) {
build = parseBuild();
}
consumeNextCharacter(CharType.EOL);
return new Version(normal, preRelease, build);
} | java | private Version parseValidSemVer() {
NormalVersion normal = parseVersionCore();
MetadataVersion preRelease = MetadataVersion.NULL;
MetadataVersion build = MetadataVersion.NULL;
Character next = consumeNextCharacter(CharType.HYPHEN, CharType.PLUS, CharType.EOL);
if (CharType.HYPHEN.isMatchedBy(next)) {
preRelease = parsePreRelease();
next = consumeNextCharacter(CharType.PLUS, CharType.EOL);
if (CharType.PLUS.isMatchedBy(next)) {
build = parseBuild();
}
} else if (CharType.PLUS.isMatchedBy(next)) {
build = parseBuild();
}
consumeNextCharacter(CharType.EOL);
return new Version(normal, preRelease, build);
} | [
"private",
"Version",
"parseValidSemVer",
"(",
")",
"{",
"NormalVersion",
"normal",
"=",
"parseVersionCore",
"(",
")",
";",
"MetadataVersion",
"preRelease",
"=",
"MetadataVersion",
".",
"NULL",
";",
"MetadataVersion",
"build",
"=",
"MetadataVersion",
".",
"NULL",
";",
"Character",
"next",
"=",
"consumeNextCharacter",
"(",
"CharType",
".",
"HYPHEN",
",",
"CharType",
".",
"PLUS",
",",
"CharType",
".",
"EOL",
")",
";",
"if",
"(",
"CharType",
".",
"HYPHEN",
".",
"isMatchedBy",
"(",
"next",
")",
")",
"{",
"preRelease",
"=",
"parsePreRelease",
"(",
")",
";",
"next",
"=",
"consumeNextCharacter",
"(",
"CharType",
".",
"PLUS",
",",
"CharType",
".",
"EOL",
")",
";",
"if",
"(",
"CharType",
".",
"PLUS",
".",
"isMatchedBy",
"(",
"next",
")",
")",
"{",
"build",
"=",
"parseBuild",
"(",
")",
";",
"}",
"}",
"else",
"if",
"(",
"CharType",
".",
"PLUS",
".",
"isMatchedBy",
"(",
"next",
")",
")",
"{",
"build",
"=",
"parseBuild",
"(",
")",
";",
"}",
"consumeNextCharacter",
"(",
"CharType",
".",
"EOL",
")",
";",
"return",
"new",
"Version",
"(",
"normal",
",",
"preRelease",
",",
"build",
")",
";",
"}"
] | Parses the {@literal <valid semver>} non-terminal.
<pre>
{@literal
<valid semver> ::= <version core>
| <version core> "-" <pre-release>
| <version core> "+" <build>
| <version core> "-" <pre-release> "+" <build>
}
</pre>
@return a valid version object | [
"Parses",
"the",
"{",
"@literal",
"<valid",
"semver",
">",
"}",
"non",
"-",
"terminal",
"."
] | train | https://github.com/Kurento/kurento-module-creator/blob/c371516c665b902b5476433496a5aefcbca86d64/src/main/java/com/github/zafarkhaja/semver/VersionParser.java#L221-L238 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/JapaneseCalendar.java | JapaneseCalendar.handleGetLimit | @SuppressWarnings("fallthrough")
protected int handleGetLimit(int field, int limitType) {
"""
Override GregorianCalendar. We should really handle YEAR_WOY and
EXTENDED_YEAR here too to implement the 1..5000000 range, but it's
not critical.
"""
switch (field) {
case ERA:
if (limitType == MINIMUM || limitType == GREATEST_MINIMUM) {
return 0;
}
return CURRENT_ERA;
case YEAR:
{
switch (limitType) {
case MINIMUM:
case GREATEST_MINIMUM:
return 1;
case LEAST_MAXIMUM:
return 1;
case MAXIMUM:
return super.handleGetLimit(field, MAXIMUM) - ERAS[CURRENT_ERA*3];
}
//Fall through to the default if not handled above
}
default:
return super.handleGetLimit(field, limitType);
}
} | java | @SuppressWarnings("fallthrough")
protected int handleGetLimit(int field, int limitType) {
switch (field) {
case ERA:
if (limitType == MINIMUM || limitType == GREATEST_MINIMUM) {
return 0;
}
return CURRENT_ERA;
case YEAR:
{
switch (limitType) {
case MINIMUM:
case GREATEST_MINIMUM:
return 1;
case LEAST_MAXIMUM:
return 1;
case MAXIMUM:
return super.handleGetLimit(field, MAXIMUM) - ERAS[CURRENT_ERA*3];
}
//Fall through to the default if not handled above
}
default:
return super.handleGetLimit(field, limitType);
}
} | [
"@",
"SuppressWarnings",
"(",
"\"fallthrough\"",
")",
"protected",
"int",
"handleGetLimit",
"(",
"int",
"field",
",",
"int",
"limitType",
")",
"{",
"switch",
"(",
"field",
")",
"{",
"case",
"ERA",
":",
"if",
"(",
"limitType",
"==",
"MINIMUM",
"||",
"limitType",
"==",
"GREATEST_MINIMUM",
")",
"{",
"return",
"0",
";",
"}",
"return",
"CURRENT_ERA",
";",
"case",
"YEAR",
":",
"{",
"switch",
"(",
"limitType",
")",
"{",
"case",
"MINIMUM",
":",
"case",
"GREATEST_MINIMUM",
":",
"return",
"1",
";",
"case",
"LEAST_MAXIMUM",
":",
"return",
"1",
";",
"case",
"MAXIMUM",
":",
"return",
"super",
".",
"handleGetLimit",
"(",
"field",
",",
"MAXIMUM",
")",
"-",
"ERAS",
"[",
"CURRENT_ERA",
"*",
"3",
"]",
";",
"}",
"//Fall through to the default if not handled above",
"}",
"default",
":",
"return",
"super",
".",
"handleGetLimit",
"(",
"field",
",",
"limitType",
")",
";",
"}",
"}"
] | Override GregorianCalendar. We should really handle YEAR_WOY and
EXTENDED_YEAR here too to implement the 1..5000000 range, but it's
not critical. | [
"Override",
"GregorianCalendar",
".",
"We",
"should",
"really",
"handle",
"YEAR_WOY",
"and",
"EXTENDED_YEAR",
"here",
"too",
"to",
"implement",
"the",
"1",
"..",
"5000000",
"range",
"but",
"it",
"s",
"not",
"critical",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/JapaneseCalendar.java#L587-L611 |
Netflix/netflix-graph | src/main/java/com/netflix/nfgraph/build/NFBuildGraph.java | NFBuildGraph.addConnection | public void addConnection(NFBuildGraphNode fromNode, NFPropertySpec propertySpec, int connectionModelIndex, NFBuildGraphNode toNode) {
"""
Add a connection to this graph. This method is exposed for efficiency purposes. It is more efficient than
{@code addConnection(String connectionModel, String nodeType, int fromOrdinal, String viaPropertyName, int toOrdinal)}
as it avoids multiple lookups for <code>fromNode</code>, <code>propertySpec</code>, <code>connectionModelIndex</code>
and <code>toNode</code>.
"""
fromNode.addConnection(connectionModelIndex, propertySpec, toNode.getOrdinal());
toNode.incrementNumIncomingConnections();
} | java | public void addConnection(NFBuildGraphNode fromNode, NFPropertySpec propertySpec, int connectionModelIndex, NFBuildGraphNode toNode) {
fromNode.addConnection(connectionModelIndex, propertySpec, toNode.getOrdinal());
toNode.incrementNumIncomingConnections();
} | [
"public",
"void",
"addConnection",
"(",
"NFBuildGraphNode",
"fromNode",
",",
"NFPropertySpec",
"propertySpec",
",",
"int",
"connectionModelIndex",
",",
"NFBuildGraphNode",
"toNode",
")",
"{",
"fromNode",
".",
"addConnection",
"(",
"connectionModelIndex",
",",
"propertySpec",
",",
"toNode",
".",
"getOrdinal",
"(",
")",
")",
";",
"toNode",
".",
"incrementNumIncomingConnections",
"(",
")",
";",
"}"
] | Add a connection to this graph. This method is exposed for efficiency purposes. It is more efficient than
{@code addConnection(String connectionModel, String nodeType, int fromOrdinal, String viaPropertyName, int toOrdinal)}
as it avoids multiple lookups for <code>fromNode</code>, <code>propertySpec</code>, <code>connectionModelIndex</code>
and <code>toNode</code>. | [
"Add",
"a",
"connection",
"to",
"this",
"graph",
".",
"This",
"method",
"is",
"exposed",
"for",
"efficiency",
"purposes",
".",
"It",
"is",
"more",
"efficient",
"than",
"{"
] | train | https://github.com/Netflix/netflix-graph/blob/ee129252a08a9f51dd296d6fca2f0b28b7be284e/src/main/java/com/netflix/nfgraph/build/NFBuildGraph.java#L119-L122 |
arquillian/arquillian-algeron | common/git/src/main/java/org/arquillian/algeron/git/GitOperations.java | GitOperations.pushToRepository | public Iterable<PushResult> pushToRepository(Git git, String remote, String username, String password) {
"""
Push all changes and tags to given remote.
@param git
instance.
@param remote
to be used.
@param username
to login.
@param password
to login.
@return List of all results of given push.
"""
try {
return git.push()
.setRemote(remote)
.setPushAll()
.setPushTags()
.setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password))
.call();
} catch (GitAPIException e) {
throw new IllegalStateException(e);
}
} | java | public Iterable<PushResult> pushToRepository(Git git, String remote, String username, String password) {
try {
return git.push()
.setRemote(remote)
.setPushAll()
.setPushTags()
.setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password))
.call();
} catch (GitAPIException e) {
throw new IllegalStateException(e);
}
} | [
"public",
"Iterable",
"<",
"PushResult",
">",
"pushToRepository",
"(",
"Git",
"git",
",",
"String",
"remote",
",",
"String",
"username",
",",
"String",
"password",
")",
"{",
"try",
"{",
"return",
"git",
".",
"push",
"(",
")",
".",
"setRemote",
"(",
"remote",
")",
".",
"setPushAll",
"(",
")",
".",
"setPushTags",
"(",
")",
".",
"setCredentialsProvider",
"(",
"new",
"UsernamePasswordCredentialsProvider",
"(",
"username",
",",
"password",
")",
")",
".",
"call",
"(",
")",
";",
"}",
"catch",
"(",
"GitAPIException",
"e",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"e",
")",
";",
"}",
"}"
] | Push all changes and tags to given remote.
@param git
instance.
@param remote
to be used.
@param username
to login.
@param password
to login.
@return List of all results of given push. | [
"Push",
"all",
"changes",
"and",
"tags",
"to",
"given",
"remote",
"."
] | train | https://github.com/arquillian/arquillian-algeron/blob/ec79372defdafe99ab2f7bb696f1c1eabdbbacb6/common/git/src/main/java/org/arquillian/algeron/git/GitOperations.java#L306-L317 |
Carbonado/Carbonado | src/main/java/com/amazon/carbonado/raw/DataEncoder.java | DataEncoder.writeLength | public static int writeLength(int valueLength, OutputStream out) throws IOException {
"""
Writes a positive length value in up to five bytes.
@return number of bytes written
@since 1.2
"""
if (valueLength < 128) {
out.write(valueLength);
return 1;
} else if (valueLength < 16384) {
out.write((valueLength >> 8) | 0x80);
out.write(valueLength);
return 2;
} else if (valueLength < 2097152) {
out.write((valueLength >> 16) | 0xc0);
out.write(valueLength >> 8);
out.write(valueLength);
return 3;
} else if (valueLength < 268435456) {
out.write((valueLength >> 24) | 0xe0);
out.write(valueLength >> 16);
out.write(valueLength >> 8);
out.write(valueLength);
return 4;
} else {
out.write(0xf0);
out.write(valueLength >> 24);
out.write(valueLength >> 16);
out.write(valueLength >> 8);
out.write(valueLength);
return 5;
}
} | java | public static int writeLength(int valueLength, OutputStream out) throws IOException {
if (valueLength < 128) {
out.write(valueLength);
return 1;
} else if (valueLength < 16384) {
out.write((valueLength >> 8) | 0x80);
out.write(valueLength);
return 2;
} else if (valueLength < 2097152) {
out.write((valueLength >> 16) | 0xc0);
out.write(valueLength >> 8);
out.write(valueLength);
return 3;
} else if (valueLength < 268435456) {
out.write((valueLength >> 24) | 0xe0);
out.write(valueLength >> 16);
out.write(valueLength >> 8);
out.write(valueLength);
return 4;
} else {
out.write(0xf0);
out.write(valueLength >> 24);
out.write(valueLength >> 16);
out.write(valueLength >> 8);
out.write(valueLength);
return 5;
}
} | [
"public",
"static",
"int",
"writeLength",
"(",
"int",
"valueLength",
",",
"OutputStream",
"out",
")",
"throws",
"IOException",
"{",
"if",
"(",
"valueLength",
"<",
"128",
")",
"{",
"out",
".",
"write",
"(",
"valueLength",
")",
";",
"return",
"1",
";",
"}",
"else",
"if",
"(",
"valueLength",
"<",
"16384",
")",
"{",
"out",
".",
"write",
"(",
"(",
"valueLength",
">>",
"8",
")",
"|",
"0x80",
")",
";",
"out",
".",
"write",
"(",
"valueLength",
")",
";",
"return",
"2",
";",
"}",
"else",
"if",
"(",
"valueLength",
"<",
"2097152",
")",
"{",
"out",
".",
"write",
"(",
"(",
"valueLength",
">>",
"16",
")",
"|",
"0xc0",
")",
";",
"out",
".",
"write",
"(",
"valueLength",
">>",
"8",
")",
";",
"out",
".",
"write",
"(",
"valueLength",
")",
";",
"return",
"3",
";",
"}",
"else",
"if",
"(",
"valueLength",
"<",
"268435456",
")",
"{",
"out",
".",
"write",
"(",
"(",
"valueLength",
">>",
"24",
")",
"|",
"0xe0",
")",
";",
"out",
".",
"write",
"(",
"valueLength",
">>",
"16",
")",
";",
"out",
".",
"write",
"(",
"valueLength",
">>",
"8",
")",
";",
"out",
".",
"write",
"(",
"valueLength",
")",
";",
"return",
"4",
";",
"}",
"else",
"{",
"out",
".",
"write",
"(",
"0xf0",
")",
";",
"out",
".",
"write",
"(",
"valueLength",
">>",
"24",
")",
";",
"out",
".",
"write",
"(",
"valueLength",
">>",
"16",
")",
";",
"out",
".",
"write",
"(",
"valueLength",
">>",
"8",
")",
";",
"out",
".",
"write",
"(",
"valueLength",
")",
";",
"return",
"5",
";",
"}",
"}"
] | Writes a positive length value in up to five bytes.
@return number of bytes written
@since 1.2 | [
"Writes",
"a",
"positive",
"length",
"value",
"in",
"up",
"to",
"five",
"bytes",
"."
] | train | https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/raw/DataEncoder.java#L616-L643 |
Stratio/stratio-connector-commons | connector-commons/src/main/java/com/stratio/connector/commons/connection/ConnectionHandler.java | ConnectionHandler.createConnection | public void createConnection(ICredentials credentials, ConnectorClusterConfig config) throws ConnectionException {
"""
This method create a connection.
@param credentials the cluster configuration.
@param config the connection options.
@throws ConnectionException if the connection already exists.
"""
logger.info("Creating new connection...");
Connection connection = createNativeConnection(credentials, config);
String connectionName = config.getName().getName();
synchronized (connections) {
if (!connections.containsKey(connectionName)) {
connections.put(connectionName, connection);
logger.info("Connected to [" + connectionName + "]");
} else {
String msg = "The connection [" + connectionName + "] already exists";
logger.error(msg);
throw new ConnectionException(msg);
}
}
} | java | public void createConnection(ICredentials credentials, ConnectorClusterConfig config) throws ConnectionException {
logger.info("Creating new connection...");
Connection connection = createNativeConnection(credentials, config);
String connectionName = config.getName().getName();
synchronized (connections) {
if (!connections.containsKey(connectionName)) {
connections.put(connectionName, connection);
logger.info("Connected to [" + connectionName + "]");
} else {
String msg = "The connection [" + connectionName + "] already exists";
logger.error(msg);
throw new ConnectionException(msg);
}
}
} | [
"public",
"void",
"createConnection",
"(",
"ICredentials",
"credentials",
",",
"ConnectorClusterConfig",
"config",
")",
"throws",
"ConnectionException",
"{",
"logger",
".",
"info",
"(",
"\"Creating new connection...\"",
")",
";",
"Connection",
"connection",
"=",
"createNativeConnection",
"(",
"credentials",
",",
"config",
")",
";",
"String",
"connectionName",
"=",
"config",
".",
"getName",
"(",
")",
".",
"getName",
"(",
")",
";",
"synchronized",
"(",
"connections",
")",
"{",
"if",
"(",
"!",
"connections",
".",
"containsKey",
"(",
"connectionName",
")",
")",
"{",
"connections",
".",
"put",
"(",
"connectionName",
",",
"connection",
")",
";",
"logger",
".",
"info",
"(",
"\"Connected to [\"",
"+",
"connectionName",
"+",
"\"]\"",
")",
";",
"}",
"else",
"{",
"String",
"msg",
"=",
"\"The connection [\"",
"+",
"connectionName",
"+",
"\"] already exists\"",
";",
"logger",
".",
"error",
"(",
"msg",
")",
";",
"throw",
"new",
"ConnectionException",
"(",
"msg",
")",
";",
"}",
"}",
"}"
] | This method create a connection.
@param credentials the cluster configuration.
@param config the connection options.
@throws ConnectionException if the connection already exists. | [
"This",
"method",
"create",
"a",
"connection",
"."
] | train | https://github.com/Stratio/stratio-connector-commons/blob/d7cc66cb9591344a13055962e87a91f01c3707d1/connector-commons/src/main/java/com/stratio/connector/commons/connection/ConnectionHandler.java#L72-L90 |
teatrove/teatrove | trove/src/main/java/org/teatrove/trove/classfile/ConstantIntegerInfo.java | ConstantIntegerInfo.make | static ConstantIntegerInfo make(ConstantPool cp, int value) {
"""
Will return either a new ConstantIntegerInfo object or one already in
the constant pool. If it is a new ConstantIntegerInfo, it will be
inserted into the pool.
"""
ConstantInfo ci = new ConstantIntegerInfo(value);
return (ConstantIntegerInfo)cp.addConstant(ci);
} | java | static ConstantIntegerInfo make(ConstantPool cp, int value) {
ConstantInfo ci = new ConstantIntegerInfo(value);
return (ConstantIntegerInfo)cp.addConstant(ci);
} | [
"static",
"ConstantIntegerInfo",
"make",
"(",
"ConstantPool",
"cp",
",",
"int",
"value",
")",
"{",
"ConstantInfo",
"ci",
"=",
"new",
"ConstantIntegerInfo",
"(",
"value",
")",
";",
"return",
"(",
"ConstantIntegerInfo",
")",
"cp",
".",
"addConstant",
"(",
"ci",
")",
";",
"}"
] | Will return either a new ConstantIntegerInfo object or one already in
the constant pool. If it is a new ConstantIntegerInfo, it will be
inserted into the pool. | [
"Will",
"return",
"either",
"a",
"new",
"ConstantIntegerInfo",
"object",
"or",
"one",
"already",
"in",
"the",
"constant",
"pool",
".",
"If",
"it",
"is",
"a",
"new",
"ConstantIntegerInfo",
"it",
"will",
"be",
"inserted",
"into",
"the",
"pool",
"."
] | train | https://github.com/teatrove/teatrove/blob/7039bdd4da6817ff8c737f7e4e07bac7e3ad8bea/trove/src/main/java/org/teatrove/trove/classfile/ConstantIntegerInfo.java#L35-L38 |
elki-project/elki | elki/src/main/java/de/lmu/ifi/dbs/elki/algorithm/statistics/DistanceStatisticsWithClasses.java | DistanceStatisticsWithClasses.exactMinMax | private DoubleMinMax exactMinMax(Relation<O> relation, DistanceQuery<O> distFunc) {
"""
Compute the exact maximum and minimum.
@param relation Relation to process
@param distFunc Distance function
@return Exact maximum and minimum
"""
final FiniteProgress progress = LOG.isVerbose() ? new FiniteProgress("Exact fitting distance computations", relation.size(), LOG) : null;
DoubleMinMax minmax = new DoubleMinMax();
// find exact minimum and maximum first.
for(DBIDIter iditer = relation.iterDBIDs(); iditer.valid(); iditer.advance()) {
for(DBIDIter iditer2 = relation.iterDBIDs(); iditer2.valid(); iditer2.advance()) {
// skip the point itself.
if(DBIDUtil.equal(iditer, iditer2)) {
continue;
}
double d = distFunc.distance(iditer, iditer2);
minmax.put(d);
}
LOG.incrementProcessed(progress);
}
LOG.ensureCompleted(progress);
return minmax;
} | java | private DoubleMinMax exactMinMax(Relation<O> relation, DistanceQuery<O> distFunc) {
final FiniteProgress progress = LOG.isVerbose() ? new FiniteProgress("Exact fitting distance computations", relation.size(), LOG) : null;
DoubleMinMax minmax = new DoubleMinMax();
// find exact minimum and maximum first.
for(DBIDIter iditer = relation.iterDBIDs(); iditer.valid(); iditer.advance()) {
for(DBIDIter iditer2 = relation.iterDBIDs(); iditer2.valid(); iditer2.advance()) {
// skip the point itself.
if(DBIDUtil.equal(iditer, iditer2)) {
continue;
}
double d = distFunc.distance(iditer, iditer2);
minmax.put(d);
}
LOG.incrementProcessed(progress);
}
LOG.ensureCompleted(progress);
return minmax;
} | [
"private",
"DoubleMinMax",
"exactMinMax",
"(",
"Relation",
"<",
"O",
">",
"relation",
",",
"DistanceQuery",
"<",
"O",
">",
"distFunc",
")",
"{",
"final",
"FiniteProgress",
"progress",
"=",
"LOG",
".",
"isVerbose",
"(",
")",
"?",
"new",
"FiniteProgress",
"(",
"\"Exact fitting distance computations\"",
",",
"relation",
".",
"size",
"(",
")",
",",
"LOG",
")",
":",
"null",
";",
"DoubleMinMax",
"minmax",
"=",
"new",
"DoubleMinMax",
"(",
")",
";",
"// find exact minimum and maximum first.",
"for",
"(",
"DBIDIter",
"iditer",
"=",
"relation",
".",
"iterDBIDs",
"(",
")",
";",
"iditer",
".",
"valid",
"(",
")",
";",
"iditer",
".",
"advance",
"(",
")",
")",
"{",
"for",
"(",
"DBIDIter",
"iditer2",
"=",
"relation",
".",
"iterDBIDs",
"(",
")",
";",
"iditer2",
".",
"valid",
"(",
")",
";",
"iditer2",
".",
"advance",
"(",
")",
")",
"{",
"// skip the point itself.",
"if",
"(",
"DBIDUtil",
".",
"equal",
"(",
"iditer",
",",
"iditer2",
")",
")",
"{",
"continue",
";",
"}",
"double",
"d",
"=",
"distFunc",
".",
"distance",
"(",
"iditer",
",",
"iditer2",
")",
";",
"minmax",
".",
"put",
"(",
"d",
")",
";",
"}",
"LOG",
".",
"incrementProcessed",
"(",
"progress",
")",
";",
"}",
"LOG",
".",
"ensureCompleted",
"(",
"progress",
")",
";",
"return",
"minmax",
";",
"}"
] | Compute the exact maximum and minimum.
@param relation Relation to process
@param distFunc Distance function
@return Exact maximum and minimum | [
"Compute",
"the",
"exact",
"maximum",
"and",
"minimum",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki/src/main/java/de/lmu/ifi/dbs/elki/algorithm/statistics/DistanceStatisticsWithClasses.java#L357-L374 |
google/closure-compiler | src/com/google/javascript/jscomp/CrossChunkCodeMotion.java | CrossChunkCodeMotion.isInstanceofFor | private boolean isInstanceofFor(Node expression, Node reference) {
"""
Is the expression of the form {@code x instanceof Ref}?
@param expression
@param reference Ref node must be equivalent to this node
"""
return expression.isInstanceOf() && expression.getLastChild().isEquivalentTo(reference);
} | java | private boolean isInstanceofFor(Node expression, Node reference) {
return expression.isInstanceOf() && expression.getLastChild().isEquivalentTo(reference);
} | [
"private",
"boolean",
"isInstanceofFor",
"(",
"Node",
"expression",
",",
"Node",
"reference",
")",
"{",
"return",
"expression",
".",
"isInstanceOf",
"(",
")",
"&&",
"expression",
".",
"getLastChild",
"(",
")",
".",
"isEquivalentTo",
"(",
"reference",
")",
";",
"}"
] | Is the expression of the form {@code x instanceof Ref}?
@param expression
@param reference Ref node must be equivalent to this node | [
"Is",
"the",
"expression",
"of",
"the",
"form",
"{",
"@code",
"x",
"instanceof",
"Ref",
"}",
"?"
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CrossChunkCodeMotion.java#L761-L763 |
liferay/com-liferay-commerce | commerce-user-segment-service/src/main/java/com/liferay/commerce/user/segment/service/persistence/impl/CommerceUserSegmentEntryPersistenceImpl.java | CommerceUserSegmentEntryPersistenceImpl.findByGroupId | @Override
public List<CommerceUserSegmentEntry> findByGroupId(long groupId,
int start, int end,
OrderByComparator<CommerceUserSegmentEntry> orderByComparator) {
"""
Returns an ordered range of all the commerce user segment entries where groupId = ?.
<p>
Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceUserSegmentEntryModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
</p>
@param groupId the group ID
@param start the lower bound of the range of commerce user segment entries
@param end the upper bound of the range of commerce user segment entries (not inclusive)
@param orderByComparator the comparator to order the results by (optionally <code>null</code>)
@return the ordered range of matching commerce user segment entries
"""
return findByGroupId(groupId, start, end, orderByComparator, true);
} | java | @Override
public List<CommerceUserSegmentEntry> findByGroupId(long groupId,
int start, int end,
OrderByComparator<CommerceUserSegmentEntry> orderByComparator) {
return findByGroupId(groupId, start, end, orderByComparator, true);
} | [
"@",
"Override",
"public",
"List",
"<",
"CommerceUserSegmentEntry",
">",
"findByGroupId",
"(",
"long",
"groupId",
",",
"int",
"start",
",",
"int",
"end",
",",
"OrderByComparator",
"<",
"CommerceUserSegmentEntry",
">",
"orderByComparator",
")",
"{",
"return",
"findByGroupId",
"(",
"groupId",
",",
"start",
",",
"end",
",",
"orderByComparator",
",",
"true",
")",
";",
"}"
] | Returns an ordered range of all the commerce user segment entries where groupId = ?.
<p>
Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceUserSegmentEntryModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
</p>
@param groupId the group ID
@param start the lower bound of the range of commerce user segment entries
@param end the upper bound of the range of commerce user segment entries (not inclusive)
@param orderByComparator the comparator to order the results by (optionally <code>null</code>)
@return the ordered range of matching commerce user segment entries | [
"Returns",
"an",
"ordered",
"range",
"of",
"all",
"the",
"commerce",
"user",
"segment",
"entries",
"where",
"groupId",
"=",
"?",
";",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-user-segment-service/src/main/java/com/liferay/commerce/user/segment/service/persistence/impl/CommerceUserSegmentEntryPersistenceImpl.java#L163-L168 |
IBM/ibm-cos-sdk-java | ibm-cos-java-sdk-s3/src/main/java/com/ibm/cloud/objectstorage/services/aspera/transfer/AsperaTransferManager.java | AsperaTransferManager.processTransfer | public AsperaTransaction processTransfer(String transferSpecStr, String bucketName, String key, String fileName, ProgressListener progressListener) {
"""
Process the transfer spec to call the underlying Aspera libraries to begin the transfer
@param transferSpecStr
@param bucketName
@param key
@param fileName
@return
"""
// Generate session id
String xferId = UUID.randomUUID().toString();
AsperaTransactionImpl asperaTransaction = null;
try {
TransferProgress transferProgress = new TransferProgress();
S3ProgressListenerChain listenerChain = new S3ProgressListenerChain(
new TransferProgressUpdatingListener(transferProgress),
progressListener);
log.trace("AsperaTransferManager.processTransfer >> creating AsperaTransactionImpl " + System.nanoTime());
asperaTransaction = new AsperaTransactionImpl(xferId, bucketName, key, fileName, transferProgress, listenerChain);
log.trace("AsperaTransferManager.processTransfer << creating AsperaTransactionImpl " + System.nanoTime());
asperaFaspManagerWrapper.setAsperaTransaction(asperaTransaction);
log.trace("AsperaTransferManager.processTransfer >> start transfer " + System.nanoTime());
asperaFaspManagerWrapper.startTransfer(xferId, transferSpecStr);
log.trace("AsperaTransferManager.processTransfer >> end transfer " + System.nanoTime());
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return asperaTransaction;
} | java | public AsperaTransaction processTransfer(String transferSpecStr, String bucketName, String key, String fileName, ProgressListener progressListener) {
// Generate session id
String xferId = UUID.randomUUID().toString();
AsperaTransactionImpl asperaTransaction = null;
try {
TransferProgress transferProgress = new TransferProgress();
S3ProgressListenerChain listenerChain = new S3ProgressListenerChain(
new TransferProgressUpdatingListener(transferProgress),
progressListener);
log.trace("AsperaTransferManager.processTransfer >> creating AsperaTransactionImpl " + System.nanoTime());
asperaTransaction = new AsperaTransactionImpl(xferId, bucketName, key, fileName, transferProgress, listenerChain);
log.trace("AsperaTransferManager.processTransfer << creating AsperaTransactionImpl " + System.nanoTime());
asperaFaspManagerWrapper.setAsperaTransaction(asperaTransaction);
log.trace("AsperaTransferManager.processTransfer >> start transfer " + System.nanoTime());
asperaFaspManagerWrapper.startTransfer(xferId, transferSpecStr);
log.trace("AsperaTransferManager.processTransfer >> end transfer " + System.nanoTime());
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return asperaTransaction;
} | [
"public",
"AsperaTransaction",
"processTransfer",
"(",
"String",
"transferSpecStr",
",",
"String",
"bucketName",
",",
"String",
"key",
",",
"String",
"fileName",
",",
"ProgressListener",
"progressListener",
")",
"{",
"// Generate session id",
"String",
"xferId",
"=",
"UUID",
".",
"randomUUID",
"(",
")",
".",
"toString",
"(",
")",
";",
"AsperaTransactionImpl",
"asperaTransaction",
"=",
"null",
";",
"try",
"{",
"TransferProgress",
"transferProgress",
"=",
"new",
"TransferProgress",
"(",
")",
";",
"S3ProgressListenerChain",
"listenerChain",
"=",
"new",
"S3ProgressListenerChain",
"(",
"new",
"TransferProgressUpdatingListener",
"(",
"transferProgress",
")",
",",
"progressListener",
")",
";",
"log",
".",
"trace",
"(",
"\"AsperaTransferManager.processTransfer >> creating AsperaTransactionImpl \"",
"+",
"System",
".",
"nanoTime",
"(",
")",
")",
";",
"asperaTransaction",
"=",
"new",
"AsperaTransactionImpl",
"(",
"xferId",
",",
"bucketName",
",",
"key",
",",
"fileName",
",",
"transferProgress",
",",
"listenerChain",
")",
";",
"log",
".",
"trace",
"(",
"\"AsperaTransferManager.processTransfer << creating AsperaTransactionImpl \"",
"+",
"System",
".",
"nanoTime",
"(",
")",
")",
";",
"asperaFaspManagerWrapper",
".",
"setAsperaTransaction",
"(",
"asperaTransaction",
")",
";",
"log",
".",
"trace",
"(",
"\"AsperaTransferManager.processTransfer >> start transfer \"",
"+",
"System",
".",
"nanoTime",
"(",
")",
")",
";",
"asperaFaspManagerWrapper",
".",
"startTransfer",
"(",
"xferId",
",",
"transferSpecStr",
")",
";",
"log",
".",
"trace",
"(",
"\"AsperaTransferManager.processTransfer >> end transfer \"",
"+",
"System",
".",
"nanoTime",
"(",
")",
")",
";",
"}",
"catch",
"(",
"IllegalArgumentException",
"e",
")",
"{",
"// TODO Auto-generated catch block",
"e",
".",
"printStackTrace",
"(",
")",
";",
"}",
"catch",
"(",
"SecurityException",
"e1",
")",
"{",
"// TODO Auto-generated catch block",
"e1",
".",
"printStackTrace",
"(",
")",
";",
"}",
"return",
"asperaTransaction",
";",
"}"
] | Process the transfer spec to call the underlying Aspera libraries to begin the transfer
@param transferSpecStr
@param bucketName
@param key
@param fileName
@return | [
"Process",
"the",
"transfer",
"spec",
"to",
"call",
"the",
"underlying",
"Aspera",
"libraries",
"to",
"begin",
"the",
"transfer"
] | train | https://github.com/IBM/ibm-cos-sdk-java/blob/d0bb2dd754c328a05e7dba8dc42e28b271b6daf2/ibm-cos-java-sdk-s3/src/main/java/com/ibm/cloud/objectstorage/services/aspera/transfer/AsperaTransferManager.java#L286-L317 |
sdl/odata | odata_renderer/src/main/java/com/sdl/odata/renderer/json/writer/JsonServiceDocumentWriter.java | JsonServiceDocumentWriter.buildJson | public String buildJson() throws ODataRenderException {
"""
The main method for Writer.
It builds the service root document according to spec.
@return output in json
@throws ODataRenderException If unable to render the json service document
"""
LOG.debug("Start building Json service root document");
try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) {
JsonGenerator jsonGenerator = JSON_FACTORY.createGenerator(stream, JsonEncoding.UTF8);
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField(CONTEXT, getContextURL(uri, entityDataModel));
jsonGenerator.writeArrayFieldStart(VALUE);
List<EntitySet> entities = entityDataModel.getEntityContainer().getEntitySets();
for (EntitySet entity : entities) {
if (entity.isIncludedInServiceDocument()) {
writeObject(jsonGenerator, entity);
}
}
List<Singleton> singletons = entityDataModel.getEntityContainer().getSingletons();
for (Singleton singleton : singletons) {
writeObject(jsonGenerator, singleton);
}
jsonGenerator.writeEndArray();
jsonGenerator.writeEndObject();
jsonGenerator.close();
return stream.toString(StandardCharsets.UTF_8.name());
} catch (IOException e) {
throw new ODataRenderException("It is unable to render service document", e);
}
} | java | public String buildJson() throws ODataRenderException {
LOG.debug("Start building Json service root document");
try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) {
JsonGenerator jsonGenerator = JSON_FACTORY.createGenerator(stream, JsonEncoding.UTF8);
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField(CONTEXT, getContextURL(uri, entityDataModel));
jsonGenerator.writeArrayFieldStart(VALUE);
List<EntitySet> entities = entityDataModel.getEntityContainer().getEntitySets();
for (EntitySet entity : entities) {
if (entity.isIncludedInServiceDocument()) {
writeObject(jsonGenerator, entity);
}
}
List<Singleton> singletons = entityDataModel.getEntityContainer().getSingletons();
for (Singleton singleton : singletons) {
writeObject(jsonGenerator, singleton);
}
jsonGenerator.writeEndArray();
jsonGenerator.writeEndObject();
jsonGenerator.close();
return stream.toString(StandardCharsets.UTF_8.name());
} catch (IOException e) {
throw new ODataRenderException("It is unable to render service document", e);
}
} | [
"public",
"String",
"buildJson",
"(",
")",
"throws",
"ODataRenderException",
"{",
"LOG",
".",
"debug",
"(",
"\"Start building Json service root document\"",
")",
";",
"try",
"(",
"ByteArrayOutputStream",
"stream",
"=",
"new",
"ByteArrayOutputStream",
"(",
")",
")",
"{",
"JsonGenerator",
"jsonGenerator",
"=",
"JSON_FACTORY",
".",
"createGenerator",
"(",
"stream",
",",
"JsonEncoding",
".",
"UTF8",
")",
";",
"jsonGenerator",
".",
"writeStartObject",
"(",
")",
";",
"jsonGenerator",
".",
"writeStringField",
"(",
"CONTEXT",
",",
"getContextURL",
"(",
"uri",
",",
"entityDataModel",
")",
")",
";",
"jsonGenerator",
".",
"writeArrayFieldStart",
"(",
"VALUE",
")",
";",
"List",
"<",
"EntitySet",
">",
"entities",
"=",
"entityDataModel",
".",
"getEntityContainer",
"(",
")",
".",
"getEntitySets",
"(",
")",
";",
"for",
"(",
"EntitySet",
"entity",
":",
"entities",
")",
"{",
"if",
"(",
"entity",
".",
"isIncludedInServiceDocument",
"(",
")",
")",
"{",
"writeObject",
"(",
"jsonGenerator",
",",
"entity",
")",
";",
"}",
"}",
"List",
"<",
"Singleton",
">",
"singletons",
"=",
"entityDataModel",
".",
"getEntityContainer",
"(",
")",
".",
"getSingletons",
"(",
")",
";",
"for",
"(",
"Singleton",
"singleton",
":",
"singletons",
")",
"{",
"writeObject",
"(",
"jsonGenerator",
",",
"singleton",
")",
";",
"}",
"jsonGenerator",
".",
"writeEndArray",
"(",
")",
";",
"jsonGenerator",
".",
"writeEndObject",
"(",
")",
";",
"jsonGenerator",
".",
"close",
"(",
")",
";",
"return",
"stream",
".",
"toString",
"(",
"StandardCharsets",
".",
"UTF_8",
".",
"name",
"(",
")",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"ODataRenderException",
"(",
"\"It is unable to render service document\"",
",",
"e",
")",
";",
"}",
"}"
] | The main method for Writer.
It builds the service root document according to spec.
@return output in json
@throws ODataRenderException If unable to render the json service document | [
"The",
"main",
"method",
"for",
"Writer",
".",
"It",
"builds",
"the",
"service",
"root",
"document",
"according",
"to",
"spec",
"."
] | train | https://github.com/sdl/odata/blob/eb747d73e9af0f4e59a25b82ed656e526a7e2189/odata_renderer/src/main/java/com/sdl/odata/renderer/json/writer/JsonServiceDocumentWriter.java#L68-L96 |
spring-projects/spring-hateoas | src/main/java/org/springframework/hateoas/server/reactive/WebFluxLinkBuilder.java | WebFluxLinkBuilder.linkTo | public static WebFluxBuilder linkTo(Object invocation, ServerWebExchange exchange) {
"""
Create a {@link WebFluxLinkBuilder} using an explicitly defined {@link ServerWebExchange}. This is possible if your
WebFlux method includes the exchange and you want to pass it straight in.
@param invocation must not be {@literal null}.
@param exchange must not be {@literal null}.
"""
return new WebFluxBuilder(linkToInternal(invocation, Mono.just(getBuilder(exchange))));
} | java | public static WebFluxBuilder linkTo(Object invocation, ServerWebExchange exchange) {
return new WebFluxBuilder(linkToInternal(invocation, Mono.just(getBuilder(exchange))));
} | [
"public",
"static",
"WebFluxBuilder",
"linkTo",
"(",
"Object",
"invocation",
",",
"ServerWebExchange",
"exchange",
")",
"{",
"return",
"new",
"WebFluxBuilder",
"(",
"linkToInternal",
"(",
"invocation",
",",
"Mono",
".",
"just",
"(",
"getBuilder",
"(",
"exchange",
")",
")",
")",
")",
";",
"}"
] | Create a {@link WebFluxLinkBuilder} using an explicitly defined {@link ServerWebExchange}. This is possible if your
WebFlux method includes the exchange and you want to pass it straight in.
@param invocation must not be {@literal null}.
@param exchange must not be {@literal null}. | [
"Create",
"a",
"{",
"@link",
"WebFluxLinkBuilder",
"}",
"using",
"an",
"explicitly",
"defined",
"{",
"@link",
"ServerWebExchange",
"}",
".",
"This",
"is",
"possible",
"if",
"your",
"WebFlux",
"method",
"includes",
"the",
"exchange",
"and",
"you",
"want",
"to",
"pass",
"it",
"straight",
"in",
"."
] | train | https://github.com/spring-projects/spring-hateoas/blob/70ebff9309f086cd8d6a97daf67e0dc215c87d9c/src/main/java/org/springframework/hateoas/server/reactive/WebFluxLinkBuilder.java#L79-L81 |
landawn/AbacusUtil | src/com/landawn/abacus/util/DateUtil.java | DateUtil.addSeconds | public static <T extends java.util.Date> T addSeconds(final T date, final int amount) {
"""
Adds a number of seconds to a date returning a new object.
The original {@code Date} is unchanged.
@param date the date, not null
@param amount the amount to add, may be negative
@return the new {@code Date} with the amount added
@throws IllegalArgumentException if the date is null
"""
return roll(date, amount, CalendarUnit.SECOND);
} | java | public static <T extends java.util.Date> T addSeconds(final T date, final int amount) {
return roll(date, amount, CalendarUnit.SECOND);
} | [
"public",
"static",
"<",
"T",
"extends",
"java",
".",
"util",
".",
"Date",
">",
"T",
"addSeconds",
"(",
"final",
"T",
"date",
",",
"final",
"int",
"amount",
")",
"{",
"return",
"roll",
"(",
"date",
",",
"amount",
",",
"CalendarUnit",
".",
"SECOND",
")",
";",
"}"
] | Adds a number of seconds to a date returning a new object.
The original {@code Date} is unchanged.
@param date the date, not null
@param amount the amount to add, may be negative
@return the new {@code Date} with the amount added
@throws IllegalArgumentException if the date is null | [
"Adds",
"a",
"number",
"of",
"seconds",
"to",
"a",
"date",
"returning",
"a",
"new",
"object",
".",
"The",
"original",
"{",
"@code",
"Date",
"}",
"is",
"unchanged",
"."
] | train | https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/DateUtil.java#L1035-L1037 |
ZenHarbinger/l2fprod-properties-editor | src/main/java/com/l2fprod/common/propertysheet/PropertySheetTable.java | PropertySheetTable.getIndent | static int getIndent(PropertySheetTable table, Item item) {
"""
Calculates the required left indent for a given item, given its type and
its hierarchy level.
"""
int indent;
if (item.isProperty()) {
// it is a property, it has no parent or a category, and no child
if ((item.getParent() == null || !item.getParent().isProperty())
&& !item.hasToggle()) {
indent = table.getWantsExtraIndent() ? HOTSPOT_SIZE : 0;
} else {
// it is a property with children
if (item.hasToggle()) {
indent = item.getDepth() * HOTSPOT_SIZE;
} else {
indent = (item.getDepth() + 1) * HOTSPOT_SIZE;
}
}
if (table.getSheetModel().getMode() == PropertySheet.VIEW_AS_CATEGORIES
&& table.getWantsExtraIndent()) {
indent += HOTSPOT_SIZE;
}
} else {
// category has no indent
indent = 0;
}
return indent;
} | java | static int getIndent(PropertySheetTable table, Item item) {
int indent;
if (item.isProperty()) {
// it is a property, it has no parent or a category, and no child
if ((item.getParent() == null || !item.getParent().isProperty())
&& !item.hasToggle()) {
indent = table.getWantsExtraIndent() ? HOTSPOT_SIZE : 0;
} else {
// it is a property with children
if (item.hasToggle()) {
indent = item.getDepth() * HOTSPOT_SIZE;
} else {
indent = (item.getDepth() + 1) * HOTSPOT_SIZE;
}
}
if (table.getSheetModel().getMode() == PropertySheet.VIEW_AS_CATEGORIES
&& table.getWantsExtraIndent()) {
indent += HOTSPOT_SIZE;
}
} else {
// category has no indent
indent = 0;
}
return indent;
} | [
"static",
"int",
"getIndent",
"(",
"PropertySheetTable",
"table",
",",
"Item",
"item",
")",
"{",
"int",
"indent",
";",
"if",
"(",
"item",
".",
"isProperty",
"(",
")",
")",
"{",
"// it is a property, it has no parent or a category, and no child\r",
"if",
"(",
"(",
"item",
".",
"getParent",
"(",
")",
"==",
"null",
"||",
"!",
"item",
".",
"getParent",
"(",
")",
".",
"isProperty",
"(",
")",
")",
"&&",
"!",
"item",
".",
"hasToggle",
"(",
")",
")",
"{",
"indent",
"=",
"table",
".",
"getWantsExtraIndent",
"(",
")",
"?",
"HOTSPOT_SIZE",
":",
"0",
";",
"}",
"else",
"{",
"// it is a property with children\r",
"if",
"(",
"item",
".",
"hasToggle",
"(",
")",
")",
"{",
"indent",
"=",
"item",
".",
"getDepth",
"(",
")",
"*",
"HOTSPOT_SIZE",
";",
"}",
"else",
"{",
"indent",
"=",
"(",
"item",
".",
"getDepth",
"(",
")",
"+",
"1",
")",
"*",
"HOTSPOT_SIZE",
";",
"}",
"}",
"if",
"(",
"table",
".",
"getSheetModel",
"(",
")",
".",
"getMode",
"(",
")",
"==",
"PropertySheet",
".",
"VIEW_AS_CATEGORIES",
"&&",
"table",
".",
"getWantsExtraIndent",
"(",
")",
")",
"{",
"indent",
"+=",
"HOTSPOT_SIZE",
";",
"}",
"}",
"else",
"{",
"// category has no indent\r",
"indent",
"=",
"0",
";",
"}",
"return",
"indent",
";",
"}"
] | Calculates the required left indent for a given item, given its type and
its hierarchy level. | [
"Calculates",
"the",
"required",
"left",
"indent",
"for",
"a",
"given",
"item",
"given",
"its",
"type",
"and",
"its",
"hierarchy",
"level",
"."
] | train | https://github.com/ZenHarbinger/l2fprod-properties-editor/blob/d9b15c3f0b6ac1d9a2a9d315be073d2a4a419c32/src/main/java/com/l2fprod/common/propertysheet/PropertySheetTable.java#L632-L659 |
alkacon/opencms-core | src/org/opencms/db/CmsDriverManager.java | CmsDriverManager.readGroup | public CmsGroup readGroup(CmsDbContext dbc, String groupname) throws CmsDataAccessException {
"""
Reads a group based on its name.<p>
@param dbc the current database context
@param groupname the name of the group that is to be read
@return the requested group
@throws CmsDataAccessException if operation was not successful
"""
CmsGroup group = null;
// try to read group from cache
group = m_monitor.getCachedGroup(groupname);
if (group == null) {
group = getUserDriver(dbc).readGroup(dbc, groupname);
m_monitor.cacheGroup(group);
}
return group;
} | java | public CmsGroup readGroup(CmsDbContext dbc, String groupname) throws CmsDataAccessException {
CmsGroup group = null;
// try to read group from cache
group = m_monitor.getCachedGroup(groupname);
if (group == null) {
group = getUserDriver(dbc).readGroup(dbc, groupname);
m_monitor.cacheGroup(group);
}
return group;
} | [
"public",
"CmsGroup",
"readGroup",
"(",
"CmsDbContext",
"dbc",
",",
"String",
"groupname",
")",
"throws",
"CmsDataAccessException",
"{",
"CmsGroup",
"group",
"=",
"null",
";",
"// try to read group from cache",
"group",
"=",
"m_monitor",
".",
"getCachedGroup",
"(",
"groupname",
")",
";",
"if",
"(",
"group",
"==",
"null",
")",
"{",
"group",
"=",
"getUserDriver",
"(",
"dbc",
")",
".",
"readGroup",
"(",
"dbc",
",",
"groupname",
")",
";",
"m_monitor",
".",
"cacheGroup",
"(",
"group",
")",
";",
"}",
"return",
"group",
";",
"}"
] | Reads a group based on its name.<p>
@param dbc the current database context
@param groupname the name of the group that is to be read
@return the requested group
@throws CmsDataAccessException if operation was not successful | [
"Reads",
"a",
"group",
"based",
"on",
"its",
"name",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsDriverManager.java#L6927-L6937 |
gallandarakhneorg/afc | maven/maventools/src/main/java/org/arakhne/maven/AbstractArakhneMojo.java | AbstractArakhneMojo.removePathPrefix | public static final String removePathPrefix(File prefix, File file) {
"""
Remove the path prefix from a file.
@param prefix path prefix to remove.
@param file input filename.
@return the {@code file} without the prefix.
"""
final String r = file.getAbsolutePath().replaceFirst(
"^" //$NON-NLS-1$
+ Pattern.quote(prefix.getAbsolutePath()),
EMPTY_STRING);
if (r.startsWith(File.separator)) {
return r.substring(File.separator.length());
}
return r;
} | java | public static final String removePathPrefix(File prefix, File file) {
final String r = file.getAbsolutePath().replaceFirst(
"^" //$NON-NLS-1$
+ Pattern.quote(prefix.getAbsolutePath()),
EMPTY_STRING);
if (r.startsWith(File.separator)) {
return r.substring(File.separator.length());
}
return r;
} | [
"public",
"static",
"final",
"String",
"removePathPrefix",
"(",
"File",
"prefix",
",",
"File",
"file",
")",
"{",
"final",
"String",
"r",
"=",
"file",
".",
"getAbsolutePath",
"(",
")",
".",
"replaceFirst",
"(",
"\"^\"",
"//$NON-NLS-1$",
"+",
"Pattern",
".",
"quote",
"(",
"prefix",
".",
"getAbsolutePath",
"(",
")",
")",
",",
"EMPTY_STRING",
")",
";",
"if",
"(",
"r",
".",
"startsWith",
"(",
"File",
".",
"separator",
")",
")",
"{",
"return",
"r",
".",
"substring",
"(",
"File",
".",
"separator",
".",
"length",
"(",
")",
")",
";",
"}",
"return",
"r",
";",
"}"
] | Remove the path prefix from a file.
@param prefix path prefix to remove.
@param file input filename.
@return the {@code file} without the prefix. | [
"Remove",
"the",
"path",
"prefix",
"from",
"a",
"file",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/maven/maventools/src/main/java/org/arakhne/maven/AbstractArakhneMojo.java#L398-L407 |
SpartaTech/sparta-spring-web-utils | src/main/java/org/sparta/springwebutils/queryloader/impl/FileQueryLoader.java | FileQueryLoader.loadfromFromFile | private String loadfromFromFile(String queryName) throws IllegalStateException {
"""
Loads the query from the informed path and adds to cache
@param queryName File name for the query to be loaded
@return requested Query
@throws IllegalStateException In case query was not found
"""
try (final InputStream is = getClass().getResourceAsStream(scriptsFolder + queryName + ".sql");) {
String sql = StringUtils.join(IOUtils.readLines(is, StandardCharsets.UTF_8), IOUtils.LINE_SEPARATOR);
// Look for tokens
final String[] tokens = StringUtils.substringsBetween(sql, "${", "}");
if (tokens != null && tokens.length > 0) {
final Map<String, String> values = Arrays.stream(tokens).collect(Collectors.toMap(
Function.identity(),
this::load,
(o, n) -> o
));
sql = StrSubstitutor.replace(sql, values);
}
return sql;
} catch (Exception e) {
throw new IllegalStateException("Could not load query " + scriptsFolder + queryName, e);
}
} | java | private String loadfromFromFile(String queryName) throws IllegalStateException {
try (final InputStream is = getClass().getResourceAsStream(scriptsFolder + queryName + ".sql");) {
String sql = StringUtils.join(IOUtils.readLines(is, StandardCharsets.UTF_8), IOUtils.LINE_SEPARATOR);
// Look for tokens
final String[] tokens = StringUtils.substringsBetween(sql, "${", "}");
if (tokens != null && tokens.length > 0) {
final Map<String, String> values = Arrays.stream(tokens).collect(Collectors.toMap(
Function.identity(),
this::load,
(o, n) -> o
));
sql = StrSubstitutor.replace(sql, values);
}
return sql;
} catch (Exception e) {
throw new IllegalStateException("Could not load query " + scriptsFolder + queryName, e);
}
} | [
"private",
"String",
"loadfromFromFile",
"(",
"String",
"queryName",
")",
"throws",
"IllegalStateException",
"{",
"try",
"(",
"final",
"InputStream",
"is",
"=",
"getClass",
"(",
")",
".",
"getResourceAsStream",
"(",
"scriptsFolder",
"+",
"queryName",
"+",
"\".sql\"",
")",
";",
")",
"{",
"String",
"sql",
"=",
"StringUtils",
".",
"join",
"(",
"IOUtils",
".",
"readLines",
"(",
"is",
",",
"StandardCharsets",
".",
"UTF_8",
")",
",",
"IOUtils",
".",
"LINE_SEPARATOR",
")",
";",
"// Look for tokens",
"final",
"String",
"[",
"]",
"tokens",
"=",
"StringUtils",
".",
"substringsBetween",
"(",
"sql",
",",
"\"${\"",
",",
"\"}\"",
")",
";",
"if",
"(",
"tokens",
"!=",
"null",
"&&",
"tokens",
".",
"length",
">",
"0",
")",
"{",
"final",
"Map",
"<",
"String",
",",
"String",
">",
"values",
"=",
"Arrays",
".",
"stream",
"(",
"tokens",
")",
".",
"collect",
"(",
"Collectors",
".",
"toMap",
"(",
"Function",
".",
"identity",
"(",
")",
",",
"this",
"::",
"load",
",",
"(",
"o",
",",
"n",
")",
"->",
"o",
")",
")",
";",
"sql",
"=",
"StrSubstitutor",
".",
"replace",
"(",
"sql",
",",
"values",
")",
";",
"}",
"return",
"sql",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Could not load query \"",
"+",
"scriptsFolder",
"+",
"queryName",
",",
"e",
")",
";",
"}",
"}"
] | Loads the query from the informed path and adds to cache
@param queryName File name for the query to be loaded
@return requested Query
@throws IllegalStateException In case query was not found | [
"Loads",
"the",
"query",
"from",
"the",
"informed",
"path",
"and",
"adds",
"to",
"cache"
] | train | https://github.com/SpartaTech/sparta-spring-web-utils/blob/f5382474d46a6048d58707fc64e7936277e8b2ce/src/main/java/org/sparta/springwebutils/queryloader/impl/FileQueryLoader.java#L82-L102 |
weld/core | modules/ejb/src/main/java/org/jboss/weld/module/ejb/SessionBeanImpl.java | SessionBeanImpl.of | public static <T> SessionBean<T> of(BeanAttributes<T> attributes, InternalEjbDescriptor<T> ejbDescriptor, BeanManagerImpl beanManager, EnhancedAnnotatedType<T> type) {
"""
Creates a simple, annotation defined Enterprise Web Bean using the annotations specified on type
@param <T> The type
@param beanManager the current manager
@param type the AnnotatedType to use
@return An Enterprise Web Bean
"""
return new SessionBeanImpl<T>(attributes, type, ejbDescriptor, new StringBeanIdentifier(SessionBeans.createIdentifier(type, ejbDescriptor)), beanManager);
} | java | public static <T> SessionBean<T> of(BeanAttributes<T> attributes, InternalEjbDescriptor<T> ejbDescriptor, BeanManagerImpl beanManager, EnhancedAnnotatedType<T> type) {
return new SessionBeanImpl<T>(attributes, type, ejbDescriptor, new StringBeanIdentifier(SessionBeans.createIdentifier(type, ejbDescriptor)), beanManager);
} | [
"public",
"static",
"<",
"T",
">",
"SessionBean",
"<",
"T",
">",
"of",
"(",
"BeanAttributes",
"<",
"T",
">",
"attributes",
",",
"InternalEjbDescriptor",
"<",
"T",
">",
"ejbDescriptor",
",",
"BeanManagerImpl",
"beanManager",
",",
"EnhancedAnnotatedType",
"<",
"T",
">",
"type",
")",
"{",
"return",
"new",
"SessionBeanImpl",
"<",
"T",
">",
"(",
"attributes",
",",
"type",
",",
"ejbDescriptor",
",",
"new",
"StringBeanIdentifier",
"(",
"SessionBeans",
".",
"createIdentifier",
"(",
"type",
",",
"ejbDescriptor",
")",
")",
",",
"beanManager",
")",
";",
"}"
] | Creates a simple, annotation defined Enterprise Web Bean using the annotations specified on type
@param <T> The type
@param beanManager the current manager
@param type the AnnotatedType to use
@return An Enterprise Web Bean | [
"Creates",
"a",
"simple",
"annotation",
"defined",
"Enterprise",
"Web",
"Bean",
"using",
"the",
"annotations",
"specified",
"on",
"type"
] | train | https://github.com/weld/core/blob/567a2eaf95b168597d23a56be89bf05a7834b2aa/modules/ejb/src/main/java/org/jboss/weld/module/ejb/SessionBeanImpl.java#L76-L78 |
triceo/splitlog | splitlog-api/src/main/java/com/github/triceo/splitlog/logging/SplitlogLoggerInvocationHandler.java | SplitlogLoggerInvocationHandler.invoke | @Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
"""
Will call the proxied method, but only if
{@link SplitlogLoggerFactory#isLoggingEnabled()} is true at the time.
"""
if (SplitlogLoggerFactory.isLoggingEnabled()) {
SplitlogLoggerFactory.increaseMessageCounter();
return method.invoke(this.proxied, args);
} else {
// logging is not enabled, don't proxy the call
return null;
}
} | java | @Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
if (SplitlogLoggerFactory.isLoggingEnabled()) {
SplitlogLoggerFactory.increaseMessageCounter();
return method.invoke(this.proxied, args);
} else {
// logging is not enabled, don't proxy the call
return null;
}
} | [
"@",
"Override",
"public",
"Object",
"invoke",
"(",
"final",
"Object",
"proxy",
",",
"final",
"Method",
"method",
",",
"final",
"Object",
"[",
"]",
"args",
")",
"throws",
"Throwable",
"{",
"if",
"(",
"SplitlogLoggerFactory",
".",
"isLoggingEnabled",
"(",
")",
")",
"{",
"SplitlogLoggerFactory",
".",
"increaseMessageCounter",
"(",
")",
";",
"return",
"method",
".",
"invoke",
"(",
"this",
".",
"proxied",
",",
"args",
")",
";",
"}",
"else",
"{",
"// logging is not enabled, don't proxy the call",
"return",
"null",
";",
"}",
"}"
] | Will call the proxied method, but only if
{@link SplitlogLoggerFactory#isLoggingEnabled()} is true at the time. | [
"Will",
"call",
"the",
"proxied",
"method",
"but",
"only",
"if",
"{"
] | train | https://github.com/triceo/splitlog/blob/4e1b188e8c814119f5cf7343bbc53917843d68a2/splitlog-api/src/main/java/com/github/triceo/splitlog/logging/SplitlogLoggerInvocationHandler.java#L26-L35 |
MKLab-ITI/multimedia-indexing | src/main/java/gr/iti/mklab/visual/aggregation/AbstractFeatureAggregator.java | AbstractFeatureAggregator.readQuantizer | public static double[][] readQuantizer(String filename, int numCentroids, int centroidLength)
throws IOException {
"""
Reads a quantizer (codebook) from the given file and returns it in a 2-dimensional double array.
@param filename
name of the file containing the quantizer
@param numCentroids
number of centroids of the quantizer
@param centroidLength
length of each centroid
@return the quantizer as a 2-dimensional double array
@throws IOException
"""
double[][] quantizer = new double[numCentroids][centroidLength];
// load the quantizer
BufferedReader in = new BufferedReader(new FileReader(filename));
String line;
int counter = 0;
while ((line = in.readLine()) != null) {
// skip header lines
if (!line.contains(",")) { // not a csv data line
continue;
}
String[] centerStrings = line.split(",");
for (int i = 0; i < centerStrings.length; i++) {
quantizer[counter][i] = Double.parseDouble(centerStrings[i]);
}
counter++;
}
in.close();
return quantizer;
} | java | public static double[][] readQuantizer(String filename, int numCentroids, int centroidLength)
throws IOException {
double[][] quantizer = new double[numCentroids][centroidLength];
// load the quantizer
BufferedReader in = new BufferedReader(new FileReader(filename));
String line;
int counter = 0;
while ((line = in.readLine()) != null) {
// skip header lines
if (!line.contains(",")) { // not a csv data line
continue;
}
String[] centerStrings = line.split(",");
for (int i = 0; i < centerStrings.length; i++) {
quantizer[counter][i] = Double.parseDouble(centerStrings[i]);
}
counter++;
}
in.close();
return quantizer;
} | [
"public",
"static",
"double",
"[",
"]",
"[",
"]",
"readQuantizer",
"(",
"String",
"filename",
",",
"int",
"numCentroids",
",",
"int",
"centroidLength",
")",
"throws",
"IOException",
"{",
"double",
"[",
"]",
"[",
"]",
"quantizer",
"=",
"new",
"double",
"[",
"numCentroids",
"]",
"[",
"centroidLength",
"]",
";",
"// load the quantizer\r",
"BufferedReader",
"in",
"=",
"new",
"BufferedReader",
"(",
"new",
"FileReader",
"(",
"filename",
")",
")",
";",
"String",
"line",
";",
"int",
"counter",
"=",
"0",
";",
"while",
"(",
"(",
"line",
"=",
"in",
".",
"readLine",
"(",
")",
")",
"!=",
"null",
")",
"{",
"// skip header lines\r",
"if",
"(",
"!",
"line",
".",
"contains",
"(",
"\",\"",
")",
")",
"{",
"// not a csv data line\r",
"continue",
";",
"}",
"String",
"[",
"]",
"centerStrings",
"=",
"line",
".",
"split",
"(",
"\",\"",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"centerStrings",
".",
"length",
";",
"i",
"++",
")",
"{",
"quantizer",
"[",
"counter",
"]",
"[",
"i",
"]",
"=",
"Double",
".",
"parseDouble",
"(",
"centerStrings",
"[",
"i",
"]",
")",
";",
"}",
"counter",
"++",
";",
"}",
"in",
".",
"close",
"(",
")",
";",
"return",
"quantizer",
";",
"}"
] | Reads a quantizer (codebook) from the given file and returns it in a 2-dimensional double array.
@param filename
name of the file containing the quantizer
@param numCentroids
number of centroids of the quantizer
@param centroidLength
length of each centroid
@return the quantizer as a 2-dimensional double array
@throws IOException | [
"Reads",
"a",
"quantizer",
"(",
"codebook",
")",
"from",
"the",
"given",
"file",
"and",
"returns",
"it",
"in",
"a",
"2",
"-",
"dimensional",
"double",
"array",
"."
] | train | https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/aggregation/AbstractFeatureAggregator.java#L234-L254 |
biojava/biojava | biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/AFPAlignmentDisplay.java | AFPAlignmentDisplay.getAlign | public static void getAlign(AFPChain afpChain,Atom[] ca1,Atom[] ca2) {
"""
Extract the alignment output
<p>eg<pre>
STWNTWACTWHLKQP--WSTILILA
111111111111 22222222
SQNNTYACSWKLKSWNNNSTILILG
</pre>
Those position pairs labeled by 1 and 2 are equivalent positions, belongs to
two blocks 1 and 2. The residues between labeled residues are non-equivalent,
with '-' filling in their resulting gaps.
<p>
The three lines can be accessed using
{@link AFPChain#getAlnseq1()}, {@link AFPChain#getAlnsymb()},
and {@link AFPChain#getAlnseq2()}.
"""
getAlign(afpChain, ca1, ca2, false);
} | java | public static void getAlign(AFPChain afpChain,Atom[] ca1,Atom[] ca2) {
getAlign(afpChain, ca1, ca2, false);
} | [
"public",
"static",
"void",
"getAlign",
"(",
"AFPChain",
"afpChain",
",",
"Atom",
"[",
"]",
"ca1",
",",
"Atom",
"[",
"]",
"ca2",
")",
"{",
"getAlign",
"(",
"afpChain",
",",
"ca1",
",",
"ca2",
",",
"false",
")",
";",
"}"
] | Extract the alignment output
<p>eg<pre>
STWNTWACTWHLKQP--WSTILILA
111111111111 22222222
SQNNTYACSWKLKSWNNNSTILILG
</pre>
Those position pairs labeled by 1 and 2 are equivalent positions, belongs to
two blocks 1 and 2. The residues between labeled residues are non-equivalent,
with '-' filling in their resulting gaps.
<p>
The three lines can be accessed using
{@link AFPChain#getAlnseq1()}, {@link AFPChain#getAlnsymb()},
and {@link AFPChain#getAlnseq2()}. | [
"Extract",
"the",
"alignment",
"output",
"<p",
">",
"eg<pre",
">",
"STWNTWACTWHLKQP",
"--",
"WSTILILA",
"111111111111",
"22222222",
"SQNNTYACSWKLKSWNNNSTILILG",
"<",
"/",
"pre",
">",
"Those",
"position",
"pairs",
"labeled",
"by",
"1",
"and",
"2",
"are",
"equivalent",
"positions",
"belongs",
"to",
"two",
"blocks",
"1",
"and",
"2",
".",
"The",
"residues",
"between",
"labeled",
"residues",
"are",
"non",
"-",
"equivalent",
"with",
"-",
"filling",
"in",
"their",
"resulting",
"gaps",
".",
"<p",
">",
"The",
"three",
"lines",
"can",
"be",
"accessed",
"using",
"{",
"@link",
"AFPChain#getAlnseq1",
"()",
"}",
"{",
"@link",
"AFPChain#getAlnsymb",
"()",
"}",
"and",
"{",
"@link",
"AFPChain#getAlnseq2",
"()",
"}",
"."
] | train | https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/AFPAlignmentDisplay.java#L152-L154 |
protobufel/protobuf-el | protobufel/src/main/java/com/github/protobufel/DynamicMessage.java | DynamicMessage.parseFrom | public static DynamicMessage parseFrom(final Descriptor type, final InputStream input)
throws IOException {
"""
Parse a message of the given type from {@code input} and return it.
"""
return wrap(com.google.protobuf.DynamicMessage.parseFrom(type, input));
} | java | public static DynamicMessage parseFrom(final Descriptor type, final InputStream input)
throws IOException {
return wrap(com.google.protobuf.DynamicMessage.parseFrom(type, input));
} | [
"public",
"static",
"DynamicMessage",
"parseFrom",
"(",
"final",
"Descriptor",
"type",
",",
"final",
"InputStream",
"input",
")",
"throws",
"IOException",
"{",
"return",
"wrap",
"(",
"com",
".",
"google",
".",
"protobuf",
".",
"DynamicMessage",
".",
"parseFrom",
"(",
"type",
",",
"input",
")",
")",
";",
"}"
] | Parse a message of the given type from {@code input} and return it. | [
"Parse",
"a",
"message",
"of",
"the",
"given",
"type",
"from",
"{"
] | train | https://github.com/protobufel/protobuf-el/blob/3a600e2f7a8e74b637f44eee0331ef6e57e7441c/protobufel/src/main/java/com/github/protobufel/DynamicMessage.java#L165-L168 |
liferay/com-liferay-commerce | commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPTaxCategoryPersistenceImpl.java | CPTaxCategoryPersistenceImpl.findByGroupId | @Override
public List<CPTaxCategory> findByGroupId(long groupId) {
"""
Returns all the cp tax categories where groupId = ?.
@param groupId the group ID
@return the matching cp tax categories
"""
return findByGroupId(groupId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
} | java | @Override
public List<CPTaxCategory> findByGroupId(long groupId) {
return findByGroupId(groupId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
} | [
"@",
"Override",
"public",
"List",
"<",
"CPTaxCategory",
">",
"findByGroupId",
"(",
"long",
"groupId",
")",
"{",
"return",
"findByGroupId",
"(",
"groupId",
",",
"QueryUtil",
".",
"ALL_POS",
",",
"QueryUtil",
".",
"ALL_POS",
",",
"null",
")",
";",
"}"
] | Returns all the cp tax categories where groupId = ?.
@param groupId the group ID
@return the matching cp tax categories | [
"Returns",
"all",
"the",
"cp",
"tax",
"categories",
"where",
"groupId",
"=",
"?",
";",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPTaxCategoryPersistenceImpl.java#L121-L124 |
phax/ph-schedule | ph-mini-quartz/src/main/java/com/helger/quartz/impl/triggers/CronTrigger.java | CronTrigger.willFireOn | public boolean willFireOn (final Calendar aTest, final boolean dayOnly) {
"""
<p>
Determines whether the date and (optionally) time of the given Calendar
instance falls on a scheduled fire-time of this trigger.
</p>
<p>
Note that the value returned is NOT validated against the related
{@link ICalendar} (if any)
</p>
@param aTest
the date to compare
@param dayOnly
if set to true, the method will only determine if the trigger will
fire during the day represented by the given Calendar (hours,
minutes and seconds will be ignored).
@see #willFireOn(Calendar)
"""
final Calendar test = (Calendar) aTest.clone ();
test.set (Calendar.MILLISECOND, 0); // don't compare millis.
if (dayOnly)
{
test.set (Calendar.HOUR_OF_DAY, 0);
test.set (Calendar.MINUTE, 0);
test.set (Calendar.SECOND, 0);
}
final Date testTime = test.getTime ();
Date fta = getFireTimeAfter (new Date (test.getTime ().getTime () - 1000));
if (fta == null)
return false;
final Calendar p = Calendar.getInstance (test.getTimeZone (), Locale.getDefault (Locale.Category.FORMAT));
p.setTime (fta);
final int year = p.get (Calendar.YEAR);
final int month = p.get (Calendar.MONTH);
final int day = p.get (Calendar.DATE);
if (dayOnly)
{
return (year == test.get (Calendar.YEAR) &&
month == test.get (Calendar.MONTH) &&
day == test.get (Calendar.DATE));
}
while (fta.before (testTime))
{
fta = getFireTimeAfter (fta);
}
return fta.equals (testTime);
} | java | public boolean willFireOn (final Calendar aTest, final boolean dayOnly)
{
final Calendar test = (Calendar) aTest.clone ();
test.set (Calendar.MILLISECOND, 0); // don't compare millis.
if (dayOnly)
{
test.set (Calendar.HOUR_OF_DAY, 0);
test.set (Calendar.MINUTE, 0);
test.set (Calendar.SECOND, 0);
}
final Date testTime = test.getTime ();
Date fta = getFireTimeAfter (new Date (test.getTime ().getTime () - 1000));
if (fta == null)
return false;
final Calendar p = Calendar.getInstance (test.getTimeZone (), Locale.getDefault (Locale.Category.FORMAT));
p.setTime (fta);
final int year = p.get (Calendar.YEAR);
final int month = p.get (Calendar.MONTH);
final int day = p.get (Calendar.DATE);
if (dayOnly)
{
return (year == test.get (Calendar.YEAR) &&
month == test.get (Calendar.MONTH) &&
day == test.get (Calendar.DATE));
}
while (fta.before (testTime))
{
fta = getFireTimeAfter (fta);
}
return fta.equals (testTime);
} | [
"public",
"boolean",
"willFireOn",
"(",
"final",
"Calendar",
"aTest",
",",
"final",
"boolean",
"dayOnly",
")",
"{",
"final",
"Calendar",
"test",
"=",
"(",
"Calendar",
")",
"aTest",
".",
"clone",
"(",
")",
";",
"test",
".",
"set",
"(",
"Calendar",
".",
"MILLISECOND",
",",
"0",
")",
";",
"// don't compare millis.",
"if",
"(",
"dayOnly",
")",
"{",
"test",
".",
"set",
"(",
"Calendar",
".",
"HOUR_OF_DAY",
",",
"0",
")",
";",
"test",
".",
"set",
"(",
"Calendar",
".",
"MINUTE",
",",
"0",
")",
";",
"test",
".",
"set",
"(",
"Calendar",
".",
"SECOND",
",",
"0",
")",
";",
"}",
"final",
"Date",
"testTime",
"=",
"test",
".",
"getTime",
"(",
")",
";",
"Date",
"fta",
"=",
"getFireTimeAfter",
"(",
"new",
"Date",
"(",
"test",
".",
"getTime",
"(",
")",
".",
"getTime",
"(",
")",
"-",
"1000",
")",
")",
";",
"if",
"(",
"fta",
"==",
"null",
")",
"return",
"false",
";",
"final",
"Calendar",
"p",
"=",
"Calendar",
".",
"getInstance",
"(",
"test",
".",
"getTimeZone",
"(",
")",
",",
"Locale",
".",
"getDefault",
"(",
"Locale",
".",
"Category",
".",
"FORMAT",
")",
")",
";",
"p",
".",
"setTime",
"(",
"fta",
")",
";",
"final",
"int",
"year",
"=",
"p",
".",
"get",
"(",
"Calendar",
".",
"YEAR",
")",
";",
"final",
"int",
"month",
"=",
"p",
".",
"get",
"(",
"Calendar",
".",
"MONTH",
")",
";",
"final",
"int",
"day",
"=",
"p",
".",
"get",
"(",
"Calendar",
".",
"DATE",
")",
";",
"if",
"(",
"dayOnly",
")",
"{",
"return",
"(",
"year",
"==",
"test",
".",
"get",
"(",
"Calendar",
".",
"YEAR",
")",
"&&",
"month",
"==",
"test",
".",
"get",
"(",
"Calendar",
".",
"MONTH",
")",
"&&",
"day",
"==",
"test",
".",
"get",
"(",
"Calendar",
".",
"DATE",
")",
")",
";",
"}",
"while",
"(",
"fta",
".",
"before",
"(",
"testTime",
")",
")",
"{",
"fta",
"=",
"getFireTimeAfter",
"(",
"fta",
")",
";",
"}",
"return",
"fta",
".",
"equals",
"(",
"testTime",
")",
";",
"}"
] | <p>
Determines whether the date and (optionally) time of the given Calendar
instance falls on a scheduled fire-time of this trigger.
</p>
<p>
Note that the value returned is NOT validated against the related
{@link ICalendar} (if any)
</p>
@param aTest
the date to compare
@param dayOnly
if set to true, the method will only determine if the trigger will
fire during the day represented by the given Calendar (hours,
minutes and seconds will be ignored).
@see #willFireOn(Calendar) | [
"<p",
">",
"Determines",
"whether",
"the",
"date",
"and",
"(",
"optionally",
")",
"time",
"of",
"the",
"given",
"Calendar",
"instance",
"falls",
"on",
"a",
"scheduled",
"fire",
"-",
"time",
"of",
"this",
"trigger",
".",
"<",
"/",
"p",
">",
"<p",
">",
"Note",
"that",
"the",
"value",
"returned",
"is",
"NOT",
"validated",
"against",
"the",
"related",
"{",
"@link",
"ICalendar",
"}",
"(",
"if",
"any",
")",
"<",
"/",
"p",
">"
] | train | https://github.com/phax/ph-schedule/blob/b000790b46a9f8d23ad44cc20591f753d07c0229/ph-mini-quartz/src/main/java/com/helger/quartz/impl/triggers/CronTrigger.java#L434-L473 |
pip-services3-java/pip-services3-commons-java | src/org/pipservices3/commons/convert/DoubleConverter.java | DoubleConverter.toDoubleWithDefault | public static double toDoubleWithDefault(Object value, double defaultValue) {
"""
Converts value into doubles or returns default value when conversion is not
possible.
@param value the value to convert.
@param defaultValue the default value.
@return double value or default when conversion is not supported.
@see DoubleConverter#toNullableDouble(Object)
"""
Double result = toNullableDouble(value);
return result != null ? (double) result : defaultValue;
} | java | public static double toDoubleWithDefault(Object value, double defaultValue) {
Double result = toNullableDouble(value);
return result != null ? (double) result : defaultValue;
} | [
"public",
"static",
"double",
"toDoubleWithDefault",
"(",
"Object",
"value",
",",
"double",
"defaultValue",
")",
"{",
"Double",
"result",
"=",
"toNullableDouble",
"(",
"value",
")",
";",
"return",
"result",
"!=",
"null",
"?",
"(",
"double",
")",
"result",
":",
"defaultValue",
";",
"}"
] | Converts value into doubles or returns default value when conversion is not
possible.
@param value the value to convert.
@param defaultValue the default value.
@return double value or default when conversion is not supported.
@see DoubleConverter#toNullableDouble(Object) | [
"Converts",
"value",
"into",
"doubles",
"or",
"returns",
"default",
"value",
"when",
"conversion",
"is",
"not",
"possible",
"."
] | train | https://github.com/pip-services3-java/pip-services3-commons-java/blob/a8a0c3e5ec58f0663c295aa855c6b3afad2af86a/src/org/pipservices3/commons/convert/DoubleConverter.java#L89-L92 |
kakawait/cas-security-spring-boot-starter | spring-security-cas-extension/src/main/java/com/kakawait/spring/security/cas/client/CasAuthorizationInterceptor.java | CasAuthorizationInterceptor.intercept | @Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
throws IOException {
"""
{@inheritDoc}
@throws IllegalStateException if proxy ticket retrieves from {@link ProxyTicketProvider#getProxyTicket(String)}
is null or blank
"""
String service = request.getURI().toASCIIString();
String proxyTicket = proxyTicketProvider.getProxyTicket(service);
if (!StringUtils.hasText(proxyTicket)) {
throw new IllegalStateException(
String.format("Proxy ticket provider returned a null proxy ticket for service %s.", service));
}
URI uri = UriComponentsBuilder
.fromUri(request.getURI())
.replaceQueryParam(serviceProperties.getArtifactParameter(), proxyTicket)
.build().toUri();
return execution.execute(new HttpRequestWrapper(request) {
@Override
public URI getURI() {
return uri;
}
}, body);
} | java | @Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
throws IOException {
String service = request.getURI().toASCIIString();
String proxyTicket = proxyTicketProvider.getProxyTicket(service);
if (!StringUtils.hasText(proxyTicket)) {
throw new IllegalStateException(
String.format("Proxy ticket provider returned a null proxy ticket for service %s.", service));
}
URI uri = UriComponentsBuilder
.fromUri(request.getURI())
.replaceQueryParam(serviceProperties.getArtifactParameter(), proxyTicket)
.build().toUri();
return execution.execute(new HttpRequestWrapper(request) {
@Override
public URI getURI() {
return uri;
}
}, body);
} | [
"@",
"Override",
"public",
"ClientHttpResponse",
"intercept",
"(",
"HttpRequest",
"request",
",",
"byte",
"[",
"]",
"body",
",",
"ClientHttpRequestExecution",
"execution",
")",
"throws",
"IOException",
"{",
"String",
"service",
"=",
"request",
".",
"getURI",
"(",
")",
".",
"toASCIIString",
"(",
")",
";",
"String",
"proxyTicket",
"=",
"proxyTicketProvider",
".",
"getProxyTicket",
"(",
"service",
")",
";",
"if",
"(",
"!",
"StringUtils",
".",
"hasText",
"(",
"proxyTicket",
")",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"String",
".",
"format",
"(",
"\"Proxy ticket provider returned a null proxy ticket for service %s.\"",
",",
"service",
")",
")",
";",
"}",
"URI",
"uri",
"=",
"UriComponentsBuilder",
".",
"fromUri",
"(",
"request",
".",
"getURI",
"(",
")",
")",
".",
"replaceQueryParam",
"(",
"serviceProperties",
".",
"getArtifactParameter",
"(",
")",
",",
"proxyTicket",
")",
".",
"build",
"(",
")",
".",
"toUri",
"(",
")",
";",
"return",
"execution",
".",
"execute",
"(",
"new",
"HttpRequestWrapper",
"(",
"request",
")",
"{",
"@",
"Override",
"public",
"URI",
"getURI",
"(",
")",
"{",
"return",
"uri",
";",
"}",
"}",
",",
"body",
")",
";",
"}"
] | {@inheritDoc}
@throws IllegalStateException if proxy ticket retrieves from {@link ProxyTicketProvider#getProxyTicket(String)}
is null or blank | [
"{",
"@inheritDoc",
"}"
] | train | https://github.com/kakawait/cas-security-spring-boot-starter/blob/f42e7829f6f3ff1f64803a09577bca3c6f60e347/spring-security-cas-extension/src/main/java/com/kakawait/spring/security/cas/client/CasAuthorizationInterceptor.java#L42-L61 |
UrielCh/ovh-java-sdk | ovh-java-sdk-dedicatedserver/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedserver.java | ApiOvhDedicatedserver.serviceName_statistics_partition_partition_GET | public OvhRtmPartition serviceName_statistics_partition_partition_GET(String serviceName, String partition) throws IOException {
"""
Get this object properties
REST: GET /dedicated/server/{serviceName}/statistics/partition/{partition}
@param serviceName [required] The internal name of your dedicated server
@param partition [required] Partition
"""
String qPath = "/dedicated/server/{serviceName}/statistics/partition/{partition}";
StringBuilder sb = path(qPath, serviceName, partition);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhRtmPartition.class);
} | java | public OvhRtmPartition serviceName_statistics_partition_partition_GET(String serviceName, String partition) throws IOException {
String qPath = "/dedicated/server/{serviceName}/statistics/partition/{partition}";
StringBuilder sb = path(qPath, serviceName, partition);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhRtmPartition.class);
} | [
"public",
"OvhRtmPartition",
"serviceName_statistics_partition_partition_GET",
"(",
"String",
"serviceName",
",",
"String",
"partition",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/dedicated/server/{serviceName}/statistics/partition/{partition}\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"serviceName",
",",
"partition",
")",
";",
"String",
"resp",
"=",
"exec",
"(",
"qPath",
",",
"\"GET\"",
",",
"sb",
".",
"toString",
"(",
")",
",",
"null",
")",
";",
"return",
"convertTo",
"(",
"resp",
",",
"OvhRtmPartition",
".",
"class",
")",
";",
"}"
] | Get this object properties
REST: GET /dedicated/server/{serviceName}/statistics/partition/{partition}
@param serviceName [required] The internal name of your dedicated server
@param partition [required] Partition | [
"Get",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dedicatedserver/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedserver.java#L1264-L1269 |
SimiaCryptus/utilities | java-util/src/main/java/com/simiacryptus/util/binary/BitOutputStream.java | BitOutputStream.writeBoundedLong | public Bits writeBoundedLong(final long value, final long max)
throws IOException {
"""
Write bounded long bits.
@param value the value
@param max the max
@return the bits
@throws IOException the io exception
"""
final int bits = 0 >= max ? 0 : (int) (Math
.floor(Math.log(max) / Math.log(2)) + 1);
if (0 < bits) {
Bits toWrite = new Bits(value, bits);
this.write(toWrite);
return toWrite;
}
else {
return Bits.NULL;
}
} | java | public Bits writeBoundedLong(final long value, final long max)
throws IOException {
final int bits = 0 >= max ? 0 : (int) (Math
.floor(Math.log(max) / Math.log(2)) + 1);
if (0 < bits) {
Bits toWrite = new Bits(value, bits);
this.write(toWrite);
return toWrite;
}
else {
return Bits.NULL;
}
} | [
"public",
"Bits",
"writeBoundedLong",
"(",
"final",
"long",
"value",
",",
"final",
"long",
"max",
")",
"throws",
"IOException",
"{",
"final",
"int",
"bits",
"=",
"0",
">=",
"max",
"?",
"0",
":",
"(",
"int",
")",
"(",
"Math",
".",
"floor",
"(",
"Math",
".",
"log",
"(",
"max",
")",
"/",
"Math",
".",
"log",
"(",
"2",
")",
")",
"+",
"1",
")",
";",
"if",
"(",
"0",
"<",
"bits",
")",
"{",
"Bits",
"toWrite",
"=",
"new",
"Bits",
"(",
"value",
",",
"bits",
")",
";",
"this",
".",
"write",
"(",
"toWrite",
")",
";",
"return",
"toWrite",
";",
"}",
"else",
"{",
"return",
"Bits",
".",
"NULL",
";",
"}",
"}"
] | Write bounded long bits.
@param value the value
@param max the max
@return the bits
@throws IOException the io exception | [
"Write",
"bounded",
"long",
"bits",
"."
] | train | https://github.com/SimiaCryptus/utilities/blob/b5a5e73449aae57de7dbfca2ed7a074432c5b17e/java-util/src/main/java/com/simiacryptus/util/binary/BitOutputStream.java#L180-L192 |
mgm-tp/jfunk | jfunk-data-generator/src/main/java/com/mgmtp/jfunk/data/generator/util/XmlElementFinder.java | XmlElementFinder.getChild | public static Element getChild(final String name, final Element root) {
"""
Searches for the Child with the given name ignoring namespaces
@return the Child with the name ignoring namespaces
"""
@SuppressWarnings("unchecked")
List<Element> allChildren = root.getChildren();
for (Element child : allChildren) {
if (child.getName().equals(name)) {
return child;
}
}
return null;
} | java | public static Element getChild(final String name, final Element root) {
@SuppressWarnings("unchecked")
List<Element> allChildren = root.getChildren();
for (Element child : allChildren) {
if (child.getName().equals(name)) {
return child;
}
}
return null;
} | [
"public",
"static",
"Element",
"getChild",
"(",
"final",
"String",
"name",
",",
"final",
"Element",
"root",
")",
"{",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"List",
"<",
"Element",
">",
"allChildren",
"=",
"root",
".",
"getChildren",
"(",
")",
";",
"for",
"(",
"Element",
"child",
":",
"allChildren",
")",
"{",
"if",
"(",
"child",
".",
"getName",
"(",
")",
".",
"equals",
"(",
"name",
")",
")",
"{",
"return",
"child",
";",
"}",
"}",
"return",
"null",
";",
"}"
] | Searches for the Child with the given name ignoring namespaces
@return the Child with the name ignoring namespaces | [
"Searches",
"for",
"the",
"Child",
"with",
"the",
"given",
"name",
"ignoring",
"namespaces"
] | train | https://github.com/mgm-tp/jfunk/blob/5b9fecac5778b988bb458085ded39ea9a4c7c2ae/jfunk-data-generator/src/main/java/com/mgmtp/jfunk/data/generator/util/XmlElementFinder.java#L151-L160 |
VoltDB/voltdb | src/frontend/org/voltcore/utils/CoreUtils.java | CoreUtils.getScheduledThreadPoolExecutor | public static ScheduledThreadPoolExecutor getScheduledThreadPoolExecutor(String name, int poolSize, int stackSize) {
"""
/*
Have shutdown actually means shutdown. Tasks that need to complete should use
futures.
"""
ScheduledThreadPoolExecutor ses = new ScheduledThreadPoolExecutor(poolSize, getThreadFactory(null, name, stackSize, poolSize > 1, null));
ses.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
ses.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
return ses;
} | java | public static ScheduledThreadPoolExecutor getScheduledThreadPoolExecutor(String name, int poolSize, int stackSize) {
ScheduledThreadPoolExecutor ses = new ScheduledThreadPoolExecutor(poolSize, getThreadFactory(null, name, stackSize, poolSize > 1, null));
ses.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
ses.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
return ses;
} | [
"public",
"static",
"ScheduledThreadPoolExecutor",
"getScheduledThreadPoolExecutor",
"(",
"String",
"name",
",",
"int",
"poolSize",
",",
"int",
"stackSize",
")",
"{",
"ScheduledThreadPoolExecutor",
"ses",
"=",
"new",
"ScheduledThreadPoolExecutor",
"(",
"poolSize",
",",
"getThreadFactory",
"(",
"null",
",",
"name",
",",
"stackSize",
",",
"poolSize",
">",
"1",
",",
"null",
")",
")",
";",
"ses",
".",
"setContinueExistingPeriodicTasksAfterShutdownPolicy",
"(",
"false",
")",
";",
"ses",
".",
"setExecuteExistingDelayedTasksAfterShutdownPolicy",
"(",
"false",
")",
";",
"return",
"ses",
";",
"}"
] | /*
Have shutdown actually means shutdown. Tasks that need to complete should use
futures. | [
"/",
"*",
"Have",
"shutdown",
"actually",
"means",
"shutdown",
".",
"Tasks",
"that",
"need",
"to",
"complete",
"should",
"use",
"futures",
"."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltcore/utils/CoreUtils.java#L496-L501 |
alkacon/opencms-core | src-setup/org/opencms/setup/ui/CmsSetupStep03Database.java | CmsSetupStep03Database.updateDb | private void updateDb(String dbName, String webapp) {
"""
Switches DB type.
@param dbName the database type
@param webapp the webapp name
"""
m_mainLayout.removeAllComponents();
m_setupBean.setDatabase(dbName);
CmsDbSettingsPanel panel = new CmsDbSettingsPanel(m_setupBean);
m_panel[0] = panel;
panel.initFromSetupBean(webapp);
m_mainLayout.addComponent(panel);
} | java | private void updateDb(String dbName, String webapp) {
m_mainLayout.removeAllComponents();
m_setupBean.setDatabase(dbName);
CmsDbSettingsPanel panel = new CmsDbSettingsPanel(m_setupBean);
m_panel[0] = panel;
panel.initFromSetupBean(webapp);
m_mainLayout.addComponent(panel);
} | [
"private",
"void",
"updateDb",
"(",
"String",
"dbName",
",",
"String",
"webapp",
")",
"{",
"m_mainLayout",
".",
"removeAllComponents",
"(",
")",
";",
"m_setupBean",
".",
"setDatabase",
"(",
"dbName",
")",
";",
"CmsDbSettingsPanel",
"panel",
"=",
"new",
"CmsDbSettingsPanel",
"(",
"m_setupBean",
")",
";",
"m_panel",
"[",
"0",
"]",
"=",
"panel",
";",
"panel",
".",
"initFromSetupBean",
"(",
"webapp",
")",
";",
"m_mainLayout",
".",
"addComponent",
"(",
"panel",
")",
";",
"}"
] | Switches DB type.
@param dbName the database type
@param webapp the webapp name | [
"Switches",
"DB",
"type",
"."
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-setup/org/opencms/setup/ui/CmsSetupStep03Database.java#L334-L342 |
allengeorge/libraft | libraft-agent/src/main/java/io/libraft/agent/rpc/Handshakers.java | Handshakers.getServerIdFromHandshake | static String getServerIdFromHandshake(ChannelBuffer handshakeBuffer, ObjectMapper mapper) throws IOException {
"""
Extract the unique id of the Raft server that sent a handshake
message from its wire representation.
@param handshakeBuffer instance of {@code ChannelBuffer} that contains
the encoded handshake message
@param mapper instance of {@code ObjectMapper} used to map handshake fields
in the encoded message to their corresponding Java representation
@return unique id of the Raft server that sent the handshake message
@throws IOException if a valid handshake cannot be read from the {@code handshakeBuffer}
"""
Handshake handshake = getHandshakeFromBuffer(handshakeBuffer, mapper);
return handshake.getServerId();
} | java | static String getServerIdFromHandshake(ChannelBuffer handshakeBuffer, ObjectMapper mapper) throws IOException {
Handshake handshake = getHandshakeFromBuffer(handshakeBuffer, mapper);
return handshake.getServerId();
} | [
"static",
"String",
"getServerIdFromHandshake",
"(",
"ChannelBuffer",
"handshakeBuffer",
",",
"ObjectMapper",
"mapper",
")",
"throws",
"IOException",
"{",
"Handshake",
"handshake",
"=",
"getHandshakeFromBuffer",
"(",
"handshakeBuffer",
",",
"mapper",
")",
";",
"return",
"handshake",
".",
"getServerId",
"(",
")",
";",
"}"
] | Extract the unique id of the Raft server that sent a handshake
message from its wire representation.
@param handshakeBuffer instance of {@code ChannelBuffer} that contains
the encoded handshake message
@param mapper instance of {@code ObjectMapper} used to map handshake fields
in the encoded message to their corresponding Java representation
@return unique id of the Raft server that sent the handshake message
@throws IOException if a valid handshake cannot be read from the {@code handshakeBuffer} | [
"Extract",
"the",
"unique",
"id",
"of",
"the",
"Raft",
"server",
"that",
"sent",
"a",
"handshake",
"message",
"from",
"its",
"wire",
"representation",
"."
] | train | https://github.com/allengeorge/libraft/blob/00d68bb5e68d4020af59df3c8a9a14380108ac89/libraft-agent/src/main/java/io/libraft/agent/rpc/Handshakers.java#L121-L124 |
cdapio/tigon | tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java | Bytes.putBigDecimal | public static int putBigDecimal(byte[] bytes, int offset, BigDecimal val) {
"""
Put a BigDecimal value out to the specified byte array position.
@param bytes the byte array
@param offset position in the array
@param val BigDecimal to write out
@return incremented offset
"""
if (bytes == null) {
return offset;
}
byte[] valueBytes = val.unscaledValue().toByteArray();
byte[] result = new byte[valueBytes.length + SIZEOF_INT];
offset = putInt(result, offset, val.scale());
return putBytes(result, offset, valueBytes, 0, valueBytes.length);
} | java | public static int putBigDecimal(byte[] bytes, int offset, BigDecimal val) {
if (bytes == null) {
return offset;
}
byte[] valueBytes = val.unscaledValue().toByteArray();
byte[] result = new byte[valueBytes.length + SIZEOF_INT];
offset = putInt(result, offset, val.scale());
return putBytes(result, offset, valueBytes, 0, valueBytes.length);
} | [
"public",
"static",
"int",
"putBigDecimal",
"(",
"byte",
"[",
"]",
"bytes",
",",
"int",
"offset",
",",
"BigDecimal",
"val",
")",
"{",
"if",
"(",
"bytes",
"==",
"null",
")",
"{",
"return",
"offset",
";",
"}",
"byte",
"[",
"]",
"valueBytes",
"=",
"val",
".",
"unscaledValue",
"(",
")",
".",
"toByteArray",
"(",
")",
";",
"byte",
"[",
"]",
"result",
"=",
"new",
"byte",
"[",
"valueBytes",
".",
"length",
"+",
"SIZEOF_INT",
"]",
";",
"offset",
"=",
"putInt",
"(",
"result",
",",
"offset",
",",
"val",
".",
"scale",
"(",
")",
")",
";",
"return",
"putBytes",
"(",
"result",
",",
"offset",
",",
"valueBytes",
",",
"0",
",",
"valueBytes",
".",
"length",
")",
";",
"}"
] | Put a BigDecimal value out to the specified byte array position.
@param bytes the byte array
@param offset position in the array
@param val BigDecimal to write out
@return incremented offset | [
"Put",
"a",
"BigDecimal",
"value",
"out",
"to",
"the",
"specified",
"byte",
"array",
"position",
"."
] | train | https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java#L740-L749 |
OpenLiberty/open-liberty | dev/com.ibm.ws.crypto.passwordutil/src/com/ibm/websphere/crypto/PasswordUtil.java | PasswordUtil.isHashed | public static boolean isHashed(String encoded_string) {
"""
Determine if the provided string is hashed by examining the algorithm tag.
Note that this method is only avaiable for the Liberty profile.
@param encoded_string the string with the encoded algorithm tag.
@return true if the encoded algorithm is hash. false otherwise.
"""
String algorithm = getCryptoAlgorithm(encoded_string);
return isValidAlgorithm(algorithm, PasswordCipherUtil.getSupportedHashAlgorithms());
} | java | public static boolean isHashed(String encoded_string) {
String algorithm = getCryptoAlgorithm(encoded_string);
return isValidAlgorithm(algorithm, PasswordCipherUtil.getSupportedHashAlgorithms());
} | [
"public",
"static",
"boolean",
"isHashed",
"(",
"String",
"encoded_string",
")",
"{",
"String",
"algorithm",
"=",
"getCryptoAlgorithm",
"(",
"encoded_string",
")",
";",
"return",
"isValidAlgorithm",
"(",
"algorithm",
",",
"PasswordCipherUtil",
".",
"getSupportedHashAlgorithms",
"(",
")",
")",
";",
"}"
] | Determine if the provided string is hashed by examining the algorithm tag.
Note that this method is only avaiable for the Liberty profile.
@param encoded_string the string with the encoded algorithm tag.
@return true if the encoded algorithm is hash. false otherwise. | [
"Determine",
"if",
"the",
"provided",
"string",
"is",
"hashed",
"by",
"examining",
"the",
"algorithm",
"tag",
".",
"Note",
"that",
"this",
"method",
"is",
"only",
"avaiable",
"for",
"the",
"Liberty",
"profile",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.crypto.passwordutil/src/com/ibm/websphere/crypto/PasswordUtil.java#L371-L374 |
netty/netty | common/src/main/java/io/netty/util/internal/ReflectionUtil.java | ReflectionUtil.trySetAccessible | public static Throwable trySetAccessible(AccessibleObject object, boolean checkAccessible) {
"""
Try to call {@link AccessibleObject#setAccessible(boolean)} but will catch any {@link SecurityException} and
{@link java.lang.reflect.InaccessibleObjectException} and return it.
The caller must check if it returns {@code null} and if not handle the returned exception.
"""
if (checkAccessible && !PlatformDependent0.isExplicitTryReflectionSetAccessible()) {
return new UnsupportedOperationException("Reflective setAccessible(true) disabled");
}
try {
object.setAccessible(true);
return null;
} catch (SecurityException e) {
return e;
} catch (RuntimeException e) {
return handleInaccessibleObjectException(e);
}
} | java | public static Throwable trySetAccessible(AccessibleObject object, boolean checkAccessible) {
if (checkAccessible && !PlatformDependent0.isExplicitTryReflectionSetAccessible()) {
return new UnsupportedOperationException("Reflective setAccessible(true) disabled");
}
try {
object.setAccessible(true);
return null;
} catch (SecurityException e) {
return e;
} catch (RuntimeException e) {
return handleInaccessibleObjectException(e);
}
} | [
"public",
"static",
"Throwable",
"trySetAccessible",
"(",
"AccessibleObject",
"object",
",",
"boolean",
"checkAccessible",
")",
"{",
"if",
"(",
"checkAccessible",
"&&",
"!",
"PlatformDependent0",
".",
"isExplicitTryReflectionSetAccessible",
"(",
")",
")",
"{",
"return",
"new",
"UnsupportedOperationException",
"(",
"\"Reflective setAccessible(true) disabled\"",
")",
";",
"}",
"try",
"{",
"object",
".",
"setAccessible",
"(",
"true",
")",
";",
"return",
"null",
";",
"}",
"catch",
"(",
"SecurityException",
"e",
")",
"{",
"return",
"e",
";",
"}",
"catch",
"(",
"RuntimeException",
"e",
")",
"{",
"return",
"handleInaccessibleObjectException",
"(",
"e",
")",
";",
"}",
"}"
] | Try to call {@link AccessibleObject#setAccessible(boolean)} but will catch any {@link SecurityException} and
{@link java.lang.reflect.InaccessibleObjectException} and return it.
The caller must check if it returns {@code null} and if not handle the returned exception. | [
"Try",
"to",
"call",
"{"
] | train | https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/common/src/main/java/io/netty/util/internal/ReflectionUtil.java#L29-L41 |
redkale/redkale | src/org/redkale/net/http/MultiPart.java | MultiPart.save | public boolean save(long max, OutputStream out) throws IOException {
"""
将文件流写进out, 如果超出max指定的值则中断并返回false
@param max 最大长度限制
@param out 输出流
@return 是否成功
@throws IOException 异常
"""
byte[] bytes = new byte[4096];
int pos;
InputStream in0 = this.getInputStream();
while ((pos = in0.read(bytes)) != -1) {
if (max < 0) return false;
out.write(bytes, 0, pos);
max -= pos;
}
return true;
} | java | public boolean save(long max, OutputStream out) throws IOException {
byte[] bytes = new byte[4096];
int pos;
InputStream in0 = this.getInputStream();
while ((pos = in0.read(bytes)) != -1) {
if (max < 0) return false;
out.write(bytes, 0, pos);
max -= pos;
}
return true;
} | [
"public",
"boolean",
"save",
"(",
"long",
"max",
",",
"OutputStream",
"out",
")",
"throws",
"IOException",
"{",
"byte",
"[",
"]",
"bytes",
"=",
"new",
"byte",
"[",
"4096",
"]",
";",
"int",
"pos",
";",
"InputStream",
"in0",
"=",
"this",
".",
"getInputStream",
"(",
")",
";",
"while",
"(",
"(",
"pos",
"=",
"in0",
".",
"read",
"(",
"bytes",
")",
")",
"!=",
"-",
"1",
")",
"{",
"if",
"(",
"max",
"<",
"0",
")",
"return",
"false",
";",
"out",
".",
"write",
"(",
"bytes",
",",
"0",
",",
"pos",
")",
";",
"max",
"-=",
"pos",
";",
"}",
"return",
"true",
";",
"}"
] | 将文件流写进out, 如果超出max指定的值则中断并返回false
@param max 最大长度限制
@param out 输出流
@return 是否成功
@throws IOException 异常 | [
"将文件流写进out,",
"如果超出max指定的值则中断并返回false"
] | train | https://github.com/redkale/redkale/blob/ea5169b5c5ea7412fd762331c0c497165832e901/src/org/redkale/net/http/MultiPart.java#L80-L90 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/TimeZoneGenericNames.java | TimeZoneGenericNames.getPartialLocationName | private String getPartialLocationName(String tzID, String mzID, boolean isLong, String mzDisplayName) {
"""
Private method for formatting partial location names. This format
is used when a generic name of a meta zone is available, but the given
time zone is not a reference zone (golden zone) of the meta zone.
@param tzID the canonical time zone ID
@param mzID the meta zone ID
@param isLong true when long generic name
@param mzDisplayName the meta zone generic display name
@return the partial location format string
"""
String letter = isLong ? "L" : "S";
String key = tzID + "&" + mzID + "#" + letter;
String name = _genericPartialLocationNamesMap.get(key);
if (name != null) {
return name;
}
String location = null;
String countryCode = ZoneMeta.getCanonicalCountry(tzID);
if (countryCode != null) {
// Is this the golden zone for the region?
String regionalGolden = _tznames.getReferenceZoneID(mzID, countryCode);
if (tzID.equals(regionalGolden)) {
// Use country name
location = getLocaleDisplayNames().regionDisplayName(countryCode);
} else {
// Otherwise, use exemplar city name
location = _tznames.getExemplarLocationName(tzID);
}
} else {
location = _tznames.getExemplarLocationName(tzID);
if (location == null) {
// This could happen when the time zone is not associated with a country,
// and its ID is not hierarchical, for example, CST6CDT.
// We use the canonical ID itself as the location for this case.
location = tzID;
}
}
name = formatPattern(Pattern.FALLBACK_FORMAT, location, mzDisplayName);
synchronized (this) { // we have to sync the name map and the trie
String tmp = _genericPartialLocationNamesMap.putIfAbsent(key.intern(), name.intern());
if (tmp == null) {
NameInfo info = new NameInfo(tzID.intern(),
isLong ? GenericNameType.LONG : GenericNameType.SHORT);
_gnamesTrie.put(name, info);
} else {
name = tmp;
}
}
return name;
} | java | private String getPartialLocationName(String tzID, String mzID, boolean isLong, String mzDisplayName) {
String letter = isLong ? "L" : "S";
String key = tzID + "&" + mzID + "#" + letter;
String name = _genericPartialLocationNamesMap.get(key);
if (name != null) {
return name;
}
String location = null;
String countryCode = ZoneMeta.getCanonicalCountry(tzID);
if (countryCode != null) {
// Is this the golden zone for the region?
String regionalGolden = _tznames.getReferenceZoneID(mzID, countryCode);
if (tzID.equals(regionalGolden)) {
// Use country name
location = getLocaleDisplayNames().regionDisplayName(countryCode);
} else {
// Otherwise, use exemplar city name
location = _tznames.getExemplarLocationName(tzID);
}
} else {
location = _tznames.getExemplarLocationName(tzID);
if (location == null) {
// This could happen when the time zone is not associated with a country,
// and its ID is not hierarchical, for example, CST6CDT.
// We use the canonical ID itself as the location for this case.
location = tzID;
}
}
name = formatPattern(Pattern.FALLBACK_FORMAT, location, mzDisplayName);
synchronized (this) { // we have to sync the name map and the trie
String tmp = _genericPartialLocationNamesMap.putIfAbsent(key.intern(), name.intern());
if (tmp == null) {
NameInfo info = new NameInfo(tzID.intern(),
isLong ? GenericNameType.LONG : GenericNameType.SHORT);
_gnamesTrie.put(name, info);
} else {
name = tmp;
}
}
return name;
} | [
"private",
"String",
"getPartialLocationName",
"(",
"String",
"tzID",
",",
"String",
"mzID",
",",
"boolean",
"isLong",
",",
"String",
"mzDisplayName",
")",
"{",
"String",
"letter",
"=",
"isLong",
"?",
"\"L\"",
":",
"\"S\"",
";",
"String",
"key",
"=",
"tzID",
"+",
"\"&\"",
"+",
"mzID",
"+",
"\"#\"",
"+",
"letter",
";",
"String",
"name",
"=",
"_genericPartialLocationNamesMap",
".",
"get",
"(",
"key",
")",
";",
"if",
"(",
"name",
"!=",
"null",
")",
"{",
"return",
"name",
";",
"}",
"String",
"location",
"=",
"null",
";",
"String",
"countryCode",
"=",
"ZoneMeta",
".",
"getCanonicalCountry",
"(",
"tzID",
")",
";",
"if",
"(",
"countryCode",
"!=",
"null",
")",
"{",
"// Is this the golden zone for the region?",
"String",
"regionalGolden",
"=",
"_tznames",
".",
"getReferenceZoneID",
"(",
"mzID",
",",
"countryCode",
")",
";",
"if",
"(",
"tzID",
".",
"equals",
"(",
"regionalGolden",
")",
")",
"{",
"// Use country name",
"location",
"=",
"getLocaleDisplayNames",
"(",
")",
".",
"regionDisplayName",
"(",
"countryCode",
")",
";",
"}",
"else",
"{",
"// Otherwise, use exemplar city name",
"location",
"=",
"_tznames",
".",
"getExemplarLocationName",
"(",
"tzID",
")",
";",
"}",
"}",
"else",
"{",
"location",
"=",
"_tznames",
".",
"getExemplarLocationName",
"(",
"tzID",
")",
";",
"if",
"(",
"location",
"==",
"null",
")",
"{",
"// This could happen when the time zone is not associated with a country,",
"// and its ID is not hierarchical, for example, CST6CDT.",
"// We use the canonical ID itself as the location for this case.",
"location",
"=",
"tzID",
";",
"}",
"}",
"name",
"=",
"formatPattern",
"(",
"Pattern",
".",
"FALLBACK_FORMAT",
",",
"location",
",",
"mzDisplayName",
")",
";",
"synchronized",
"(",
"this",
")",
"{",
"// we have to sync the name map and the trie",
"String",
"tmp",
"=",
"_genericPartialLocationNamesMap",
".",
"putIfAbsent",
"(",
"key",
".",
"intern",
"(",
")",
",",
"name",
".",
"intern",
"(",
")",
")",
";",
"if",
"(",
"tmp",
"==",
"null",
")",
"{",
"NameInfo",
"info",
"=",
"new",
"NameInfo",
"(",
"tzID",
".",
"intern",
"(",
")",
",",
"isLong",
"?",
"GenericNameType",
".",
"LONG",
":",
"GenericNameType",
".",
"SHORT",
")",
";",
"_gnamesTrie",
".",
"put",
"(",
"name",
",",
"info",
")",
";",
"}",
"else",
"{",
"name",
"=",
"tmp",
";",
"}",
"}",
"return",
"name",
";",
"}"
] | Private method for formatting partial location names. This format
is used when a generic name of a meta zone is available, but the given
time zone is not a reference zone (golden zone) of the meta zone.
@param tzID the canonical time zone ID
@param mzID the meta zone ID
@param isLong true when long generic name
@param mzDisplayName the meta zone generic display name
@return the partial location format string | [
"Private",
"method",
"for",
"formatting",
"partial",
"location",
"names",
".",
"This",
"format",
"is",
"used",
"when",
"a",
"generic",
"name",
"of",
"a",
"meta",
"zone",
"is",
"available",
"but",
"the",
"given",
"time",
"zone",
"is",
"not",
"a",
"reference",
"zone",
"(",
"golden",
"zone",
")",
"of",
"the",
"meta",
"zone",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/TimeZoneGenericNames.java#L543-L583 |
kiegroup/droolsjbpm-integration | kie-server-parent/kie-server-remote/kie-server-client/src/main/java/org/kie/server/client/KieServicesFactory.java | KieServicesFactory.newRestConfiguration | public static KieServicesConfiguration newRestConfiguration( String serverUrl, String login, String password, long timeout ) {
"""
Creates a new configuration object for REST based service
@param serverUrl the URL to the server (e.g.: "http://localhost:8080")
@param login user login
@param password user password
@param timeout the maximum timeout in milliseconds
@return configuration instance
"""
return new KieServicesConfigurationImpl( serverUrl, login, password, timeout );
} | java | public static KieServicesConfiguration newRestConfiguration( String serverUrl, String login, String password, long timeout ) {
return new KieServicesConfigurationImpl( serverUrl, login, password, timeout );
} | [
"public",
"static",
"KieServicesConfiguration",
"newRestConfiguration",
"(",
"String",
"serverUrl",
",",
"String",
"login",
",",
"String",
"password",
",",
"long",
"timeout",
")",
"{",
"return",
"new",
"KieServicesConfigurationImpl",
"(",
"serverUrl",
",",
"login",
",",
"password",
",",
"timeout",
")",
";",
"}"
] | Creates a new configuration object for REST based service
@param serverUrl the URL to the server (e.g.: "http://localhost:8080")
@param login user login
@param password user password
@param timeout the maximum timeout in milliseconds
@return configuration instance | [
"Creates",
"a",
"new",
"configuration",
"object",
"for",
"REST",
"based",
"service"
] | train | https://github.com/kiegroup/droolsjbpm-integration/blob/6c26200ab03855dbb92b56ca0c6363cdec0eaf2c/kie-server-parent/kie-server-remote/kie-server-client/src/main/java/org/kie/server/client/KieServicesFactory.java#L47-L49 |
Azure/azure-sdk-for-java | appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServiceEnvironmentsInner.java | AppServiceEnvironmentsInner.listWebWorkerMetricsAsync | public Observable<Page<ResourceMetricInner>> listWebWorkerMetricsAsync(final String resourceGroupName, final String name, final String workerPoolName, final Boolean details, final String filter) {
"""
Get metrics for a worker pool of a AppServiceEnvironment (App Service Environment).
Get metrics for a worker pool of a AppServiceEnvironment (App Service Environment).
@param resourceGroupName Name of the resource group to which the resource belongs.
@param name Name of the App Service Environment.
@param workerPoolName Name of worker pool
@param details Specify <code>true</code> to include instance details. The default is <code>false</code>.
@param filter Return only usages/metrics specified in the filter. Filter conforms to odata syntax. Example: $filter=(name.value eq 'Metric1' or name.value eq 'Metric2') and startTime eq '2014-01-01T00:00:00Z' and endTime eq '2014-12-31T23:59:59Z' and timeGrain eq duration'[Hour|Minute|Day]'.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<ResourceMetricInner> object
"""
return listWebWorkerMetricsWithServiceResponseAsync(resourceGroupName, name, workerPoolName, details, filter)
.map(new Func1<ServiceResponse<Page<ResourceMetricInner>>, Page<ResourceMetricInner>>() {
@Override
public Page<ResourceMetricInner> call(ServiceResponse<Page<ResourceMetricInner>> response) {
return response.body();
}
});
} | java | public Observable<Page<ResourceMetricInner>> listWebWorkerMetricsAsync(final String resourceGroupName, final String name, final String workerPoolName, final Boolean details, final String filter) {
return listWebWorkerMetricsWithServiceResponseAsync(resourceGroupName, name, workerPoolName, details, filter)
.map(new Func1<ServiceResponse<Page<ResourceMetricInner>>, Page<ResourceMetricInner>>() {
@Override
public Page<ResourceMetricInner> call(ServiceResponse<Page<ResourceMetricInner>> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Page",
"<",
"ResourceMetricInner",
">",
">",
"listWebWorkerMetricsAsync",
"(",
"final",
"String",
"resourceGroupName",
",",
"final",
"String",
"name",
",",
"final",
"String",
"workerPoolName",
",",
"final",
"Boolean",
"details",
",",
"final",
"String",
"filter",
")",
"{",
"return",
"listWebWorkerMetricsWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"name",
",",
"workerPoolName",
",",
"details",
",",
"filter",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"ResourceMetricInner",
">",
">",
",",
"Page",
"<",
"ResourceMetricInner",
">",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"Page",
"<",
"ResourceMetricInner",
">",
"call",
"(",
"ServiceResponse",
"<",
"Page",
"<",
"ResourceMetricInner",
">",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Get metrics for a worker pool of a AppServiceEnvironment (App Service Environment).
Get metrics for a worker pool of a AppServiceEnvironment (App Service Environment).
@param resourceGroupName Name of the resource group to which the resource belongs.
@param name Name of the App Service Environment.
@param workerPoolName Name of worker pool
@param details Specify <code>true</code> to include instance details. The default is <code>false</code>.
@param filter Return only usages/metrics specified in the filter. Filter conforms to odata syntax. Example: $filter=(name.value eq 'Metric1' or name.value eq 'Metric2') and startTime eq '2014-01-01T00:00:00Z' and endTime eq '2014-12-31T23:59:59Z' and timeGrain eq duration'[Hour|Minute|Day]'.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<ResourceMetricInner> object | [
"Get",
"metrics",
"for",
"a",
"worker",
"pool",
"of",
"a",
"AppServiceEnvironment",
"(",
"App",
"Service",
"Environment",
")",
".",
"Get",
"metrics",
"for",
"a",
"worker",
"pool",
"of",
"a",
"AppServiceEnvironment",
"(",
"App",
"Service",
"Environment",
")",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServiceEnvironmentsInner.java#L6248-L6256 |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/kv/KeyValueHandler.java | KeyValueHandler.handleSnappyCompression | private void handleSnappyCompression(final ChannelHandlerContext ctx, final BinaryMemcacheRequest r) {
"""
Helper method which performs snappy compression on the request path.
Note that even if we compress and switch out the content, we are not releasing the
original buffer! This is happening on the decode side and we still need to keep in mind
that a NMVB could be returned and the original msg needs to be re-sent.
"""
if (!(r instanceof FullBinaryMemcacheRequest)) {
// we only need to handle requests which send content
return;
}
FullBinaryMemcacheRequest request = (FullBinaryMemcacheRequest) r;
int uncompressedLength = request.content().readableBytes();
// don't bother compressing if below the min compression size
if (uncompressedLength < minCompressionSize || uncompressedLength == 0) {
return;
}
ByteBuf compressedContent;
try {
compressedContent = tryCompress(request.content());
} catch (Exception ex) {
throw new RuntimeException("Could not snappy-compress value.", ex);
}
if (compressedContent != null) {
// compressed is smaller, so adapt and apply new content
request.setDataType((byte)(request.getDataType() | DATATYPE_SNAPPY));
request.setContent(compressedContent);
request.setTotalBodyLength(
request.getExtrasLength()
+ request.getKeyLength()
+ compressedContent.readableBytes()
);
}
} | java | private void handleSnappyCompression(final ChannelHandlerContext ctx, final BinaryMemcacheRequest r) {
if (!(r instanceof FullBinaryMemcacheRequest)) {
// we only need to handle requests which send content
return;
}
FullBinaryMemcacheRequest request = (FullBinaryMemcacheRequest) r;
int uncompressedLength = request.content().readableBytes();
// don't bother compressing if below the min compression size
if (uncompressedLength < minCompressionSize || uncompressedLength == 0) {
return;
}
ByteBuf compressedContent;
try {
compressedContent = tryCompress(request.content());
} catch (Exception ex) {
throw new RuntimeException("Could not snappy-compress value.", ex);
}
if (compressedContent != null) {
// compressed is smaller, so adapt and apply new content
request.setDataType((byte)(request.getDataType() | DATATYPE_SNAPPY));
request.setContent(compressedContent);
request.setTotalBodyLength(
request.getExtrasLength()
+ request.getKeyLength()
+ compressedContent.readableBytes()
);
}
} | [
"private",
"void",
"handleSnappyCompression",
"(",
"final",
"ChannelHandlerContext",
"ctx",
",",
"final",
"BinaryMemcacheRequest",
"r",
")",
"{",
"if",
"(",
"!",
"(",
"r",
"instanceof",
"FullBinaryMemcacheRequest",
")",
")",
"{",
"// we only need to handle requests which send content",
"return",
";",
"}",
"FullBinaryMemcacheRequest",
"request",
"=",
"(",
"FullBinaryMemcacheRequest",
")",
"r",
";",
"int",
"uncompressedLength",
"=",
"request",
".",
"content",
"(",
")",
".",
"readableBytes",
"(",
")",
";",
"// don't bother compressing if below the min compression size",
"if",
"(",
"uncompressedLength",
"<",
"minCompressionSize",
"||",
"uncompressedLength",
"==",
"0",
")",
"{",
"return",
";",
"}",
"ByteBuf",
"compressedContent",
";",
"try",
"{",
"compressedContent",
"=",
"tryCompress",
"(",
"request",
".",
"content",
"(",
")",
")",
";",
"}",
"catch",
"(",
"Exception",
"ex",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Could not snappy-compress value.\"",
",",
"ex",
")",
";",
"}",
"if",
"(",
"compressedContent",
"!=",
"null",
")",
"{",
"// compressed is smaller, so adapt and apply new content",
"request",
".",
"setDataType",
"(",
"(",
"byte",
")",
"(",
"request",
".",
"getDataType",
"(",
")",
"|",
"DATATYPE_SNAPPY",
")",
")",
";",
"request",
".",
"setContent",
"(",
"compressedContent",
")",
";",
"request",
".",
"setTotalBodyLength",
"(",
"request",
".",
"getExtrasLength",
"(",
")",
"+",
"request",
".",
"getKeyLength",
"(",
")",
"+",
"compressedContent",
".",
"readableBytes",
"(",
")",
")",
";",
"}",
"}"
] | Helper method which performs snappy compression on the request path.
Note that even if we compress and switch out the content, we are not releasing the
original buffer! This is happening on the decode side and we still need to keep in mind
that a NMVB could be returned and the original msg needs to be re-sent. | [
"Helper",
"method",
"which",
"performs",
"snappy",
"compression",
"on",
"the",
"request",
"path",
"."
] | train | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/kv/KeyValueHandler.java#L323-L354 |
MGunlogson/CuckooFilter4J | src/main/java/com/github/mgunlogson/cuckoofilter4j/RamUsageEstimator.java | RamUsageEstimator.adjustForField | static long adjustForField(long sizeSoFar, final Field f) {
"""
This method returns the maximum representation size of an object. <code>sizeSoFar</code>
is the object's size measured so far. <code>f</code> is the field being probed.
<p>The returned offset will be the maximum of whatever was measured so far and
<code>f</code> field's offset and representation size (unaligned).
"""
final Class<?> type = f.getType();
final int fsize = type.isPrimitive() ? primitiveSizes.get(type) : NUM_BYTES_OBJECT_REF;
// TODO: No alignments based on field type/ subclass fields alignments?
return sizeSoFar + fsize;
} | java | static long adjustForField(long sizeSoFar, final Field f) {
final Class<?> type = f.getType();
final int fsize = type.isPrimitive() ? primitiveSizes.get(type) : NUM_BYTES_OBJECT_REF;
// TODO: No alignments based on field type/ subclass fields alignments?
return sizeSoFar + fsize;
} | [
"static",
"long",
"adjustForField",
"(",
"long",
"sizeSoFar",
",",
"final",
"Field",
"f",
")",
"{",
"final",
"Class",
"<",
"?",
">",
"type",
"=",
"f",
".",
"getType",
"(",
")",
";",
"final",
"int",
"fsize",
"=",
"type",
".",
"isPrimitive",
"(",
")",
"?",
"primitiveSizes",
".",
"get",
"(",
"type",
")",
":",
"NUM_BYTES_OBJECT_REF",
";",
"// TODO: No alignments based on field type/ subclass fields alignments?\r",
"return",
"sizeSoFar",
"+",
"fsize",
";",
"}"
] | This method returns the maximum representation size of an object. <code>sizeSoFar</code>
is the object's size measured so far. <code>f</code> is the field being probed.
<p>The returned offset will be the maximum of whatever was measured so far and
<code>f</code> field's offset and representation size (unaligned). | [
"This",
"method",
"returns",
"the",
"maximum",
"representation",
"size",
"of",
"an",
"object",
".",
"<code",
">",
"sizeSoFar<",
"/",
"code",
">",
"is",
"the",
"object",
"s",
"size",
"measured",
"so",
"far",
".",
"<code",
">",
"f<",
"/",
"code",
">",
"is",
"the",
"field",
"being",
"probed",
"."
] | train | https://github.com/MGunlogson/CuckooFilter4J/blob/e8472aa150b201f05046d1c81cac5a5ca4348db8/src/main/java/com/github/mgunlogson/cuckoofilter4j/RamUsageEstimator.java#L376-L381 |
threerings/playn | java/src/playn/java/JavaGLContext.java | JavaGLContext.convertImage | static BufferedImage convertImage (BufferedImage image) {
"""
Converts the given image into a format for quick upload to the GPU.
"""
switch (image.getType()) {
case BufferedImage.TYPE_INT_ARGB_PRE:
return image; // Already good to go
case BufferedImage.TYPE_4BYTE_ABGR:
image.coerceData(true); // Just premultiply the alpha and it's fine
return image;
}
// Didn't know an easy thing to do, so create a whole new image in our preferred format
BufferedImage convertedImage = new BufferedImage(image.getWidth(), image.getHeight(),
BufferedImage.TYPE_INT_ARGB_PRE);
Graphics g = convertedImage.getGraphics();
g.setColor(new Color(0f, 0f, 0f, 0f));
g.fillRect(0, 0, image.getWidth(), image.getHeight());
g.drawImage(image, 0, 0, null);
return convertedImage;
} | java | static BufferedImage convertImage (BufferedImage image) {
switch (image.getType()) {
case BufferedImage.TYPE_INT_ARGB_PRE:
return image; // Already good to go
case BufferedImage.TYPE_4BYTE_ABGR:
image.coerceData(true); // Just premultiply the alpha and it's fine
return image;
}
// Didn't know an easy thing to do, so create a whole new image in our preferred format
BufferedImage convertedImage = new BufferedImage(image.getWidth(), image.getHeight(),
BufferedImage.TYPE_INT_ARGB_PRE);
Graphics g = convertedImage.getGraphics();
g.setColor(new Color(0f, 0f, 0f, 0f));
g.fillRect(0, 0, image.getWidth(), image.getHeight());
g.drawImage(image, 0, 0, null);
return convertedImage;
} | [
"static",
"BufferedImage",
"convertImage",
"(",
"BufferedImage",
"image",
")",
"{",
"switch",
"(",
"image",
".",
"getType",
"(",
")",
")",
"{",
"case",
"BufferedImage",
".",
"TYPE_INT_ARGB_PRE",
":",
"return",
"image",
";",
"// Already good to go",
"case",
"BufferedImage",
".",
"TYPE_4BYTE_ABGR",
":",
"image",
".",
"coerceData",
"(",
"true",
")",
";",
"// Just premultiply the alpha and it's fine",
"return",
"image",
";",
"}",
"// Didn't know an easy thing to do, so create a whole new image in our preferred format",
"BufferedImage",
"convertedImage",
"=",
"new",
"BufferedImage",
"(",
"image",
".",
"getWidth",
"(",
")",
",",
"image",
".",
"getHeight",
"(",
")",
",",
"BufferedImage",
".",
"TYPE_INT_ARGB_PRE",
")",
";",
"Graphics",
"g",
"=",
"convertedImage",
".",
"getGraphics",
"(",
")",
";",
"g",
".",
"setColor",
"(",
"new",
"Color",
"(",
"0f",
",",
"0f",
",",
"0f",
",",
"0f",
")",
")",
";",
"g",
".",
"fillRect",
"(",
"0",
",",
"0",
",",
"image",
".",
"getWidth",
"(",
")",
",",
"image",
".",
"getHeight",
"(",
")",
")",
";",
"g",
".",
"drawImage",
"(",
"image",
",",
"0",
",",
"0",
",",
"null",
")",
";",
"return",
"convertedImage",
";",
"}"
] | Converts the given image into a format for quick upload to the GPU. | [
"Converts",
"the",
"given",
"image",
"into",
"a",
"format",
"for",
"quick",
"upload",
"to",
"the",
"GPU",
"."
] | train | https://github.com/threerings/playn/blob/c266eeb39188dcada4b00992a0d1199759e03d42/java/src/playn/java/JavaGLContext.java#L37-L55 |
mozilla/rhino | src/org/mozilla/javascript/ScriptableObject.java | ScriptableObject.defineOwnProperty | public void defineOwnProperty(Context cx, Object id, ScriptableObject desc) {
"""
Defines a property on an object.
@param cx the current Context
@param id the name/index of the property
@param desc the new property descriptor, as described in 8.6.1
"""
checkPropertyDefinition(desc);
defineOwnProperty(cx, id, desc, true);
} | java | public void defineOwnProperty(Context cx, Object id, ScriptableObject desc) {
checkPropertyDefinition(desc);
defineOwnProperty(cx, id, desc, true);
} | [
"public",
"void",
"defineOwnProperty",
"(",
"Context",
"cx",
",",
"Object",
"id",
",",
"ScriptableObject",
"desc",
")",
"{",
"checkPropertyDefinition",
"(",
"desc",
")",
";",
"defineOwnProperty",
"(",
"cx",
",",
"id",
",",
"desc",
",",
"true",
")",
";",
"}"
] | Defines a property on an object.
@param cx the current Context
@param id the name/index of the property
@param desc the new property descriptor, as described in 8.6.1 | [
"Defines",
"a",
"property",
"on",
"an",
"object",
"."
] | train | https://github.com/mozilla/rhino/blob/fa8a86df11d37623f5faa8d445a5876612bc47b0/src/org/mozilla/javascript/ScriptableObject.java#L1898-L1901 |
citrusframework/citrus | modules/citrus-core/src/main/java/com/consol/citrus/actions/ReceiveMessageAction.java | ReceiveMessageAction.receiveSelected | private Message receiveSelected(TestContext context, String selectorString) {
"""
Receives the message with the respective message receiver implementation
also using a message selector.
@param context the test context.
@param selectorString the message selector string.
@return
"""
if (log.isDebugEnabled()) {
log.debug("Setting message selector: '" + selectorString + "'");
}
Endpoint messageEndpoint = getOrCreateEndpoint(context);
Consumer consumer = messageEndpoint.createConsumer();
if (consumer instanceof SelectiveConsumer) {
if (receiveTimeout > 0) {
return ((SelectiveConsumer) messageEndpoint.createConsumer()).receive(
context.replaceDynamicContentInString(selectorString),
context, receiveTimeout);
} else {
return ((SelectiveConsumer) messageEndpoint.createConsumer()).receive(
context.replaceDynamicContentInString(selectorString),
context, messageEndpoint.getEndpointConfiguration().getTimeout());
}
} else {
log.warn(String.format("Unable to receive selective with consumer implementation: '%s'", consumer.getClass()));
return receive(context);
}
} | java | private Message receiveSelected(TestContext context, String selectorString) {
if (log.isDebugEnabled()) {
log.debug("Setting message selector: '" + selectorString + "'");
}
Endpoint messageEndpoint = getOrCreateEndpoint(context);
Consumer consumer = messageEndpoint.createConsumer();
if (consumer instanceof SelectiveConsumer) {
if (receiveTimeout > 0) {
return ((SelectiveConsumer) messageEndpoint.createConsumer()).receive(
context.replaceDynamicContentInString(selectorString),
context, receiveTimeout);
} else {
return ((SelectiveConsumer) messageEndpoint.createConsumer()).receive(
context.replaceDynamicContentInString(selectorString),
context, messageEndpoint.getEndpointConfiguration().getTimeout());
}
} else {
log.warn(String.format("Unable to receive selective with consumer implementation: '%s'", consumer.getClass()));
return receive(context);
}
} | [
"private",
"Message",
"receiveSelected",
"(",
"TestContext",
"context",
",",
"String",
"selectorString",
")",
"{",
"if",
"(",
"log",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"log",
".",
"debug",
"(",
"\"Setting message selector: '\"",
"+",
"selectorString",
"+",
"\"'\"",
")",
";",
"}",
"Endpoint",
"messageEndpoint",
"=",
"getOrCreateEndpoint",
"(",
"context",
")",
";",
"Consumer",
"consumer",
"=",
"messageEndpoint",
".",
"createConsumer",
"(",
")",
";",
"if",
"(",
"consumer",
"instanceof",
"SelectiveConsumer",
")",
"{",
"if",
"(",
"receiveTimeout",
">",
"0",
")",
"{",
"return",
"(",
"(",
"SelectiveConsumer",
")",
"messageEndpoint",
".",
"createConsumer",
"(",
")",
")",
".",
"receive",
"(",
"context",
".",
"replaceDynamicContentInString",
"(",
"selectorString",
")",
",",
"context",
",",
"receiveTimeout",
")",
";",
"}",
"else",
"{",
"return",
"(",
"(",
"SelectiveConsumer",
")",
"messageEndpoint",
".",
"createConsumer",
"(",
")",
")",
".",
"receive",
"(",
"context",
".",
"replaceDynamicContentInString",
"(",
"selectorString",
")",
",",
"context",
",",
"messageEndpoint",
".",
"getEndpointConfiguration",
"(",
")",
".",
"getTimeout",
"(",
")",
")",
";",
"}",
"}",
"else",
"{",
"log",
".",
"warn",
"(",
"String",
".",
"format",
"(",
"\"Unable to receive selective with consumer implementation: '%s'\"",
",",
"consumer",
".",
"getClass",
"(",
")",
")",
")",
";",
"return",
"receive",
"(",
"context",
")",
";",
"}",
"}"
] | Receives the message with the respective message receiver implementation
also using a message selector.
@param context the test context.
@param selectorString the message selector string.
@return | [
"Receives",
"the",
"message",
"with",
"the",
"respective",
"message",
"receiver",
"implementation",
"also",
"using",
"a",
"message",
"selector",
"."
] | train | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/actions/ReceiveMessageAction.java#L151-L172 |
BBN-E/bue-common-open | common-core-open/src/main/java/com/bbn/bue/common/parameters/Parameters.java | Parameters.getPositiveDoubleList | public List<Double> getPositiveDoubleList(final String param) {
"""
Gets a parameter whose value is a (possibly empty) list of positive doubles.
"""
return getList(param, new StringToDouble(),
new IsPositive<Double>(), "positive double");
} | java | public List<Double> getPositiveDoubleList(final String param) {
return getList(param, new StringToDouble(),
new IsPositive<Double>(), "positive double");
} | [
"public",
"List",
"<",
"Double",
">",
"getPositiveDoubleList",
"(",
"final",
"String",
"param",
")",
"{",
"return",
"getList",
"(",
"param",
",",
"new",
"StringToDouble",
"(",
")",
",",
"new",
"IsPositive",
"<",
"Double",
">",
"(",
")",
",",
"\"positive double\"",
")",
";",
"}"
] | Gets a parameter whose value is a (possibly empty) list of positive doubles. | [
"Gets",
"a",
"parameter",
"whose",
"value",
"is",
"a",
"(",
"possibly",
"empty",
")",
"list",
"of",
"positive",
"doubles",
"."
] | train | https://github.com/BBN-E/bue-common-open/blob/d618652674d647867306e2e4b987a21b7c29c015/common-core-open/src/main/java/com/bbn/bue/common/parameters/Parameters.java#L701-L704 |
lucee/Lucee | core/src/main/java/lucee/runtime/schedule/StorageUtil.java | StorageUtil.toResource | public Resource toResource(Config config, Element el, String attributeName) {
"""
/*
public File toFile(Element el,String attributeName) { String attributeValue =
el.getAttribute(attributeName); if(attributeValue==null || attributeValue.trim().length()==0)
return null; return new File(attributeValue); }
"""
String attributeValue = el.getAttribute(attributeName);
if (attributeValue == null || attributeValue.trim().length() == 0) return null;
return config.getResource(attributeValue);
} | java | public Resource toResource(Config config, Element el, String attributeName) {
String attributeValue = el.getAttribute(attributeName);
if (attributeValue == null || attributeValue.trim().length() == 0) return null;
return config.getResource(attributeValue);
} | [
"public",
"Resource",
"toResource",
"(",
"Config",
"config",
",",
"Element",
"el",
",",
"String",
"attributeName",
")",
"{",
"String",
"attributeValue",
"=",
"el",
".",
"getAttribute",
"(",
"attributeName",
")",
";",
"if",
"(",
"attributeValue",
"==",
"null",
"||",
"attributeValue",
".",
"trim",
"(",
")",
".",
"length",
"(",
")",
"==",
"0",
")",
"return",
"null",
";",
"return",
"config",
".",
"getResource",
"(",
"attributeValue",
")",
";",
"}"
] | /*
public File toFile(Element el,String attributeName) { String attributeValue =
el.getAttribute(attributeName); if(attributeValue==null || attributeValue.trim().length()==0)
return null; return new File(attributeValue); } | [
"/",
"*",
"public",
"File",
"toFile",
"(",
"Element",
"el",
"String",
"attributeName",
")",
"{",
"String",
"attributeValue",
"=",
"el",
".",
"getAttribute",
"(",
"attributeName",
")",
";",
"if",
"(",
"attributeValue",
"==",
"null",
"||",
"attributeValue",
".",
"trim",
"()",
".",
"length",
"()",
"==",
"0",
")",
"return",
"null",
";",
"return",
"new",
"File",
"(",
"attributeValue",
")",
";",
"}"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/schedule/StorageUtil.java#L173-L177 |
kiegroup/jbpm | jbpm-query-jpa/src/main/java/org/jbpm/query/jpa/data/QueryWhere.java | QueryWhere.addParameter | public <T> QueryCriteria addParameter( String listId, T... param ) {
"""
This method should be used for<ol>
<li>Normal parameters</li>
<li>Regular expression parameters</li>
</ol>
This method should <b>not</b> be used for<ol>
<li>Range parameters</li>
</ol>
@param listId
@param param
@return
"""
if( param.length == 0 ) {
return null;
}
if( QueryCriteriaType.REGEXP.equals(this.type) && ! (param[0] instanceof String) ) {
throw new IllegalArgumentException("Only String parameters may be used in regular expressions.");
}
QueryCriteria criteria = new QueryCriteria(listId, this.union, this.type, param.length);
for( T paramElem : param ) {
criteria.addParameter(paramElem);
}
addCriteria(criteria);
return criteria;
} | java | public <T> QueryCriteria addParameter( String listId, T... param ) {
if( param.length == 0 ) {
return null;
}
if( QueryCriteriaType.REGEXP.equals(this.type) && ! (param[0] instanceof String) ) {
throw new IllegalArgumentException("Only String parameters may be used in regular expressions.");
}
QueryCriteria criteria = new QueryCriteria(listId, this.union, this.type, param.length);
for( T paramElem : param ) {
criteria.addParameter(paramElem);
}
addCriteria(criteria);
return criteria;
} | [
"public",
"<",
"T",
">",
"QueryCriteria",
"addParameter",
"(",
"String",
"listId",
",",
"T",
"...",
"param",
")",
"{",
"if",
"(",
"param",
".",
"length",
"==",
"0",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"QueryCriteriaType",
".",
"REGEXP",
".",
"equals",
"(",
"this",
".",
"type",
")",
"&&",
"!",
"(",
"param",
"[",
"0",
"]",
"instanceof",
"String",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Only String parameters may be used in regular expressions.\"",
")",
";",
"}",
"QueryCriteria",
"criteria",
"=",
"new",
"QueryCriteria",
"(",
"listId",
",",
"this",
".",
"union",
",",
"this",
".",
"type",
",",
"param",
".",
"length",
")",
";",
"for",
"(",
"T",
"paramElem",
":",
"param",
")",
"{",
"criteria",
".",
"addParameter",
"(",
"paramElem",
")",
";",
"}",
"addCriteria",
"(",
"criteria",
")",
";",
"return",
"criteria",
";",
"}"
] | This method should be used for<ol>
<li>Normal parameters</li>
<li>Regular expression parameters</li>
</ol>
This method should <b>not</b> be used for<ol>
<li>Range parameters</li>
</ol>
@param listId
@param param
@return | [
"This",
"method",
"should",
"be",
"used",
"for<ol",
">",
"<li",
">",
"Normal",
"parameters<",
"/",
"li",
">",
"<li",
">",
"Regular",
"expression",
"parameters<",
"/",
"li",
">",
"<",
"/",
"ol",
">",
"This",
"method",
"should",
"<b",
">",
"not<",
"/",
"b",
">",
"be",
"used",
"for<ol",
">",
"<li",
">",
"Range",
"parameters<",
"/",
"li",
">",
"<",
"/",
"ol",
">"
] | train | https://github.com/kiegroup/jbpm/blob/c3473c728aa382ebbea01e380c5e754a96647b82/jbpm-query-jpa/src/main/java/org/jbpm/query/jpa/data/QueryWhere.java#L126-L139 |
apache/groovy | src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java | DefaultGroovyMethods.toSorted | public static <K, V> Map<K, V> toSorted(Map<K, V> self, @ClosureParams(value=FromString.class, options= {
"""
Sorts the elements from the given map into a new ordered map using
the supplied Closure condition as a comparator to determine the ordering. The original map is unchanged.
<p>
If the closure has two parameters it is used like a traditional Comparator. I.e. it should compare
its two entry parameters for order, returning a negative integer, zero, or a positive integer when the
first parameter is less than, equal to, or greater than the second respectively. Otherwise,
the Closure is assumed to take a single entry parameter and return a Comparable (typically an Integer)
which is then used for further comparison.
<pre class="groovyTestCase">
def map = [a:5, b:3, c:6, d:4].toSorted { a, b {@code ->} a.value {@code <=>} b.value }
assert map.toString() == '[b:3, d:4, a:5, c:6]'
</pre>
@param self the original unsorted map
@param condition a Closure used as a comparator
@return the sorted map
@since 2.4.0
""""Map.Entry<K,V>","Map.Entry<K,V>,Map.Entry<K,V>"}) Closure condition) {
Comparator<Map.Entry<K,V>> comparator = (condition.getMaximumNumberOfParameters() == 1) ? new OrderBy<Map.Entry<K,V>>(condition) : new ClosureComparator<Map.Entry<K,V>>(condition);
return toSorted(self, comparator);
} | java | public static <K, V> Map<K, V> toSorted(Map<K, V> self, @ClosureParams(value=FromString.class, options={"Map.Entry<K,V>","Map.Entry<K,V>,Map.Entry<K,V>"}) Closure condition) {
Comparator<Map.Entry<K,V>> comparator = (condition.getMaximumNumberOfParameters() == 1) ? new OrderBy<Map.Entry<K,V>>(condition) : new ClosureComparator<Map.Entry<K,V>>(condition);
return toSorted(self, comparator);
} | [
"public",
"static",
"<",
"K",
",",
"V",
">",
"Map",
"<",
"K",
",",
"V",
">",
"toSorted",
"(",
"Map",
"<",
"K",
",",
"V",
">",
"self",
",",
"@",
"ClosureParams",
"(",
"value",
"=",
"FromString",
".",
"class",
",",
"options",
"=",
"{",
"\"Map.Entry<K,V>\"",
",",
"\"Map.Entry<K,V>,Map.Entry<K,V>\"",
"}",
")",
"Closure",
"condition",
")",
"{",
"Comparator",
"<",
"Map",
".",
"Entry",
"<",
"K",
",",
"V",
">",
">",
"comparator",
"=",
"(",
"condition",
".",
"getMaximumNumberOfParameters",
"(",
")",
"==",
"1",
")",
"?",
"new",
"OrderBy",
"<",
"Map",
".",
"Entry",
"<",
"K",
",",
"V",
">",
">",
"(",
"condition",
")",
":",
"new",
"ClosureComparator",
"<",
"Map",
".",
"Entry",
"<",
"K",
",",
"V",
">",
">",
"(",
"condition",
")",
";",
"return",
"toSorted",
"(",
"self",
",",
"comparator",
")",
";",
"}"
] | Sorts the elements from the given map into a new ordered map using
the supplied Closure condition as a comparator to determine the ordering. The original map is unchanged.
<p>
If the closure has two parameters it is used like a traditional Comparator. I.e. it should compare
its two entry parameters for order, returning a negative integer, zero, or a positive integer when the
first parameter is less than, equal to, or greater than the second respectively. Otherwise,
the Closure is assumed to take a single entry parameter and return a Comparable (typically an Integer)
which is then used for further comparison.
<pre class="groovyTestCase">
def map = [a:5, b:3, c:6, d:4].toSorted { a, b {@code ->} a.value {@code <=>} b.value }
assert map.toString() == '[b:3, d:4, a:5, c:6]'
</pre>
@param self the original unsorted map
@param condition a Closure used as a comparator
@return the sorted map
@since 2.4.0 | [
"Sorts",
"the",
"elements",
"from",
"the",
"given",
"map",
"into",
"a",
"new",
"ordered",
"map",
"using",
"the",
"supplied",
"Closure",
"condition",
"as",
"a",
"comparator",
"to",
"determine",
"the",
"ordering",
".",
"The",
"original",
"map",
"is",
"unchanged",
".",
"<p",
">",
"If",
"the",
"closure",
"has",
"two",
"parameters",
"it",
"is",
"used",
"like",
"a",
"traditional",
"Comparator",
".",
"I",
".",
"e",
".",
"it",
"should",
"compare",
"its",
"two",
"entry",
"parameters",
"for",
"order",
"returning",
"a",
"negative",
"integer",
"zero",
"or",
"a",
"positive",
"integer",
"when",
"the",
"first",
"parameter",
"is",
"less",
"than",
"equal",
"to",
"or",
"greater",
"than",
"the",
"second",
"respectively",
".",
"Otherwise",
"the",
"Closure",
"is",
"assumed",
"to",
"take",
"a",
"single",
"entry",
"parameter",
"and",
"return",
"a",
"Comparable",
"(",
"typically",
"an",
"Integer",
")",
"which",
"is",
"then",
"used",
"for",
"further",
"comparison",
".",
"<pre",
"class",
"=",
"groovyTestCase",
">",
"def",
"map",
"=",
"[",
"a",
":",
"5",
"b",
":",
"3",
"c",
":",
"6",
"d",
":",
"4",
"]",
".",
"toSorted",
"{",
"a",
"b",
"{",
"@code",
"-",
">",
"}",
"a",
".",
"value",
"{",
"@code",
"<",
"=",
">",
"}",
"b",
".",
"value",
"}",
"assert",
"map",
".",
"toString",
"()",
"==",
"[",
"b",
":",
"3",
"d",
":",
"4",
"a",
":",
"5",
"c",
":",
"6",
"]",
"<",
"/",
"pre",
">"
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L9621-L9624 |
sksamuel/scrimage | scrimage-filters/src/main/java/thirdparty/marvin/image/MarvinImage.java | MarvinImage.getBufferedImage | public BufferedImage getBufferedImage(int width, int height) {
"""
Resize and return the image passing the new height and width
@param height
@param width
@return
"""
// using the new approach of Java 2D API
BufferedImage buf = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = (Graphics2D) buf.getGraphics();
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2d.drawImage(image, 0, 0, width, height, null);
g2d.dispose();
return (buf);
} | java | public BufferedImage getBufferedImage(int width, int height) {
// using the new approach of Java 2D API
BufferedImage buf = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = (Graphics2D) buf.getGraphics();
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2d.drawImage(image, 0, 0, width, height, null);
g2d.dispose();
return (buf);
} | [
"public",
"BufferedImage",
"getBufferedImage",
"(",
"int",
"width",
",",
"int",
"height",
")",
"{",
"// using the new approach of Java 2D API",
"BufferedImage",
"buf",
"=",
"new",
"BufferedImage",
"(",
"width",
",",
"height",
",",
"BufferedImage",
".",
"TYPE_INT_ARGB",
")",
";",
"Graphics2D",
"g2d",
"=",
"(",
"Graphics2D",
")",
"buf",
".",
"getGraphics",
"(",
")",
";",
"g2d",
".",
"setRenderingHint",
"(",
"RenderingHints",
".",
"KEY_INTERPOLATION",
",",
"RenderingHints",
".",
"VALUE_INTERPOLATION_BILINEAR",
")",
";",
"g2d",
".",
"drawImage",
"(",
"image",
",",
"0",
",",
"0",
",",
"width",
",",
"height",
",",
"null",
")",
";",
"g2d",
".",
"dispose",
"(",
")",
";",
"return",
"(",
"buf",
")",
";",
"}"
] | Resize and return the image passing the new height and width
@param height
@param width
@return | [
"Resize",
"and",
"return",
"the",
"image",
"passing",
"the",
"new",
"height",
"and",
"width"
] | train | https://github.com/sksamuel/scrimage/blob/52dab448136e6657a71951b0e6b7d5e64dc979ac/scrimage-filters/src/main/java/thirdparty/marvin/image/MarvinImage.java#L480-L488 |
OpenLiberty/open-liberty | dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/CacheProviderWrapper.java | CacheProviderWrapper.getEntry | @Override
public com.ibm.websphere.cache.CacheEntry getEntry(EntryInfo ei, boolean checkAskPermission) {
"""
This returns the cache entry identified by the specified entryInfo.
It returns null if not in the cache.
@param ei The entryInfo for the entry.
@param checkAskPermission true to check askPermission from sharing policy (No effect on CoreCache)
@return The entry identified by the entryInfo.getIdObject().
"""
final String methodName = "getEntry()";
com.ibm.websphere.cache.CacheEntry ce = null;
Object id = null;
if (ei != null) {
id = ei.getIdObject();
ce = this.coreCache.get(id);
}
if (tc.isDebugEnabled()) {
Tr.debug(tc, methodName + " cacheName=" + cacheName + " id=" + id + " cacheEntry=" + ce);
}
return ce;
} | java | @Override
public com.ibm.websphere.cache.CacheEntry getEntry(EntryInfo ei, boolean checkAskPermission) {
final String methodName = "getEntry()";
com.ibm.websphere.cache.CacheEntry ce = null;
Object id = null;
if (ei != null) {
id = ei.getIdObject();
ce = this.coreCache.get(id);
}
if (tc.isDebugEnabled()) {
Tr.debug(tc, methodName + " cacheName=" + cacheName + " id=" + id + " cacheEntry=" + ce);
}
return ce;
} | [
"@",
"Override",
"public",
"com",
".",
"ibm",
".",
"websphere",
".",
"cache",
".",
"CacheEntry",
"getEntry",
"(",
"EntryInfo",
"ei",
",",
"boolean",
"checkAskPermission",
")",
"{",
"final",
"String",
"methodName",
"=",
"\"getEntry()\"",
";",
"com",
".",
"ibm",
".",
"websphere",
".",
"cache",
".",
"CacheEntry",
"ce",
"=",
"null",
";",
"Object",
"id",
"=",
"null",
";",
"if",
"(",
"ei",
"!=",
"null",
")",
"{",
"id",
"=",
"ei",
".",
"getIdObject",
"(",
")",
";",
"ce",
"=",
"this",
".",
"coreCache",
".",
"get",
"(",
"id",
")",
";",
"}",
"if",
"(",
"tc",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"Tr",
".",
"debug",
"(",
"tc",
",",
"methodName",
"+",
"\" cacheName=\"",
"+",
"cacheName",
"+",
"\" id=\"",
"+",
"id",
"+",
"\" cacheEntry=\"",
"+",
"ce",
")",
";",
"}",
"return",
"ce",
";",
"}"
] | This returns the cache entry identified by the specified entryInfo.
It returns null if not in the cache.
@param ei The entryInfo for the entry.
@param checkAskPermission true to check askPermission from sharing policy (No effect on CoreCache)
@return The entry identified by the entryInfo.getIdObject(). | [
"This",
"returns",
"the",
"cache",
"entry",
"identified",
"by",
"the",
"specified",
"entryInfo",
".",
"It",
"returns",
"null",
"if",
"not",
"in",
"the",
"cache",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/CacheProviderWrapper.java#L158-L171 |
fcrepo3/fcrepo | fcrepo-security/fcrepo-security-jaas/src/main/java/org/fcrepo/server/security/jaas/AuthFilterJAAS.java | AuthFilterJAAS.addRolesToSubject | private void addRolesToSubject(Subject subject, Set<String> userRoles) {
"""
Adds roles to the Subject object.
@param subject
the subject that was returned from authentication.
@param userRoles
the set of user roles that were found.
"""
if (userRoles == null) {
userRoles = Collections.emptySet();
}
Map<String, Set<String>> attributes =
SubjectUtils.getAttributes(subject);
Set<String> roles = attributes.get(ROLE_KEY);
if (roles == null) {
roles = new HashSet<String>(userRoles);
attributes.put(ROLE_KEY, roles);
} else {
roles.addAll(userRoles);
}
if (logger.isDebugEnabled()) {
for (String role : userRoles) {
logger.debug("added role: {}", role);
}
}
} | java | private void addRolesToSubject(Subject subject, Set<String> userRoles) {
if (userRoles == null) {
userRoles = Collections.emptySet();
}
Map<String, Set<String>> attributes =
SubjectUtils.getAttributes(subject);
Set<String> roles = attributes.get(ROLE_KEY);
if (roles == null) {
roles = new HashSet<String>(userRoles);
attributes.put(ROLE_KEY, roles);
} else {
roles.addAll(userRoles);
}
if (logger.isDebugEnabled()) {
for (String role : userRoles) {
logger.debug("added role: {}", role);
}
}
} | [
"private",
"void",
"addRolesToSubject",
"(",
"Subject",
"subject",
",",
"Set",
"<",
"String",
">",
"userRoles",
")",
"{",
"if",
"(",
"userRoles",
"==",
"null",
")",
"{",
"userRoles",
"=",
"Collections",
".",
"emptySet",
"(",
")",
";",
"}",
"Map",
"<",
"String",
",",
"Set",
"<",
"String",
">",
">",
"attributes",
"=",
"SubjectUtils",
".",
"getAttributes",
"(",
"subject",
")",
";",
"Set",
"<",
"String",
">",
"roles",
"=",
"attributes",
".",
"get",
"(",
"ROLE_KEY",
")",
";",
"if",
"(",
"roles",
"==",
"null",
")",
"{",
"roles",
"=",
"new",
"HashSet",
"<",
"String",
">",
"(",
"userRoles",
")",
";",
"attributes",
".",
"put",
"(",
"ROLE_KEY",
",",
"roles",
")",
";",
"}",
"else",
"{",
"roles",
".",
"addAll",
"(",
"userRoles",
")",
";",
"}",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"for",
"(",
"String",
"role",
":",
"userRoles",
")",
"{",
"logger",
".",
"debug",
"(",
"\"added role: {}\"",
",",
"role",
")",
";",
"}",
"}",
"}"
] | Adds roles to the Subject object.
@param subject
the subject that was returned from authentication.
@param userRoles
the set of user roles that were found. | [
"Adds",
"roles",
"to",
"the",
"Subject",
"object",
"."
] | train | https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-security/fcrepo-security-jaas/src/main/java/org/fcrepo/server/security/jaas/AuthFilterJAAS.java#L516-L536 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.