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
cdk/cdk
tool/sdg/src/main/java/org/openscience/cdk/layout/OverlapResolver.java
OverlapResolver.resolveOverlap
public double resolveOverlap(IAtomContainer ac, IRingSet sssr) { """ Main method to be called to resolve overlap situations. @param ac The atomcontainer in which the atom or bond overlap exists @param sssr A ring set for this atom container if one exists, otherwhise null """ Vector overlappingAtoms = new Vector(); Vector overlappingBonds = new Vector(); logger.debug("Start of resolveOverlap"); double overlapScore = getOverlapScore(ac, overlappingAtoms, overlappingBonds); if (overlapScore > 0) { overlapScore = displace(ac, overlappingAtoms, overlappingBonds); } logger.debug("overlapScore = " + overlapScore); logger.debug("End of resolveOverlap"); return overlapScore; }
java
public double resolveOverlap(IAtomContainer ac, IRingSet sssr) { Vector overlappingAtoms = new Vector(); Vector overlappingBonds = new Vector(); logger.debug("Start of resolveOverlap"); double overlapScore = getOverlapScore(ac, overlappingAtoms, overlappingBonds); if (overlapScore > 0) { overlapScore = displace(ac, overlappingAtoms, overlappingBonds); } logger.debug("overlapScore = " + overlapScore); logger.debug("End of resolveOverlap"); return overlapScore; }
[ "public", "double", "resolveOverlap", "(", "IAtomContainer", "ac", ",", "IRingSet", "sssr", ")", "{", "Vector", "overlappingAtoms", "=", "new", "Vector", "(", ")", ";", "Vector", "overlappingBonds", "=", "new", "Vector", "(", ")", ";", "logger", ".", "debug", "(", "\"Start of resolveOverlap\"", ")", ";", "double", "overlapScore", "=", "getOverlapScore", "(", "ac", ",", "overlappingAtoms", ",", "overlappingBonds", ")", ";", "if", "(", "overlapScore", ">", "0", ")", "{", "overlapScore", "=", "displace", "(", "ac", ",", "overlappingAtoms", ",", "overlappingBonds", ")", ";", "}", "logger", ".", "debug", "(", "\"overlapScore = \"", "+", "overlapScore", ")", ";", "logger", ".", "debug", "(", "\"End of resolveOverlap\"", ")", ";", "return", "overlapScore", ";", "}" ]
Main method to be called to resolve overlap situations. @param ac The atomcontainer in which the atom or bond overlap exists @param sssr A ring set for this atom container if one exists, otherwhise null
[ "Main", "method", "to", "be", "called", "to", "resolve", "overlap", "situations", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/tool/sdg/src/main/java/org/openscience/cdk/layout/OverlapResolver.java#L69-L81
jOOQ/jOOL
jOOL-java-8/src/main/java/org/jooq/lambda/Unchecked.java
Unchecked.toIntBiFunction
public static <T, U> ToIntBiFunction<T, U> toIntBiFunction(CheckedToIntBiFunction<T, U> function) { """ Wrap a {@link CheckedToIntBiFunction} in a {@link ToIntBiFunction}. """ return toIntBiFunction(function, THROWABLE_TO_RUNTIME_EXCEPTION); }
java
public static <T, U> ToIntBiFunction<T, U> toIntBiFunction(CheckedToIntBiFunction<T, U> function) { return toIntBiFunction(function, THROWABLE_TO_RUNTIME_EXCEPTION); }
[ "public", "static", "<", "T", ",", "U", ">", "ToIntBiFunction", "<", "T", ",", "U", ">", "toIntBiFunction", "(", "CheckedToIntBiFunction", "<", "T", ",", "U", ">", "function", ")", "{", "return", "toIntBiFunction", "(", "function", ",", "THROWABLE_TO_RUNTIME_EXCEPTION", ")", ";", "}" ]
Wrap a {@link CheckedToIntBiFunction} in a {@link ToIntBiFunction}.
[ "Wrap", "a", "{" ]
train
https://github.com/jOOQ/jOOL/blob/889d87c85ca57bafd4eddd78e0f7ae2804d2ee86/jOOL-java-8/src/main/java/org/jooq/lambda/Unchecked.java#L367-L369
hexagonframework/spring-data-ebean
src/main/java/org/springframework/data/ebean/repository/query/StringQueryParameterBinder.java
StringQueryParameterBinder.getBindingFor
private ParameterBinding getBindingFor(Object ebeanQuery, int position, Parameter parameter) { """ Finds the {@link LikeParameterBinding} to be applied before binding a parameter value to the query. @param ebeanQuery must not be {@literal null}. @param position @param parameter must not be {@literal null}. @return the {@link ParameterBinding} for the given parameters or {@literal null} if none available. """ Assert.notNull(ebeanQuery, "EbeanQueryWrapper must not be null!"); Assert.notNull(parameter, "Parameter must not be null!"); if (parameter.isNamedParameter()) { return query.getBindingFor(parameter.getName().orElseThrow(() -> new IllegalArgumentException("Parameter needs to be named!"))); } try { return query.getBindingFor(position); } catch (IllegalArgumentException ex) { // We should actually reject parameters unavailable, but as EclipseLink doesn't implement ….getParameter(int) for // native queries correctly we need to fall back to an indexed parameter // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=427892 return new ParameterBinding(position); } }
java
private ParameterBinding getBindingFor(Object ebeanQuery, int position, Parameter parameter) { Assert.notNull(ebeanQuery, "EbeanQueryWrapper must not be null!"); Assert.notNull(parameter, "Parameter must not be null!"); if (parameter.isNamedParameter()) { return query.getBindingFor(parameter.getName().orElseThrow(() -> new IllegalArgumentException("Parameter needs to be named!"))); } try { return query.getBindingFor(position); } catch (IllegalArgumentException ex) { // We should actually reject parameters unavailable, but as EclipseLink doesn't implement ….getParameter(int) for // native queries correctly we need to fall back to an indexed parameter // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=427892 return new ParameterBinding(position); } }
[ "private", "ParameterBinding", "getBindingFor", "(", "Object", "ebeanQuery", ",", "int", "position", ",", "Parameter", "parameter", ")", "{", "Assert", ".", "notNull", "(", "ebeanQuery", ",", "\"EbeanQueryWrapper must not be null!\"", ")", ";", "Assert", ".", "notNull", "(", "parameter", ",", "\"Parameter must not be null!\"", ")", ";", "if", "(", "parameter", ".", "isNamedParameter", "(", ")", ")", "{", "return", "query", ".", "getBindingFor", "(", "parameter", ".", "getName", "(", ")", ".", "orElseThrow", "(", "(", ")", "->", "new", "IllegalArgumentException", "(", "\"Parameter needs to be named!\"", ")", ")", ")", ";", "}", "try", "{", "return", "query", ".", "getBindingFor", "(", "position", ")", ";", "}", "catch", "(", "IllegalArgumentException", "ex", ")", "{", "// We should actually reject parameters unavailable, but as EclipseLink doesn't implement ….getParameter(int) for\r", "// native queries correctly we need to fall back to an indexed parameter\r", "// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=427892\r", "return", "new", "ParameterBinding", "(", "position", ")", ";", "}", "}" ]
Finds the {@link LikeParameterBinding} to be applied before binding a parameter value to the query. @param ebeanQuery must not be {@literal null}. @param position @param parameter must not be {@literal null}. @return the {@link ParameterBinding} for the given parameters or {@literal null} if none available.
[ "Finds", "the", "{", "@link", "LikeParameterBinding", "}", "to", "be", "applied", "before", "binding", "a", "parameter", "value", "to", "the", "query", "." ]
train
https://github.com/hexagonframework/spring-data-ebean/blob/dd11b97654982403b50dd1d5369cadad71fce410/src/main/java/org/springframework/data/ebean/repository/query/StringQueryParameterBinder.java#L67-L87
DataSketches/sketches-core
src/main/java/com/yahoo/sketches/BoundsOnBinomialProportions.java
BoundsOnBinomialProportions.approximateLowerBoundOnP
public static double approximateLowerBoundOnP(final long n, final long k, final double numStdDevs) { """ Computes lower bound of approximate Clopper-Pearson confidence interval for a binomial proportion. <p>Implementation Notes:<br> The approximateLowerBoundOnP is defined with respect to the right tail of the binomial distribution.</p> <ul> <li>We want to solve for the <i>p</i> for which sum<sub><i>j,k,n</i></sub>bino(<i>j;n,p</i>) = delta.</li> <li>We now restate that in terms of the left tail.</li> <li>We want to solve for the p for which sum<sub><i>j,0,(k-1)</i></sub>bino(<i>j;n,p</i>) = 1 - delta.</li> <li>Define <i>x</i> = 1-<i>p</i>.</li> <li>We want to solve for the <i>x</i> for which I<sub><i>x(n-k+1,k)</i></sub> = 1 - delta.</li> <li>We specify 1-delta via numStdDevs through the right tail of the standard normal distribution.</li> <li>Smaller values of numStdDevs correspond to bigger values of 1-delta and hence to smaller values of delta. In fact, usefully small values of delta correspond to negative values of numStdDevs.</li> <li>return <i>p</i> = 1-<i>x</i>.</li> </ul> @param n is the number of trials. Must be non-negative. @param k is the number of successes. Must be non-negative, and cannot exceed n. @param numStdDevs the number of standard deviations defining the confidence interval @return the lower bound of the approximate Clopper-Pearson confidence interval for the unknown success probability. """ checkInputs(n, k); if (n == 0) { return 0.0; } // the coin was never flipped, so we know nothing else if (k == 0) { return 0.0; } else if (k == 1) { return (exactLowerBoundOnPForKequalsOne(n, deltaOfNumStdevs(numStdDevs))); } else if (k == n) { return (exactLowerBoundOnPForKequalsN(n, deltaOfNumStdevs(numStdDevs))); } else { final double x = abramowitzStegunFormula26p5p22((n - k) + 1, k, (-1.0 * numStdDevs)); return (1.0 - x); // which is p } }
java
public static double approximateLowerBoundOnP(final long n, final long k, final double numStdDevs) { checkInputs(n, k); if (n == 0) { return 0.0; } // the coin was never flipped, so we know nothing else if (k == 0) { return 0.0; } else if (k == 1) { return (exactLowerBoundOnPForKequalsOne(n, deltaOfNumStdevs(numStdDevs))); } else if (k == n) { return (exactLowerBoundOnPForKequalsN(n, deltaOfNumStdevs(numStdDevs))); } else { final double x = abramowitzStegunFormula26p5p22((n - k) + 1, k, (-1.0 * numStdDevs)); return (1.0 - x); // which is p } }
[ "public", "static", "double", "approximateLowerBoundOnP", "(", "final", "long", "n", ",", "final", "long", "k", ",", "final", "double", "numStdDevs", ")", "{", "checkInputs", "(", "n", ",", "k", ")", ";", "if", "(", "n", "==", "0", ")", "{", "return", "0.0", ";", "}", "// the coin was never flipped, so we know nothing", "else", "if", "(", "k", "==", "0", ")", "{", "return", "0.0", ";", "}", "else", "if", "(", "k", "==", "1", ")", "{", "return", "(", "exactLowerBoundOnPForKequalsOne", "(", "n", ",", "deltaOfNumStdevs", "(", "numStdDevs", ")", ")", ")", ";", "}", "else", "if", "(", "k", "==", "n", ")", "{", "return", "(", "exactLowerBoundOnPForKequalsN", "(", "n", ",", "deltaOfNumStdevs", "(", "numStdDevs", ")", ")", ")", ";", "}", "else", "{", "final", "double", "x", "=", "abramowitzStegunFormula26p5p22", "(", "(", "n", "-", "k", ")", "+", "1", ",", "k", ",", "(", "-", "1.0", "*", "numStdDevs", ")", ")", ";", "return", "(", "1.0", "-", "x", ")", ";", "// which is p", "}", "}" ]
Computes lower bound of approximate Clopper-Pearson confidence interval for a binomial proportion. <p>Implementation Notes:<br> The approximateLowerBoundOnP is defined with respect to the right tail of the binomial distribution.</p> <ul> <li>We want to solve for the <i>p</i> for which sum<sub><i>j,k,n</i></sub>bino(<i>j;n,p</i>) = delta.</li> <li>We now restate that in terms of the left tail.</li> <li>We want to solve for the p for which sum<sub><i>j,0,(k-1)</i></sub>bino(<i>j;n,p</i>) = 1 - delta.</li> <li>Define <i>x</i> = 1-<i>p</i>.</li> <li>We want to solve for the <i>x</i> for which I<sub><i>x(n-k+1,k)</i></sub> = 1 - delta.</li> <li>We specify 1-delta via numStdDevs through the right tail of the standard normal distribution.</li> <li>Smaller values of numStdDevs correspond to bigger values of 1-delta and hence to smaller values of delta. In fact, usefully small values of delta correspond to negative values of numStdDevs.</li> <li>return <i>p</i> = 1-<i>x</i>.</li> </ul> @param n is the number of trials. Must be non-negative. @param k is the number of successes. Must be non-negative, and cannot exceed n. @param numStdDevs the number of standard deviations defining the confidence interval @return the lower bound of the approximate Clopper-Pearson confidence interval for the unknown success probability.
[ "Computes", "lower", "bound", "of", "approximate", "Clopper", "-", "Pearson", "confidence", "interval", "for", "a", "binomial", "proportion", "." ]
train
https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/BoundsOnBinomialProportions.java#L93-L103
SG-O/miIO
src/main/java/de/sg_o/app/miio/vacuum/Vacuum.java
Vacuum.resetConsumable
public boolean resetConsumable(VacuumConsumableStatus.Names consumable) throws CommandExecutionException { """ Reset a vacuums consumable. @param consumable The consumable to reset @return True if the consumable has been reset. @throws CommandExecutionException When there has been a error during the communication or the response was invalid. """ if (consumable == null) throw new CommandExecutionException(CommandExecutionException.Error.INVALID_PARAMETERS); JSONArray params = new JSONArray(); params.put(consumable.toString()); return sendOk("reset_consumable", params); }
java
public boolean resetConsumable(VacuumConsumableStatus.Names consumable) throws CommandExecutionException { if (consumable == null) throw new CommandExecutionException(CommandExecutionException.Error.INVALID_PARAMETERS); JSONArray params = new JSONArray(); params.put(consumable.toString()); return sendOk("reset_consumable", params); }
[ "public", "boolean", "resetConsumable", "(", "VacuumConsumableStatus", ".", "Names", "consumable", ")", "throws", "CommandExecutionException", "{", "if", "(", "consumable", "==", "null", ")", "throw", "new", "CommandExecutionException", "(", "CommandExecutionException", ".", "Error", ".", "INVALID_PARAMETERS", ")", ";", "JSONArray", "params", "=", "new", "JSONArray", "(", ")", ";", "params", ".", "put", "(", "consumable", ".", "toString", "(", ")", ")", ";", "return", "sendOk", "(", "\"reset_consumable\"", ",", "params", ")", ";", "}" ]
Reset a vacuums consumable. @param consumable The consumable to reset @return True if the consumable has been reset. @throws CommandExecutionException When there has been a error during the communication or the response was invalid.
[ "Reset", "a", "vacuums", "consumable", "." ]
train
https://github.com/SG-O/miIO/blob/f352dbd2a699d2cdb1b412ca5e6cbb0c38ca779b/src/main/java/de/sg_o/app/miio/vacuum/Vacuum.java#L99-L104
jcuda/jcuda
JCudaJava/src/main/java/jcuda/nvrtc/JNvrtc.java
JNvrtc.nvrtcGetLoweredName
public static int nvrtcGetLoweredName(nvrtcProgram prog, String name_expression, String lowered_name[]) { """ Extracts the lowered (mangled) name for a __global__ function or function template instantiation, and updates *lowered_name to point to it. The memory containing the name is released when the NVRTC program is destroyed by nvrtcDestroyProgram.<br> <br> The identical name expression must have been previously provided to nvrtcAddNameExpression. @param prog CUDA Runtime Compilation program. @param name_expression constant expression denoting a __global__ function or function template instantiation. @param lowered_name initialized by the function to point to a C string containing the lowered (mangled) name corresponding to the provided name expression. @return NVRTC_SUCCESS, NVRTC_ERROR_NO_LOWERED_NAMES_BEFORE_COMPILATION, NVRTC_ERROR_NAME_EXPRESSION_NOT_VALID @see #nvrtcAddNameExpression """ return checkResult(nvrtcGetLoweredNameNative(prog, name_expression, lowered_name)); }
java
public static int nvrtcGetLoweredName(nvrtcProgram prog, String name_expression, String lowered_name[]) { return checkResult(nvrtcGetLoweredNameNative(prog, name_expression, lowered_name)); }
[ "public", "static", "int", "nvrtcGetLoweredName", "(", "nvrtcProgram", "prog", ",", "String", "name_expression", ",", "String", "lowered_name", "[", "]", ")", "{", "return", "checkResult", "(", "nvrtcGetLoweredNameNative", "(", "prog", ",", "name_expression", ",", "lowered_name", ")", ")", ";", "}" ]
Extracts the lowered (mangled) name for a __global__ function or function template instantiation, and updates *lowered_name to point to it. The memory containing the name is released when the NVRTC program is destroyed by nvrtcDestroyProgram.<br> <br> The identical name expression must have been previously provided to nvrtcAddNameExpression. @param prog CUDA Runtime Compilation program. @param name_expression constant expression denoting a __global__ function or function template instantiation. @param lowered_name initialized by the function to point to a C string containing the lowered (mangled) name corresponding to the provided name expression. @return NVRTC_SUCCESS, NVRTC_ERROR_NO_LOWERED_NAMES_BEFORE_COMPILATION, NVRTC_ERROR_NAME_EXPRESSION_NOT_VALID @see #nvrtcAddNameExpression
[ "Extracts", "the", "lowered", "(", "mangled", ")", "name", "for", "a", "__global__", "function", "or", "function", "template", "instantiation", "and", "updates", "*", "lowered_name", "to", "point", "to", "it", ".", "The", "memory", "containing", "the", "name", "is", "released", "when", "the", "NVRTC", "program", "is", "destroyed", "by", "nvrtcDestroyProgram", ".", "<br", ">", "<br", ">", "The", "identical", "name", "expression", "must", "have", "been", "previously", "provided", "to", "nvrtcAddNameExpression", "." ]
train
https://github.com/jcuda/jcuda/blob/468528b5b9b37dfceb6ed83fcfd889e9b359f984/JCudaJava/src/main/java/jcuda/nvrtc/JNvrtc.java#L327-L330
apache/groovy
subprojects/groovy-sql/src/main/java/groovy/sql/Sql.java
Sql.eachRow
public void eachRow(String sql, @ClosureParams(value=SimpleType.class, options="java.sql.ResultSetMetaData") Closure metaClosure, @ClosureParams(value=SimpleType.class, options="groovy.sql.GroovyResultSet") Closure rowClosure) throws SQLException { """ Performs the given SQL query calling the given <code>rowClosure</code> with each row of the result set. The row will be a <code>GroovyResultSet</code> which is a <code>ResultSet</code> that supports accessing the fields using property style notation and ordinal index values. In addition, the <code>metaClosure</code> will be called once passing in the <code>ResultSetMetaData</code> as argument. <p> Example usage: <pre> def printColNames = { meta {@code ->} (1..meta.columnCount).each { print meta.getColumnLabel(it).padRight(20) } println() } def printRow = { row {@code ->} row.toRowResult().values().each{ print it.toString().padRight(20) } println() } sql.eachRow("select * from PERSON", printColNames, printRow) </pre> <p> Resource handling is performed automatically where appropriate. @param sql the sql statement @param metaClosure called for meta data (only once after sql execution) @param rowClosure called for each row with a GroovyResultSet @throws SQLException if a database access error occurs """ eachRow(sql, metaClosure, 0, 0, rowClosure); }
java
public void eachRow(String sql, @ClosureParams(value=SimpleType.class, options="java.sql.ResultSetMetaData") Closure metaClosure, @ClosureParams(value=SimpleType.class, options="groovy.sql.GroovyResultSet") Closure rowClosure) throws SQLException { eachRow(sql, metaClosure, 0, 0, rowClosure); }
[ "public", "void", "eachRow", "(", "String", "sql", ",", "@", "ClosureParams", "(", "value", "=", "SimpleType", ".", "class", ",", "options", "=", "\"java.sql.ResultSetMetaData\"", ")", "Closure", "metaClosure", ",", "@", "ClosureParams", "(", "value", "=", "SimpleType", ".", "class", ",", "options", "=", "\"groovy.sql.GroovyResultSet\"", ")", "Closure", "rowClosure", ")", "throws", "SQLException", "{", "eachRow", "(", "sql", ",", "metaClosure", ",", "0", ",", "0", ",", "rowClosure", ")", ";", "}" ]
Performs the given SQL query calling the given <code>rowClosure</code> with each row of the result set. The row will be a <code>GroovyResultSet</code> which is a <code>ResultSet</code> that supports accessing the fields using property style notation and ordinal index values. In addition, the <code>metaClosure</code> will be called once passing in the <code>ResultSetMetaData</code> as argument. <p> Example usage: <pre> def printColNames = { meta {@code ->} (1..meta.columnCount).each { print meta.getColumnLabel(it).padRight(20) } println() } def printRow = { row {@code ->} row.toRowResult().values().each{ print it.toString().padRight(20) } println() } sql.eachRow("select * from PERSON", printColNames, printRow) </pre> <p> Resource handling is performed automatically where appropriate. @param sql the sql statement @param metaClosure called for meta data (only once after sql execution) @param rowClosure called for each row with a GroovyResultSet @throws SQLException if a database access error occurs
[ "Performs", "the", "given", "SQL", "query", "calling", "the", "given", "<code", ">", "rowClosure<", "/", "code", ">", "with", "each", "row", "of", "the", "result", "set", ".", "The", "row", "will", "be", "a", "<code", ">", "GroovyResultSet<", "/", "code", ">", "which", "is", "a", "<code", ">", "ResultSet<", "/", "code", ">", "that", "supports", "accessing", "the", "fields", "using", "property", "style", "notation", "and", "ordinal", "index", "values", ".", "In", "addition", "the", "<code", ">", "metaClosure<", "/", "code", ">", "will", "be", "called", "once", "passing", "in", "the", "<code", ">", "ResultSetMetaData<", "/", "code", ">", "as", "argument", ".", "<p", ">", "Example", "usage", ":", "<pre", ">", "def", "printColNames", "=", "{", "meta", "{", "@code", "-", ">", "}", "(", "1", "..", "meta", ".", "columnCount", ")", ".", "each", "{", "print", "meta", ".", "getColumnLabel", "(", "it", ")", ".", "padRight", "(", "20", ")", "}", "println", "()", "}", "def", "printRow", "=", "{", "row", "{", "@code", "-", ">", "}", "row", ".", "toRowResult", "()", ".", "values", "()", ".", "each", "{", "print", "it", ".", "toString", "()", ".", "padRight", "(", "20", ")", "}", "println", "()", "}", "sql", ".", "eachRow", "(", "select", "*", "from", "PERSON", "printColNames", "printRow", ")", "<", "/", "pre", ">", "<p", ">", "Resource", "handling", "is", "performed", "automatically", "where", "appropriate", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-sql/src/main/java/groovy/sql/Sql.java#L1175-L1178
aws/aws-sdk-java
aws-java-sdk-apigatewayv2/src/main/java/com/amazonaws/services/apigatewayv2/model/UpdateIntegrationResponseRequest.java
UpdateIntegrationResponseRequest.withResponseParameters
public UpdateIntegrationResponseRequest withResponseParameters(java.util.Map<String, String> responseParameters) { """ <p> A key-value map specifying response parameters that are passed to the method response from the backend. The key is a method response header parameter name and the mapped value is an integration response header value, a static value enclosed within a pair of single quotes, or a JSON expression from the integration response body. The mapping key must match the pattern of method.response.header.{name} , where name is a valid and unique header name. The mapped non-static value must match the pattern of integration.response.header.{name} or integration.response.body.{JSON-expression} , where {name} is a valid and unique response header name and {JSON-expression} is a valid JSON expression without the $ prefix. </p> @param responseParameters A key-value map specifying response parameters that are passed to the method response from the backend. The key is a method response header parameter name and the mapped value is an integration response header value, a static value enclosed within a pair of single quotes, or a JSON expression from the integration response body. The mapping key must match the pattern of method.response.header.{name} , where name is a valid and unique header name. The mapped non-static value must match the pattern of integration.response.header.{name} or integration.response.body.{JSON-expression} , where {name} is a valid and unique response header name and {JSON-expression} is a valid JSON expression without the $ prefix. @return Returns a reference to this object so that method calls can be chained together. """ setResponseParameters(responseParameters); return this; }
java
public UpdateIntegrationResponseRequest withResponseParameters(java.util.Map<String, String> responseParameters) { setResponseParameters(responseParameters); return this; }
[ "public", "UpdateIntegrationResponseRequest", "withResponseParameters", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "responseParameters", ")", "{", "setResponseParameters", "(", "responseParameters", ")", ";", "return", "this", ";", "}" ]
<p> A key-value map specifying response parameters that are passed to the method response from the backend. The key is a method response header parameter name and the mapped value is an integration response header value, a static value enclosed within a pair of single quotes, or a JSON expression from the integration response body. The mapping key must match the pattern of method.response.header.{name} , where name is a valid and unique header name. The mapped non-static value must match the pattern of integration.response.header.{name} or integration.response.body.{JSON-expression} , where {name} is a valid and unique response header name and {JSON-expression} is a valid JSON expression without the $ prefix. </p> @param responseParameters A key-value map specifying response parameters that are passed to the method response from the backend. The key is a method response header parameter name and the mapped value is an integration response header value, a static value enclosed within a pair of single quotes, or a JSON expression from the integration response body. The mapping key must match the pattern of method.response.header.{name} , where name is a valid and unique header name. The mapped non-static value must match the pattern of integration.response.header.{name} or integration.response.body.{JSON-expression} , where {name} is a valid and unique response header name and {JSON-expression} is a valid JSON expression without the $ prefix. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "A", "key", "-", "value", "map", "specifying", "response", "parameters", "that", "are", "passed", "to", "the", "method", "response", "from", "the", "backend", ".", "The", "key", "is", "a", "method", "response", "header", "parameter", "name", "and", "the", "mapped", "value", "is", "an", "integration", "response", "header", "value", "a", "static", "value", "enclosed", "within", "a", "pair", "of", "single", "quotes", "or", "a", "JSON", "expression", "from", "the", "integration", "response", "body", ".", "The", "mapping", "key", "must", "match", "the", "pattern", "of", "method", ".", "response", ".", "header", ".", "{", "name", "}", "where", "name", "is", "a", "valid", "and", "unique", "header", "name", ".", "The", "mapped", "non", "-", "static", "value", "must", "match", "the", "pattern", "of", "integration", ".", "response", ".", "header", ".", "{", "name", "}", "or", "integration", ".", "response", ".", "body", ".", "{", "JSON", "-", "expression", "}", "where", "{", "name", "}", "is", "a", "valid", "and", "unique", "response", "header", "name", "and", "{", "JSON", "-", "expression", "}", "is", "a", "valid", "JSON", "expression", "without", "the", "$", "prefix", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-apigatewayv2/src/main/java/com/amazonaws/services/apigatewayv2/model/UpdateIntegrationResponseRequest.java#L462-L465
Azure/azure-sdk-for-java
network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/NetworkWatchersInner.java
NetworkWatchersInner.beginCheckConnectivity
public ConnectivityInformationInner beginCheckConnectivity(String resourceGroupName, String networkWatcherName, ConnectivityParameters parameters) { """ Verifies the possibility of establishing a direct TCP connection from a virtual machine to a given endpoint including another VM or an arbitrary remote server. @param resourceGroupName The name of the network watcher resource group. @param networkWatcherName The name of the network watcher resource. @param parameters Parameters that determine how the connectivity check will be performed. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the ConnectivityInformationInner object if successful. """ return beginCheckConnectivityWithServiceResponseAsync(resourceGroupName, networkWatcherName, parameters).toBlocking().single().body(); }
java
public ConnectivityInformationInner beginCheckConnectivity(String resourceGroupName, String networkWatcherName, ConnectivityParameters parameters) { return beginCheckConnectivityWithServiceResponseAsync(resourceGroupName, networkWatcherName, parameters).toBlocking().single().body(); }
[ "public", "ConnectivityInformationInner", "beginCheckConnectivity", "(", "String", "resourceGroupName", ",", "String", "networkWatcherName", ",", "ConnectivityParameters", "parameters", ")", "{", "return", "beginCheckConnectivityWithServiceResponseAsync", "(", "resourceGroupName", ",", "networkWatcherName", ",", "parameters", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Verifies the possibility of establishing a direct TCP connection from a virtual machine to a given endpoint including another VM or an arbitrary remote server. @param resourceGroupName The name of the network watcher resource group. @param networkWatcherName The name of the network watcher resource. @param parameters Parameters that determine how the connectivity check will be performed. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the ConnectivityInformationInner object if successful.
[ "Verifies", "the", "possibility", "of", "establishing", "a", "direct", "TCP", "connection", "from", "a", "virtual", "machine", "to", "a", "given", "endpoint", "including", "another", "VM", "or", "an", "arbitrary", "remote", "server", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/NetworkWatchersInner.java#L2215-L2217
apache/flink
flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/join/TimeBoundedStreamJoin.java
TimeBoundedStreamJoin.calExpirationTime
private long calExpirationTime(long operatorTime, long relativeSize) { """ Calculate the expiration time with the given operator time and relative window size. @param operatorTime the operator time @param relativeSize the relative window size @return the expiration time for cached rows """ if (operatorTime < Long.MAX_VALUE) { return operatorTime - relativeSize - allowedLateness - 1; } else { // When operatorTime = Long.MaxValue, it means the stream has reached the end. return Long.MAX_VALUE; } }
java
private long calExpirationTime(long operatorTime, long relativeSize) { if (operatorTime < Long.MAX_VALUE) { return operatorTime - relativeSize - allowedLateness - 1; } else { // When operatorTime = Long.MaxValue, it means the stream has reached the end. return Long.MAX_VALUE; } }
[ "private", "long", "calExpirationTime", "(", "long", "operatorTime", ",", "long", "relativeSize", ")", "{", "if", "(", "operatorTime", "<", "Long", ".", "MAX_VALUE", ")", "{", "return", "operatorTime", "-", "relativeSize", "-", "allowedLateness", "-", "1", ";", "}", "else", "{", "// When operatorTime = Long.MaxValue, it means the stream has reached the end.", "return", "Long", ".", "MAX_VALUE", ";", "}", "}" ]
Calculate the expiration time with the given operator time and relative window size. @param operatorTime the operator time @param relativeSize the relative window size @return the expiration time for cached rows
[ "Calculate", "the", "expiration", "time", "with", "the", "given", "operator", "time", "and", "relative", "window", "size", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/join/TimeBoundedStreamJoin.java#L348-L355
OpenLiberty/open-liberty
dev/com.ibm.ws.ejbcontainer.mdb/src/com/ibm/ws/ejbcontainer/mdb/internal/MDBRuntimeImpl.java
MDBRuntimeImpl.getRRSXAResource
@Override public XAResource getRRSXAResource(String activationSpecId, Xid xid) throws XAResourceNotAvailableException { """ Method to get the XAResource corresponding to an ActivationSpec from the RRSXAResourceFactory @param activationSpecId The id of the ActivationSpec @param xid Transaction branch qualifier @return the XAResource """ RRSXAResourceFactory factory = rrsXAResFactorySvcRef.getService(); if (factory == null) { return null; } else { return factory.getTwoPhaseXAResource(xid); } }
java
@Override public XAResource getRRSXAResource(String activationSpecId, Xid xid) throws XAResourceNotAvailableException { RRSXAResourceFactory factory = rrsXAResFactorySvcRef.getService(); if (factory == null) { return null; } else { return factory.getTwoPhaseXAResource(xid); } }
[ "@", "Override", "public", "XAResource", "getRRSXAResource", "(", "String", "activationSpecId", ",", "Xid", "xid", ")", "throws", "XAResourceNotAvailableException", "{", "RRSXAResourceFactory", "factory", "=", "rrsXAResFactorySvcRef", ".", "getService", "(", ")", ";", "if", "(", "factory", "==", "null", ")", "{", "return", "null", ";", "}", "else", "{", "return", "factory", ".", "getTwoPhaseXAResource", "(", "xid", ")", ";", "}", "}" ]
Method to get the XAResource corresponding to an ActivationSpec from the RRSXAResourceFactory @param activationSpecId The id of the ActivationSpec @param xid Transaction branch qualifier @return the XAResource
[ "Method", "to", "get", "the", "XAResource", "corresponding", "to", "an", "ActivationSpec", "from", "the", "RRSXAResourceFactory" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ejbcontainer.mdb/src/com/ibm/ws/ejbcontainer/mdb/internal/MDBRuntimeImpl.java#L408-L417
wildfly/wildfly-core
cli/src/main/java/org/jboss/as/cli/scriptsupport/CLI.java
CLI.cmd
public Result cmd(String cliCommand) { """ Execute a CLI command. This can be any command that you might execute on the CLI command line, including both server-side operations and local commands such as 'cd' or 'cn'. @param cliCommand A CLI command. @return A result object that provides all information about the execution of the command. """ try { // The intent here is to return a Response when this is doable. if (ctx.isWorkflowMode() || ctx.isBatchMode()) { ctx.handle(cliCommand); return new Result(cliCommand, ctx.getExitCode()); } handler.parse(ctx.getCurrentNodePath(), cliCommand, ctx); if (handler.getFormat() == OperationFormat.INSTANCE) { ModelNode request = ctx.buildRequest(cliCommand); ModelNode response = ctx.execute(request, cliCommand); return new Result(cliCommand, request, response); } else { ctx.handle(cliCommand); return new Result(cliCommand, ctx.getExitCode()); } } catch (CommandLineException cfe) { throw new IllegalArgumentException("Error handling command: " + cliCommand, cfe); } catch (IOException ioe) { throw new IllegalStateException("Unable to send command " + cliCommand + " to server.", ioe); } }
java
public Result cmd(String cliCommand) { try { // The intent here is to return a Response when this is doable. if (ctx.isWorkflowMode() || ctx.isBatchMode()) { ctx.handle(cliCommand); return new Result(cliCommand, ctx.getExitCode()); } handler.parse(ctx.getCurrentNodePath(), cliCommand, ctx); if (handler.getFormat() == OperationFormat.INSTANCE) { ModelNode request = ctx.buildRequest(cliCommand); ModelNode response = ctx.execute(request, cliCommand); return new Result(cliCommand, request, response); } else { ctx.handle(cliCommand); return new Result(cliCommand, ctx.getExitCode()); } } catch (CommandLineException cfe) { throw new IllegalArgumentException("Error handling command: " + cliCommand, cfe); } catch (IOException ioe) { throw new IllegalStateException("Unable to send command " + cliCommand + " to server.", ioe); } }
[ "public", "Result", "cmd", "(", "String", "cliCommand", ")", "{", "try", "{", "// The intent here is to return a Response when this is doable.", "if", "(", "ctx", ".", "isWorkflowMode", "(", ")", "||", "ctx", ".", "isBatchMode", "(", ")", ")", "{", "ctx", ".", "handle", "(", "cliCommand", ")", ";", "return", "new", "Result", "(", "cliCommand", ",", "ctx", ".", "getExitCode", "(", ")", ")", ";", "}", "handler", ".", "parse", "(", "ctx", ".", "getCurrentNodePath", "(", ")", ",", "cliCommand", ",", "ctx", ")", ";", "if", "(", "handler", ".", "getFormat", "(", ")", "==", "OperationFormat", ".", "INSTANCE", ")", "{", "ModelNode", "request", "=", "ctx", ".", "buildRequest", "(", "cliCommand", ")", ";", "ModelNode", "response", "=", "ctx", ".", "execute", "(", "request", ",", "cliCommand", ")", ";", "return", "new", "Result", "(", "cliCommand", ",", "request", ",", "response", ")", ";", "}", "else", "{", "ctx", ".", "handle", "(", "cliCommand", ")", ";", "return", "new", "Result", "(", "cliCommand", ",", "ctx", ".", "getExitCode", "(", ")", ")", ";", "}", "}", "catch", "(", "CommandLineException", "cfe", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Error handling command: \"", "+", "cliCommand", ",", "cfe", ")", ";", "}", "catch", "(", "IOException", "ioe", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Unable to send command \"", "+", "cliCommand", "+", "\" to server.\"", ",", "ioe", ")", ";", "}", "}" ]
Execute a CLI command. This can be any command that you might execute on the CLI command line, including both server-side operations and local commands such as 'cd' or 'cn'. @param cliCommand A CLI command. @return A result object that provides all information about the execution of the command.
[ "Execute", "a", "CLI", "command", ".", "This", "can", "be", "any", "command", "that", "you", "might", "execute", "on", "the", "CLI", "command", "line", "including", "both", "server", "-", "side", "operations", "and", "local", "commands", "such", "as", "cd", "or", "cn", "." ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/cli/src/main/java/org/jboss/as/cli/scriptsupport/CLI.java#L231-L254
alkacon/opencms-core
src/org/opencms/xml/page/CmsXmlPage.java
CmsXmlPage.getLinkTable
public CmsLinkTable getLinkTable(String name, Locale locale) { """ Returns the link table of an element.<p> @param name name of the element @param locale locale of the element @return the link table """ CmsXmlHtmlValue value = (CmsXmlHtmlValue)getValue(name, locale); if (value != null) { return value.getLinkTable(); } return new CmsLinkTable(); }
java
public CmsLinkTable getLinkTable(String name, Locale locale) { CmsXmlHtmlValue value = (CmsXmlHtmlValue)getValue(name, locale); if (value != null) { return value.getLinkTable(); } return new CmsLinkTable(); }
[ "public", "CmsLinkTable", "getLinkTable", "(", "String", "name", ",", "Locale", "locale", ")", "{", "CmsXmlHtmlValue", "value", "=", "(", "CmsXmlHtmlValue", ")", "getValue", "(", "name", ",", "locale", ")", ";", "if", "(", "value", "!=", "null", ")", "{", "return", "value", ".", "getLinkTable", "(", ")", ";", "}", "return", "new", "CmsLinkTable", "(", ")", ";", "}" ]
Returns the link table of an element.<p> @param name name of the element @param locale locale of the element @return the link table
[ "Returns", "the", "link", "table", "of", "an", "element", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/page/CmsXmlPage.java#L295-L302
kefirfromperm/kefirbb
src/org/kefirsf/bb/DomConfigurationFactory.java
DomConfigurationFactory.parseConstant
private Constant parseConstant(Node el, boolean ignoreCase) { """ Parse constant pattern element @param el DOM element @param ignoreCase if true the constant must ignore case @return constant definition """ return new Constant( nodeAttribute(el, TAG_CONSTANT_ATTR_VALUE), nodeAttribute(el, TAG_CONSTANT_ATTR_IGNORE_CASE, ignoreCase), nodeAttribute(el, TAG_ATTR_GHOST, PatternElement.DEFAULT_GHOST_VALUE) ); }
java
private Constant parseConstant(Node el, boolean ignoreCase) { return new Constant( nodeAttribute(el, TAG_CONSTANT_ATTR_VALUE), nodeAttribute(el, TAG_CONSTANT_ATTR_IGNORE_CASE, ignoreCase), nodeAttribute(el, TAG_ATTR_GHOST, PatternElement.DEFAULT_GHOST_VALUE) ); }
[ "private", "Constant", "parseConstant", "(", "Node", "el", ",", "boolean", "ignoreCase", ")", "{", "return", "new", "Constant", "(", "nodeAttribute", "(", "el", ",", "TAG_CONSTANT_ATTR_VALUE", ")", ",", "nodeAttribute", "(", "el", ",", "TAG_CONSTANT_ATTR_IGNORE_CASE", ",", "ignoreCase", ")", ",", "nodeAttribute", "(", "el", ",", "TAG_ATTR_GHOST", ",", "PatternElement", ".", "DEFAULT_GHOST_VALUE", ")", ")", ";", "}" ]
Parse constant pattern element @param el DOM element @param ignoreCase if true the constant must ignore case @return constant definition
[ "Parse", "constant", "pattern", "element" ]
train
https://github.com/kefirfromperm/kefirbb/blob/8c36fc3d3dc27459b0cdc179b87582df30420856/src/org/kefirsf/bb/DomConfigurationFactory.java#L454-L460
kuali/ojb-1.0.4
src/java/org/apache/ojb/broker/query/Criteria.java
Criteria.addNotEqualToColumn
public void addNotEqualToColumn(String attribute, String colName) { """ Adds and equals (<>) criteria for column comparison. The column Name will NOT be translated. <br> name <> T_BOSS.LASTNMAE @param attribute The field name to be used @param colName The name of the column to compare with """ // PAW // FieldCriteria c = FieldCriteria.buildNotEqualToCriteria(attribute, colName, getAlias()); FieldCriteria c = FieldCriteria.buildNotEqualToCriteria(attribute, colName, getUserAlias(attribute)); c.setTranslateField(false); addSelectionCriteria(c); }
java
public void addNotEqualToColumn(String attribute, String colName) { // PAW // FieldCriteria c = FieldCriteria.buildNotEqualToCriteria(attribute, colName, getAlias()); FieldCriteria c = FieldCriteria.buildNotEqualToCriteria(attribute, colName, getUserAlias(attribute)); c.setTranslateField(false); addSelectionCriteria(c); }
[ "public", "void", "addNotEqualToColumn", "(", "String", "attribute", ",", "String", "colName", ")", "{", "// PAW\r", "// FieldCriteria c = FieldCriteria.buildNotEqualToCriteria(attribute, colName, getAlias());\r", "FieldCriteria", "c", "=", "FieldCriteria", ".", "buildNotEqualToCriteria", "(", "attribute", ",", "colName", ",", "getUserAlias", "(", "attribute", ")", ")", ";", "c", ".", "setTranslateField", "(", "false", ")", ";", "addSelectionCriteria", "(", "c", ")", ";", "}" ]
Adds and equals (<>) criteria for column comparison. The column Name will NOT be translated. <br> name <> T_BOSS.LASTNMAE @param attribute The field name to be used @param colName The name of the column to compare with
[ "Adds", "and", "equals", "(", "<", ">", ")", "criteria", "for", "column", "comparison", ".", "The", "column", "Name", "will", "NOT", "be", "translated", ".", "<br", ">", "name", "<", ">", "T_BOSS", ".", "LASTNMAE" ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/query/Criteria.java#L374-L381
ontop/ontop
client/protege/src/main/java/it/unibz/inf/ontop/protege/utils/JDBCConnectionManager.java
JDBCConnectionManager.createConnection
public Connection createConnection(String url, String username, String password) throws SQLException { """ Constructs a new database connection object and retrieves it. @return The connection object. @throws SQLException """ if (connection != null && !connection.isClosed()) return connection; connection = DriverManager.getConnection(url, username, password); return connection; }
java
public Connection createConnection(String url, String username, String password) throws SQLException { if (connection != null && !connection.isClosed()) return connection; connection = DriverManager.getConnection(url, username, password); return connection; }
[ "public", "Connection", "createConnection", "(", "String", "url", ",", "String", "username", ",", "String", "password", ")", "throws", "SQLException", "{", "if", "(", "connection", "!=", "null", "&&", "!", "connection", ".", "isClosed", "(", ")", ")", "return", "connection", ";", "connection", "=", "DriverManager", ".", "getConnection", "(", "url", ",", "username", ",", "password", ")", ";", "return", "connection", ";", "}" ]
Constructs a new database connection object and retrieves it. @return The connection object. @throws SQLException
[ "Constructs", "a", "new", "database", "connection", "object", "and", "retrieves", "it", "." ]
train
https://github.com/ontop/ontop/blob/ddf78b26981b6129ee9a1a59310016830f5352e4/client/protege/src/main/java/it/unibz/inf/ontop/protege/utils/JDBCConnectionManager.java#L79-L86
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/io/stream/NonBlockingBitOutputStream.java
NonBlockingBitOutputStream.writeBits
public void writeBits (final int aValue, @Nonnegative final int nNumBits) throws IOException { """ Write the specified number of bits from the int value to the stream. Corresponding to the InputStream, the bits are written starting at the highest bit ( &gt;&gt; aNumberOfBits ), going down to the lowest bit ( &gt;&gt; 0 ). @param aValue the int containing the bits that should be written to the stream. @param nNumBits how many bits of the integer should be written to the stream. @throws IOException In case writing to the output stream failed """ ValueEnforcer.isBetweenInclusive (nNumBits, "NumberOfBits", 1, CGlobal.BITS_PER_INT); for (int i = nNumBits - 1; i >= 0; i--) writeBit ((aValue >> i) & 1); } /** * Write the current cache to the stream and reset the buffer. * * @throws IOException * In case writing to the output stream failed */ public void flush () throws IOException { if (m_nBufferedBitCount > 0) { if (m_nBufferedBitCount != CGlobal.BITS_PER_BYTE) if (LOGGER.isDebugEnabled ()) LOGGER.debug ("Flushing BitOutputStream with only " + m_nBufferedBitCount + " bits"); m_aOS.write ((byte) m_nBuffer); m_nBufferedBitCount = 0; m_nBuffer = 0; } } /** * Flush the data and close the underlying output stream. */ public void close () { StreamHelper.flush (this); StreamHelper.close (m_aOS); m_aOS = null; } @Override public String toString () { return new ToStringGenerator (this).append ("OS", m_aOS) .append ("highOrderBitFirst", m_bHighOrderBitFirst) .append ("buffer", m_nBuffer) .append ("bitCount", m_nBufferedBitCount) .getToString (); } }
java
public void writeBits (final int aValue, @Nonnegative final int nNumBits) throws IOException { ValueEnforcer.isBetweenInclusive (nNumBits, "NumberOfBits", 1, CGlobal.BITS_PER_INT); for (int i = nNumBits - 1; i >= 0; i--) writeBit ((aValue >> i) & 1); } /** * Write the current cache to the stream and reset the buffer. * * @throws IOException * In case writing to the output stream failed */ public void flush () throws IOException { if (m_nBufferedBitCount > 0) { if (m_nBufferedBitCount != CGlobal.BITS_PER_BYTE) if (LOGGER.isDebugEnabled ()) LOGGER.debug ("Flushing BitOutputStream with only " + m_nBufferedBitCount + " bits"); m_aOS.write ((byte) m_nBuffer); m_nBufferedBitCount = 0; m_nBuffer = 0; } } /** * Flush the data and close the underlying output stream. */ public void close () { StreamHelper.flush (this); StreamHelper.close (m_aOS); m_aOS = null; } @Override public String toString () { return new ToStringGenerator (this).append ("OS", m_aOS) .append ("highOrderBitFirst", m_bHighOrderBitFirst) .append ("buffer", m_nBuffer) .append ("bitCount", m_nBufferedBitCount) .getToString (); } }
[ "public", "void", "writeBits", "(", "final", "int", "aValue", ",", "@", "Nonnegative", "final", "int", "nNumBits", ")", "throws", "IOException", "{", "ValueEnforcer", ".", "isBetweenInclusive", "(", "nNumBits", ",", "\"NumberOfBits\"", ",", "1", ",", "CGlobal", ".", "BITS_PER_INT", ")", ";", "for", "(", "int", "i", "=", "nNumBits", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "writeBit", "(", "(", "aValue", ">>", "i", ")", "&", "1", ")", ";", "}", "/**\n * Write the current cache to the stream and reset the buffer.\n *\n * @throws IOException\n * In case writing to the output stream failed\n */", "public", "void", "flush", "(", ")", "throws", "IOException", "{", "if", "(", "m_nBufferedBitCount", ">", "0", ")", "{", "if", "(", "m_nBufferedBitCount", "!=", "CGlobal", ".", "BITS_PER_BYTE", ")", "if", "(", "LOGGER", ".", "isDebugEnabled", "(", ")", ")", "LOGGER", ".", "debug", "(", "\"Flushing BitOutputStream with only \"", "+", "m_nBufferedBitCount", "+", "\" bits\"", ")", ";", "m_aOS", ".", "write", "(", "(", "byte", ")", "m_nBuffer", ")", ";", "m_nBufferedBitCount", "=", "0", ";", "m_nBuffer", "=", "0", ";", "}", "}", "/**\n * Flush the data and close the underlying output stream.\n */", "public", "void", "close", "", "(", ")", "{", "StreamHelper", ".", "flush", "(", "this", ")", ";", "StreamHelper", ".", "close", "(", "m_aOS", ")", ";", "m_aOS", "=", "null", ";", "}", "@", "Override", "public", "String", "toString", "", "(", ")", "{", "return", "new", "ToStringGenerator", "(", "this", ")", ".", "append", "(", "\"OS\"", ",", "m_aOS", ")", ".", "append", "(", "\"highOrderBitFirst\"", ",", "m_bHighOrderBitFirst", ")", ".", "append", "(", "\"buffer\"", ",", "m_nBuffer", ")", ".", "append", "(", "\"bitCount\"", ",", "m_nBufferedBitCount", ")", ".", "getToString", "(", ")", ";", "}", "}" ]
Write the specified number of bits from the int value to the stream. Corresponding to the InputStream, the bits are written starting at the highest bit ( &gt;&gt; aNumberOfBits ), going down to the lowest bit ( &gt;&gt; 0 ). @param aValue the int containing the bits that should be written to the stream. @param nNumBits how many bits of the integer should be written to the stream. @throws IOException In case writing to the output stream failed
[ "Write", "the", "specified", "number", "of", "bits", "from", "the", "int", "value", "to", "the", "stream", ".", "Corresponding", "to", "the", "InputStream", "the", "bits", "are", "written", "starting", "at", "the", "highest", "bit", "(", "&gt", ";", "&gt", ";", "aNumberOfBits", ")", "going", "down", "to", "the", "lowest", "bit", "(", "&gt", ";", "&gt", ";", "0", ")", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/io/stream/NonBlockingBitOutputStream.java#L138-L184
lionsoul2014/jcseg
jcseg-core/src/main/java/org/lionsoul/jcseg/tokenizer/core/ADictionary.java
ADictionary.resetSuffixLength
public static boolean resetSuffixLength(JcsegTaskConfig config, ADictionary dic, int mixLength) { """ check and reset the value of the {@link ADictionary#mixSuffixLength} @param config @param dic @param mixLength @return boolean """ if ( mixLength <= config.MAX_LENGTH && mixLength > dic.mixSuffixLength ) { dic.mixSuffixLength = mixLength; return true; } return false; }
java
public static boolean resetSuffixLength(JcsegTaskConfig config, ADictionary dic, int mixLength) { if ( mixLength <= config.MAX_LENGTH && mixLength > dic.mixSuffixLength ) { dic.mixSuffixLength = mixLength; return true; } return false; }
[ "public", "static", "boolean", "resetSuffixLength", "(", "JcsegTaskConfig", "config", ",", "ADictionary", "dic", ",", "int", "mixLength", ")", "{", "if", "(", "mixLength", "<=", "config", ".", "MAX_LENGTH", "&&", "mixLength", ">", "dic", ".", "mixSuffixLength", ")", "{", "dic", ".", "mixSuffixLength", "=", "mixLength", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
check and reset the value of the {@link ADictionary#mixSuffixLength} @param config @param dic @param mixLength @return boolean
[ "check", "and", "reset", "the", "value", "of", "the", "{", "@link", "ADictionary#mixSuffixLength", "}" ]
train
https://github.com/lionsoul2014/jcseg/blob/7c8a912e3bbcaf4f8de701180b9c24e2e444a94b/jcseg-core/src/main/java/org/lionsoul/jcseg/tokenizer/core/ADictionary.java#L852-L861
minio/minio-java
api/src/main/java/io/minio/MinioClient.java
MinioClient.completeMultipart
private void completeMultipart(String bucketName, String objectName, String uploadId, Part[] parts) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException { """ Executes complete multipart upload of given bucket name, object name, upload ID and parts. """ Map<String,String> queryParamMap = new HashMap<>(); queryParamMap.put(UPLOAD_ID, uploadId); CompleteMultipartUpload completeManifest = new CompleteMultipartUpload(parts); HttpResponse response = executePost(bucketName, objectName, null, queryParamMap, completeManifest); // Fixing issue https://github.com/minio/minio-java/issues/391 String bodyContent = ""; Scanner scanner = new Scanner(response.body().charStream()); try { // read entire body stream to string. scanner.useDelimiter("\\A"); if (scanner.hasNext()) { bodyContent = scanner.next(); } } finally { response.body().close(); scanner.close(); } bodyContent = bodyContent.trim(); if (!bodyContent.isEmpty()) { ErrorResponse errorResponse = new ErrorResponse(new StringReader(bodyContent)); if (errorResponse.code() != null) { throw new ErrorResponseException(errorResponse, response.response()); } } }
java
private void completeMultipart(String bucketName, String objectName, String uploadId, Part[] parts) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException { Map<String,String> queryParamMap = new HashMap<>(); queryParamMap.put(UPLOAD_ID, uploadId); CompleteMultipartUpload completeManifest = new CompleteMultipartUpload(parts); HttpResponse response = executePost(bucketName, objectName, null, queryParamMap, completeManifest); // Fixing issue https://github.com/minio/minio-java/issues/391 String bodyContent = ""; Scanner scanner = new Scanner(response.body().charStream()); try { // read entire body stream to string. scanner.useDelimiter("\\A"); if (scanner.hasNext()) { bodyContent = scanner.next(); } } finally { response.body().close(); scanner.close(); } bodyContent = bodyContent.trim(); if (!bodyContent.isEmpty()) { ErrorResponse errorResponse = new ErrorResponse(new StringReader(bodyContent)); if (errorResponse.code() != null) { throw new ErrorResponseException(errorResponse, response.response()); } } }
[ "private", "void", "completeMultipart", "(", "String", "bucketName", ",", "String", "objectName", ",", "String", "uploadId", ",", "Part", "[", "]", "parts", ")", "throws", "InvalidBucketNameException", ",", "NoSuchAlgorithmException", ",", "InsufficientDataException", ",", "IOException", ",", "InvalidKeyException", ",", "NoResponseException", ",", "XmlPullParserException", ",", "ErrorResponseException", ",", "InternalException", "{", "Map", "<", "String", ",", "String", ">", "queryParamMap", "=", "new", "HashMap", "<>", "(", ")", ";", "queryParamMap", ".", "put", "(", "UPLOAD_ID", ",", "uploadId", ")", ";", "CompleteMultipartUpload", "completeManifest", "=", "new", "CompleteMultipartUpload", "(", "parts", ")", ";", "HttpResponse", "response", "=", "executePost", "(", "bucketName", ",", "objectName", ",", "null", ",", "queryParamMap", ",", "completeManifest", ")", ";", "// Fixing issue https://github.com/minio/minio-java/issues/391", "String", "bodyContent", "=", "\"\"", ";", "Scanner", "scanner", "=", "new", "Scanner", "(", "response", ".", "body", "(", ")", ".", "charStream", "(", ")", ")", ";", "try", "{", "// read entire body stream to string.", "scanner", ".", "useDelimiter", "(", "\"\\\\A\"", ")", ";", "if", "(", "scanner", ".", "hasNext", "(", ")", ")", "{", "bodyContent", "=", "scanner", ".", "next", "(", ")", ";", "}", "}", "finally", "{", "response", ".", "body", "(", ")", ".", "close", "(", ")", ";", "scanner", ".", "close", "(", ")", ";", "}", "bodyContent", "=", "bodyContent", ".", "trim", "(", ")", ";", "if", "(", "!", "bodyContent", ".", "isEmpty", "(", ")", ")", "{", "ErrorResponse", "errorResponse", "=", "new", "ErrorResponse", "(", "new", "StringReader", "(", "bodyContent", ")", ")", ";", "if", "(", "errorResponse", ".", "code", "(", ")", "!=", "null", ")", "{", "throw", "new", "ErrorResponseException", "(", "errorResponse", ",", "response", ".", "response", "(", ")", ")", ";", "}", "}", "}" ]
Executes complete multipart upload of given bucket name, object name, upload ID and parts.
[ "Executes", "complete", "multipart", "upload", "of", "given", "bucket", "name", "object", "name", "upload", "ID", "and", "parts", "." ]
train
https://github.com/minio/minio-java/blob/b2028f56403c89ce2d5900ae813bc1314c87bc7f/api/src/main/java/io/minio/MinioClient.java#L4746-L4778
Azure/azure-sdk-for-java
sql/resource-manager/v2017_10_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_10_01_preview/implementation/ElasticPoolsInner.java
ElasticPoolsInner.listByServerAsync
public Observable<Page<ElasticPoolInner>> listByServerAsync(final String resourceGroupName, final String serverName, final Integer skip) { """ Gets all elastic pools in a server. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @param skip The number of elements in the collection to skip. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;ElasticPoolInner&gt; object """ return listByServerWithServiceResponseAsync(resourceGroupName, serverName, skip) .map(new Func1<ServiceResponse<Page<ElasticPoolInner>>, Page<ElasticPoolInner>>() { @Override public Page<ElasticPoolInner> call(ServiceResponse<Page<ElasticPoolInner>> response) { return response.body(); } }); }
java
public Observable<Page<ElasticPoolInner>> listByServerAsync(final String resourceGroupName, final String serverName, final Integer skip) { return listByServerWithServiceResponseAsync(resourceGroupName, serverName, skip) .map(new Func1<ServiceResponse<Page<ElasticPoolInner>>, Page<ElasticPoolInner>>() { @Override public Page<ElasticPoolInner> call(ServiceResponse<Page<ElasticPoolInner>> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Page", "<", "ElasticPoolInner", ">", ">", "listByServerAsync", "(", "final", "String", "resourceGroupName", ",", "final", "String", "serverName", ",", "final", "Integer", "skip", ")", "{", "return", "listByServerWithServiceResponseAsync", "(", "resourceGroupName", ",", "serverName", ",", "skip", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "Page", "<", "ElasticPoolInner", ">", ">", ",", "Page", "<", "ElasticPoolInner", ">", ">", "(", ")", "{", "@", "Override", "public", "Page", "<", "ElasticPoolInner", ">", "call", "(", "ServiceResponse", "<", "Page", "<", "ElasticPoolInner", ">", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Gets all elastic pools in a server. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @param skip The number of elements in the collection to skip. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;ElasticPoolInner&gt; object
[ "Gets", "all", "elastic", "pools", "in", "a", "server", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2017_10_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_10_01_preview/implementation/ElasticPoolsInner.java#L273-L281
wuman/orientdb-android
core/src/main/java/com/orientechnologies/orient/core/db/graph/OGraphDatabase.java
OGraphDatabase.getEdgesBetweenVertexes
public Set<ODocument> getEdgesBetweenVertexes(final ODocument iVertex1, final ODocument iVertex2, final String[] iLabels) { """ Returns all the edges between the vertexes iVertex1 and iVertex2 with label between the array of labels passed as iLabels. @param iVertex1 First Vertex @param iVertex2 Second Vertex @param iLabels Array of strings with the labels to get as filter @return The Set with the common Edges between the two vertexes. If edges aren't found the set is empty """ return getEdgesBetweenVertexes(iVertex1, iVertex2, iLabels, null); }
java
public Set<ODocument> getEdgesBetweenVertexes(final ODocument iVertex1, final ODocument iVertex2, final String[] iLabels) { return getEdgesBetweenVertexes(iVertex1, iVertex2, iLabels, null); }
[ "public", "Set", "<", "ODocument", ">", "getEdgesBetweenVertexes", "(", "final", "ODocument", "iVertex1", ",", "final", "ODocument", "iVertex2", ",", "final", "String", "[", "]", "iLabels", ")", "{", "return", "getEdgesBetweenVertexes", "(", "iVertex1", ",", "iVertex2", ",", "iLabels", ",", "null", ")", ";", "}" ]
Returns all the edges between the vertexes iVertex1 and iVertex2 with label between the array of labels passed as iLabels. @param iVertex1 First Vertex @param iVertex2 Second Vertex @param iLabels Array of strings with the labels to get as filter @return The Set with the common Edges between the two vertexes. If edges aren't found the set is empty
[ "Returns", "all", "the", "edges", "between", "the", "vertexes", "iVertex1", "and", "iVertex2", "with", "label", "between", "the", "array", "of", "labels", "passed", "as", "iLabels", "." ]
train
https://github.com/wuman/orientdb-android/blob/ff9b17e4349f26168b2d0c4facb1a18cbfbe8cf0/core/src/main/java/com/orientechnologies/orient/core/db/graph/OGraphDatabase.java#L353-L355
GoogleCloudPlatform/bigdata-interop
gcsio/src/main/java/com/google/cloud/hadoop/gcsio/PrefixMappedItemCache.java
PrefixMappedItemCache.containsListRaw
@VisibleForTesting boolean containsListRaw(String bucket, String objectName) { """ Checks if the prefix map contains an exact entry for the given bucket/objectName. """ return prefixMap.containsKey(new PrefixKey(bucket, objectName)); }
java
@VisibleForTesting boolean containsListRaw(String bucket, String objectName) { return prefixMap.containsKey(new PrefixKey(bucket, objectName)); }
[ "@", "VisibleForTesting", "boolean", "containsListRaw", "(", "String", "bucket", ",", "String", "objectName", ")", "{", "return", "prefixMap", ".", "containsKey", "(", "new", "PrefixKey", "(", "bucket", ",", "objectName", ")", ")", ";", "}" ]
Checks if the prefix map contains an exact entry for the given bucket/objectName.
[ "Checks", "if", "the", "prefix", "map", "contains", "an", "exact", "entry", "for", "the", "given", "bucket", "/", "objectName", "." ]
train
https://github.com/GoogleCloudPlatform/bigdata-interop/blob/918d91c80a63e36046edb28972a5c65d3326a858/gcsio/src/main/java/com/google/cloud/hadoop/gcsio/PrefixMappedItemCache.java#L318-L321
casmi/casmi
src/main/java/casmi/graphics/element/Ellipse.java
Ellipse.setCenterColor
public void setCenterColor(Color color) { """ Sets the color of this Ellipse's center. @param color The color of the Ellipse's center. """ if (centerColor == null) { centerColor = new RGBColor(0.0, 0.0, 0.0); } setGradation(true); this.centerColor = color; }
java
public void setCenterColor(Color color) { if (centerColor == null) { centerColor = new RGBColor(0.0, 0.0, 0.0); } setGradation(true); this.centerColor = color; }
[ "public", "void", "setCenterColor", "(", "Color", "color", ")", "{", "if", "(", "centerColor", "==", "null", ")", "{", "centerColor", "=", "new", "RGBColor", "(", "0.0", ",", "0.0", ",", "0.0", ")", ";", "}", "setGradation", "(", "true", ")", ";", "this", ".", "centerColor", "=", "color", ";", "}" ]
Sets the color of this Ellipse's center. @param color The color of the Ellipse's center.
[ "Sets", "the", "color", "of", "this", "Ellipse", "s", "center", "." ]
train
https://github.com/casmi/casmi/blob/90f6514a9cbce0685186e7a92beb69e22a3b11c4/src/main/java/casmi/graphics/element/Ellipse.java#L313-L319
sebastiangraf/treetank
interfacemodules/xml/src/main/java/org/treetank/service/xml/xpath/PipelineBuilder.java
PipelineBuilder.addPredicate
public void addPredicate(final INodeReadTrx mTransaction) { """ Adds a predicate to the pipeline. @param mTransaction Transaction to operate with. """ assert getPipeStack().size() >= 2; final AbsAxis mPredicate = getPipeStack().pop().getExpr(); if (mPredicate instanceof LiteralExpr) { mPredicate.hasNext(); // if is numeric literal -> abbrev for position() final int type = mTransaction.getNode().getTypeKey(); if (type == NamePageHash.generateHashForString("xs:integer") || type == NamePageHash.generateHashForString("xs:double") || type == NamePageHash.generateHashForString("xs:float") || type == NamePageHash.generateHashForString("xs:decimal")) { throw new IllegalStateException("function fn:position() is not implemented yet."); // getExpression().add( // new PosFilter(transaction, (int) // Double.parseDouble(transaction // .getValue()))); // return; // TODO: YES! it is dirty! // AtomicValue pos = // new AtomicValue(mTransaction.getNode().getRawValue(), // mTransaction // .keyForName("xs:integer")); // long position = mTransaction.getItemList().addItem(pos); // mPredicate.reset(mTransaction.getNode().getNodeKey()); // IAxis function = // new FNPosition(mTransaction, new ArrayList<IAxis>(), // FuncDef.POS.getMin(), FuncDef.POS // .getMax(), // mTransaction.keyForName(FuncDef.POS.getReturnType())); // IAxis expectedPos = new LiteralExpr(mTransaction, position); // // mPredicate = new ValueComp(mTransaction, function, // expectedPos, CompKind.EQ); } } getExpression().add(new PredicateFilterAxis(mTransaction, mPredicate)); }
java
public void addPredicate(final INodeReadTrx mTransaction) { assert getPipeStack().size() >= 2; final AbsAxis mPredicate = getPipeStack().pop().getExpr(); if (mPredicate instanceof LiteralExpr) { mPredicate.hasNext(); // if is numeric literal -> abbrev for position() final int type = mTransaction.getNode().getTypeKey(); if (type == NamePageHash.generateHashForString("xs:integer") || type == NamePageHash.generateHashForString("xs:double") || type == NamePageHash.generateHashForString("xs:float") || type == NamePageHash.generateHashForString("xs:decimal")) { throw new IllegalStateException("function fn:position() is not implemented yet."); // getExpression().add( // new PosFilter(transaction, (int) // Double.parseDouble(transaction // .getValue()))); // return; // TODO: YES! it is dirty! // AtomicValue pos = // new AtomicValue(mTransaction.getNode().getRawValue(), // mTransaction // .keyForName("xs:integer")); // long position = mTransaction.getItemList().addItem(pos); // mPredicate.reset(mTransaction.getNode().getNodeKey()); // IAxis function = // new FNPosition(mTransaction, new ArrayList<IAxis>(), // FuncDef.POS.getMin(), FuncDef.POS // .getMax(), // mTransaction.keyForName(FuncDef.POS.getReturnType())); // IAxis expectedPos = new LiteralExpr(mTransaction, position); // // mPredicate = new ValueComp(mTransaction, function, // expectedPos, CompKind.EQ); } } getExpression().add(new PredicateFilterAxis(mTransaction, mPredicate)); }
[ "public", "void", "addPredicate", "(", "final", "INodeReadTrx", "mTransaction", ")", "{", "assert", "getPipeStack", "(", ")", ".", "size", "(", ")", ">=", "2", ";", "final", "AbsAxis", "mPredicate", "=", "getPipeStack", "(", ")", ".", "pop", "(", ")", ".", "getExpr", "(", ")", ";", "if", "(", "mPredicate", "instanceof", "LiteralExpr", ")", "{", "mPredicate", ".", "hasNext", "(", ")", ";", "// if is numeric literal -> abbrev for position()", "final", "int", "type", "=", "mTransaction", ".", "getNode", "(", ")", ".", "getTypeKey", "(", ")", ";", "if", "(", "type", "==", "NamePageHash", ".", "generateHashForString", "(", "\"xs:integer\"", ")", "||", "type", "==", "NamePageHash", ".", "generateHashForString", "(", "\"xs:double\"", ")", "||", "type", "==", "NamePageHash", ".", "generateHashForString", "(", "\"xs:float\"", ")", "||", "type", "==", "NamePageHash", ".", "generateHashForString", "(", "\"xs:decimal\"", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"function fn:position() is not implemented yet.\"", ")", ";", "// getExpression().add(", "// new PosFilter(transaction, (int)", "// Double.parseDouble(transaction", "// .getValue())));", "// return; // TODO: YES! it is dirty!", "// AtomicValue pos =", "// new AtomicValue(mTransaction.getNode().getRawValue(),", "// mTransaction", "// .keyForName(\"xs:integer\"));", "// long position = mTransaction.getItemList().addItem(pos);", "// mPredicate.reset(mTransaction.getNode().getNodeKey());", "// IAxis function =", "// new FNPosition(mTransaction, new ArrayList<IAxis>(),", "// FuncDef.POS.getMin(), FuncDef.POS", "// .getMax(),", "// mTransaction.keyForName(FuncDef.POS.getReturnType()));", "// IAxis expectedPos = new LiteralExpr(mTransaction, position);", "//", "// mPredicate = new ValueComp(mTransaction, function,", "// expectedPos, CompKind.EQ);", "}", "}", "getExpression", "(", ")", ".", "add", "(", "new", "PredicateFilterAxis", "(", "mTransaction", ",", "mPredicate", ")", ")", ";", "}" ]
Adds a predicate to the pipeline. @param mTransaction Transaction to operate with.
[ "Adds", "a", "predicate", "to", "the", "pipeline", "." ]
train
https://github.com/sebastiangraf/treetank/blob/9b96d631b6c2a8502a0cc958dcb02bd6a6fd8b60/interfacemodules/xml/src/main/java/org/treetank/service/xml/xpath/PipelineBuilder.java#L537-L582
alkacon/opencms-core
src/org/opencms/db/CmsSecurityManager.java
CmsSecurityManager.writePropertyObject
public void writePropertyObject(CmsRequestContext context, CmsResource resource, CmsProperty property) throws CmsException, CmsSecurityException { """ Writes a property for a specified resource.<p> @param context the current request context @param resource the resource to write the property for @param property the property to write @throws CmsException if something goes wrong @throws CmsSecurityException if the user has insufficient permission for the given resource ({@link CmsPermissionSet#ACCESS_WRITE} required) @see CmsObject#writePropertyObject(String, CmsProperty) @see org.opencms.file.types.I_CmsResourceType#writePropertyObject(CmsObject, CmsSecurityManager, CmsResource, CmsProperty) """ CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.IGNORE_EXPIRATION); m_driverManager.writePropertyObject(dbc, resource, property); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_WRITE_PROP_2, property.getName(), context.getSitePath(resource)), e); } finally { dbc.clear(); } }
java
public void writePropertyObject(CmsRequestContext context, CmsResource resource, CmsProperty property) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.IGNORE_EXPIRATION); m_driverManager.writePropertyObject(dbc, resource, property); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_WRITE_PROP_2, property.getName(), context.getSitePath(resource)), e); } finally { dbc.clear(); } }
[ "public", "void", "writePropertyObject", "(", "CmsRequestContext", "context", ",", "CmsResource", "resource", ",", "CmsProperty", "property", ")", "throws", "CmsException", ",", "CmsSecurityException", "{", "CmsDbContext", "dbc", "=", "m_dbContextFactory", ".", "getDbContext", "(", "context", ")", ";", "try", "{", "checkOfflineProject", "(", "dbc", ")", ";", "checkPermissions", "(", "dbc", ",", "resource", ",", "CmsPermissionSet", ".", "ACCESS_WRITE", ",", "true", ",", "CmsResourceFilter", ".", "IGNORE_EXPIRATION", ")", ";", "m_driverManager", ".", "writePropertyObject", "(", "dbc", ",", "resource", ",", "property", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "dbc", ".", "report", "(", "null", ",", "Messages", ".", "get", "(", ")", ".", "container", "(", "Messages", ".", "ERR_WRITE_PROP_2", ",", "property", ".", "getName", "(", ")", ",", "context", ".", "getSitePath", "(", "resource", ")", ")", ",", "e", ")", ";", "}", "finally", "{", "dbc", ".", "clear", "(", ")", ";", "}", "}" ]
Writes a property for a specified resource.<p> @param context the current request context @param resource the resource to write the property for @param property the property to write @throws CmsException if something goes wrong @throws CmsSecurityException if the user has insufficient permission for the given resource ({@link CmsPermissionSet#ACCESS_WRITE} required) @see CmsObject#writePropertyObject(String, CmsProperty) @see org.opencms.file.types.I_CmsResourceType#writePropertyObject(CmsObject, CmsSecurityManager, CmsResource, CmsProperty)
[ "Writes", "a", "property", "for", "a", "specified", "resource", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsSecurityManager.java#L6802-L6818
alipay/sofa-rpc
core/common/src/main/java/com/alipay/sofa/rpc/common/struct/MapDifference.java
MapDifference.valueEquals
private boolean valueEquals(V leftValue, V rightValue) { """ Value equals. @param leftValue the left value @param rightValue the right value @return the boolean """ if (leftValue == rightValue) { return true; } if (leftValue == null || rightValue == null) { return false; } return leftValue.equals(rightValue); }
java
private boolean valueEquals(V leftValue, V rightValue) { if (leftValue == rightValue) { return true; } if (leftValue == null || rightValue == null) { return false; } return leftValue.equals(rightValue); }
[ "private", "boolean", "valueEquals", "(", "V", "leftValue", ",", "V", "rightValue", ")", "{", "if", "(", "leftValue", "==", "rightValue", ")", "{", "return", "true", ";", "}", "if", "(", "leftValue", "==", "null", "||", "rightValue", "==", "null", ")", "{", "return", "false", ";", "}", "return", "leftValue", ".", "equals", "(", "rightValue", ")", ";", "}" ]
Value equals. @param leftValue the left value @param rightValue the right value @return the boolean
[ "Value", "equals", "." ]
train
https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/core/common/src/main/java/com/alipay/sofa/rpc/common/struct/MapDifference.java#L101-L109
OpenLiberty/open-liberty
dev/com.ibm.ws.install/src/com/ibm/ws/install/internal/FixDependencyChecker.java
FixDependencyChecker.isUninstallable
public boolean isUninstallable(UninstallAsset uninstallAsset, Set<IFixInfo> installedFixes, List<UninstallAsset> uninstallAssets) { """ Verfiy whether the fix is uninstallable and there is no other installed fix still require this feature. @param uninstallAsset fix to be uninstalled @param installedFixes installed fixes @param uninstallAssets the list of fixes that is to be uninstalled @return the true if there is no fix that depends on the uninstall asset. return false otherwise """ if (Boolean.valueOf(System.getenv(S_DISABLE)).booleanValue()) { return true; } IFixInfo fixToBeUninstalled = uninstallAsset.getIFixInfo(); for (IFixInfo fix : installedFixes) { if (!(fixToBeUninstalled.getId().equals(fix.getId()))) { if ((!confirmNoFileConflicts(fixToBeUninstalled.getUpdates().getFiles(), fix.getUpdates().getFiles())) && (!isSupersededBy(fix.getResolves().getProblems(), fixToBeUninstalled.getResolves().getProblems()))) if (!isToBeUninstalled(fix.getId(), uninstallAssets)) return false; } } return true; }
java
public boolean isUninstallable(UninstallAsset uninstallAsset, Set<IFixInfo> installedFixes, List<UninstallAsset> uninstallAssets) { if (Boolean.valueOf(System.getenv(S_DISABLE)).booleanValue()) { return true; } IFixInfo fixToBeUninstalled = uninstallAsset.getIFixInfo(); for (IFixInfo fix : installedFixes) { if (!(fixToBeUninstalled.getId().equals(fix.getId()))) { if ((!confirmNoFileConflicts(fixToBeUninstalled.getUpdates().getFiles(), fix.getUpdates().getFiles())) && (!isSupersededBy(fix.getResolves().getProblems(), fixToBeUninstalled.getResolves().getProblems()))) if (!isToBeUninstalled(fix.getId(), uninstallAssets)) return false; } } return true; }
[ "public", "boolean", "isUninstallable", "(", "UninstallAsset", "uninstallAsset", ",", "Set", "<", "IFixInfo", ">", "installedFixes", ",", "List", "<", "UninstallAsset", ">", "uninstallAssets", ")", "{", "if", "(", "Boolean", ".", "valueOf", "(", "System", ".", "getenv", "(", "S_DISABLE", ")", ")", ".", "booleanValue", "(", ")", ")", "{", "return", "true", ";", "}", "IFixInfo", "fixToBeUninstalled", "=", "uninstallAsset", ".", "getIFixInfo", "(", ")", ";", "for", "(", "IFixInfo", "fix", ":", "installedFixes", ")", "{", "if", "(", "!", "(", "fixToBeUninstalled", ".", "getId", "(", ")", ".", "equals", "(", "fix", ".", "getId", "(", ")", ")", ")", ")", "{", "if", "(", "(", "!", "confirmNoFileConflicts", "(", "fixToBeUninstalled", ".", "getUpdates", "(", ")", ".", "getFiles", "(", ")", ",", "fix", ".", "getUpdates", "(", ")", ".", "getFiles", "(", ")", ")", ")", "&&", "(", "!", "isSupersededBy", "(", "fix", ".", "getResolves", "(", ")", ".", "getProblems", "(", ")", ",", "fixToBeUninstalled", ".", "getResolves", "(", ")", ".", "getProblems", "(", ")", ")", ")", ")", "if", "(", "!", "isToBeUninstalled", "(", "fix", ".", "getId", "(", ")", ",", "uninstallAssets", ")", ")", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Verfiy whether the fix is uninstallable and there is no other installed fix still require this feature. @param uninstallAsset fix to be uninstalled @param installedFixes installed fixes @param uninstallAssets the list of fixes that is to be uninstalled @return the true if there is no fix that depends on the uninstall asset. return false otherwise
[ "Verfiy", "whether", "the", "fix", "is", "uninstallable", "and", "there", "is", "no", "other", "installed", "fix", "still", "require", "this", "feature", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.install/src/com/ibm/ws/install/internal/FixDependencyChecker.java#L74-L90
nyla-solutions/nyla
nyla.solutions.core/src/main/java/nyla/solutions/core/operations/ClassPath.java
ClassPath.findClass
public Class<?> findClass(String className) { """ Find the class by it name @param className the class name @return the existing of loaded class """ Class<?> result = null; // look in hash map result = (Class<?>) classes.get(className); if (result != null) { return result; } try { return findSystemClass(className); } catch (Exception e) { Debugger.printWarn(e); } try { URL resourceURL = ClassLoader.getSystemResource(className.replace( '.', File.separatorChar) + ".class"); if (resourceURL == null) return null; String classPath = resourceURL.getFile(); classPath = classPath.substring(1); return loadClass(className, new File(classPath)); } catch (Exception e) { Debugger.printError(e); return null; } }
java
public Class<?> findClass(String className) { Class<?> result = null; // look in hash map result = (Class<?>) classes.get(className); if (result != null) { return result; } try { return findSystemClass(className); } catch (Exception e) { Debugger.printWarn(e); } try { URL resourceURL = ClassLoader.getSystemResource(className.replace( '.', File.separatorChar) + ".class"); if (resourceURL == null) return null; String classPath = resourceURL.getFile(); classPath = classPath.substring(1); return loadClass(className, new File(classPath)); } catch (Exception e) { Debugger.printError(e); return null; } }
[ "public", "Class", "<", "?", ">", "findClass", "(", "String", "className", ")", "{", "Class", "<", "?", ">", "result", "=", "null", ";", "// look in hash map\r", "result", "=", "(", "Class", "<", "?", ">", ")", "classes", ".", "get", "(", "className", ")", ";", "if", "(", "result", "!=", "null", ")", "{", "return", "result", ";", "}", "try", "{", "return", "findSystemClass", "(", "className", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "Debugger", ".", "printWarn", "(", "e", ")", ";", "}", "try", "{", "URL", "resourceURL", "=", "ClassLoader", ".", "getSystemResource", "(", "className", ".", "replace", "(", "'", "'", ",", "File", ".", "separatorChar", ")", "+", "\".class\"", ")", ";", "if", "(", "resourceURL", "==", "null", ")", "return", "null", ";", "String", "classPath", "=", "resourceURL", ".", "getFile", "(", ")", ";", "classPath", "=", "classPath", ".", "substring", "(", "1", ")", ";", "return", "loadClass", "(", "className", ",", "new", "File", "(", "classPath", ")", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "Debugger", ".", "printError", "(", "e", ")", ";", "return", "null", ";", "}", "}" ]
Find the class by it name @param className the class name @return the existing of loaded class
[ "Find", "the", "class", "by", "it", "name" ]
train
https://github.com/nyla-solutions/nyla/blob/38d5b843c76eae9762bbca20453ed0f0ad8412a9/nyla.solutions.core/src/main/java/nyla/solutions/core/operations/ClassPath.java#L417-L457
alkacon/opencms-core
src/org/opencms/ade/configuration/CmsADEManager.java
CmsADEManager.elementFromJson
protected CmsContainerElementBean elementFromJson(JSONObject data) throws JSONException { """ Creates an element from its serialized data.<p> @param data the serialized data @return the restored element bean @throws JSONException if the serialized data got corrupted """ CmsUUID element = new CmsUUID(data.getString(FavListProp.ELEMENT.name().toLowerCase())); CmsUUID formatter = null; if (data.has(FavListProp.FORMATTER.name().toLowerCase())) { formatter = new CmsUUID(data.getString(FavListProp.FORMATTER.name().toLowerCase())); } Map<String, String> properties = new HashMap<String, String>(); JSONObject props = data.getJSONObject(FavListProp.PROPERTIES.name().toLowerCase()); Iterator<String> keys = props.keys(); while (keys.hasNext()) { String key = keys.next(); properties.put(key, props.getString(key)); } return new CmsContainerElementBean(element, formatter, properties, false); }
java
protected CmsContainerElementBean elementFromJson(JSONObject data) throws JSONException { CmsUUID element = new CmsUUID(data.getString(FavListProp.ELEMENT.name().toLowerCase())); CmsUUID formatter = null; if (data.has(FavListProp.FORMATTER.name().toLowerCase())) { formatter = new CmsUUID(data.getString(FavListProp.FORMATTER.name().toLowerCase())); } Map<String, String> properties = new HashMap<String, String>(); JSONObject props = data.getJSONObject(FavListProp.PROPERTIES.name().toLowerCase()); Iterator<String> keys = props.keys(); while (keys.hasNext()) { String key = keys.next(); properties.put(key, props.getString(key)); } return new CmsContainerElementBean(element, formatter, properties, false); }
[ "protected", "CmsContainerElementBean", "elementFromJson", "(", "JSONObject", "data", ")", "throws", "JSONException", "{", "CmsUUID", "element", "=", "new", "CmsUUID", "(", "data", ".", "getString", "(", "FavListProp", ".", "ELEMENT", ".", "name", "(", ")", ".", "toLowerCase", "(", ")", ")", ")", ";", "CmsUUID", "formatter", "=", "null", ";", "if", "(", "data", ".", "has", "(", "FavListProp", ".", "FORMATTER", ".", "name", "(", ")", ".", "toLowerCase", "(", ")", ")", ")", "{", "formatter", "=", "new", "CmsUUID", "(", "data", ".", "getString", "(", "FavListProp", ".", "FORMATTER", ".", "name", "(", ")", ".", "toLowerCase", "(", ")", ")", ")", ";", "}", "Map", "<", "String", ",", "String", ">", "properties", "=", "new", "HashMap", "<", "String", ",", "String", ">", "(", ")", ";", "JSONObject", "props", "=", "data", ".", "getJSONObject", "(", "FavListProp", ".", "PROPERTIES", ".", "name", "(", ")", ".", "toLowerCase", "(", ")", ")", ";", "Iterator", "<", "String", ">", "keys", "=", "props", ".", "keys", "(", ")", ";", "while", "(", "keys", ".", "hasNext", "(", ")", ")", "{", "String", "key", "=", "keys", ".", "next", "(", ")", ";", "properties", ".", "put", "(", "key", ",", "props", ".", "getString", "(", "key", ")", ")", ";", "}", "return", "new", "CmsContainerElementBean", "(", "element", ",", "formatter", ",", "properties", ",", "false", ")", ";", "}" ]
Creates an element from its serialized data.<p> @param data the serialized data @return the restored element bean @throws JSONException if the serialized data got corrupted
[ "Creates", "an", "element", "from", "its", "serialized", "data", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/configuration/CmsADEManager.java#L1317-L1334
powermock/powermock
powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java
PowerMock.createStrictMockAndExpectNew
public static synchronized <T> T createStrictMockAndExpectNew(Class<T> type, Object... arguments) throws Exception { """ Convenience method for createStrictMock followed by expectNew. @param type The class that should be mocked. @param arguments The constructor arguments. @return A mock object of the same type as the mock. @throws Exception """ T mock = createStrictMock(type); expectStrictNew(type, arguments).andReturn(mock); return mock; }
java
public static synchronized <T> T createStrictMockAndExpectNew(Class<T> type, Object... arguments) throws Exception { T mock = createStrictMock(type); expectStrictNew(type, arguments).andReturn(mock); return mock; }
[ "public", "static", "synchronized", "<", "T", ">", "T", "createStrictMockAndExpectNew", "(", "Class", "<", "T", ">", "type", ",", "Object", "...", "arguments", ")", "throws", "Exception", "{", "T", "mock", "=", "createStrictMock", "(", "type", ")", ";", "expectStrictNew", "(", "type", ",", "arguments", ")", ".", "andReturn", "(", "mock", ")", ";", "return", "mock", ";", "}" ]
Convenience method for createStrictMock followed by expectNew. @param type The class that should be mocked. @param arguments The constructor arguments. @return A mock object of the same type as the mock. @throws Exception
[ "Convenience", "method", "for", "createStrictMock", "followed", "by", "expectNew", "." ]
train
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java#L1578-L1582
grpc/grpc-java
api/src/main/java/io/grpc/ClientInterceptors.java
ClientInterceptors.interceptForward
public static Channel interceptForward(Channel channel, List<? extends ClientInterceptor> interceptors) { """ Create a new {@link Channel} that will call {@code interceptors} before starting a call on the given channel. The first interceptor will have its {@link ClientInterceptor#interceptCall} called first. @param channel the underlying channel to intercept. @param interceptors a list of interceptors to bind to {@code channel}. @return a new channel instance with the interceptors applied. """ List<? extends ClientInterceptor> copy = new ArrayList<>(interceptors); Collections.reverse(copy); return intercept(channel, copy); }
java
public static Channel interceptForward(Channel channel, List<? extends ClientInterceptor> interceptors) { List<? extends ClientInterceptor> copy = new ArrayList<>(interceptors); Collections.reverse(copy); return intercept(channel, copy); }
[ "public", "static", "Channel", "interceptForward", "(", "Channel", "channel", ",", "List", "<", "?", "extends", "ClientInterceptor", ">", "interceptors", ")", "{", "List", "<", "?", "extends", "ClientInterceptor", ">", "copy", "=", "new", "ArrayList", "<>", "(", "interceptors", ")", ";", "Collections", ".", "reverse", "(", "copy", ")", ";", "return", "intercept", "(", "channel", ",", "copy", ")", ";", "}" ]
Create a new {@link Channel} that will call {@code interceptors} before starting a call on the given channel. The first interceptor will have its {@link ClientInterceptor#interceptCall} called first. @param channel the underlying channel to intercept. @param interceptors a list of interceptors to bind to {@code channel}. @return a new channel instance with the interceptors applied.
[ "Create", "a", "new", "{", "@link", "Channel", "}", "that", "will", "call", "{", "@code", "interceptors", "}", "before", "starting", "a", "call", "on", "the", "given", "channel", ".", "The", "first", "interceptor", "will", "have", "its", "{", "@link", "ClientInterceptor#interceptCall", "}", "called", "first", "." ]
train
https://github.com/grpc/grpc-java/blob/973885457f9609de232d2553b82c67f6c3ff57bf/api/src/main/java/io/grpc/ClientInterceptors.java#L57-L62
johncarl81/transfuse
transfuse-api/src/main/java/org/androidtransfuse/intentFactory/IntentFactory.java
IntentFactory.buildPendingIntent
public PendingIntent buildPendingIntent(int requestCode, int flags, IntentFactoryStrategy parameters) { """ Build a PendingIntent specified by the given input Strategy. @param requestCode request code for the sender @param flags intent flags @param parameters Strategy instance @return PendingIntent """ return PendingIntent.getActivity(context, requestCode, buildIntent(parameters), flags); }
java
public PendingIntent buildPendingIntent(int requestCode, int flags, IntentFactoryStrategy parameters){ return PendingIntent.getActivity(context, requestCode, buildIntent(parameters), flags); }
[ "public", "PendingIntent", "buildPendingIntent", "(", "int", "requestCode", ",", "int", "flags", ",", "IntentFactoryStrategy", "parameters", ")", "{", "return", "PendingIntent", ".", "getActivity", "(", "context", ",", "requestCode", ",", "buildIntent", "(", "parameters", ")", ",", "flags", ")", ";", "}" ]
Build a PendingIntent specified by the given input Strategy. @param requestCode request code for the sender @param flags intent flags @param parameters Strategy instance @return PendingIntent
[ "Build", "a", "PendingIntent", "specified", "by", "the", "given", "input", "Strategy", "." ]
train
https://github.com/johncarl81/transfuse/blob/a5f837504797a6c4f8628f7e1dde09b8e6368c8b/transfuse-api/src/main/java/org/androidtransfuse/intentFactory/IntentFactory.java#L134-L136
stratosphere/stratosphere
stratosphere-runtime/src/main/java/eu/stratosphere/nephele/executiongraph/ExecutionGraph.java
ExecutionGraph.getInputVertex
public ExecutionVertex getInputVertex(final int stage, final int index) { """ Returns the input vertex with the specified index for the given stage @param stage the index of the stage @param index the index of the input vertex to return @return the input vertex with the specified index or <code>null</code> if no input vertex with such an index exists in that stage """ try { final ExecutionStage s = this.stages.get(stage); if (s == null) { return null; } return s.getInputExecutionVertex(index); } catch (ArrayIndexOutOfBoundsException e) { return null; } }
java
public ExecutionVertex getInputVertex(final int stage, final int index) { try { final ExecutionStage s = this.stages.get(stage); if (s == null) { return null; } return s.getInputExecutionVertex(index); } catch (ArrayIndexOutOfBoundsException e) { return null; } }
[ "public", "ExecutionVertex", "getInputVertex", "(", "final", "int", "stage", ",", "final", "int", "index", ")", "{", "try", "{", "final", "ExecutionStage", "s", "=", "this", ".", "stages", ".", "get", "(", "stage", ")", ";", "if", "(", "s", "==", "null", ")", "{", "return", "null", ";", "}", "return", "s", ".", "getInputExecutionVertex", "(", "index", ")", ";", "}", "catch", "(", "ArrayIndexOutOfBoundsException", "e", ")", "{", "return", "null", ";", "}", "}" ]
Returns the input vertex with the specified index for the given stage @param stage the index of the stage @param index the index of the input vertex to return @return the input vertex with the specified index or <code>null</code> if no input vertex with such an index exists in that stage
[ "Returns", "the", "input", "vertex", "with", "the", "specified", "index", "for", "the", "given", "stage" ]
train
https://github.com/stratosphere/stratosphere/blob/c543a08f9676c5b2b0a7088123bd6e795a8ae0c8/stratosphere-runtime/src/main/java/eu/stratosphere/nephele/executiongraph/ExecutionGraph.java#L676-L689
Azure/azure-sdk-for-java
network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/VirtualNetworkGatewaysInner.java
VirtualNetworkGatewaysInner.beginGetBgpPeerStatusAsync
public Observable<BgpPeerStatusListResultInner> beginGetBgpPeerStatusAsync(String resourceGroupName, String virtualNetworkGatewayName, String peer) { """ The GetBgpPeerStatus operation retrieves the status of all BGP peers. @param resourceGroupName The name of the resource group. @param virtualNetworkGatewayName The name of the virtual network gateway. @param peer The IP address of the peer to retrieve the status of. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the BgpPeerStatusListResultInner object """ return beginGetBgpPeerStatusWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayName, peer).map(new Func1<ServiceResponse<BgpPeerStatusListResultInner>, BgpPeerStatusListResultInner>() { @Override public BgpPeerStatusListResultInner call(ServiceResponse<BgpPeerStatusListResultInner> response) { return response.body(); } }); }
java
public Observable<BgpPeerStatusListResultInner> beginGetBgpPeerStatusAsync(String resourceGroupName, String virtualNetworkGatewayName, String peer) { return beginGetBgpPeerStatusWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayName, peer).map(new Func1<ServiceResponse<BgpPeerStatusListResultInner>, BgpPeerStatusListResultInner>() { @Override public BgpPeerStatusListResultInner call(ServiceResponse<BgpPeerStatusListResultInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "BgpPeerStatusListResultInner", ">", "beginGetBgpPeerStatusAsync", "(", "String", "resourceGroupName", ",", "String", "virtualNetworkGatewayName", ",", "String", "peer", ")", "{", "return", "beginGetBgpPeerStatusWithServiceResponseAsync", "(", "resourceGroupName", ",", "virtualNetworkGatewayName", ",", "peer", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "BgpPeerStatusListResultInner", ">", ",", "BgpPeerStatusListResultInner", ">", "(", ")", "{", "@", "Override", "public", "BgpPeerStatusListResultInner", "call", "(", "ServiceResponse", "<", "BgpPeerStatusListResultInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
The GetBgpPeerStatus operation retrieves the status of all BGP peers. @param resourceGroupName The name of the resource group. @param virtualNetworkGatewayName The name of the virtual network gateway. @param peer The IP address of the peer to retrieve the status of. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the BgpPeerStatusListResultInner object
[ "The", "GetBgpPeerStatus", "operation", "retrieves", "the", "status", "of", "all", "BGP", "peers", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/VirtualNetworkGatewaysInner.java#L2195-L2202
tomgibara/bits
src/main/java/com/tomgibara/bits/FileBitReaderFactory.java
FileBitReaderFactory.openReader
public BitReader openReader() throws BitStreamException { """ Opens a reader over the bits of the file. The characteristics of the returned reader are determined by the {@link Mode} in which the factory was created. Any reader returned by this method SHOULD eventually be closed by passing it to the {@link #closeReader(BitReader)} method. Not doing so may risk leaking system resources. @return a new reader over the file @throws BitStreamException if the reader could not be opened, typically because the file could not be read """ try { switch(mode) { case MEMORY : return new ByteArrayBitReader(getBytes()); case STREAM : return new InputStreamBitReader(new BufferedInputStream(new FileInputStream(file), bufferSize)); case CHANNEL: return new FileChannelBitReader(new RandomAccessFile(file, "r").getChannel(), ByteBuffer.allocateDirect(bufferSize)); default: throw new IllegalStateException("Unexpected mode: " + mode); } } catch (IOException e) { throw new BitStreamException(e); } }
java
public BitReader openReader() throws BitStreamException { try { switch(mode) { case MEMORY : return new ByteArrayBitReader(getBytes()); case STREAM : return new InputStreamBitReader(new BufferedInputStream(new FileInputStream(file), bufferSize)); case CHANNEL: return new FileChannelBitReader(new RandomAccessFile(file, "r").getChannel(), ByteBuffer.allocateDirect(bufferSize)); default: throw new IllegalStateException("Unexpected mode: " + mode); } } catch (IOException e) { throw new BitStreamException(e); } }
[ "public", "BitReader", "openReader", "(", ")", "throws", "BitStreamException", "{", "try", "{", "switch", "(", "mode", ")", "{", "case", "MEMORY", ":", "return", "new", "ByteArrayBitReader", "(", "getBytes", "(", ")", ")", ";", "case", "STREAM", ":", "return", "new", "InputStreamBitReader", "(", "new", "BufferedInputStream", "(", "new", "FileInputStream", "(", "file", ")", ",", "bufferSize", ")", ")", ";", "case", "CHANNEL", ":", "return", "new", "FileChannelBitReader", "(", "new", "RandomAccessFile", "(", "file", ",", "\"r\"", ")", ".", "getChannel", "(", ")", ",", "ByteBuffer", ".", "allocateDirect", "(", "bufferSize", ")", ")", ";", "default", ":", "throw", "new", "IllegalStateException", "(", "\"Unexpected mode: \"", "+", "mode", ")", ";", "}", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "BitStreamException", "(", "e", ")", ";", "}", "}" ]
Opens a reader over the bits of the file. The characteristics of the returned reader are determined by the {@link Mode} in which the factory was created. Any reader returned by this method SHOULD eventually be closed by passing it to the {@link #closeReader(BitReader)} method. Not doing so may risk leaking system resources. @return a new reader over the file @throws BitStreamException if the reader could not be opened, typically because the file could not be read
[ "Opens", "a", "reader", "over", "the", "bits", "of", "the", "file", ".", "The", "characteristics", "of", "the", "returned", "reader", "are", "determined", "by", "the", "{", "@link", "Mode", "}", "in", "which", "the", "factory", "was", "created", "." ]
train
https://github.com/tomgibara/bits/blob/56c32c0a30efd3d7c4e7c6600a0ca39e51eecc97/src/main/java/com/tomgibara/bits/FileBitReaderFactory.java#L165-L176
Hygieia/Hygieia
collectors/feature/versionone/src/main/java/com/capitalone/dashboard/util/DateUtil.java
DateUtil.evaluateSprintLength
public boolean evaluateSprintLength(String startDate, String endDate, int maxKanbanIterationLength) { """ Evaluates whether a sprint length appears to be kanban or scrum @param startDate The start date of a sprint in ISO format @param endDate The end date of a sprint in ISO format @return True indicates a scrum sprint; False indicates a Kanban sprint """ boolean sprintIndicator = false; Calendar startCalendar = Calendar.getInstance(); Calendar endCalendar = Calendar.getInstance(); if (!StringUtils.isAnyEmpty(startDate) && !StringUtils.isAnyEmpty(endDate)) { Date strDt = convertIntoDate(startDate.substring(0, 4) + "-" + startDate.substring(5, 7) + "-" + startDate.substring(8, 10), "yyyy-MM-dd" ); Date endDt = convertIntoDate(endDate.substring(0, 4) + "-" + endDate.substring(5, 7) + "-" + endDate.substring(8, 10), "yyyy-MM-dd"); if (strDt != null && endDate != null) { startCalendar.setTime(strDt); endCalendar.setTime(endDt); long diffMill = endCalendar.getTimeInMillis() - startCalendar.getTimeInMillis(); long diffDays = TimeUnit.DAYS.convert(diffMill, TimeUnit.MILLISECONDS); if (diffDays <= maxKanbanIterationLength) { // Scrum-enough sprintIndicator = true; } } } else { // Default to kanban sprintIndicator = false; } return sprintIndicator; }
java
public boolean evaluateSprintLength(String startDate, String endDate, int maxKanbanIterationLength) { boolean sprintIndicator = false; Calendar startCalendar = Calendar.getInstance(); Calendar endCalendar = Calendar.getInstance(); if (!StringUtils.isAnyEmpty(startDate) && !StringUtils.isAnyEmpty(endDate)) { Date strDt = convertIntoDate(startDate.substring(0, 4) + "-" + startDate.substring(5, 7) + "-" + startDate.substring(8, 10), "yyyy-MM-dd" ); Date endDt = convertIntoDate(endDate.substring(0, 4) + "-" + endDate.substring(5, 7) + "-" + endDate.substring(8, 10), "yyyy-MM-dd"); if (strDt != null && endDate != null) { startCalendar.setTime(strDt); endCalendar.setTime(endDt); long diffMill = endCalendar.getTimeInMillis() - startCalendar.getTimeInMillis(); long diffDays = TimeUnit.DAYS.convert(diffMill, TimeUnit.MILLISECONDS); if (diffDays <= maxKanbanIterationLength) { // Scrum-enough sprintIndicator = true; } } } else { // Default to kanban sprintIndicator = false; } return sprintIndicator; }
[ "public", "boolean", "evaluateSprintLength", "(", "String", "startDate", ",", "String", "endDate", ",", "int", "maxKanbanIterationLength", ")", "{", "boolean", "sprintIndicator", "=", "false", ";", "Calendar", "startCalendar", "=", "Calendar", ".", "getInstance", "(", ")", ";", "Calendar", "endCalendar", "=", "Calendar", ".", "getInstance", "(", ")", ";", "if", "(", "!", "StringUtils", ".", "isAnyEmpty", "(", "startDate", ")", "&&", "!", "StringUtils", ".", "isAnyEmpty", "(", "endDate", ")", ")", "{", "Date", "strDt", "=", "convertIntoDate", "(", "startDate", ".", "substring", "(", "0", ",", "4", ")", "+", "\"-\"", "+", "startDate", ".", "substring", "(", "5", ",", "7", ")", "+", "\"-\"", "+", "startDate", ".", "substring", "(", "8", ",", "10", ")", ",", "\"yyyy-MM-dd\"", ")", ";", "Date", "endDt", "=", "convertIntoDate", "(", "endDate", ".", "substring", "(", "0", ",", "4", ")", "+", "\"-\"", "+", "endDate", ".", "substring", "(", "5", ",", "7", ")", "+", "\"-\"", "+", "endDate", ".", "substring", "(", "8", ",", "10", ")", ",", "\"yyyy-MM-dd\"", ")", ";", "if", "(", "strDt", "!=", "null", "&&", "endDate", "!=", "null", ")", "{", "startCalendar", ".", "setTime", "(", "strDt", ")", ";", "endCalendar", ".", "setTime", "(", "endDt", ")", ";", "long", "diffMill", "=", "endCalendar", ".", "getTimeInMillis", "(", ")", "-", "startCalendar", ".", "getTimeInMillis", "(", ")", ";", "long", "diffDays", "=", "TimeUnit", ".", "DAYS", ".", "convert", "(", "diffMill", ",", "TimeUnit", ".", "MILLISECONDS", ")", ";", "if", "(", "diffDays", "<=", "maxKanbanIterationLength", ")", "{", "// Scrum-enough", "sprintIndicator", "=", "true", ";", "}", "}", "}", "else", "{", "// Default to kanban", "sprintIndicator", "=", "false", ";", "}", "return", "sprintIndicator", ";", "}" ]
Evaluates whether a sprint length appears to be kanban or scrum @param startDate The start date of a sprint in ISO format @param endDate The end date of a sprint in ISO format @return True indicates a scrum sprint; False indicates a Kanban sprint
[ "Evaluates", "whether", "a", "sprint", "length", "appears", "to", "be", "kanban", "or", "scrum" ]
train
https://github.com/Hygieia/Hygieia/blob/d8b67a590da2744acf59bcd99d9b34ef1bb84890/collectors/feature/versionone/src/main/java/com/capitalone/dashboard/util/DateUtil.java#L85-L114
lemire/sparsebitmap
src/main/java/sparsebitmap/SparseBitmap.java
SparseBitmap.match
public static boolean match(SkippableIterator o1, SkippableIterator o2) { """ Synchronize two iterators @param o1 the first iterator @param o2 the second iterator @return true, if successful """ while (o1.getCurrentWordOffset() != o2.getCurrentWordOffset()) { if (o1.getCurrentWordOffset() < o2.getCurrentWordOffset()) { o1.advanceUntil(o2.getCurrentWordOffset()); if (!o1.hasValue()) return false; } if (o1.getCurrentWordOffset() > o2.getCurrentWordOffset()) { o2.advanceUntil(o1.getCurrentWordOffset()); if (!o2.hasValue()) return false; } } return true; }
java
public static boolean match(SkippableIterator o1, SkippableIterator o2) { while (o1.getCurrentWordOffset() != o2.getCurrentWordOffset()) { if (o1.getCurrentWordOffset() < o2.getCurrentWordOffset()) { o1.advanceUntil(o2.getCurrentWordOffset()); if (!o1.hasValue()) return false; } if (o1.getCurrentWordOffset() > o2.getCurrentWordOffset()) { o2.advanceUntil(o1.getCurrentWordOffset()); if (!o2.hasValue()) return false; } } return true; }
[ "public", "static", "boolean", "match", "(", "SkippableIterator", "o1", ",", "SkippableIterator", "o2", ")", "{", "while", "(", "o1", ".", "getCurrentWordOffset", "(", ")", "!=", "o2", ".", "getCurrentWordOffset", "(", ")", ")", "{", "if", "(", "o1", ".", "getCurrentWordOffset", "(", ")", "<", "o2", ".", "getCurrentWordOffset", "(", ")", ")", "{", "o1", ".", "advanceUntil", "(", "o2", ".", "getCurrentWordOffset", "(", ")", ")", ";", "if", "(", "!", "o1", ".", "hasValue", "(", ")", ")", "return", "false", ";", "}", "if", "(", "o1", ".", "getCurrentWordOffset", "(", ")", ">", "o2", ".", "getCurrentWordOffset", "(", ")", ")", "{", "o2", ".", "advanceUntil", "(", "o1", ".", "getCurrentWordOffset", "(", ")", ")", ";", "if", "(", "!", "o2", ".", "hasValue", "(", ")", ")", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Synchronize two iterators @param o1 the first iterator @param o2 the second iterator @return true, if successful
[ "Synchronize", "two", "iterators" ]
train
https://github.com/lemire/sparsebitmap/blob/f362e0811c32f68adfe4b748d513c46857898ec9/src/main/java/sparsebitmap/SparseBitmap.java#L1080-L1094
ThreeTen/threeten-extra
src/main/java/org/threeten/extra/chrono/AccountingDate.java
AccountingDate.ofYearDay
static AccountingDate ofYearDay(AccountingChronology chronology, int prolepticYear, int dayOfYear) { """ Obtains an {@code AccountingDate} representing a date in the given Accounting calendar system from the proleptic-year and day-of-year fields. <p> This returns an {@code AccountingDate} with the specified fields. The day must be valid for the year, otherwise an exception will be thrown. @param chronology the Accounting chronology to base the date on, not null @param prolepticYear the Accounting proleptic-year @param dayOfYear the Accounting day-of-year, from 1 to 371 @return the date in Accounting calendar system, not null @throws DateTimeException if the value of any field is out of range, or if the day-of-year is invalid for the year, NullPointerException if an AccountingChronology was not provided """ Objects.requireNonNull(chronology, "A previously setup chronology is required."); YEAR.checkValidValue(prolepticYear); DAY_OF_YEAR_RANGE.checkValidValue(dayOfYear, DAY_OF_YEAR); boolean leap = chronology.isLeapYear(prolepticYear); if (dayOfYear > WEEKS_IN_YEAR * DAYS_IN_WEEK && !leap) { throw new DateTimeException("Invalid date 'DayOfYear " + dayOfYear + "' as '" + prolepticYear + "' is not a leap year"); } int month = (leap ? chronology.getDivision().getMonthFromElapsedWeeks((dayOfYear - 1) / DAYS_IN_WEEK, chronology.getLeapWeekInMonth()) : chronology.getDivision().getMonthFromElapsedWeeks((dayOfYear - 1) / DAYS_IN_WEEK)); int dayOfMonth = dayOfYear - (leap ? chronology.getDivision().getWeeksAtStartOfMonth(month, chronology.getLeapWeekInMonth()) : chronology.getDivision().getWeeksAtStartOfMonth(month)) * DAYS_IN_WEEK; return new AccountingDate(chronology, prolepticYear, month, dayOfMonth); }
java
static AccountingDate ofYearDay(AccountingChronology chronology, int prolepticYear, int dayOfYear) { Objects.requireNonNull(chronology, "A previously setup chronology is required."); YEAR.checkValidValue(prolepticYear); DAY_OF_YEAR_RANGE.checkValidValue(dayOfYear, DAY_OF_YEAR); boolean leap = chronology.isLeapYear(prolepticYear); if (dayOfYear > WEEKS_IN_YEAR * DAYS_IN_WEEK && !leap) { throw new DateTimeException("Invalid date 'DayOfYear " + dayOfYear + "' as '" + prolepticYear + "' is not a leap year"); } int month = (leap ? chronology.getDivision().getMonthFromElapsedWeeks((dayOfYear - 1) / DAYS_IN_WEEK, chronology.getLeapWeekInMonth()) : chronology.getDivision().getMonthFromElapsedWeeks((dayOfYear - 1) / DAYS_IN_WEEK)); int dayOfMonth = dayOfYear - (leap ? chronology.getDivision().getWeeksAtStartOfMonth(month, chronology.getLeapWeekInMonth()) : chronology.getDivision().getWeeksAtStartOfMonth(month)) * DAYS_IN_WEEK; return new AccountingDate(chronology, prolepticYear, month, dayOfMonth); }
[ "static", "AccountingDate", "ofYearDay", "(", "AccountingChronology", "chronology", ",", "int", "prolepticYear", ",", "int", "dayOfYear", ")", "{", "Objects", ".", "requireNonNull", "(", "chronology", ",", "\"A previously setup chronology is required.\"", ")", ";", "YEAR", ".", "checkValidValue", "(", "prolepticYear", ")", ";", "DAY_OF_YEAR_RANGE", ".", "checkValidValue", "(", "dayOfYear", ",", "DAY_OF_YEAR", ")", ";", "boolean", "leap", "=", "chronology", ".", "isLeapYear", "(", "prolepticYear", ")", ";", "if", "(", "dayOfYear", ">", "WEEKS_IN_YEAR", "*", "DAYS_IN_WEEK", "&&", "!", "leap", ")", "{", "throw", "new", "DateTimeException", "(", "\"Invalid date 'DayOfYear \"", "+", "dayOfYear", "+", "\"' as '\"", "+", "prolepticYear", "+", "\"' is not a leap year\"", ")", ";", "}", "int", "month", "=", "(", "leap", "?", "chronology", ".", "getDivision", "(", ")", ".", "getMonthFromElapsedWeeks", "(", "(", "dayOfYear", "-", "1", ")", "/", "DAYS_IN_WEEK", ",", "chronology", ".", "getLeapWeekInMonth", "(", ")", ")", ":", "chronology", ".", "getDivision", "(", ")", ".", "getMonthFromElapsedWeeks", "(", "(", "dayOfYear", "-", "1", ")", "/", "DAYS_IN_WEEK", ")", ")", ";", "int", "dayOfMonth", "=", "dayOfYear", "-", "(", "leap", "?", "chronology", ".", "getDivision", "(", ")", ".", "getWeeksAtStartOfMonth", "(", "month", ",", "chronology", ".", "getLeapWeekInMonth", "(", ")", ")", ":", "chronology", ".", "getDivision", "(", ")", ".", "getWeeksAtStartOfMonth", "(", "month", ")", ")", "*", "DAYS_IN_WEEK", ";", "return", "new", "AccountingDate", "(", "chronology", ",", "prolepticYear", ",", "month", ",", "dayOfMonth", ")", ";", "}" ]
Obtains an {@code AccountingDate} representing a date in the given Accounting calendar system from the proleptic-year and day-of-year fields. <p> This returns an {@code AccountingDate} with the specified fields. The day must be valid for the year, otherwise an exception will be thrown. @param chronology the Accounting chronology to base the date on, not null @param prolepticYear the Accounting proleptic-year @param dayOfYear the Accounting day-of-year, from 1 to 371 @return the date in Accounting calendar system, not null @throws DateTimeException if the value of any field is out of range, or if the day-of-year is invalid for the year, NullPointerException if an AccountingChronology was not provided
[ "Obtains", "an", "{", "@code", "AccountingDate", "}", "representing", "a", "date", "in", "the", "given", "Accounting", "calendar", "system", "from", "the", "proleptic", "-", "year", "and", "day", "-", "of", "-", "year", "fields", ".", "<p", ">", "This", "returns", "an", "{", "@code", "AccountingDate", "}", "with", "the", "specified", "fields", ".", "The", "day", "must", "be", "valid", "for", "the", "year", "otherwise", "an", "exception", "will", "be", "thrown", "." ]
train
https://github.com/ThreeTen/threeten-extra/blob/e94ecd3592ef70e54d6eea21095239ea9ffbab78/src/main/java/org/threeten/extra/chrono/AccountingDate.java#L232-L247
iipc/webarchive-commons
src/main/java/org/archive/util/TextUtils.java
TextUtils.getMatcher
public static Matcher getMatcher(String pattern, CharSequence input) { """ Get a matcher object for a precompiled regex pattern. This method tries to reuse Matcher objects for efficiency. It can hold for recycling one Matcher per pattern per thread. Matchers retrieved should be returned for reuse via the recycleMatcher() method, but no errors will occur if they are not. This method is a hotspot frequently accessed. @param pattern the string pattern to use @param input the character sequence the matcher should be using @return a matcher object loaded with the submitted character sequence """ if (pattern == null) { throw new IllegalArgumentException("String 'pattern' must not be null"); } input = new InterruptibleCharSequence(input); final Map<String,Matcher> matchers = TL_MATCHER_MAP.get(); Matcher m = (Matcher)matchers.get(pattern); if(m == null) { m = PATTERNS.getUnchecked(pattern).matcher(input); } else { matchers.put(pattern,null); m.reset(input); } return m; }
java
public static Matcher getMatcher(String pattern, CharSequence input) { if (pattern == null) { throw new IllegalArgumentException("String 'pattern' must not be null"); } input = new InterruptibleCharSequence(input); final Map<String,Matcher> matchers = TL_MATCHER_MAP.get(); Matcher m = (Matcher)matchers.get(pattern); if(m == null) { m = PATTERNS.getUnchecked(pattern).matcher(input); } else { matchers.put(pattern,null); m.reset(input); } return m; }
[ "public", "static", "Matcher", "getMatcher", "(", "String", "pattern", ",", "CharSequence", "input", ")", "{", "if", "(", "pattern", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"String 'pattern' must not be null\"", ")", ";", "}", "input", "=", "new", "InterruptibleCharSequence", "(", "input", ")", ";", "final", "Map", "<", "String", ",", "Matcher", ">", "matchers", "=", "TL_MATCHER_MAP", ".", "get", "(", ")", ";", "Matcher", "m", "=", "(", "Matcher", ")", "matchers", ".", "get", "(", "pattern", ")", ";", "if", "(", "m", "==", "null", ")", "{", "m", "=", "PATTERNS", ".", "getUnchecked", "(", "pattern", ")", ".", "matcher", "(", "input", ")", ";", "}", "else", "{", "matchers", ".", "put", "(", "pattern", ",", "null", ")", ";", "m", ".", "reset", "(", "input", ")", ";", "}", "return", "m", ";", "}" ]
Get a matcher object for a precompiled regex pattern. This method tries to reuse Matcher objects for efficiency. It can hold for recycling one Matcher per pattern per thread. Matchers retrieved should be returned for reuse via the recycleMatcher() method, but no errors will occur if they are not. This method is a hotspot frequently accessed. @param pattern the string pattern to use @param input the character sequence the matcher should be using @return a matcher object loaded with the submitted character sequence
[ "Get", "a", "matcher", "object", "for", "a", "precompiled", "regex", "pattern", "." ]
train
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/util/TextUtils.java#L80-L94
schallee/alib4j
jms/src/main/java/net/darkmist/alib/jms/Messages.java
Messages.writeToMapped
private static File writeToMapped(BytesMessage msg, File file) throws IOException, JMSException { """ /* blasted. java 7 private static Path writeToMapped(BytesMessage msg, Path path) throws IOException, JMSException { ByteBuffer buf; FileChannel fc; try ( FileChannel fc = FileChannel.open(path, EnumSet.of(StandardOpenOption.CREATE_NEW)); ) { logger.debug("Mapping file {}", file); buf = fc.map(FileChannel.MapMode.READ_WRITE, 0, msg.getBodyLength()); logger.debug("Writting message to byte buffer."); writeTo(msg, buf); logger.debug("Success writing message to file {} using file map.", file); return path; } } """ // writeToMapped(msg, file.toPath()); ByteBuffer buf; FileChannel fc=null; RandomAccessFile raf=null; try { raf = new RandomAccessFile(file, "rw"); fc = raf.getChannel(); buf = fc.map(FileChannel.MapMode.READ_WRITE, 0, msg.getBodyLength()); logger.debug("Writting message to byte buffer."); writeTo(msg, buf); logger.debug("Success writing message to file {} using file map. Closing", file); fc.close(); raf.close(); return file; } finally { fc=Closer.close(fc); raf=Closer.close(raf); } }
java
private static File writeToMapped(BytesMessage msg, File file) throws IOException, JMSException { // writeToMapped(msg, file.toPath()); ByteBuffer buf; FileChannel fc=null; RandomAccessFile raf=null; try { raf = new RandomAccessFile(file, "rw"); fc = raf.getChannel(); buf = fc.map(FileChannel.MapMode.READ_WRITE, 0, msg.getBodyLength()); logger.debug("Writting message to byte buffer."); writeTo(msg, buf); logger.debug("Success writing message to file {} using file map. Closing", file); fc.close(); raf.close(); return file; } finally { fc=Closer.close(fc); raf=Closer.close(raf); } }
[ "private", "static", "File", "writeToMapped", "(", "BytesMessage", "msg", ",", "File", "file", ")", "throws", "IOException", ",", "JMSException", "{", "// writeToMapped(msg, file.toPath());", "ByteBuffer", "buf", ";", "FileChannel", "fc", "=", "null", ";", "RandomAccessFile", "raf", "=", "null", ";", "try", "{", "raf", "=", "new", "RandomAccessFile", "(", "file", ",", "\"rw\"", ")", ";", "fc", "=", "raf", ".", "getChannel", "(", ")", ";", "buf", "=", "fc", ".", "map", "(", "FileChannel", ".", "MapMode", ".", "READ_WRITE", ",", "0", ",", "msg", ".", "getBodyLength", "(", ")", ")", ";", "logger", ".", "debug", "(", "\"Writting message to byte buffer.\"", ")", ";", "writeTo", "(", "msg", ",", "buf", ")", ";", "logger", ".", "debug", "(", "\"Success writing message to file {} using file map. Closing\"", ",", "file", ")", ";", "fc", ".", "close", "(", ")", ";", "raf", ".", "close", "(", ")", ";", "return", "file", ";", "}", "finally", "{", "fc", "=", "Closer", ".", "close", "(", "fc", ")", ";", "raf", "=", "Closer", ".", "close", "(", "raf", ")", ";", "}", "}" ]
/* blasted. java 7 private static Path writeToMapped(BytesMessage msg, Path path) throws IOException, JMSException { ByteBuffer buf; FileChannel fc; try ( FileChannel fc = FileChannel.open(path, EnumSet.of(StandardOpenOption.CREATE_NEW)); ) { logger.debug("Mapping file {}", file); buf = fc.map(FileChannel.MapMode.READ_WRITE, 0, msg.getBodyLength()); logger.debug("Writting message to byte buffer."); writeTo(msg, buf); logger.debug("Success writing message to file {} using file map.", file); return path; } }
[ "/", "*", "blasted", ".", "java", "7", "private", "static", "Path", "writeToMapped", "(", "BytesMessage", "msg", "Path", "path", ")", "throws", "IOException", "JMSException", "{", "ByteBuffer", "buf", ";", "FileChannel", "fc", ";" ]
train
https://github.com/schallee/alib4j/blob/0e0718aee574bbb62268e1cf58e99286529ce529/jms/src/main/java/net/darkmist/alib/jms/Messages.java#L204-L229
actorapp/actor-platform
actor-sdk/sdk-core/runtime/runtime-android/src/main/java/im/actor/runtime/android/time/SntpClient.java
SntpClient.readTimeStamp
private long readTimeStamp(byte[] buffer, int offset) { """ Reads the NTP time stamp at the given offset in the buffer and returns it as a system time (milliseconds since January 1, 1970). """ long seconds = read32(buffer, offset); long fraction = read32(buffer, offset + 4); return ((seconds - OFFSET_1900_TO_1970) * 1000) + ((fraction * 1000L) / 0x100000000L); }
java
private long readTimeStamp(byte[] buffer, int offset) { long seconds = read32(buffer, offset); long fraction = read32(buffer, offset + 4); return ((seconds - OFFSET_1900_TO_1970) * 1000) + ((fraction * 1000L) / 0x100000000L); }
[ "private", "long", "readTimeStamp", "(", "byte", "[", "]", "buffer", ",", "int", "offset", ")", "{", "long", "seconds", "=", "read32", "(", "buffer", ",", "offset", ")", ";", "long", "fraction", "=", "read32", "(", "buffer", ",", "offset", "+", "4", ")", ";", "return", "(", "(", "seconds", "-", "OFFSET_1900_TO_1970", ")", "*", "1000", ")", "+", "(", "(", "fraction", "*", "1000L", ")", "/", "0x100000000", "L", ")", ";", "}" ]
Reads the NTP time stamp at the given offset in the buffer and returns it as a system time (milliseconds since January 1, 1970).
[ "Reads", "the", "NTP", "time", "stamp", "at", "the", "given", "offset", "in", "the", "buffer", "and", "returns", "it", "as", "a", "system", "time", "(", "milliseconds", "since", "January", "1", "1970", ")", "." ]
train
https://github.com/actorapp/actor-platform/blob/5123c1584757c6eeea0ed2a0e7e043629871a0c6/actor-sdk/sdk-core/runtime/runtime-android/src/main/java/im/actor/runtime/android/time/SntpClient.java#L186-L190
alkacon/opencms-core
src/org/opencms/staticexport/CmsStaticExportManager.java
CmsStaticExportManager.getCacheKey
public String getCacheKey(String siteRoot, String uri) { """ Returns the key for the online, export and secure cache.<p> @param siteRoot the site root of the resource @param uri the URI of the resource @return a key for the cache """ return new StringBuffer(siteRoot).append(uri).toString(); }
java
public String getCacheKey(String siteRoot, String uri) { return new StringBuffer(siteRoot).append(uri).toString(); }
[ "public", "String", "getCacheKey", "(", "String", "siteRoot", ",", "String", "uri", ")", "{", "return", "new", "StringBuffer", "(", "siteRoot", ")", ".", "append", "(", "uri", ")", ".", "toString", "(", ")", ";", "}" ]
Returns the key for the online, export and secure cache.<p> @param siteRoot the site root of the resource @param uri the URI of the resource @return a key for the cache
[ "Returns", "the", "key", "for", "the", "online", "export", "and", "secure", "cache", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/staticexport/CmsStaticExportManager.java#L830-L833
JOML-CI/JOML
src/org/joml/Matrix4f.java
Matrix4f.lookAtLH
public Matrix4f lookAtLH(float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ) { """ Apply a "lookat" transformation to this matrix for a left-handed coordinate system, that aligns <code>+z</code> with <code>center - eye</code>. <p> If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookat matrix, then the new matrix will be <code>M * L</code>. So when transforming a vector <code>v</code> with the new matrix by using <code>M * L * v</code>, the lookat transformation will be applied first! <p> In order to set the matrix to a lookat transformation without post-multiplying it, use {@link #setLookAtLH(float, float, float, float, float, float, float, float, float) setLookAtLH()}. @see #lookAtLH(Vector3fc, Vector3fc, Vector3fc) @see #setLookAtLH(float, float, float, float, float, float, float, float, float) @param eyeX the x-coordinate of the eye/camera location @param eyeY the y-coordinate of the eye/camera location @param eyeZ the z-coordinate of the eye/camera location @param centerX the x-coordinate of the point to look at @param centerY the y-coordinate of the point to look at @param centerZ the z-coordinate of the point to look at @param upX the x-coordinate of the up vector @param upY the y-coordinate of the up vector @param upZ the z-coordinate of the up vector @return a matrix holding the result """ return lookAtLH(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ, thisOrNew()); }
java
public Matrix4f lookAtLH(float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ) { return lookAtLH(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ, thisOrNew()); }
[ "public", "Matrix4f", "lookAtLH", "(", "float", "eyeX", ",", "float", "eyeY", ",", "float", "eyeZ", ",", "float", "centerX", ",", "float", "centerY", ",", "float", "centerZ", ",", "float", "upX", ",", "float", "upY", ",", "float", "upZ", ")", "{", "return", "lookAtLH", "(", "eyeX", ",", "eyeY", ",", "eyeZ", ",", "centerX", ",", "centerY", ",", "centerZ", ",", "upX", ",", "upY", ",", "upZ", ",", "thisOrNew", "(", ")", ")", ";", "}" ]
Apply a "lookat" transformation to this matrix for a left-handed coordinate system, that aligns <code>+z</code> with <code>center - eye</code>. <p> If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookat matrix, then the new matrix will be <code>M * L</code>. So when transforming a vector <code>v</code> with the new matrix by using <code>M * L * v</code>, the lookat transformation will be applied first! <p> In order to set the matrix to a lookat transformation without post-multiplying it, use {@link #setLookAtLH(float, float, float, float, float, float, float, float, float) setLookAtLH()}. @see #lookAtLH(Vector3fc, Vector3fc, Vector3fc) @see #setLookAtLH(float, float, float, float, float, float, float, float, float) @param eyeX the x-coordinate of the eye/camera location @param eyeY the y-coordinate of the eye/camera location @param eyeZ the z-coordinate of the eye/camera location @param centerX the x-coordinate of the point to look at @param centerY the y-coordinate of the point to look at @param centerZ the z-coordinate of the point to look at @param upX the x-coordinate of the up vector @param upY the y-coordinate of the up vector @param upZ the z-coordinate of the up vector @return a matrix holding the result
[ "Apply", "a", "lookat", "transformation", "to", "this", "matrix", "for", "a", "left", "-", "handed", "coordinate", "system", "that", "aligns", "<code", ">", "+", "z<", "/", "code", ">", "with", "<code", ">", "center", "-", "eye<", "/", "code", ">", ".", "<p", ">", "If", "<code", ">", "M<", "/", "code", ">", "is", "<code", ">", "this<", "/", "code", ">", "matrix", "and", "<code", ">", "L<", "/", "code", ">", "the", "lookat", "matrix", "then", "the", "new", "matrix", "will", "be", "<code", ">", "M", "*", "L<", "/", "code", ">", ".", "So", "when", "transforming", "a", "vector", "<code", ">", "v<", "/", "code", ">", "with", "the", "new", "matrix", "by", "using", "<code", ">", "M", "*", "L", "*", "v<", "/", "code", ">", "the", "lookat", "transformation", "will", "be", "applied", "first!", "<p", ">", "In", "order", "to", "set", "the", "matrix", "to", "a", "lookat", "transformation", "without", "post", "-", "multiplying", "it", "use", "{", "@link", "#setLookAtLH", "(", "float", "float", "float", "float", "float", "float", "float", "float", "float", ")", "setLookAtLH", "()", "}", "." ]
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4f.java#L9091-L9095
NoraUi/NoraUi
src/main/java/com/github/noraui/application/steps/CommonSteps.java
CommonSteps.clickOnXpathByJs
@Conditioned @Quand("Je clique via js sur xpath '(.*)' de '(.*)' page[\\.|\\?]") @When("I click by js on xpath '(.*)' from '(.*)' page[\\.|\\?]") public void clickOnXpathByJs(String xpath, String page, List<GherkinStepCondition> conditions) throws TechnicalException, FailureException { """ Click on html element using Javascript if all 'expected' parameters equals 'actual' parameters in conditions. @param xpath xpath of html element @param page The concerned page of toClick @param conditions list of 'expected' values condition and 'actual' values ({@link com.github.noraui.gherkin.GherkinStepCondition}). @throws TechnicalException is thrown if you have a technical error (format, configuration, datas, ...) in NoraUi. Exception with {@value com.github.noraui.utils.Messages#FAIL_MESSAGE_UNABLE_TO_OPEN_ON_CLICK} message (with screenshot, with exception) @throws FailureException if the scenario encounters a functional error """ logger.debug("clickOnByJs with xpath {} on {} page", xpath, page); clickOnByJs(Page.getInstance(page), xpath); }
java
@Conditioned @Quand("Je clique via js sur xpath '(.*)' de '(.*)' page[\\.|\\?]") @When("I click by js on xpath '(.*)' from '(.*)' page[\\.|\\?]") public void clickOnXpathByJs(String xpath, String page, List<GherkinStepCondition> conditions) throws TechnicalException, FailureException { logger.debug("clickOnByJs with xpath {} on {} page", xpath, page); clickOnByJs(Page.getInstance(page), xpath); }
[ "@", "Conditioned", "@", "Quand", "(", "\"Je clique via js sur xpath '(.*)' de '(.*)' page[\\\\.|\\\\?]\"", ")", "@", "When", "(", "\"I click by js on xpath '(.*)' from '(.*)' page[\\\\.|\\\\?]\"", ")", "public", "void", "clickOnXpathByJs", "(", "String", "xpath", ",", "String", "page", ",", "List", "<", "GherkinStepCondition", ">", "conditions", ")", "throws", "TechnicalException", ",", "FailureException", "{", "logger", ".", "debug", "(", "\"clickOnByJs with xpath {} on {} page\"", ",", "xpath", ",", "page", ")", ";", "clickOnByJs", "(", "Page", ".", "getInstance", "(", "page", ")", ",", "xpath", ")", ";", "}" ]
Click on html element using Javascript if all 'expected' parameters equals 'actual' parameters in conditions. @param xpath xpath of html element @param page The concerned page of toClick @param conditions list of 'expected' values condition and 'actual' values ({@link com.github.noraui.gherkin.GherkinStepCondition}). @throws TechnicalException is thrown if you have a technical error (format, configuration, datas, ...) in NoraUi. Exception with {@value com.github.noraui.utils.Messages#FAIL_MESSAGE_UNABLE_TO_OPEN_ON_CLICK} message (with screenshot, with exception) @throws FailureException if the scenario encounters a functional error
[ "Click", "on", "html", "element", "using", "Javascript", "if", "all", "expected", "parameters", "equals", "actual", "parameters", "in", "conditions", "." ]
train
https://github.com/NoraUi/NoraUi/blob/5f491a3339c7d3c20d7207760bdaf2acdb8f260c/src/main/java/com/github/noraui/application/steps/CommonSteps.java#L430-L436
ModeShape/modeshape
modeshape-jcr/src/main/java/org/modeshape/jcr/spi/index/provider/IndexChangeAdapters.java
IndexChangeAdapters.forMixinTypes
public static IndexChangeAdapter forMixinTypes( ExecutionContext context, NodeTypePredicate matcher, String workspaceName, ProvidedIndex<?> index ) { """ Create an {@link IndexChangeAdapter} implementation that handles the "jcr:mixinTypes" property. @param context the execution context; may not be null @param matcher the node type matcher used to determine which nodes should be included in the index; may not be null @param workspaceName the name of the workspace; may not be null @param index the local index that should be used; may not be null @return the new {@link IndexChangeAdapter}; never null """ return new MixinTypesChangeAdapter(context, matcher, workspaceName, index); }
java
public static IndexChangeAdapter forMixinTypes( ExecutionContext context, NodeTypePredicate matcher, String workspaceName, ProvidedIndex<?> index ) { return new MixinTypesChangeAdapter(context, matcher, workspaceName, index); }
[ "public", "static", "IndexChangeAdapter", "forMixinTypes", "(", "ExecutionContext", "context", ",", "NodeTypePredicate", "matcher", ",", "String", "workspaceName", ",", "ProvidedIndex", "<", "?", ">", "index", ")", "{", "return", "new", "MixinTypesChangeAdapter", "(", "context", ",", "matcher", ",", "workspaceName", ",", "index", ")", ";", "}" ]
Create an {@link IndexChangeAdapter} implementation that handles the "jcr:mixinTypes" property. @param context the execution context; may not be null @param matcher the node type matcher used to determine which nodes should be included in the index; may not be null @param workspaceName the name of the workspace; may not be null @param index the local index that should be used; may not be null @return the new {@link IndexChangeAdapter}; never null
[ "Create", "an", "{", "@link", "IndexChangeAdapter", "}", "implementation", "that", "handles", "the", "jcr", ":", "mixinTypes", "property", "." ]
train
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-jcr/src/main/java/org/modeshape/jcr/spi/index/provider/IndexChangeAdapters.java#L160-L165
elki-project/elki
elki-core-util/src/main/java/de/lmu/ifi/dbs/elki/utilities/datastructures/QuickSelect.java
QuickSelect.quickSelect
public static double quickSelect(double[] data, int rank) { """ QuickSelect is essentially quicksort, except that we only "sort" that half of the array that we are interested in. Note: the array is <b>modified</b> by this. @param data Data to process @param rank Rank position that we are interested in (integer!) @return Value at the given rank """ quickSelect(data, 0, data.length, rank); return data[rank]; }
java
public static double quickSelect(double[] data, int rank) { quickSelect(data, 0, data.length, rank); return data[rank]; }
[ "public", "static", "double", "quickSelect", "(", "double", "[", "]", "data", ",", "int", "rank", ")", "{", "quickSelect", "(", "data", ",", "0", ",", "data", ".", "length", ",", "rank", ")", ";", "return", "data", "[", "rank", "]", ";", "}" ]
QuickSelect is essentially quicksort, except that we only "sort" that half of the array that we are interested in. Note: the array is <b>modified</b> by this. @param data Data to process @param rank Rank position that we are interested in (integer!) @return Value at the given rank
[ "QuickSelect", "is", "essentially", "quicksort", "except", "that", "we", "only", "sort", "that", "half", "of", "the", "array", "that", "we", "are", "interested", "in", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-util/src/main/java/de/lmu/ifi/dbs/elki/utilities/datastructures/QuickSelect.java#L362-L365
VoltDB/voltdb
src/frontend/org/voltdb/jdbc/JDBC4PreparedStatement.java
JDBC4PreparedStatement.setBytes
@Override public void setBytes(int parameterIndex, byte[] x) throws SQLException { """ Sets the designated parameter to the given Java array of bytes. """ checkParameterBounds(parameterIndex); this.parameters[parameterIndex-1] = x; }
java
@Override public void setBytes(int parameterIndex, byte[] x) throws SQLException { checkParameterBounds(parameterIndex); this.parameters[parameterIndex-1] = x; }
[ "@", "Override", "public", "void", "setBytes", "(", "int", "parameterIndex", ",", "byte", "[", "]", "x", ")", "throws", "SQLException", "{", "checkParameterBounds", "(", "parameterIndex", ")", ";", "this", ".", "parameters", "[", "parameterIndex", "-", "1", "]", "=", "x", ";", "}" ]
Sets the designated parameter to the given Java array of bytes.
[ "Sets", "the", "designated", "parameter", "to", "the", "given", "Java", "array", "of", "bytes", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/jdbc/JDBC4PreparedStatement.java#L262-L267
xm-online/xm-commons
xm-commons-permission/src/main/java/com/icthh/xm/commons/permission/inspector/kafka/PrivilegeEventProducer.java
PrivilegeEventProducer.sendEvent
public void sendEvent(String eventId, Set<Privilege> privileges) { """ Build MS_PRIVILEGES message for system queue event and send it. @param eventId the event id @param privileges the event data (privileges) """ // TODO do not use yml in json events... String ymlPrivileges = PrivilegeMapper.privilegesToYml(privileges); SystemEvent event = buildSystemEvent(eventId, ymlPrivileges); serializeEvent(event).ifPresent(this::send); }
java
public void sendEvent(String eventId, Set<Privilege> privileges) { // TODO do not use yml in json events... String ymlPrivileges = PrivilegeMapper.privilegesToYml(privileges); SystemEvent event = buildSystemEvent(eventId, ymlPrivileges); serializeEvent(event).ifPresent(this::send); }
[ "public", "void", "sendEvent", "(", "String", "eventId", ",", "Set", "<", "Privilege", ">", "privileges", ")", "{", "// TODO do not use yml in json events...", "String", "ymlPrivileges", "=", "PrivilegeMapper", ".", "privilegesToYml", "(", "privileges", ")", ";", "SystemEvent", "event", "=", "buildSystemEvent", "(", "eventId", ",", "ymlPrivileges", ")", ";", "serializeEvent", "(", "event", ")", ".", "ifPresent", "(", "this", "::", "send", ")", ";", "}" ]
Build MS_PRIVILEGES message for system queue event and send it. @param eventId the event id @param privileges the event data (privileges)
[ "Build", "MS_PRIVILEGES", "message", "for", "system", "queue", "event", "and", "send", "it", "." ]
train
https://github.com/xm-online/xm-commons/blob/43eb2273adb96f40830d7b905ee3a767b8715caf/xm-commons-permission/src/main/java/com/icthh/xm/commons/permission/inspector/kafka/PrivilegeEventProducer.java#L60-L66
foundation-runtime/service-directory
1.2/sd-api/src/main/java/com/cisco/oss/foundation/directory/registration/DirectoryRegistrationService.java
DirectoryRegistrationService.unregisterService
public void unregisterService(String serviceName, String providerAddress) { """ Unregister a ProvidedServiceInstance The ProvidedServiceInstance is uniquely identified by serviceName and providerAddress @param serviceName the serviceName of ProvidedServiceInstance. @param providerAddress the provierAddress of ProvidedServiceInstance. """ getServiceDirectoryClient().unregisterInstance(serviceName, providerAddress, disableOwnerError); }
java
public void unregisterService(String serviceName, String providerAddress) { getServiceDirectoryClient().unregisterInstance(serviceName, providerAddress, disableOwnerError); }
[ "public", "void", "unregisterService", "(", "String", "serviceName", ",", "String", "providerAddress", ")", "{", "getServiceDirectoryClient", "(", ")", ".", "unregisterInstance", "(", "serviceName", ",", "providerAddress", ",", "disableOwnerError", ")", ";", "}" ]
Unregister a ProvidedServiceInstance The ProvidedServiceInstance is uniquely identified by serviceName and providerAddress @param serviceName the serviceName of ProvidedServiceInstance. @param providerAddress the provierAddress of ProvidedServiceInstance.
[ "Unregister", "a", "ProvidedServiceInstance", "The", "ProvidedServiceInstance", "is", "uniquely", "identified", "by", "serviceName", "and", "providerAddress" ]
train
https://github.com/foundation-runtime/service-directory/blob/a7bdefe173dc99e75eff4a24e07e6407e62f2ed4/1.2/sd-api/src/main/java/com/cisco/oss/foundation/directory/registration/DirectoryRegistrationService.java#L195-L197
apereo/cas
core/cas-server-core-webflow-api/src/main/java/org/apereo/cas/web/flow/actions/AuthenticationExceptionHandlerAction.java
AuthenticationExceptionHandlerAction.handleAuthenticationException
protected String handleAuthenticationException(final AuthenticationException e, final RequestContext requestContext) { """ Maps an authentication exception onto a state name equal to the simple class name of the handler errors. with highest precedence. Also sets an ERROR severity message in the message context of the form {@code [messageBundlePrefix][exceptionClassSimpleName]} for for the first handler error that is configured. If no match is found, {@value #UNKNOWN} is returned. @param e Authentication error to handle. @param requestContext the spring context @return Name of next flow state to transition to or {@value #UNKNOWN} """ if (e.getHandlerErrors().containsKey(UnauthorizedServiceForPrincipalException.class.getSimpleName())) { val url = WebUtils.getUnauthorizedRedirectUrlFromFlowScope(requestContext); if (url != null) { LOGGER.warn("Unauthorized service access for principal; CAS will be redirecting to [{}]", url); return CasWebflowConstants.STATE_ID_SERVICE_UNAUTHZ_CHECK; } } val values = e.getHandlerErrors().values().stream().map(Throwable::getClass).collect(Collectors.toList()); val handlerErrorName = this.errors .stream() .filter(values::contains) .map(Class::getSimpleName) .findFirst() .orElseGet(() -> { LOGGER.debug("Unable to translate handler errors of the authentication exception [{}]. Returning [{}]", e, UNKNOWN); return UNKNOWN; }); val messageContext = requestContext.getMessageContext(); val messageCode = this.messageBundlePrefix + handlerErrorName; messageContext.addMessage(new MessageBuilder().error().code(messageCode).build()); return handlerErrorName; }
java
protected String handleAuthenticationException(final AuthenticationException e, final RequestContext requestContext) { if (e.getHandlerErrors().containsKey(UnauthorizedServiceForPrincipalException.class.getSimpleName())) { val url = WebUtils.getUnauthorizedRedirectUrlFromFlowScope(requestContext); if (url != null) { LOGGER.warn("Unauthorized service access for principal; CAS will be redirecting to [{}]", url); return CasWebflowConstants.STATE_ID_SERVICE_UNAUTHZ_CHECK; } } val values = e.getHandlerErrors().values().stream().map(Throwable::getClass).collect(Collectors.toList()); val handlerErrorName = this.errors .stream() .filter(values::contains) .map(Class::getSimpleName) .findFirst() .orElseGet(() -> { LOGGER.debug("Unable to translate handler errors of the authentication exception [{}]. Returning [{}]", e, UNKNOWN); return UNKNOWN; }); val messageContext = requestContext.getMessageContext(); val messageCode = this.messageBundlePrefix + handlerErrorName; messageContext.addMessage(new MessageBuilder().error().code(messageCode).build()); return handlerErrorName; }
[ "protected", "String", "handleAuthenticationException", "(", "final", "AuthenticationException", "e", ",", "final", "RequestContext", "requestContext", ")", "{", "if", "(", "e", ".", "getHandlerErrors", "(", ")", ".", "containsKey", "(", "UnauthorizedServiceForPrincipalException", ".", "class", ".", "getSimpleName", "(", ")", ")", ")", "{", "val", "url", "=", "WebUtils", ".", "getUnauthorizedRedirectUrlFromFlowScope", "(", "requestContext", ")", ";", "if", "(", "url", "!=", "null", ")", "{", "LOGGER", ".", "warn", "(", "\"Unauthorized service access for principal; CAS will be redirecting to [{}]\"", ",", "url", ")", ";", "return", "CasWebflowConstants", ".", "STATE_ID_SERVICE_UNAUTHZ_CHECK", ";", "}", "}", "val", "values", "=", "e", ".", "getHandlerErrors", "(", ")", ".", "values", "(", ")", ".", "stream", "(", ")", ".", "map", "(", "Throwable", "::", "getClass", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ";", "val", "handlerErrorName", "=", "this", ".", "errors", ".", "stream", "(", ")", ".", "filter", "(", "values", "::", "contains", ")", ".", "map", "(", "Class", "::", "getSimpleName", ")", ".", "findFirst", "(", ")", ".", "orElseGet", "(", "(", ")", "->", "{", "LOGGER", ".", "debug", "(", "\"Unable to translate handler errors of the authentication exception [{}]. Returning [{}]\"", ",", "e", ",", "UNKNOWN", ")", ";", "return", "UNKNOWN", ";", "}", ")", ";", "val", "messageContext", "=", "requestContext", ".", "getMessageContext", "(", ")", ";", "val", "messageCode", "=", "this", ".", "messageBundlePrefix", "+", "handlerErrorName", ";", "messageContext", ".", "addMessage", "(", "new", "MessageBuilder", "(", ")", ".", "error", "(", ")", ".", "code", "(", "messageCode", ")", ".", "build", "(", ")", ")", ";", "return", "handlerErrorName", ";", "}" ]
Maps an authentication exception onto a state name equal to the simple class name of the handler errors. with highest precedence. Also sets an ERROR severity message in the message context of the form {@code [messageBundlePrefix][exceptionClassSimpleName]} for for the first handler error that is configured. If no match is found, {@value #UNKNOWN} is returned. @param e Authentication error to handle. @param requestContext the spring context @return Name of next flow state to transition to or {@value #UNKNOWN}
[ "Maps", "an", "authentication", "exception", "onto", "a", "state", "name", "equal", "to", "the", "simple", "class", "name", "of", "the", "handler", "errors", ".", "with", "highest", "precedence", ".", "Also", "sets", "an", "ERROR", "severity", "message", "in", "the", "message", "context", "of", "the", "form", "{", "@code", "[", "messageBundlePrefix", "]", "[", "exceptionClassSimpleName", "]", "}", "for", "for", "the", "first", "handler", "error", "that", "is", "configured", ".", "If", "no", "match", "is", "found", "{", "@value", "#UNKNOWN", "}", "is", "returned", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-webflow-api/src/main/java/org/apereo/cas/web/flow/actions/AuthenticationExceptionHandlerAction.java#L102-L125
BrunoEberhard/minimal-j
src/main/java/org/minimalj/repository/DataSourceFactory.java
DataSourceFactory.oracleDbDataSource
public static DataSource oracleDbDataSource(String url, String user, String password) { """ Don't forget to add the dependency to ojdbc like this in your pom.xml <pre> &lt;dependency&gt; &lt;groupId&gt;com.oracle&lt;/groupId&gt; &lt;artifactId&gt;ojdbc7&lt;/artifactId&gt; &lt;version&gt;12.1.0.2&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; </pre> You need to register at the oracle maven repository to actually get the driver. @param url for example "jdbc:oracle:thin:@localhost:1521:orcl" @param user User @param password Password @return DataSource """ try { @SuppressWarnings("unchecked") Class<? extends DataSource> dataSourceClass = (Class<? extends DataSource>) Class.forName("oracle.jdbc.pool.OracleDataSource"); DataSource dataSource = dataSourceClass.newInstance(); dataSourceClass.getMethod("setURL", String.class).invoke(dataSource, url); dataSourceClass.getMethod("setUser", String.class).invoke(dataSource, user); dataSourceClass.getMethod("setPassword", String.class).invoke(dataSource, password); // OracleDataSource dataSource = new OracleDataSource(); // dataSource.setURL(url); // dataSource.setUser(user); // dataSource.setPassword(password); return dataSource; } catch (Exception e) { throw new LoggingRuntimeException(e, logger, "Cannot connect to oracle db"); } }
java
public static DataSource oracleDbDataSource(String url, String user, String password) { try { @SuppressWarnings("unchecked") Class<? extends DataSource> dataSourceClass = (Class<? extends DataSource>) Class.forName("oracle.jdbc.pool.OracleDataSource"); DataSource dataSource = dataSourceClass.newInstance(); dataSourceClass.getMethod("setURL", String.class).invoke(dataSource, url); dataSourceClass.getMethod("setUser", String.class).invoke(dataSource, user); dataSourceClass.getMethod("setPassword", String.class).invoke(dataSource, password); // OracleDataSource dataSource = new OracleDataSource(); // dataSource.setURL(url); // dataSource.setUser(user); // dataSource.setPassword(password); return dataSource; } catch (Exception e) { throw new LoggingRuntimeException(e, logger, "Cannot connect to oracle db"); } }
[ "public", "static", "DataSource", "oracleDbDataSource", "(", "String", "url", ",", "String", "user", ",", "String", "password", ")", "{", "try", "{", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "Class", "<", "?", "extends", "DataSource", ">", "dataSourceClass", "=", "(", "Class", "<", "?", "extends", "DataSource", ">", ")", "Class", ".", "forName", "(", "\"oracle.jdbc.pool.OracleDataSource\"", ")", ";", "DataSource", "dataSource", "=", "dataSourceClass", ".", "newInstance", "(", ")", ";", "dataSourceClass", ".", "getMethod", "(", "\"setURL\"", ",", "String", ".", "class", ")", ".", "invoke", "(", "dataSource", ",", "url", ")", ";", "dataSourceClass", ".", "getMethod", "(", "\"setUser\"", ",", "String", ".", "class", ")", ".", "invoke", "(", "dataSource", ",", "user", ")", ";", "dataSourceClass", ".", "getMethod", "(", "\"setPassword\"", ",", "String", ".", "class", ")", ".", "invoke", "(", "dataSource", ",", "password", ")", ";", "// OracleDataSource dataSource = new OracleDataSource();", "// dataSource.setURL(url);", "// dataSource.setUser(user);", "// dataSource.setPassword(password);", "return", "dataSource", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "LoggingRuntimeException", "(", "e", ",", "logger", ",", "\"Cannot connect to oracle db\"", ")", ";", "}", "}" ]
Don't forget to add the dependency to ojdbc like this in your pom.xml <pre> &lt;dependency&gt; &lt;groupId&gt;com.oracle&lt;/groupId&gt; &lt;artifactId&gt;ojdbc7&lt;/artifactId&gt; &lt;version&gt;12.1.0.2&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; </pre> You need to register at the oracle maven repository to actually get the driver. @param url for example "jdbc:oracle:thin:@localhost:1521:orcl" @param user User @param password Password @return DataSource
[ "Don", "t", "forget", "to", "add", "the", "dependency", "to", "ojdbc", "like", "this", "in", "your", "pom", ".", "xml", "<pre", ">", "&lt", ";", "dependency&gt", ";", "&lt", ";", "groupId&gt", ";", "com", ".", "oracle&lt", ";", "/", "groupId&gt", ";", "&lt", ";", "artifactId&gt", ";", "ojdbc7&lt", ";", "/", "artifactId&gt", ";", "&lt", ";", "version&gt", ";", "12", ".", "1", ".", "0", ".", "2&lt", ";", "/", "version&gt", ";", "&lt", ";", "scope&gt", ";", "provided&lt", ";", "/", "scope&gt", ";", "&lt", ";", "/", "dependency&gt", ";", "<", "/", "pre", ">" ]
train
https://github.com/BrunoEberhard/minimal-j/blob/f7c5461b2b47a10b383aee1e2f1f150f6773703b/src/main/java/org/minimalj/repository/DataSourceFactory.java#L148-L165
acromusashi/acromusashi-stream
src/main/java/acromusashi/stream/component/rabbitmq/RabbitmqClusterContext.java
RabbitmqClusterContext.setConnectionProcessMap
public void setConnectionProcessMap(Map<String, String> connectionProcessMap) throws RabbitmqCommunicateException { """ 呼出元別、接続先RabbitMQプロセスの定義マップを検証して設定する。 @param connectionProcessMap the connectionProcessMap to set @throws RabbitmqCommunicateException 接続先RabbitMQプロセスがRabbitMQプロセス一覧に定義されていない場合 """ Map<String, String> tempConnectionProcessMap = connectionProcessMap; if (connectionProcessMap == null) { tempConnectionProcessMap = new HashMap<String, String>(); } validateProcessReference(this.mqProcessList, tempConnectionProcessMap); this.connectionProcessMap = tempConnectionProcessMap; }
java
public void setConnectionProcessMap(Map<String, String> connectionProcessMap) throws RabbitmqCommunicateException { Map<String, String> tempConnectionProcessMap = connectionProcessMap; if (connectionProcessMap == null) { tempConnectionProcessMap = new HashMap<String, String>(); } validateProcessReference(this.mqProcessList, tempConnectionProcessMap); this.connectionProcessMap = tempConnectionProcessMap; }
[ "public", "void", "setConnectionProcessMap", "(", "Map", "<", "String", ",", "String", ">", "connectionProcessMap", ")", "throws", "RabbitmqCommunicateException", "{", "Map", "<", "String", ",", "String", ">", "tempConnectionProcessMap", "=", "connectionProcessMap", ";", "if", "(", "connectionProcessMap", "==", "null", ")", "{", "tempConnectionProcessMap", "=", "new", "HashMap", "<", "String", ",", "String", ">", "(", ")", ";", "}", "validateProcessReference", "(", "this", ".", "mqProcessList", ",", "tempConnectionProcessMap", ")", ";", "this", ".", "connectionProcessMap", "=", "tempConnectionProcessMap", ";", "}" ]
呼出元別、接続先RabbitMQプロセスの定義マップを検証して設定する。 @param connectionProcessMap the connectionProcessMap to set @throws RabbitmqCommunicateException 接続先RabbitMQプロセスがRabbitMQプロセス一覧に定義されていない場合
[ "呼出元別、接続先RabbitMQプロセスの定義マップを検証して設定する。" ]
train
https://github.com/acromusashi/acromusashi-stream/blob/65b1f335d771d657c5640a2056ab5c8546eddec9/src/main/java/acromusashi/stream/component/rabbitmq/RabbitmqClusterContext.java#L169-L179
lestard/advanced-bindings
src/main/java/eu/lestard/advanced_bindings/api/MathBindings.java
MathBindings.subtractExact
public static LongBinding subtractExact(final ObservableLongValue x, final ObservableLongValue y) { """ Binding for {@link java.lang.Math#subtractExact(long, long)} @param x the first value @param y the second value to subtract from the first @return the result @throws ArithmeticException if the result overflows a long """ return createLongBinding(() -> Math.subtractExact(x.get(), y.get()), x, y); }
java
public static LongBinding subtractExact(final ObservableLongValue x, final ObservableLongValue y) { return createLongBinding(() -> Math.subtractExact(x.get(), y.get()), x, y); }
[ "public", "static", "LongBinding", "subtractExact", "(", "final", "ObservableLongValue", "x", ",", "final", "ObservableLongValue", "y", ")", "{", "return", "createLongBinding", "(", "(", ")", "->", "Math", ".", "subtractExact", "(", "x", ".", "get", "(", ")", ",", "y", ".", "get", "(", ")", ")", ",", "x", ",", "y", ")", ";", "}" ]
Binding for {@link java.lang.Math#subtractExact(long, long)} @param x the first value @param y the second value to subtract from the first @return the result @throws ArithmeticException if the result overflows a long
[ "Binding", "for", "{", "@link", "java", ".", "lang", ".", "Math#subtractExact", "(", "long", "long", ")", "}" ]
train
https://github.com/lestard/advanced-bindings/blob/054a5dde261c29f862b971765fa3da3704a13ab4/src/main/java/eu/lestard/advanced_bindings/api/MathBindings.java#L1440-L1442
krummas/DrizzleJDBC
src/main/java/org/drizzle/jdbc/DrizzleBlob.java
DrizzleBlob.setBytes
public int setBytes(final long pos, final byte[] bytes) throws SQLException { """ Writes the given array of bytes to the <code>BLOB</code> value that this <code>Blob</code> object represents, starting at position <code>pos</code>, and returns the number of bytes written. The array of bytes will overwrite the existing bytes in the <code>Blob</code> object starting at the position <code>pos</code>. If the end of the <code>Blob</code> value is reached while writing the array of bytes, then the length of the <code>Blob</code> value will be increased to accomodate the extra bytes. <p/> <b>Note:</b> If the value specified for <code>pos</code> is greater then the length+1 of the <code>BLOB</code> value then the behavior is undefined. Some JDBC drivers may throw a <code>SQLException</code> while other drivers may support this operation. @param pos the position in the <code>BLOB</code> object at which to start writing; the first position is 1 @param bytes the array of bytes to be written to the <code>BLOB</code> value that this <code>Blob</code> object represents @return the number of bytes written @see #getBytes @since 1.4 """ final int arrayPos = (int) pos - 1; final int bytesWritten; if (blobContent == null) { this.blobContent = new byte[arrayPos + bytes.length]; bytesWritten = blobContent.length; this.actualSize = bytesWritten; } else if (blobContent.length > arrayPos + bytes.length) { bytesWritten = bytes.length; } else { blobContent = Utils.copyWithLength(blobContent, arrayPos + bytes.length); actualSize = blobContent.length; bytesWritten = bytes.length; } System.arraycopy(bytes, 0, this.blobContent, arrayPos, bytes.length); return bytesWritten; }
java
public int setBytes(final long pos, final byte[] bytes) throws SQLException { final int arrayPos = (int) pos - 1; final int bytesWritten; if (blobContent == null) { this.blobContent = new byte[arrayPos + bytes.length]; bytesWritten = blobContent.length; this.actualSize = bytesWritten; } else if (blobContent.length > arrayPos + bytes.length) { bytesWritten = bytes.length; } else { blobContent = Utils.copyWithLength(blobContent, arrayPos + bytes.length); actualSize = blobContent.length; bytesWritten = bytes.length; } System.arraycopy(bytes, 0, this.blobContent, arrayPos, bytes.length); return bytesWritten; }
[ "public", "int", "setBytes", "(", "final", "long", "pos", ",", "final", "byte", "[", "]", "bytes", ")", "throws", "SQLException", "{", "final", "int", "arrayPos", "=", "(", "int", ")", "pos", "-", "1", ";", "final", "int", "bytesWritten", ";", "if", "(", "blobContent", "==", "null", ")", "{", "this", ".", "blobContent", "=", "new", "byte", "[", "arrayPos", "+", "bytes", ".", "length", "]", ";", "bytesWritten", "=", "blobContent", ".", "length", ";", "this", ".", "actualSize", "=", "bytesWritten", ";", "}", "else", "if", "(", "blobContent", ".", "length", ">", "arrayPos", "+", "bytes", ".", "length", ")", "{", "bytesWritten", "=", "bytes", ".", "length", ";", "}", "else", "{", "blobContent", "=", "Utils", ".", "copyWithLength", "(", "blobContent", ",", "arrayPos", "+", "bytes", ".", "length", ")", ";", "actualSize", "=", "blobContent", ".", "length", ";", "bytesWritten", "=", "bytes", ".", "length", ";", "}", "System", ".", "arraycopy", "(", "bytes", ",", "0", ",", "this", ".", "blobContent", ",", "arrayPos", ",", "bytes", ".", "length", ")", ";", "return", "bytesWritten", ";", "}" ]
Writes the given array of bytes to the <code>BLOB</code> value that this <code>Blob</code> object represents, starting at position <code>pos</code>, and returns the number of bytes written. The array of bytes will overwrite the existing bytes in the <code>Blob</code> object starting at the position <code>pos</code>. If the end of the <code>Blob</code> value is reached while writing the array of bytes, then the length of the <code>Blob</code> value will be increased to accomodate the extra bytes. <p/> <b>Note:</b> If the value specified for <code>pos</code> is greater then the length+1 of the <code>BLOB</code> value then the behavior is undefined. Some JDBC drivers may throw a <code>SQLException</code> while other drivers may support this operation. @param pos the position in the <code>BLOB</code> object at which to start writing; the first position is 1 @param bytes the array of bytes to be written to the <code>BLOB</code> value that this <code>Blob</code> object represents @return the number of bytes written @see #getBytes @since 1.4
[ "Writes", "the", "given", "array", "of", "bytes", "to", "the", "<code", ">", "BLOB<", "/", "code", ">", "value", "that", "this", "<code", ">", "Blob<", "/", "code", ">", "object", "represents", "starting", "at", "position", "<code", ">", "pos<", "/", "code", ">", "and", "returns", "the", "number", "of", "bytes", "written", ".", "The", "array", "of", "bytes", "will", "overwrite", "the", "existing", "bytes", "in", "the", "<code", ">", "Blob<", "/", "code", ">", "object", "starting", "at", "the", "position", "<code", ">", "pos<", "/", "code", ">", ".", "If", "the", "end", "of", "the", "<code", ">", "Blob<", "/", "code", ">", "value", "is", "reached", "while", "writing", "the", "array", "of", "bytes", "then", "the", "length", "of", "the", "<code", ">", "Blob<", "/", "code", ">", "value", "will", "be", "increased", "to", "accomodate", "the", "extra", "bytes", ".", "<p", "/", ">", "<b", ">", "Note", ":", "<", "/", "b", ">", "If", "the", "value", "specified", "for", "<code", ">", "pos<", "/", "code", ">", "is", "greater", "then", "the", "length", "+", "1", "of", "the", "<code", ">", "BLOB<", "/", "code", ">", "value", "then", "the", "behavior", "is", "undefined", ".", "Some", "JDBC", "drivers", "may", "throw", "a", "<code", ">", "SQLException<", "/", "code", ">", "while", "other", "drivers", "may", "support", "this", "operation", "." ]
train
https://github.com/krummas/DrizzleJDBC/blob/716f31fd71f3cc289edf69844d8117deb86d98d6/src/main/java/org/drizzle/jdbc/DrizzleBlob.java#L207-L226
actorapp/actor-platform
actor-sdk/sdk-core/runtime/runtime-shared/src/main/java/im/actor/runtime/markdown/MarkdownParser.java
MarkdownParser.findSpanStart
private int findSpanStart(TextCursor cursor, int limit) { """ Searching for valid formatting span start @param cursor text cursor @param limit maximum index in cursor @return span start, -1 if not found """ for (int i = cursor.currentOffset; i < limit; i++) { char c = cursor.text.charAt(i); if (c == '*' || c == '_') { // Check prev and next symbols if (isGoodAnchor(cursor.text, i - 1) && isNotSymbol(cursor.text, i + 1, c)) { return i; } } } return -1; }
java
private int findSpanStart(TextCursor cursor, int limit) { for (int i = cursor.currentOffset; i < limit; i++) { char c = cursor.text.charAt(i); if (c == '*' || c == '_') { // Check prev and next symbols if (isGoodAnchor(cursor.text, i - 1) && isNotSymbol(cursor.text, i + 1, c)) { return i; } } } return -1; }
[ "private", "int", "findSpanStart", "(", "TextCursor", "cursor", ",", "int", "limit", ")", "{", "for", "(", "int", "i", "=", "cursor", ".", "currentOffset", ";", "i", "<", "limit", ";", "i", "++", ")", "{", "char", "c", "=", "cursor", ".", "text", ".", "charAt", "(", "i", ")", ";", "if", "(", "c", "==", "'", "'", "||", "c", "==", "'", "'", ")", "{", "// Check prev and next symbols", "if", "(", "isGoodAnchor", "(", "cursor", ".", "text", ",", "i", "-", "1", ")", "&&", "isNotSymbol", "(", "cursor", ".", "text", ",", "i", "+", "1", ",", "c", ")", ")", "{", "return", "i", ";", "}", "}", "}", "return", "-", "1", ";", "}" ]
Searching for valid formatting span start @param cursor text cursor @param limit maximum index in cursor @return span start, -1 if not found
[ "Searching", "for", "valid", "formatting", "span", "start" ]
train
https://github.com/actorapp/actor-platform/blob/5123c1584757c6eeea0ed2a0e7e043629871a0c6/actor-sdk/sdk-core/runtime/runtime-shared/src/main/java/im/actor/runtime/markdown/MarkdownParser.java#L271-L282
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/clustering/GvmSpace.java
GvmSpace.distance
public double distance(Object pt1, Object pt2) { """ not used directly in algorithm, but useful - override for good performance """ Object p = newCopy(pt1); subtract(p, pt2); return magnitude(p); }
java
public double distance(Object pt1, Object pt2) { Object p = newCopy(pt1); subtract(p, pt2); return magnitude(p); }
[ "public", "double", "distance", "(", "Object", "pt1", ",", "Object", "pt2", ")", "{", "Object", "p", "=", "newCopy", "(", "pt1", ")", ";", "subtract", "(", "p", ",", "pt2", ")", ";", "return", "magnitude", "(", "p", ")", ";", "}" ]
not used directly in algorithm, but useful - override for good performance
[ "not", "used", "directly", "in", "algorithm", "but", "useful", "-", "override", "for", "good", "performance" ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/clustering/GvmSpace.java#L24-L28
UrielCh/ovh-java-sdk
ovh-java-sdk-ip/src/main/java/net/minidev/ovh/api/ApiOvhIp.java
ApiOvhIp.ip_firewall_ipOnFirewall_PUT
public void ip_firewall_ipOnFirewall_PUT(String ip, String ipOnFirewall, OvhFirewallIp body) throws IOException { """ Alter this object properties REST: PUT /ip/{ip}/firewall/{ipOnFirewall} @param body [required] New object properties @param ip [required] @param ipOnFirewall [required] """ String qPath = "/ip/{ip}/firewall/{ipOnFirewall}"; StringBuilder sb = path(qPath, ip, ipOnFirewall); exec(qPath, "PUT", sb.toString(), body); }
java
public void ip_firewall_ipOnFirewall_PUT(String ip, String ipOnFirewall, OvhFirewallIp body) throws IOException { String qPath = "/ip/{ip}/firewall/{ipOnFirewall}"; StringBuilder sb = path(qPath, ip, ipOnFirewall); exec(qPath, "PUT", sb.toString(), body); }
[ "public", "void", "ip_firewall_ipOnFirewall_PUT", "(", "String", "ip", ",", "String", "ipOnFirewall", ",", "OvhFirewallIp", "body", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/ip/{ip}/firewall/{ipOnFirewall}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "ip", ",", "ipOnFirewall", ")", ";", "exec", "(", "qPath", ",", "\"PUT\"", ",", "sb", ".", "toString", "(", ")", ",", "body", ")", ";", "}" ]
Alter this object properties REST: PUT /ip/{ip}/firewall/{ipOnFirewall} @param body [required] New object properties @param ip [required] @param ipOnFirewall [required]
[ "Alter", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-ip/src/main/java/net/minidev/ovh/api/ApiOvhIp.java#L1020-L1024
javaruntype/javaruntype
src/main/java/org/javaruntype/util/Utils.java
Utils.removeAllWhitespaces
public static String removeAllWhitespaces(final String string) { """ <p> Internal utility method. DO NOT use this method directly. </p> @param string text from which all whitespace will be removed @return the text without whitespace """ if (string == null || string.length() == 0) { return string; } final int originalSize = string.length(); final char[] charArray = new char[originalSize]; int charCount = 0; for (int i = 0; i < originalSize; i++) { final char currentChar = string.charAt(i); if (!Character.isWhitespace(currentChar)) { charArray[charCount++] = currentChar; } } if (charCount == originalSize) { return string; } return new String(charArray, 0, charCount); }
java
public static String removeAllWhitespaces(final String string) { if (string == null || string.length() == 0) { return string; } final int originalSize = string.length(); final char[] charArray = new char[originalSize]; int charCount = 0; for (int i = 0; i < originalSize; i++) { final char currentChar = string.charAt(i); if (!Character.isWhitespace(currentChar)) { charArray[charCount++] = currentChar; } } if (charCount == originalSize) { return string; } return new String(charArray, 0, charCount); }
[ "public", "static", "String", "removeAllWhitespaces", "(", "final", "String", "string", ")", "{", "if", "(", "string", "==", "null", "||", "string", ".", "length", "(", ")", "==", "0", ")", "{", "return", "string", ";", "}", "final", "int", "originalSize", "=", "string", ".", "length", "(", ")", ";", "final", "char", "[", "]", "charArray", "=", "new", "char", "[", "originalSize", "]", ";", "int", "charCount", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "originalSize", ";", "i", "++", ")", "{", "final", "char", "currentChar", "=", "string", ".", "charAt", "(", "i", ")", ";", "if", "(", "!", "Character", ".", "isWhitespace", "(", "currentChar", ")", ")", "{", "charArray", "[", "charCount", "++", "]", "=", "currentChar", ";", "}", "}", "if", "(", "charCount", "==", "originalSize", ")", "{", "return", "string", ";", "}", "return", "new", "String", "(", "charArray", ",", "0", ",", "charCount", ")", ";", "}" ]
<p> Internal utility method. DO NOT use this method directly. </p> @param string text from which all whitespace will be removed @return the text without whitespace
[ "<p", ">", "Internal", "utility", "method", ".", "DO", "NOT", "use", "this", "method", "directly", ".", "<", "/", "p", ">" ]
train
https://github.com/javaruntype/javaruntype/blob/d3c522d16fd2295d09a11570d8c951c4821eff0a/src/main/java/org/javaruntype/util/Utils.java#L208-L225
apache/groovy
src/main/java/org/codehaus/groovy/ast/expr/BinaryExpression.java
BinaryExpression.newAssignmentExpression
public static BinaryExpression newAssignmentExpression(Variable variable, Expression rhs) { """ Creates an assignment expression in which the specified expression is written into the specified variable name. """ VariableExpression lhs = new VariableExpression(variable); Token operator = Token.newPlaceholder(Types.ASSIGN); return new BinaryExpression(lhs, operator, rhs); }
java
public static BinaryExpression newAssignmentExpression(Variable variable, Expression rhs) { VariableExpression lhs = new VariableExpression(variable); Token operator = Token.newPlaceholder(Types.ASSIGN); return new BinaryExpression(lhs, operator, rhs); }
[ "public", "static", "BinaryExpression", "newAssignmentExpression", "(", "Variable", "variable", ",", "Expression", "rhs", ")", "{", "VariableExpression", "lhs", "=", "new", "VariableExpression", "(", "variable", ")", ";", "Token", "operator", "=", "Token", ".", "newPlaceholder", "(", "Types", ".", "ASSIGN", ")", ";", "return", "new", "BinaryExpression", "(", "lhs", ",", "operator", ",", "rhs", ")", ";", "}" ]
Creates an assignment expression in which the specified expression is written into the specified variable name.
[ "Creates", "an", "assignment", "expression", "in", "which", "the", "specified", "expression", "is", "written", "into", "the", "specified", "variable", "name", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/ast/expr/BinaryExpression.java#L108-L113
kiswanij/jk-util
src/main/java/com/jk/util/JKObjectUtil.java
JKObjectUtil.getFieldValue
public static Object getFieldValue(Object instance, String fieldName) { """ Gets the field value. @param instance the instance @param fieldName the field name @return the field value """ try { return PropertyUtils.getProperty(instance, fieldName); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { JK.throww(e); return null; } }
java
public static Object getFieldValue(Object instance, String fieldName) { try { return PropertyUtils.getProperty(instance, fieldName); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { JK.throww(e); return null; } }
[ "public", "static", "Object", "getFieldValue", "(", "Object", "instance", ",", "String", "fieldName", ")", "{", "try", "{", "return", "PropertyUtils", ".", "getProperty", "(", "instance", ",", "fieldName", ")", ";", "}", "catch", "(", "IllegalAccessException", "|", "InvocationTargetException", "|", "NoSuchMethodException", "e", ")", "{", "JK", ".", "throww", "(", "e", ")", ";", "return", "null", ";", "}", "}" ]
Gets the field value. @param instance the instance @param fieldName the field name @return the field value
[ "Gets", "the", "field", "value", "." ]
train
https://github.com/kiswanij/jk-util/blob/8e0c85818423406f769444c76194a748e0a0fc0a/src/main/java/com/jk/util/JKObjectUtil.java#L402-L409
graknlabs/grakn
server/src/graql/analytics/Utility.java
Utility.getResourceEdgeId
public static ConceptId getResourceEdgeId(TransactionOLTP graph, ConceptId conceptId1, ConceptId conceptId2) { """ Get the resource edge id if there is one. Return null if not. """ if (mayHaveResourceEdge(graph, conceptId1, conceptId2)) { Optional<Concept> firstConcept = graph.stream(Graql.match( var("x").id(conceptId1.getValue()), var("y").id(conceptId2.getValue()), var("z").rel(var("x")).rel(var("y"))) .get("z")) .map(answer -> answer.get("z")) .findFirst(); if (firstConcept.isPresent()) { return firstConcept.get().id(); } } return null; }
java
public static ConceptId getResourceEdgeId(TransactionOLTP graph, ConceptId conceptId1, ConceptId conceptId2) { if (mayHaveResourceEdge(graph, conceptId1, conceptId2)) { Optional<Concept> firstConcept = graph.stream(Graql.match( var("x").id(conceptId1.getValue()), var("y").id(conceptId2.getValue()), var("z").rel(var("x")).rel(var("y"))) .get("z")) .map(answer -> answer.get("z")) .findFirst(); if (firstConcept.isPresent()) { return firstConcept.get().id(); } } return null; }
[ "public", "static", "ConceptId", "getResourceEdgeId", "(", "TransactionOLTP", "graph", ",", "ConceptId", "conceptId1", ",", "ConceptId", "conceptId2", ")", "{", "if", "(", "mayHaveResourceEdge", "(", "graph", ",", "conceptId1", ",", "conceptId2", ")", ")", "{", "Optional", "<", "Concept", ">", "firstConcept", "=", "graph", ".", "stream", "(", "Graql", ".", "match", "(", "var", "(", "\"x\"", ")", ".", "id", "(", "conceptId1", ".", "getValue", "(", ")", ")", ",", "var", "(", "\"y\"", ")", ".", "id", "(", "conceptId2", ".", "getValue", "(", ")", ")", ",", "var", "(", "\"z\"", ")", ".", "rel", "(", "var", "(", "\"x\"", ")", ")", ".", "rel", "(", "var", "(", "\"y\"", ")", ")", ")", ".", "get", "(", "\"z\"", ")", ")", ".", "map", "(", "answer", "->", "answer", ".", "get", "(", "\"z\"", ")", ")", ".", "findFirst", "(", ")", ";", "if", "(", "firstConcept", ".", "isPresent", "(", ")", ")", "{", "return", "firstConcept", ".", "get", "(", ")", ".", "id", "(", ")", ";", "}", "}", "return", "null", ";", "}" ]
Get the resource edge id if there is one. Return null if not.
[ "Get", "the", "resource", "edge", "id", "if", "there", "is", "one", ".", "Return", "null", "if", "not", "." ]
train
https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/analytics/Utility.java#L125-L139
apereo/cas
support/cas-server-support-pac4j-webflow/src/main/java/org/apereo/cas/web/flow/DelegatedClientAuthenticationAction.java
DelegatedClientAuthenticationAction.isDelegatedClientAuthorizedForService
protected boolean isDelegatedClientAuthorizedForService(final Client client, final Service service) { """ Is delegated client authorized for service boolean. @param client the client @param service the service @return the boolean """ if (service == null || StringUtils.isBlank(service.getId())) { LOGGER.debug("Can not evaluate delegated authentication policy since no service was provided in the request while processing client [{}]", client); return true; } val registeredService = this.servicesManager.findServiceBy(service); if (registeredService == null || !registeredService.getAccessStrategy().isServiceAccessAllowed()) { LOGGER.warn("Service access for [{}] is denied", registeredService); return false; } LOGGER.trace("Located registered service definition [{}] matching [{}]", registeredService, service); val context = AuditableContext.builder() .registeredService(registeredService) .properties(CollectionUtils.wrap(Client.class.getSimpleName(), client.getName())) .build(); val result = delegatedAuthenticationPolicyEnforcer.execute(context); if (!result.isExecutionFailure()) { LOGGER.debug("Delegated authentication policy for [{}] allows for using client [{}]", registeredService, client); return true; } LOGGER.warn("Delegated authentication policy for [{}] refuses access to client [{}]", registeredService.getServiceId(), client); return false; }
java
protected boolean isDelegatedClientAuthorizedForService(final Client client, final Service service) { if (service == null || StringUtils.isBlank(service.getId())) { LOGGER.debug("Can not evaluate delegated authentication policy since no service was provided in the request while processing client [{}]", client); return true; } val registeredService = this.servicesManager.findServiceBy(service); if (registeredService == null || !registeredService.getAccessStrategy().isServiceAccessAllowed()) { LOGGER.warn("Service access for [{}] is denied", registeredService); return false; } LOGGER.trace("Located registered service definition [{}] matching [{}]", registeredService, service); val context = AuditableContext.builder() .registeredService(registeredService) .properties(CollectionUtils.wrap(Client.class.getSimpleName(), client.getName())) .build(); val result = delegatedAuthenticationPolicyEnforcer.execute(context); if (!result.isExecutionFailure()) { LOGGER.debug("Delegated authentication policy for [{}] allows for using client [{}]", registeredService, client); return true; } LOGGER.warn("Delegated authentication policy for [{}] refuses access to client [{}]", registeredService.getServiceId(), client); return false; }
[ "protected", "boolean", "isDelegatedClientAuthorizedForService", "(", "final", "Client", "client", ",", "final", "Service", "service", ")", "{", "if", "(", "service", "==", "null", "||", "StringUtils", ".", "isBlank", "(", "service", ".", "getId", "(", ")", ")", ")", "{", "LOGGER", ".", "debug", "(", "\"Can not evaluate delegated authentication policy since no service was provided in the request while processing client [{}]\"", ",", "client", ")", ";", "return", "true", ";", "}", "val", "registeredService", "=", "this", ".", "servicesManager", ".", "findServiceBy", "(", "service", ")", ";", "if", "(", "registeredService", "==", "null", "||", "!", "registeredService", ".", "getAccessStrategy", "(", ")", ".", "isServiceAccessAllowed", "(", ")", ")", "{", "LOGGER", ".", "warn", "(", "\"Service access for [{}] is denied\"", ",", "registeredService", ")", ";", "return", "false", ";", "}", "LOGGER", ".", "trace", "(", "\"Located registered service definition [{}] matching [{}]\"", ",", "registeredService", ",", "service", ")", ";", "val", "context", "=", "AuditableContext", ".", "builder", "(", ")", ".", "registeredService", "(", "registeredService", ")", ".", "properties", "(", "CollectionUtils", ".", "wrap", "(", "Client", ".", "class", ".", "getSimpleName", "(", ")", ",", "client", ".", "getName", "(", ")", ")", ")", ".", "build", "(", ")", ";", "val", "result", "=", "delegatedAuthenticationPolicyEnforcer", ".", "execute", "(", "context", ")", ";", "if", "(", "!", "result", ".", "isExecutionFailure", "(", ")", ")", "{", "LOGGER", ".", "debug", "(", "\"Delegated authentication policy for [{}] allows for using client [{}]\"", ",", "registeredService", ",", "client", ")", ";", "return", "true", ";", "}", "LOGGER", ".", "warn", "(", "\"Delegated authentication policy for [{}] refuses access to client [{}]\"", ",", "registeredService", ".", "getServiceId", "(", ")", ",", "client", ")", ";", "return", "false", ";", "}" ]
Is delegated client authorized for service boolean. @param client the client @param service the service @return the boolean
[ "Is", "delegated", "client", "authorized", "for", "service", "boolean", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-pac4j-webflow/src/main/java/org/apereo/cas/web/flow/DelegatedClientAuthenticationAction.java#L423-L446
moparisthebest/beehive
beehive-netui-tags/src/main/java/org/apache/beehive/netui/tags/tree/Tree.java
Tree.renderDefaultJavaScript
private String renderDefaultJavaScript(HttpServletRequest request, String realId) { """ Much of the code below is taken from the HtmlBaseTag. We need to eliminate this duplication through some type of helper methods. """ String idScript = null; // map the tagId to the real id if (TagConfig.isDefaultJavaScript()) { ScriptRequestState srs = ScriptRequestState.getScriptRequestState(request); idScript = srs.mapTagId(getScriptReporter(), _trs.tagId, realId, null); } return idScript; }
java
private String renderDefaultJavaScript(HttpServletRequest request, String realId) { String idScript = null; // map the tagId to the real id if (TagConfig.isDefaultJavaScript()) { ScriptRequestState srs = ScriptRequestState.getScriptRequestState(request); idScript = srs.mapTagId(getScriptReporter(), _trs.tagId, realId, null); } return idScript; }
[ "private", "String", "renderDefaultJavaScript", "(", "HttpServletRequest", "request", ",", "String", "realId", ")", "{", "String", "idScript", "=", "null", ";", "// map the tagId to the real id", "if", "(", "TagConfig", ".", "isDefaultJavaScript", "(", ")", ")", "{", "ScriptRequestState", "srs", "=", "ScriptRequestState", ".", "getScriptRequestState", "(", "request", ")", ";", "idScript", "=", "srs", ".", "mapTagId", "(", "getScriptReporter", "(", ")", ",", "_trs", ".", "tagId", ",", "realId", ",", "null", ")", ";", "}", "return", "idScript", ";", "}" ]
Much of the code below is taken from the HtmlBaseTag. We need to eliminate this duplication through some type of helper methods.
[ "Much", "of", "the", "code", "below", "is", "taken", "from", "the", "HtmlBaseTag", ".", "We", "need", "to", "eliminate", "this", "duplication", "through", "some", "type", "of", "helper", "methods", "." ]
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-tags/src/main/java/org/apache/beehive/netui/tags/tree/Tree.java#L1045-L1055
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/executiongraph/Execution.java
Execution.notifyCheckpointComplete
public void notifyCheckpointComplete(long checkpointId, long timestamp) { """ Notify the task of this execution about a completed checkpoint. @param checkpointId of the completed checkpoint @param timestamp of the completed checkpoint """ final LogicalSlot slot = assignedResource; if (slot != null) { final TaskManagerGateway taskManagerGateway = slot.getTaskManagerGateway(); taskManagerGateway.notifyCheckpointComplete(attemptId, getVertex().getJobId(), checkpointId, timestamp); } else { LOG.debug("The execution has no slot assigned. This indicates that the execution is " + "no longer running."); } }
java
public void notifyCheckpointComplete(long checkpointId, long timestamp) { final LogicalSlot slot = assignedResource; if (slot != null) { final TaskManagerGateway taskManagerGateway = slot.getTaskManagerGateway(); taskManagerGateway.notifyCheckpointComplete(attemptId, getVertex().getJobId(), checkpointId, timestamp); } else { LOG.debug("The execution has no slot assigned. This indicates that the execution is " + "no longer running."); } }
[ "public", "void", "notifyCheckpointComplete", "(", "long", "checkpointId", ",", "long", "timestamp", ")", "{", "final", "LogicalSlot", "slot", "=", "assignedResource", ";", "if", "(", "slot", "!=", "null", ")", "{", "final", "TaskManagerGateway", "taskManagerGateway", "=", "slot", ".", "getTaskManagerGateway", "(", ")", ";", "taskManagerGateway", ".", "notifyCheckpointComplete", "(", "attemptId", ",", "getVertex", "(", ")", ".", "getJobId", "(", ")", ",", "checkpointId", ",", "timestamp", ")", ";", "}", "else", "{", "LOG", ".", "debug", "(", "\"The execution has no slot assigned. This indicates that the execution is \"", "+", "\"no longer running.\"", ")", ";", "}", "}" ]
Notify the task of this execution about a completed checkpoint. @param checkpointId of the completed checkpoint @param timestamp of the completed checkpoint
[ "Notify", "the", "task", "of", "this", "execution", "about", "a", "completed", "checkpoint", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/executiongraph/Execution.java#L848-L859
spring-projects/spring-retry
src/main/java/org/springframework/retry/policy/NeverRetryPolicy.java
NeverRetryPolicy.registerThrowable
public void registerThrowable(RetryContext context, Throwable throwable) { """ Make the throwable available for downstream use through the context. @see org.springframework.retry.RetryPolicy#registerThrowable(org.springframework.retry.RetryContext, Throwable) """ ((NeverRetryContext) context).setFinished(); ((RetryContextSupport) context).registerThrowable(throwable); }
java
public void registerThrowable(RetryContext context, Throwable throwable) { ((NeverRetryContext) context).setFinished(); ((RetryContextSupport) context).registerThrowable(throwable); }
[ "public", "void", "registerThrowable", "(", "RetryContext", "context", ",", "Throwable", "throwable", ")", "{", "(", "(", "NeverRetryContext", ")", "context", ")", ".", "setFinished", "(", ")", ";", "(", "(", "RetryContextSupport", ")", "context", ")", ".", "registerThrowable", "(", "throwable", ")", ";", "}" ]
Make the throwable available for downstream use through the context. @see org.springframework.retry.RetryPolicy#registerThrowable(org.springframework.retry.RetryContext, Throwable)
[ "Make", "the", "throwable", "available", "for", "downstream", "use", "through", "the", "context", "." ]
train
https://github.com/spring-projects/spring-retry/blob/e2b0555f96594c2321990d0deeac45fc44d4f123/src/main/java/org/springframework/retry/policy/NeverRetryPolicy.java#L67-L70
Azure/azure-sdk-for-java
network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/VpnSitesInner.java
VpnSitesInner.beginUpdateTagsAsync
public Observable<VpnSiteInner> beginUpdateTagsAsync(String resourceGroupName, String vpnSiteName, Map<String, String> tags) { """ Updates VpnSite tags. @param resourceGroupName The resource group name of the VpnSite. @param vpnSiteName The name of the VpnSite being updated. @param tags Resource tags. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the VpnSiteInner object """ return beginUpdateTagsWithServiceResponseAsync(resourceGroupName, vpnSiteName, tags).map(new Func1<ServiceResponse<VpnSiteInner>, VpnSiteInner>() { @Override public VpnSiteInner call(ServiceResponse<VpnSiteInner> response) { return response.body(); } }); }
java
public Observable<VpnSiteInner> beginUpdateTagsAsync(String resourceGroupName, String vpnSiteName, Map<String, String> tags) { return beginUpdateTagsWithServiceResponseAsync(resourceGroupName, vpnSiteName, tags).map(new Func1<ServiceResponse<VpnSiteInner>, VpnSiteInner>() { @Override public VpnSiteInner call(ServiceResponse<VpnSiteInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "VpnSiteInner", ">", "beginUpdateTagsAsync", "(", "String", "resourceGroupName", ",", "String", "vpnSiteName", ",", "Map", "<", "String", ",", "String", ">", "tags", ")", "{", "return", "beginUpdateTagsWithServiceResponseAsync", "(", "resourceGroupName", ",", "vpnSiteName", ",", "tags", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "VpnSiteInner", ">", ",", "VpnSiteInner", ">", "(", ")", "{", "@", "Override", "public", "VpnSiteInner", "call", "(", "ServiceResponse", "<", "VpnSiteInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Updates VpnSite tags. @param resourceGroupName The resource group name of the VpnSite. @param vpnSiteName The name of the VpnSite being updated. @param tags Resource tags. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the VpnSiteInner object
[ "Updates", "VpnSite", "tags", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/VpnSitesInner.java#L629-L636
rhuss/jolokia
agent/core/src/main/java/org/jolokia/backend/MBeanServerHandler.java
MBeanServerHandler.detectServers
private ServerHandle detectServers(List<ServerDetector> pDetectors, LogHandler pLogHandler) { """ by a lookup mechanism, queried and thrown away after this method """ // Now detect the server for (ServerDetector detector : pDetectors) { try { ServerHandle info = detector.detect(mBeanServerManager); if (info != null) { return info; } } catch (Exception exp) { // We are defensive here and wont stop the servlet because // there is a problem with the server detection. A error will be logged // nevertheless, though. pLogHandler.error("Error while using detector " + detector.getClass().getSimpleName() + ": " + exp,exp); } } return null; }
java
private ServerHandle detectServers(List<ServerDetector> pDetectors, LogHandler pLogHandler) { // Now detect the server for (ServerDetector detector : pDetectors) { try { ServerHandle info = detector.detect(mBeanServerManager); if (info != null) { return info; } } catch (Exception exp) { // We are defensive here and wont stop the servlet because // there is a problem with the server detection. A error will be logged // nevertheless, though. pLogHandler.error("Error while using detector " + detector.getClass().getSimpleName() + ": " + exp,exp); } } return null; }
[ "private", "ServerHandle", "detectServers", "(", "List", "<", "ServerDetector", ">", "pDetectors", ",", "LogHandler", "pLogHandler", ")", "{", "// Now detect the server", "for", "(", "ServerDetector", "detector", ":", "pDetectors", ")", "{", "try", "{", "ServerHandle", "info", "=", "detector", ".", "detect", "(", "mBeanServerManager", ")", ";", "if", "(", "info", "!=", "null", ")", "{", "return", "info", ";", "}", "}", "catch", "(", "Exception", "exp", ")", "{", "// We are defensive here and wont stop the servlet because", "// there is a problem with the server detection. A error will be logged", "// nevertheless, though.", "pLogHandler", ".", "error", "(", "\"Error while using detector \"", "+", "detector", ".", "getClass", "(", ")", ".", "getSimpleName", "(", ")", "+", "\": \"", "+", "exp", ",", "exp", ")", ";", "}", "}", "return", "null", ";", "}" ]
by a lookup mechanism, queried and thrown away after this method
[ "by", "a", "lookup", "mechanism", "queried", "and", "thrown", "away", "after", "this", "method" ]
train
https://github.com/rhuss/jolokia/blob/dc95e7bef859b1829776c5a84c8f7738f5d7d9c3/agent/core/src/main/java/org/jolokia/backend/MBeanServerHandler.java#L287-L303
AltBeacon/android-beacon-library
lib/src/main/java/org/altbeacon/beacon/service/ScanJob.java
ScanJob.getImmediateScanJobId
public static int getImmediateScanJobId(Context context) { """ Returns the job id to be used to schedule this job. This may be set in the AndroidManifest.xml or in single process applications by using #setOverrideJobId @param context the application context @return the job id """ if (sOverrideImmediateScanJobId >= 0) { LogManager.i(TAG, "Using ImmediateScanJobId from static override: "+ sOverrideImmediateScanJobId); return sOverrideImmediateScanJobId; } return getJobIdFromManifest(context, "immediateScanJobId"); }
java
public static int getImmediateScanJobId(Context context) { if (sOverrideImmediateScanJobId >= 0) { LogManager.i(TAG, "Using ImmediateScanJobId from static override: "+ sOverrideImmediateScanJobId); return sOverrideImmediateScanJobId; } return getJobIdFromManifest(context, "immediateScanJobId"); }
[ "public", "static", "int", "getImmediateScanJobId", "(", "Context", "context", ")", "{", "if", "(", "sOverrideImmediateScanJobId", ">=", "0", ")", "{", "LogManager", ".", "i", "(", "TAG", ",", "\"Using ImmediateScanJobId from static override: \"", "+", "sOverrideImmediateScanJobId", ")", ";", "return", "sOverrideImmediateScanJobId", ";", "}", "return", "getJobIdFromManifest", "(", "context", ",", "\"immediateScanJobId\"", ")", ";", "}" ]
Returns the job id to be used to schedule this job. This may be set in the AndroidManifest.xml or in single process applications by using #setOverrideJobId @param context the application context @return the job id
[ "Returns", "the", "job", "id", "to", "be", "used", "to", "schedule", "this", "job", ".", "This", "may", "be", "set", "in", "the", "AndroidManifest", ".", "xml", "or", "in", "single", "process", "applications", "by", "using", "#setOverrideJobId" ]
train
https://github.com/AltBeacon/android-beacon-library/blob/f7f3a323ea7415d53e7bd695ff6a01f1501d5dc3/lib/src/main/java/org/altbeacon/beacon/service/ScanJob.java#L302-L309
dbracewell/hermes
hermes-core/src/main/java/com/davidbracewell/hermes/DocumentFactory.java
DocumentFactory.createRaw
public Document createRaw(@NonNull String id, @NonNull String content) { """ Creates a document with the given id and content written in the default language. This method does not apply any {@link TextNormalizer} @param id the id @param content the content @return the document """ return createRaw(id, content, defaultLanguage, Collections.emptyMap()); }
java
public Document createRaw(@NonNull String id, @NonNull String content) { return createRaw(id, content, defaultLanguage, Collections.emptyMap()); }
[ "public", "Document", "createRaw", "(", "@", "NonNull", "String", "id", ",", "@", "NonNull", "String", "content", ")", "{", "return", "createRaw", "(", "id", ",", "content", ",", "defaultLanguage", ",", "Collections", ".", "emptyMap", "(", ")", ")", ";", "}" ]
Creates a document with the given id and content written in the default language. This method does not apply any {@link TextNormalizer} @param id the id @param content the content @return the document
[ "Creates", "a", "document", "with", "the", "given", "id", "and", "content", "written", "in", "the", "default", "language", ".", "This", "method", "does", "not", "apply", "any", "{", "@link", "TextNormalizer", "}" ]
train
https://github.com/dbracewell/hermes/blob/9ebefe7ad5dea1b731ae6931a30771eb75325ea3/hermes-core/src/main/java/com/davidbracewell/hermes/DocumentFactory.java#L193-L195
mangstadt/biweekly
src/main/java/biweekly/component/VTodo.java
VTodo.setDateDue
public DateDue setDateDue(Date dateDue, boolean hasTime) { """ Sets the date that a to-do task is due by. This must NOT be set if a {@link DurationProperty} is defined. @param dateDue the due date or null to remove @param hasTime true if the date has a time component, false if it is strictly a date (if false, the given Date object should be created by a {@link java.util.Calendar Calendar} object that uses the JVM's default timezone) @return the property that was created @see <a href="http://tools.ietf.org/html/rfc5545#page-96">RFC 5545 p.96-7</a> @see <a href="http://tools.ietf.org/html/rfc2445#page-92">RFC 2445 p.92-3</a> @see <a href="http://www.imc.org/pdi/vcal-10.doc">vCal 1.0 p.30</a> """ DateDue prop = (dateDue == null) ? null : new DateDue(dateDue, hasTime); setDateDue(prop); return prop; }
java
public DateDue setDateDue(Date dateDue, boolean hasTime) { DateDue prop = (dateDue == null) ? null : new DateDue(dateDue, hasTime); setDateDue(prop); return prop; }
[ "public", "DateDue", "setDateDue", "(", "Date", "dateDue", ",", "boolean", "hasTime", ")", "{", "DateDue", "prop", "=", "(", "dateDue", "==", "null", ")", "?", "null", ":", "new", "DateDue", "(", "dateDue", ",", "hasTime", ")", ";", "setDateDue", "(", "prop", ")", ";", "return", "prop", ";", "}" ]
Sets the date that a to-do task is due by. This must NOT be set if a {@link DurationProperty} is defined. @param dateDue the due date or null to remove @param hasTime true if the date has a time component, false if it is strictly a date (if false, the given Date object should be created by a {@link java.util.Calendar Calendar} object that uses the JVM's default timezone) @return the property that was created @see <a href="http://tools.ietf.org/html/rfc5545#page-96">RFC 5545 p.96-7</a> @see <a href="http://tools.ietf.org/html/rfc2445#page-92">RFC 2445 p.92-3</a> @see <a href="http://www.imc.org/pdi/vcal-10.doc">vCal 1.0 p.30</a>
[ "Sets", "the", "date", "that", "a", "to", "-", "do", "task", "is", "due", "by", ".", "This", "must", "NOT", "be", "set", "if", "a", "{" ]
train
https://github.com/mangstadt/biweekly/blob/2e21350f85c13dfff52fdef98fdbebe2976fcf61/src/main/java/biweekly/component/VTodo.java#L1030-L1034
Alluxio/alluxio
core/server/worker/src/main/java/alluxio/worker/block/UnderFileSystemBlockStore.java
UnderFileSystemBlockStore.closeReaderOrWriter
public void closeReaderOrWriter(long sessionId, long blockId) throws IOException { """ Closes the block reader or writer and checks whether it is necessary to commit the block to Local block store. During UFS block read, this is triggered when the block is unlocked. During UFS block write, this is triggered when the UFS block is committed. @param sessionId the session ID @param blockId the block ID """ BlockInfo blockInfo; try (LockResource lr = new LockResource(mLock)) { blockInfo = mBlocks.get(new Key(sessionId, blockId)); if (blockInfo == null) { LOG.warn("Key (block ID: {}, session ID {}) is not found when cleaning up the UFS block.", blockId, sessionId); return; } } blockInfo.closeReaderOrWriter(); }
java
public void closeReaderOrWriter(long sessionId, long blockId) throws IOException { BlockInfo blockInfo; try (LockResource lr = new LockResource(mLock)) { blockInfo = mBlocks.get(new Key(sessionId, blockId)); if (blockInfo == null) { LOG.warn("Key (block ID: {}, session ID {}) is not found when cleaning up the UFS block.", blockId, sessionId); return; } } blockInfo.closeReaderOrWriter(); }
[ "public", "void", "closeReaderOrWriter", "(", "long", "sessionId", ",", "long", "blockId", ")", "throws", "IOException", "{", "BlockInfo", "blockInfo", ";", "try", "(", "LockResource", "lr", "=", "new", "LockResource", "(", "mLock", ")", ")", "{", "blockInfo", "=", "mBlocks", ".", "get", "(", "new", "Key", "(", "sessionId", ",", "blockId", ")", ")", ";", "if", "(", "blockInfo", "==", "null", ")", "{", "LOG", ".", "warn", "(", "\"Key (block ID: {}, session ID {}) is not found when cleaning up the UFS block.\"", ",", "blockId", ",", "sessionId", ")", ";", "return", ";", "}", "}", "blockInfo", ".", "closeReaderOrWriter", "(", ")", ";", "}" ]
Closes the block reader or writer and checks whether it is necessary to commit the block to Local block store. During UFS block read, this is triggered when the block is unlocked. During UFS block write, this is triggered when the UFS block is committed. @param sessionId the session ID @param blockId the block ID
[ "Closes", "the", "block", "reader", "or", "writer", "and", "checks", "whether", "it", "is", "necessary", "to", "commit", "the", "block", "to", "Local", "block", "store", "." ]
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/worker/src/main/java/alluxio/worker/block/UnderFileSystemBlockStore.java#L145-L156
UrielCh/ovh-java-sdk
ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java
ApiOvhCloud.project_serviceName_region_POST
public OvhRegion project_serviceName_region_POST(String serviceName, String region) throws IOException { """ Request access to a region REST: POST /cloud/project/{serviceName}/region @param region [required] Region to add on your project @param serviceName [required] The project id """ String qPath = "/cloud/project/{serviceName}/region"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "region", region); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhRegion.class); }
java
public OvhRegion project_serviceName_region_POST(String serviceName, String region) throws IOException { String qPath = "/cloud/project/{serviceName}/region"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "region", region); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhRegion.class); }
[ "public", "OvhRegion", "project_serviceName_region_POST", "(", "String", "serviceName", ",", "String", "region", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/cloud/project/{serviceName}/region\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ")", ";", "HashMap", "<", "String", ",", "Object", ">", "o", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "addBody", "(", "o", ",", "\"region\"", ",", "region", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"POST\"", ",", "sb", ".", "toString", "(", ")", ",", "o", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhRegion", ".", "class", ")", ";", "}" ]
Request access to a region REST: POST /cloud/project/{serviceName}/region @param region [required] Region to add on your project @param serviceName [required] The project id
[ "Request", "access", "to", "a", "region" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java#L138-L145
alibaba/ARouter
arouter-api/src/main/java/com/alibaba/android/arouter/facade/Postcard.java
Postcard.withParcelable
public Postcard withParcelable(@Nullable String key, @Nullable Parcelable value) { """ Inserts a Parcelable value into the mapping of this Bundle, replacing any existing value for the given key. Either key or value may be null. @param key a String, or null @param value a Parcelable object, or null @return current """ mBundle.putParcelable(key, value); return this; }
java
public Postcard withParcelable(@Nullable String key, @Nullable Parcelable value) { mBundle.putParcelable(key, value); return this; }
[ "public", "Postcard", "withParcelable", "(", "@", "Nullable", "String", "key", ",", "@", "Nullable", "Parcelable", "value", ")", "{", "mBundle", ".", "putParcelable", "(", "key", ",", "value", ")", ";", "return", "this", ";", "}" ]
Inserts a Parcelable value into the mapping of this Bundle, replacing any existing value for the given key. Either key or value may be null. @param key a String, or null @param value a Parcelable object, or null @return current
[ "Inserts", "a", "Parcelable", "value", "into", "the", "mapping", "of", "this", "Bundle", "replacing", "any", "existing", "value", "for", "the", "given", "key", ".", "Either", "key", "or", "value", "may", "be", "null", "." ]
train
https://github.com/alibaba/ARouter/blob/1a06912a6e14a57112db1204b43f81c43d721732/arouter-api/src/main/java/com/alibaba/android/arouter/facade/Postcard.java#L374-L377
liferay/com-liferay-commerce
commerce-tax-service/src/main/java/com/liferay/commerce/tax/service/persistence/impl/CommerceTaxMethodPersistenceImpl.java
CommerceTaxMethodPersistenceImpl.removeByG_A
@Override public void removeByG_A(long groupId, boolean active) { """ Removes all the commerce tax methods where groupId = &#63; and active = &#63; from the database. @param groupId the group ID @param active the active """ for (CommerceTaxMethod commerceTaxMethod : findByG_A(groupId, active, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(commerceTaxMethod); } }
java
@Override public void removeByG_A(long groupId, boolean active) { for (CommerceTaxMethod commerceTaxMethod : findByG_A(groupId, active, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(commerceTaxMethod); } }
[ "@", "Override", "public", "void", "removeByG_A", "(", "long", "groupId", ",", "boolean", "active", ")", "{", "for", "(", "CommerceTaxMethod", "commerceTaxMethod", ":", "findByG_A", "(", "groupId", ",", "active", ",", "QueryUtil", ".", "ALL_POS", ",", "QueryUtil", ".", "ALL_POS", ",", "null", ")", ")", "{", "remove", "(", "commerceTaxMethod", ")", ";", "}", "}" ]
Removes all the commerce tax methods where groupId = &#63; and active = &#63; from the database. @param groupId the group ID @param active the active
[ "Removes", "all", "the", "commerce", "tax", "methods", "where", "groupId", "=", "&#63", ";", "and", "active", "=", "&#63", ";", "from", "the", "database", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-tax-service/src/main/java/com/liferay/commerce/tax/service/persistence/impl/CommerceTaxMethodPersistenceImpl.java#L1332-L1338
alibaba/jstorm
jstorm-core/src/main/java/backtype/storm/ConfigValidation.java
ConfigValidation.mapFv
public static NestableFieldValidator mapFv(Class key, Class val, boolean nullAllowed) { """ Returns a new NestableFieldValidator for a Map of key to val. @param key the Class of keys in the map @param val the Class of values in the map @param nullAllowed whether or not a value of null is valid @return a NestableFieldValidator for a Map of key to val """ return mapFv(fv(key, false), fv(val, false), nullAllowed); }
java
public static NestableFieldValidator mapFv(Class key, Class val, boolean nullAllowed) { return mapFv(fv(key, false), fv(val, false), nullAllowed); }
[ "public", "static", "NestableFieldValidator", "mapFv", "(", "Class", "key", ",", "Class", "val", ",", "boolean", "nullAllowed", ")", "{", "return", "mapFv", "(", "fv", "(", "key", ",", "false", ")", ",", "fv", "(", "val", ",", "false", ")", ",", "nullAllowed", ")", ";", "}" ]
Returns a new NestableFieldValidator for a Map of key to val. @param key the Class of keys in the map @param val the Class of values in the map @param nullAllowed whether or not a value of null is valid @return a NestableFieldValidator for a Map of key to val
[ "Returns", "a", "new", "NestableFieldValidator", "for", "a", "Map", "of", "key", "to", "val", "." ]
train
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/ConfigValidation.java#L126-L128
liferay/com-liferay-commerce
commerce-notification-service/src/main/java/com/liferay/commerce/notification/service/persistence/impl/CommerceNotificationTemplatePersistenceImpl.java
CommerceNotificationTemplatePersistenceImpl.findAll
@Override public List<CommerceNotificationTemplate> findAll(int start, int end) { """ Returns a range of all the commerce notification templates. <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 CommerceNotificationTemplateModelImpl}. 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 start the lower bound of the range of commerce notification templates @param end the upper bound of the range of commerce notification templates (not inclusive) @return the range of commerce notification templates """ return findAll(start, end, null); }
java
@Override public List<CommerceNotificationTemplate> findAll(int start, int end) { return findAll(start, end, null); }
[ "@", "Override", "public", "List", "<", "CommerceNotificationTemplate", ">", "findAll", "(", "int", "start", ",", "int", "end", ")", "{", "return", "findAll", "(", "start", ",", "end", ",", "null", ")", ";", "}" ]
Returns a range of all the commerce notification templates. <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 CommerceNotificationTemplateModelImpl}. 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 start the lower bound of the range of commerce notification templates @param end the upper bound of the range of commerce notification templates (not inclusive) @return the range of commerce notification templates
[ "Returns", "a", "range", "of", "all", "the", "commerce", "notification", "templates", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-notification-service/src/main/java/com/liferay/commerce/notification/service/persistence/impl/CommerceNotificationTemplatePersistenceImpl.java#L5177-L5180
mike10004/common-helper
native-helper/src/main/java/com/github/mike10004/nativehelper/StandardWhicher.java
StandardWhicher.which
@Override public Optional<File> which(Iterable<String> filenames) { """ Returns the {@code File} object representing the pathname that is the result of joining a parent pathname with the argument filename and is valid for a given predicate. The predicate is checked with {@link #isValidResult(java.io.File) }. @param filenames the filenames to search for @return the {@code File} object, or null if not found """ for (File parent : ImmutableList.copyOf(parents)) { for (String filename : filenames) { Iterable<String> filenameVariations = transform.apply(filename); for (String filenameVariation : filenameVariations) { File file = new File(parent, filenameVariation); if (isValidResult(file)) { return Optional.of(file); } } } } return Optional.empty(); }
java
@Override public Optional<File> which(Iterable<String> filenames) { for (File parent : ImmutableList.copyOf(parents)) { for (String filename : filenames) { Iterable<String> filenameVariations = transform.apply(filename); for (String filenameVariation : filenameVariations) { File file = new File(parent, filenameVariation); if (isValidResult(file)) { return Optional.of(file); } } } } return Optional.empty(); }
[ "@", "Override", "public", "Optional", "<", "File", ">", "which", "(", "Iterable", "<", "String", ">", "filenames", ")", "{", "for", "(", "File", "parent", ":", "ImmutableList", ".", "copyOf", "(", "parents", ")", ")", "{", "for", "(", "String", "filename", ":", "filenames", ")", "{", "Iterable", "<", "String", ">", "filenameVariations", "=", "transform", ".", "apply", "(", "filename", ")", ";", "for", "(", "String", "filenameVariation", ":", "filenameVariations", ")", "{", "File", "file", "=", "new", "File", "(", "parent", ",", "filenameVariation", ")", ";", "if", "(", "isValidResult", "(", "file", ")", ")", "{", "return", "Optional", ".", "of", "(", "file", ")", ";", "}", "}", "}", "}", "return", "Optional", ".", "empty", "(", ")", ";", "}" ]
Returns the {@code File} object representing the pathname that is the result of joining a parent pathname with the argument filename and is valid for a given predicate. The predicate is checked with {@link #isValidResult(java.io.File) }. @param filenames the filenames to search for @return the {@code File} object, or null if not found
[ "Returns", "the", "{" ]
train
https://github.com/mike10004/common-helper/blob/744f82d9b0768a9ad9c63a57a37ab2c93bf408f4/native-helper/src/main/java/com/github/mike10004/nativehelper/StandardWhicher.java#L58-L72
biezhi/anima
src/main/java/io/github/biezhi/anima/core/AnimaQuery.java
AnimaQuery.updateById
public <S extends Model> int updateById(S model, Serializable id) { """ Update model by primary key @param model model instance @param id primary key value @param <S> @return affect the number of rows, normally it's 1. """ this.where(primaryKeyColumn, id); String sql = this.buildUpdateSQL(model, null); List<Object> columnValueList = AnimaUtils.toColumnValues(model, false); columnValueList.add(id); return this.execute(sql, columnValueList); }
java
public <S extends Model> int updateById(S model, Serializable id) { this.where(primaryKeyColumn, id); String sql = this.buildUpdateSQL(model, null); List<Object> columnValueList = AnimaUtils.toColumnValues(model, false); columnValueList.add(id); return this.execute(sql, columnValueList); }
[ "public", "<", "S", "extends", "Model", ">", "int", "updateById", "(", "S", "model", ",", "Serializable", "id", ")", "{", "this", ".", "where", "(", "primaryKeyColumn", ",", "id", ")", ";", "String", "sql", "=", "this", ".", "buildUpdateSQL", "(", "model", ",", "null", ")", ";", "List", "<", "Object", ">", "columnValueList", "=", "AnimaUtils", ".", "toColumnValues", "(", "model", ",", "false", ")", ";", "columnValueList", ".", "add", "(", "id", ")", ";", "return", "this", ".", "execute", "(", "sql", ",", "columnValueList", ")", ";", "}" ]
Update model by primary key @param model model instance @param id primary key value @param <S> @return affect the number of rows, normally it's 1.
[ "Update", "model", "by", "primary", "key" ]
train
https://github.com/biezhi/anima/blob/d6655e47ac4c08d9d7f961ac0569062bead8b1ed/src/main/java/io/github/biezhi/anima/core/AnimaQuery.java#L1318-L1324
apereo/cas
core/cas-server-core-util-api/src/main/java/org/apereo/cas/util/HttpUtils.java
HttpUtils.executeGet
public static HttpResponse executeGet(final String url) { """ Execute get http response. @param url the url @return the http response """ try { return executeGet(url, null, null, new LinkedHashMap<>()); } catch (final Exception e) { LOGGER.error(e.getMessage(), e); } return null; }
java
public static HttpResponse executeGet(final String url) { try { return executeGet(url, null, null, new LinkedHashMap<>()); } catch (final Exception e) { LOGGER.error(e.getMessage(), e); } return null; }
[ "public", "static", "HttpResponse", "executeGet", "(", "final", "String", "url", ")", "{", "try", "{", "return", "executeGet", "(", "url", ",", "null", ",", "null", ",", "new", "LinkedHashMap", "<>", "(", ")", ")", ";", "}", "catch", "(", "final", "Exception", "e", ")", "{", "LOGGER", ".", "error", "(", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "return", "null", ";", "}" ]
Execute get http response. @param url the url @return the http response
[ "Execute", "get", "http", "response", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-util-api/src/main/java/org/apereo/cas/util/HttpUtils.java#L272-L279
elki-project/elki
elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/linearalgebra/AffineTransformation.java
AffineTransformation.applyInverse
public double[] applyInverse(double[] v) { """ Apply the inverse transformation onto a vector @param v vector of dimensionality dim @return transformed vector of dimensionality dim """ if(inv == null) { updateInverse(); } return unhomogeneVector(times(inv, homogeneVector(v))); }
java
public double[] applyInverse(double[] v) { if(inv == null) { updateInverse(); } return unhomogeneVector(times(inv, homogeneVector(v))); }
[ "public", "double", "[", "]", "applyInverse", "(", "double", "[", "]", "v", ")", "{", "if", "(", "inv", "==", "null", ")", "{", "updateInverse", "(", ")", ";", "}", "return", "unhomogeneVector", "(", "times", "(", "inv", ",", "homogeneVector", "(", "v", ")", ")", ")", ";", "}" ]
Apply the inverse transformation onto a vector @param v vector of dimensionality dim @return transformed vector of dimensionality dim
[ "Apply", "the", "inverse", "transformation", "onto", "a", "vector" ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/linearalgebra/AffineTransformation.java#L361-L366
MenoData/Time4J
base/src/main/java/net/time4j/calendar/astro/JulianDay.java
JulianDay.ofSimplifiedTime
public static JulianDay ofSimplifiedTime(Moment moment) { """ /*[deutsch] <p>Erzeugt einen julianischen Tag auf der Zeitskala {@link TimeScale#POSIX}. </p> <p>Die Umrechnung erfordert keine delta-T-Korrektur. </p> @param moment corresponding moment @return JulianDay @throws IllegalArgumentException if the Julian day of moment is not in supported range @since 3.34/4.29 """ return new JulianDay(getValue(moment, TimeScale.POSIX), TimeScale.POSIX); }
java
public static JulianDay ofSimplifiedTime(Moment moment) { return new JulianDay(getValue(moment, TimeScale.POSIX), TimeScale.POSIX); }
[ "public", "static", "JulianDay", "ofSimplifiedTime", "(", "Moment", "moment", ")", "{", "return", "new", "JulianDay", "(", "getValue", "(", "moment", ",", "TimeScale", ".", "POSIX", ")", ",", "TimeScale", ".", "POSIX", ")", ";", "}" ]
/*[deutsch] <p>Erzeugt einen julianischen Tag auf der Zeitskala {@link TimeScale#POSIX}. </p> <p>Die Umrechnung erfordert keine delta-T-Korrektur. </p> @param moment corresponding moment @return JulianDay @throws IllegalArgumentException if the Julian day of moment is not in supported range @since 3.34/4.29
[ "/", "*", "[", "deutsch", "]", "<p", ">", "Erzeugt", "einen", "julianischen", "Tag", "auf", "der", "Zeitskala", "{", "@link", "TimeScale#POSIX", "}", ".", "<", "/", "p", ">" ]
train
https://github.com/MenoData/Time4J/blob/08b2eda6b2dbb140b92011cf7071bb087edd46a5/base/src/main/java/net/time4j/calendar/astro/JulianDay.java#L330-L334
msgpack/msgpack-java
msgpack-core/src/main/java/org/msgpack/core/MessageUnpacker.java
MessageUnpacker.unpackBinaryHeader
public int unpackBinaryHeader() throws IOException { """ Reads header of a binary. <p> This method returns number of bytes to be read. After this method call, you call a readPayload method such as {@link #readPayload(int)} with the returned count. <p> You can divide readPayload method into multiple calls. In this case, you must repeat readPayload methods until total amount of bytes becomes equal to the returned count. @return the size of the map to be read @throws MessageTypeException when value is not MessagePack Map type @throws MessageSizeException when size of the map is larger than 2^31 - 1 @throws IOException when underlying input throws IOException """ byte b = readByte(); if (Code.isFixedRaw(b)) { // FixRaw return b & 0x1f; } int len = tryReadBinaryHeader(b); if (len >= 0) { return len; } if (allowReadingStringAsBinary) { len = tryReadStringHeader(b); if (len >= 0) { return len; } } throw unexpected("Binary", b); }
java
public int unpackBinaryHeader() throws IOException { byte b = readByte(); if (Code.isFixedRaw(b)) { // FixRaw return b & 0x1f; } int len = tryReadBinaryHeader(b); if (len >= 0) { return len; } if (allowReadingStringAsBinary) { len = tryReadStringHeader(b); if (len >= 0) { return len; } } throw unexpected("Binary", b); }
[ "public", "int", "unpackBinaryHeader", "(", ")", "throws", "IOException", "{", "byte", "b", "=", "readByte", "(", ")", ";", "if", "(", "Code", ".", "isFixedRaw", "(", "b", ")", ")", "{", "// FixRaw", "return", "b", "&", "0x1f", ";", "}", "int", "len", "=", "tryReadBinaryHeader", "(", "b", ")", ";", "if", "(", "len", ">=", "0", ")", "{", "return", "len", ";", "}", "if", "(", "allowReadingStringAsBinary", ")", "{", "len", "=", "tryReadStringHeader", "(", "b", ")", ";", "if", "(", "len", ">=", "0", ")", "{", "return", "len", ";", "}", "}", "throw", "unexpected", "(", "\"Binary\"", ",", "b", ")", ";", "}" ]
Reads header of a binary. <p> This method returns number of bytes to be read. After this method call, you call a readPayload method such as {@link #readPayload(int)} with the returned count. <p> You can divide readPayload method into multiple calls. In this case, you must repeat readPayload methods until total amount of bytes becomes equal to the returned count. @return the size of the map to be read @throws MessageTypeException when value is not MessagePack Map type @throws MessageSizeException when size of the map is larger than 2^31 - 1 @throws IOException when underlying input throws IOException
[ "Reads", "header", "of", "a", "binary", "." ]
train
https://github.com/msgpack/msgpack-java/blob/16e370e348215a72a14c210b42d448d513aee015/msgpack-core/src/main/java/org/msgpack/core/MessageUnpacker.java#L1446-L1465
lucee/Lucee
core/src/main/java/lucee/runtime/op/Caster.java
Caster.toNodeList
public static NodeList toNodeList(Object o) throws PageException { """ casts a Object to a Node List @param o Object to Cast @return NodeList from Object @throws PageException """ // print.ln("nodeList:"+o); if (o instanceof NodeList) { return (NodeList) o; } else if (o instanceof ObjectWrap) { return toNodeList(((ObjectWrap) o).getEmbededObject()); } throw new CasterException(o, "NodeList"); }
java
public static NodeList toNodeList(Object o) throws PageException { // print.ln("nodeList:"+o); if (o instanceof NodeList) { return (NodeList) o; } else if (o instanceof ObjectWrap) { return toNodeList(((ObjectWrap) o).getEmbededObject()); } throw new CasterException(o, "NodeList"); }
[ "public", "static", "NodeList", "toNodeList", "(", "Object", "o", ")", "throws", "PageException", "{", "// print.ln(\"nodeList:\"+o);", "if", "(", "o", "instanceof", "NodeList", ")", "{", "return", "(", "NodeList", ")", "o", ";", "}", "else", "if", "(", "o", "instanceof", "ObjectWrap", ")", "{", "return", "toNodeList", "(", "(", "(", "ObjectWrap", ")", "o", ")", ".", "getEmbededObject", "(", ")", ")", ";", "}", "throw", "new", "CasterException", "(", "o", ",", "\"NodeList\"", ")", ";", "}" ]
casts a Object to a Node List @param o Object to Cast @return NodeList from Object @throws PageException
[ "casts", "a", "Object", "to", "a", "Node", "List" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/op/Caster.java#L4271-L4280
Swagger2Markup/swagger2markup
src/main/java/io/github/swagger2markup/internal/component/PathOperationComponent.java
PathOperationComponent.buildDeprecatedSection
private void buildDeprecatedSection(MarkupDocBuilder markupDocBuilder, PathOperation operation) { """ Builds a warning if method is deprecated. @param operation the Swagger Operation """ if (BooleanUtils.isTrue(operation.getOperation().isDeprecated())) { markupDocBuilder.block(DEPRECATED_OPERATION, MarkupBlockStyle.EXAMPLE, null, MarkupAdmonition.CAUTION); } }
java
private void buildDeprecatedSection(MarkupDocBuilder markupDocBuilder, PathOperation operation) { if (BooleanUtils.isTrue(operation.getOperation().isDeprecated())) { markupDocBuilder.block(DEPRECATED_OPERATION, MarkupBlockStyle.EXAMPLE, null, MarkupAdmonition.CAUTION); } }
[ "private", "void", "buildDeprecatedSection", "(", "MarkupDocBuilder", "markupDocBuilder", ",", "PathOperation", "operation", ")", "{", "if", "(", "BooleanUtils", ".", "isTrue", "(", "operation", ".", "getOperation", "(", ")", ".", "isDeprecated", "(", ")", ")", ")", "{", "markupDocBuilder", ".", "block", "(", "DEPRECATED_OPERATION", ",", "MarkupBlockStyle", ".", "EXAMPLE", ",", "null", ",", "MarkupAdmonition", ".", "CAUTION", ")", ";", "}", "}" ]
Builds a warning if method is deprecated. @param operation the Swagger Operation
[ "Builds", "a", "warning", "if", "method", "is", "deprecated", "." ]
train
https://github.com/Swagger2Markup/swagger2markup/blob/da83465f19a2f8a0f1fba873b5762bca8587896b/src/main/java/io/github/swagger2markup/internal/component/PathOperationComponent.java#L161-L165
OpenLiberty/open-liberty
dev/wlp-mavenRepoTasks/src/com/ibm/ws/wlp/mavenFeatures/LibertyFeaturesToMavenRepo.java
LibertyFeaturesToMavenRepo.addDependency
private static void addDependency(List<Dependency> dependencies, MavenCoordinates requiredArtifact, Constants.ArtifactType type, String scope) { """ Add dependency to the list of Maven Dependencies. @param dependencies The list of dependencies to append to. @param requiredArtifact The required artifact to add as a dependency. @param type The type of artifact, or null if jar. """ Dependency dependency = new Dependency(); dependency.setGroupId(requiredArtifact.getGroupId()); dependency.setArtifactId(requiredArtifact.getArtifactId()); dependency.setVersion(requiredArtifact.getVersion()); if(scope!=null){ dependency.setScope(scope); } if (type != null) { dependency.setType(type.getType()); } dependencies.add(dependency); }
java
private static void addDependency(List<Dependency> dependencies, MavenCoordinates requiredArtifact, Constants.ArtifactType type, String scope) { Dependency dependency = new Dependency(); dependency.setGroupId(requiredArtifact.getGroupId()); dependency.setArtifactId(requiredArtifact.getArtifactId()); dependency.setVersion(requiredArtifact.getVersion()); if(scope!=null){ dependency.setScope(scope); } if (type != null) { dependency.setType(type.getType()); } dependencies.add(dependency); }
[ "private", "static", "void", "addDependency", "(", "List", "<", "Dependency", ">", "dependencies", ",", "MavenCoordinates", "requiredArtifact", ",", "Constants", ".", "ArtifactType", "type", ",", "String", "scope", ")", "{", "Dependency", "dependency", "=", "new", "Dependency", "(", ")", ";", "dependency", ".", "setGroupId", "(", "requiredArtifact", ".", "getGroupId", "(", ")", ")", ";", "dependency", ".", "setArtifactId", "(", "requiredArtifact", ".", "getArtifactId", "(", ")", ")", ";", "dependency", ".", "setVersion", "(", "requiredArtifact", ".", "getVersion", "(", ")", ")", ";", "if", "(", "scope", "!=", "null", ")", "{", "dependency", ".", "setScope", "(", "scope", ")", ";", "}", "if", "(", "type", "!=", "null", ")", "{", "dependency", ".", "setType", "(", "type", ".", "getType", "(", ")", ")", ";", "}", "dependencies", ".", "add", "(", "dependency", ")", ";", "}" ]
Add dependency to the list of Maven Dependencies. @param dependencies The list of dependencies to append to. @param requiredArtifact The required artifact to add as a dependency. @param type The type of artifact, or null if jar.
[ "Add", "dependency", "to", "the", "list", "of", "Maven", "Dependencies", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/wlp-mavenRepoTasks/src/com/ibm/ws/wlp/mavenFeatures/LibertyFeaturesToMavenRepo.java#L416-L429
cloudfoundry/uaa
server/src/main/java/org/cloudfoundry/identity/uaa/util/UaaTokenUtils.java
UaaTokenUtils.murmurhash3x8632
public static int murmurhash3x8632(byte[] data, int offset, int len, int seed) { """ This code is public domain. The MurmurHash3 algorithm was created by Austin Appleby and put into the public domain. @see <a href="http://code.google.com/p/smhasher">http://code.google.com/p/smhasher</a> @see <a href="https://github.com/yonik/java_util/blob/master/src/util/hash/MurmurHash3.java">https://github.com/yonik/java_util/blob/master/src/util/hash/MurmurHash3.java</a> """ int c1 = 0xcc9e2d51; int c2 = 0x1b873593; int h1 = seed; int roundedEnd = offset + (len & 0xfffffffc); // round down to 4 byte block for (int i = offset; i < roundedEnd; i += 4) { // little endian load order int k1 = (data[i] & 0xff) | ((data[i + 1] & 0xff) << 8) | ((data[i + 2] & 0xff) << 16) | (data[i + 3] << 24); k1 *= c1; k1 = (k1 << 15) | (k1 >>> 17); // ROTL32(k1,15); k1 *= c2; h1 ^= k1; h1 = (h1 << 13) | (h1 >>> 19); // ROTL32(h1,13); h1 = h1 * 5 + 0xe6546b64; } // tail int k1 = 0; switch(len & 0x03) { case 3: k1 = (data[roundedEnd + 2] & 0xff) << 16; // fallthrough case 2: k1 |= (data[roundedEnd + 1] & 0xff) << 8; // fallthrough case 1: k1 |= data[roundedEnd] & 0xff; k1 *= c1; k1 = (k1 << 15) | (k1 >>> 17); // ROTL32(k1,15); k1 *= c2; h1 ^= k1; default: } // finalization h1 ^= len; // fmix(h1); h1 ^= h1 >>> 16; h1 *= 0x85ebca6b; h1 ^= h1 >>> 13; h1 *= 0xc2b2ae35; h1 ^= h1 >>> 16; return h1; }
java
public static int murmurhash3x8632(byte[] data, int offset, int len, int seed) { int c1 = 0xcc9e2d51; int c2 = 0x1b873593; int h1 = seed; int roundedEnd = offset + (len & 0xfffffffc); // round down to 4 byte block for (int i = offset; i < roundedEnd; i += 4) { // little endian load order int k1 = (data[i] & 0xff) | ((data[i + 1] & 0xff) << 8) | ((data[i + 2] & 0xff) << 16) | (data[i + 3] << 24); k1 *= c1; k1 = (k1 << 15) | (k1 >>> 17); // ROTL32(k1,15); k1 *= c2; h1 ^= k1; h1 = (h1 << 13) | (h1 >>> 19); // ROTL32(h1,13); h1 = h1 * 5 + 0xe6546b64; } // tail int k1 = 0; switch(len & 0x03) { case 3: k1 = (data[roundedEnd + 2] & 0xff) << 16; // fallthrough case 2: k1 |= (data[roundedEnd + 1] & 0xff) << 8; // fallthrough case 1: k1 |= data[roundedEnd] & 0xff; k1 *= c1; k1 = (k1 << 15) | (k1 >>> 17); // ROTL32(k1,15); k1 *= c2; h1 ^= k1; default: } // finalization h1 ^= len; // fmix(h1); h1 ^= h1 >>> 16; h1 *= 0x85ebca6b; h1 ^= h1 >>> 13; h1 *= 0xc2b2ae35; h1 ^= h1 >>> 16; return h1; }
[ "public", "static", "int", "murmurhash3x8632", "(", "byte", "[", "]", "data", ",", "int", "offset", ",", "int", "len", ",", "int", "seed", ")", "{", "int", "c1", "=", "0xcc9e2d51", ";", "int", "c2", "=", "0x1b873593", ";", "int", "h1", "=", "seed", ";", "int", "roundedEnd", "=", "offset", "+", "(", "len", "&", "0xfffffffc", ")", ";", "// round down to 4 byte block", "for", "(", "int", "i", "=", "offset", ";", "i", "<", "roundedEnd", ";", "i", "+=", "4", ")", "{", "// little endian load order", "int", "k1", "=", "(", "data", "[", "i", "]", "&", "0xff", ")", "|", "(", "(", "data", "[", "i", "+", "1", "]", "&", "0xff", ")", "<<", "8", ")", "|", "(", "(", "data", "[", "i", "+", "2", "]", "&", "0xff", ")", "<<", "16", ")", "|", "(", "data", "[", "i", "+", "3", "]", "<<", "24", ")", ";", "k1", "*=", "c1", ";", "k1", "=", "(", "k1", "<<", "15", ")", "|", "(", "k1", ">>>", "17", ")", ";", "// ROTL32(k1,15);", "k1", "*=", "c2", ";", "h1", "^=", "k1", ";", "h1", "=", "(", "h1", "<<", "13", ")", "|", "(", "h1", ">>>", "19", ")", ";", "// ROTL32(h1,13);", "h1", "=", "h1", "*", "5", "+", "0xe6546b64", ";", "}", "// tail", "int", "k1", "=", "0", ";", "switch", "(", "len", "&", "0x03", ")", "{", "case", "3", ":", "k1", "=", "(", "data", "[", "roundedEnd", "+", "2", "]", "&", "0xff", ")", "<<", "16", ";", "// fallthrough", "case", "2", ":", "k1", "|=", "(", "data", "[", "roundedEnd", "+", "1", "]", "&", "0xff", ")", "<<", "8", ";", "// fallthrough", "case", "1", ":", "k1", "|=", "data", "[", "roundedEnd", "]", "&", "0xff", ";", "k1", "*=", "c1", ";", "k1", "=", "(", "k1", "<<", "15", ")", "|", "(", "k1", ">>>", "17", ")", ";", "// ROTL32(k1,15);", "k1", "*=", "c2", ";", "h1", "^=", "k1", ";", "default", ":", "}", "// finalization", "h1", "^=", "len", ";", "// fmix(h1);", "h1", "^=", "h1", ">>>", "16", ";", "h1", "*=", "0x85ebca6b", ";", "h1", "^=", "h1", ">>>", "13", ";", "h1", "*=", "0xc2b2ae35", ";", "h1", "^=", "h1", ">>>", "16", ";", "return", "h1", ";", "}" ]
This code is public domain. The MurmurHash3 algorithm was created by Austin Appleby and put into the public domain. @see <a href="http://code.google.com/p/smhasher">http://code.google.com/p/smhasher</a> @see <a href="https://github.com/yonik/java_util/blob/master/src/util/hash/MurmurHash3.java">https://github.com/yonik/java_util/blob/master/src/util/hash/MurmurHash3.java</a>
[ "This", "code", "is", "public", "domain", "." ]
train
https://github.com/cloudfoundry/uaa/blob/e8df3d7060580c92d33461106399f9e4f36e3cd2/server/src/main/java/org/cloudfoundry/identity/uaa/util/UaaTokenUtils.java#L75-L125
fcrepo3/fcrepo
fcrepo-common/src/main/java/org/fcrepo/common/http/HttpInputStream.java
HttpInputStream.getResponseHeaderValue
public String getResponseHeaderValue(String name, String defaultVal) { """ Return the first value of a header, or the default if the fighter is not present @param name the header name @param defaultVal the default value @return String """ if (m_response.containsHeader(name)) { return m_response.getFirstHeader(name).getValue(); } else { return defaultVal; } }
java
public String getResponseHeaderValue(String name, String defaultVal) { if (m_response.containsHeader(name)) { return m_response.getFirstHeader(name).getValue(); } else { return defaultVal; } }
[ "public", "String", "getResponseHeaderValue", "(", "String", "name", ",", "String", "defaultVal", ")", "{", "if", "(", "m_response", ".", "containsHeader", "(", "name", ")", ")", "{", "return", "m_response", ".", "getFirstHeader", "(", "name", ")", ".", "getValue", "(", ")", ";", "}", "else", "{", "return", "defaultVal", ";", "}", "}" ]
Return the first value of a header, or the default if the fighter is not present @param name the header name @param defaultVal the default value @return String
[ "Return", "the", "first", "value", "of", "a", "header", "or", "the", "default", "if", "the", "fighter", "is", "not", "present" ]
train
https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-common/src/main/java/org/fcrepo/common/http/HttpInputStream.java#L101-L107
betamaxteam/betamax
betamax-core/src/main/java/software/betamax/util/ProxyOverrider.java
ProxyOverrider.getOriginalProxySelector
@Deprecated public ProxySelector getOriginalProxySelector() { """ Used by the Betamax proxy so that it can use pre-existing proxy settings when forwarding requests that do not match anything on tape. @return a proxy selector that uses the overridden proxy settings if any. """ return new ProxySelector() { @Override public List<Proxy> select(URI uri) { InetSocketAddress address = originalProxies.get(uri.getScheme()); if (address != null && !(originalNonProxyHosts.contains(uri.getHost()))) { return Collections.singletonList(new Proxy(HTTP, address)); } else { return Collections.singletonList(Proxy.NO_PROXY); } } @Override public void connectFailed(URI uri, SocketAddress sa, IOException ioe) { } }; }
java
@Deprecated public ProxySelector getOriginalProxySelector() { return new ProxySelector() { @Override public List<Proxy> select(URI uri) { InetSocketAddress address = originalProxies.get(uri.getScheme()); if (address != null && !(originalNonProxyHosts.contains(uri.getHost()))) { return Collections.singletonList(new Proxy(HTTP, address)); } else { return Collections.singletonList(Proxy.NO_PROXY); } } @Override public void connectFailed(URI uri, SocketAddress sa, IOException ioe) { } }; }
[ "@", "Deprecated", "public", "ProxySelector", "getOriginalProxySelector", "(", ")", "{", "return", "new", "ProxySelector", "(", ")", "{", "@", "Override", "public", "List", "<", "Proxy", ">", "select", "(", "URI", "uri", ")", "{", "InetSocketAddress", "address", "=", "originalProxies", ".", "get", "(", "uri", ".", "getScheme", "(", ")", ")", ";", "if", "(", "address", "!=", "null", "&&", "!", "(", "originalNonProxyHosts", ".", "contains", "(", "uri", ".", "getHost", "(", ")", ")", ")", ")", "{", "return", "Collections", ".", "singletonList", "(", "new", "Proxy", "(", "HTTP", ",", "address", ")", ")", ";", "}", "else", "{", "return", "Collections", ".", "singletonList", "(", "Proxy", ".", "NO_PROXY", ")", ";", "}", "}", "@", "Override", "public", "void", "connectFailed", "(", "URI", "uri", ",", "SocketAddress", "sa", ",", "IOException", "ioe", ")", "{", "}", "}", ";", "}" ]
Used by the Betamax proxy so that it can use pre-existing proxy settings when forwarding requests that do not match anything on tape. @return a proxy selector that uses the overridden proxy settings if any.
[ "Used", "by", "the", "Betamax", "proxy", "so", "that", "it", "can", "use", "pre", "-", "existing", "proxy", "settings", "when", "forwarding", "requests", "that", "do", "not", "match", "anything", "on", "tape", "." ]
train
https://github.com/betamaxteam/betamax/blob/30f29db9a2e2975f9d8ccd28ee3f4cea2bdf16e0/betamax-core/src/main/java/software/betamax/util/ProxyOverrider.java#L94-L111
b3log/latke
latke-core/src/main/java/org/b3log/latke/util/Crypts.java
Crypts.encryptByAES
public static String encryptByAES(final String content, final String key) { """ Encrypts by AES. @param content the specified content to encrypt @param key the specified key @return encrypted content @see #decryptByAES(java.lang.String, java.lang.String) """ try { final KeyGenerator kgen = KeyGenerator.getInstance("AES"); final SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG"); secureRandom.setSeed(key.getBytes()); kgen.init(128, secureRandom); final SecretKey secretKey = kgen.generateKey(); final byte[] enCodeFormat = secretKey.getEncoded(); final SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat, "AES"); final Cipher cipher = Cipher.getInstance("AES"); final byte[] byteContent = content.getBytes("UTF-8"); cipher.init(Cipher.ENCRYPT_MODE, keySpec); final byte[] result = cipher.doFinal(byteContent); return Hex.encodeHexString(result); } catch (final Exception e) { LOGGER.log(Level.WARN, "Encrypt failed", e); return null; } }
java
public static String encryptByAES(final String content, final String key) { try { final KeyGenerator kgen = KeyGenerator.getInstance("AES"); final SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG"); secureRandom.setSeed(key.getBytes()); kgen.init(128, secureRandom); final SecretKey secretKey = kgen.generateKey(); final byte[] enCodeFormat = secretKey.getEncoded(); final SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat, "AES"); final Cipher cipher = Cipher.getInstance("AES"); final byte[] byteContent = content.getBytes("UTF-8"); cipher.init(Cipher.ENCRYPT_MODE, keySpec); final byte[] result = cipher.doFinal(byteContent); return Hex.encodeHexString(result); } catch (final Exception e) { LOGGER.log(Level.WARN, "Encrypt failed", e); return null; } }
[ "public", "static", "String", "encryptByAES", "(", "final", "String", "content", ",", "final", "String", "key", ")", "{", "try", "{", "final", "KeyGenerator", "kgen", "=", "KeyGenerator", ".", "getInstance", "(", "\"AES\"", ")", ";", "final", "SecureRandom", "secureRandom", "=", "SecureRandom", ".", "getInstance", "(", "\"SHA1PRNG\"", ")", ";", "secureRandom", ".", "setSeed", "(", "key", ".", "getBytes", "(", ")", ")", ";", "kgen", ".", "init", "(", "128", ",", "secureRandom", ")", ";", "final", "SecretKey", "secretKey", "=", "kgen", ".", "generateKey", "(", ")", ";", "final", "byte", "[", "]", "enCodeFormat", "=", "secretKey", ".", "getEncoded", "(", ")", ";", "final", "SecretKeySpec", "keySpec", "=", "new", "SecretKeySpec", "(", "enCodeFormat", ",", "\"AES\"", ")", ";", "final", "Cipher", "cipher", "=", "Cipher", ".", "getInstance", "(", "\"AES\"", ")", ";", "final", "byte", "[", "]", "byteContent", "=", "content", ".", "getBytes", "(", "\"UTF-8\"", ")", ";", "cipher", ".", "init", "(", "Cipher", ".", "ENCRYPT_MODE", ",", "keySpec", ")", ";", "final", "byte", "[", "]", "result", "=", "cipher", ".", "doFinal", "(", "byteContent", ")", ";", "return", "Hex", ".", "encodeHexString", "(", "result", ")", ";", "}", "catch", "(", "final", "Exception", "e", ")", "{", "LOGGER", ".", "log", "(", "Level", ".", "WARN", ",", "\"Encrypt failed\"", ",", "e", ")", ";", "return", "null", ";", "}", "}" ]
Encrypts by AES. @param content the specified content to encrypt @param key the specified key @return encrypted content @see #decryptByAES(java.lang.String, java.lang.String)
[ "Encrypts", "by", "AES", "." ]
train
https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/util/Crypts.java#L71-L91
respoke/respoke-sdk-android
respokeSDK/src/main/java/com/digium/respokesdk/RespokeClient.java
RespokeClient.setPresence
public void setPresence(Object newPresence, final Respoke.TaskCompletionListener completionListener) { """ Set the presence on the client session @param newPresence The new presence to use @param completionListener A listener to receive the notification on the success or failure of the asynchronous operation """ if (isConnected()) { Object presenceToSet = newPresence; if (null == presenceToSet) { presenceToSet = "available"; } JSONObject typeData = new JSONObject(); JSONObject data = new JSONObject(); try { typeData.put("type", presenceToSet); data.put("presence", typeData); final Object finalPresence = presenceToSet; signalingChannel.sendRESTMessage("post", "/v1/presence", data, new RespokeSignalingChannel.RESTListener() { @Override public void onSuccess(Object response) { presence = finalPresence; Respoke.postTaskSuccess(completionListener); } @Override public void onError(final String errorMessage) { Respoke.postTaskError(completionListener, errorMessage); } }); } catch (JSONException e) { Respoke.postTaskError(completionListener, "Error encoding presence to json"); } } else { Respoke.postTaskError(completionListener, "Can't complete request when not connected. Please reconnect!"); } }
java
public void setPresence(Object newPresence, final Respoke.TaskCompletionListener completionListener) { if (isConnected()) { Object presenceToSet = newPresence; if (null == presenceToSet) { presenceToSet = "available"; } JSONObject typeData = new JSONObject(); JSONObject data = new JSONObject(); try { typeData.put("type", presenceToSet); data.put("presence", typeData); final Object finalPresence = presenceToSet; signalingChannel.sendRESTMessage("post", "/v1/presence", data, new RespokeSignalingChannel.RESTListener() { @Override public void onSuccess(Object response) { presence = finalPresence; Respoke.postTaskSuccess(completionListener); } @Override public void onError(final String errorMessage) { Respoke.postTaskError(completionListener, errorMessage); } }); } catch (JSONException e) { Respoke.postTaskError(completionListener, "Error encoding presence to json"); } } else { Respoke.postTaskError(completionListener, "Can't complete request when not connected. Please reconnect!"); } }
[ "public", "void", "setPresence", "(", "Object", "newPresence", ",", "final", "Respoke", ".", "TaskCompletionListener", "completionListener", ")", "{", "if", "(", "isConnected", "(", ")", ")", "{", "Object", "presenceToSet", "=", "newPresence", ";", "if", "(", "null", "==", "presenceToSet", ")", "{", "presenceToSet", "=", "\"available\"", ";", "}", "JSONObject", "typeData", "=", "new", "JSONObject", "(", ")", ";", "JSONObject", "data", "=", "new", "JSONObject", "(", ")", ";", "try", "{", "typeData", ".", "put", "(", "\"type\"", ",", "presenceToSet", ")", ";", "data", ".", "put", "(", "\"presence\"", ",", "typeData", ")", ";", "final", "Object", "finalPresence", "=", "presenceToSet", ";", "signalingChannel", ".", "sendRESTMessage", "(", "\"post\"", ",", "\"/v1/presence\"", ",", "data", ",", "new", "RespokeSignalingChannel", ".", "RESTListener", "(", ")", "{", "@", "Override", "public", "void", "onSuccess", "(", "Object", "response", ")", "{", "presence", "=", "finalPresence", ";", "Respoke", ".", "postTaskSuccess", "(", "completionListener", ")", ";", "}", "@", "Override", "public", "void", "onError", "(", "final", "String", "errorMessage", ")", "{", "Respoke", ".", "postTaskError", "(", "completionListener", ",", "errorMessage", ")", ";", "}", "}", ")", ";", "}", "catch", "(", "JSONException", "e", ")", "{", "Respoke", ".", "postTaskError", "(", "completionListener", ",", "\"Error encoding presence to json\"", ")", ";", "}", "}", "else", "{", "Respoke", ".", "postTaskError", "(", "completionListener", ",", "\"Can't complete request when not connected. Please reconnect!\"", ")", ";", "}", "}" ]
Set the presence on the client session @param newPresence The new presence to use @param completionListener A listener to receive the notification on the success or failure of the asynchronous operation
[ "Set", "the", "presence", "on", "the", "client", "session" ]
train
https://github.com/respoke/respoke-sdk-android/blob/34a15f0558d29b1f1bc8481bbc5c505e855e05ef/respokeSDK/src/main/java/com/digium/respokesdk/RespokeClient.java#L910-L946
jenkinsci/jenkins
core/src/main/java/jenkins/org/apache/commons/validator/routines/UrlValidator.java
UrlValidator.countToken
protected int countToken(String token, String target) { """ Returns the number of times the token appears in the target. @param token Token value to be counted. @param target Target value to count tokens in. @return the number of tokens. """ int tokenIndex = 0; int count = 0; while (tokenIndex != -1) { tokenIndex = target.indexOf(token, tokenIndex); if (tokenIndex > -1) { tokenIndex++; count++; } } return count; }
java
protected int countToken(String token, String target) { int tokenIndex = 0; int count = 0; while (tokenIndex != -1) { tokenIndex = target.indexOf(token, tokenIndex); if (tokenIndex > -1) { tokenIndex++; count++; } } return count; }
[ "protected", "int", "countToken", "(", "String", "token", ",", "String", "target", ")", "{", "int", "tokenIndex", "=", "0", ";", "int", "count", "=", "0", ";", "while", "(", "tokenIndex", "!=", "-", "1", ")", "{", "tokenIndex", "=", "target", ".", "indexOf", "(", "token", ",", "tokenIndex", ")", ";", "if", "(", "tokenIndex", ">", "-", "1", ")", "{", "tokenIndex", "++", ";", "count", "++", ";", "}", "}", "return", "count", ";", "}" ]
Returns the number of times the token appears in the target. @param token Token value to be counted. @param target Target value to count tokens in. @return the number of tokens.
[ "Returns", "the", "number", "of", "times", "the", "token", "appears", "in", "the", "target", "." ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/jenkins/org/apache/commons/validator/routines/UrlValidator.java#L510-L521
igniterealtime/Smack
smack-omemo/src/main/java/org/jivesoftware/smackx/omemo/OmemoService.java
OmemoService.removeStaleDevicesFromDeviceList
private OmemoCachedDeviceList removeStaleDevicesFromDeviceList(OmemoDevice userDevice, BareJid contact, OmemoCachedDeviceList contactsDeviceList, int maxAgeHours) { """ Return a copy of the given deviceList of user contact, but with stale devices marked as inactive. Never mark our own device as stale. If we haven't yet received a message from a device, store the current date as last date of message receipt to allow future decisions. A stale device is a device, from which we haven't received an OMEMO message from for more than "maxAgeMillis" milliseconds. @param userDevice our OmemoDevice. @param contact subjects BareJid. @param contactsDeviceList subjects deviceList. @return copy of subjects deviceList with stale devices marked as inactive. """ OmemoCachedDeviceList deviceList = new OmemoCachedDeviceList(contactsDeviceList); // Don't work on original list. // Iterate through original list, but modify copy instead for (int deviceId : contactsDeviceList.getActiveDevices()) { OmemoDevice device = new OmemoDevice(contact, deviceId); Date lastDeviceIdPublication = getOmemoStoreBackend().getDateOfLastDeviceIdPublication(userDevice, device); if (lastDeviceIdPublication == null) { lastDeviceIdPublication = new Date(); getOmemoStoreBackend().setDateOfLastDeviceIdPublication(userDevice, device, lastDeviceIdPublication); } Date lastMessageReceived = getOmemoStoreBackend().getDateOfLastReceivedMessage(userDevice, device); if (lastMessageReceived == null) { lastMessageReceived = new Date(); getOmemoStoreBackend().setDateOfLastReceivedMessage(userDevice, device, lastMessageReceived); } boolean stale = isStale(userDevice, device, lastDeviceIdPublication, maxAgeHours); stale &= isStale(userDevice, device, lastMessageReceived, maxAgeHours); if (stale) { deviceList.addInactiveDevice(deviceId); } } return deviceList; }
java
private OmemoCachedDeviceList removeStaleDevicesFromDeviceList(OmemoDevice userDevice, BareJid contact, OmemoCachedDeviceList contactsDeviceList, int maxAgeHours) { OmemoCachedDeviceList deviceList = new OmemoCachedDeviceList(contactsDeviceList); // Don't work on original list. // Iterate through original list, but modify copy instead for (int deviceId : contactsDeviceList.getActiveDevices()) { OmemoDevice device = new OmemoDevice(contact, deviceId); Date lastDeviceIdPublication = getOmemoStoreBackend().getDateOfLastDeviceIdPublication(userDevice, device); if (lastDeviceIdPublication == null) { lastDeviceIdPublication = new Date(); getOmemoStoreBackend().setDateOfLastDeviceIdPublication(userDevice, device, lastDeviceIdPublication); } Date lastMessageReceived = getOmemoStoreBackend().getDateOfLastReceivedMessage(userDevice, device); if (lastMessageReceived == null) { lastMessageReceived = new Date(); getOmemoStoreBackend().setDateOfLastReceivedMessage(userDevice, device, lastMessageReceived); } boolean stale = isStale(userDevice, device, lastDeviceIdPublication, maxAgeHours); stale &= isStale(userDevice, device, lastMessageReceived, maxAgeHours); if (stale) { deviceList.addInactiveDevice(deviceId); } } return deviceList; }
[ "private", "OmemoCachedDeviceList", "removeStaleDevicesFromDeviceList", "(", "OmemoDevice", "userDevice", ",", "BareJid", "contact", ",", "OmemoCachedDeviceList", "contactsDeviceList", ",", "int", "maxAgeHours", ")", "{", "OmemoCachedDeviceList", "deviceList", "=", "new", "OmemoCachedDeviceList", "(", "contactsDeviceList", ")", ";", "// Don't work on original list.", "// Iterate through original list, but modify copy instead", "for", "(", "int", "deviceId", ":", "contactsDeviceList", ".", "getActiveDevices", "(", ")", ")", "{", "OmemoDevice", "device", "=", "new", "OmemoDevice", "(", "contact", ",", "deviceId", ")", ";", "Date", "lastDeviceIdPublication", "=", "getOmemoStoreBackend", "(", ")", ".", "getDateOfLastDeviceIdPublication", "(", "userDevice", ",", "device", ")", ";", "if", "(", "lastDeviceIdPublication", "==", "null", ")", "{", "lastDeviceIdPublication", "=", "new", "Date", "(", ")", ";", "getOmemoStoreBackend", "(", ")", ".", "setDateOfLastDeviceIdPublication", "(", "userDevice", ",", "device", ",", "lastDeviceIdPublication", ")", ";", "}", "Date", "lastMessageReceived", "=", "getOmemoStoreBackend", "(", ")", ".", "getDateOfLastReceivedMessage", "(", "userDevice", ",", "device", ")", ";", "if", "(", "lastMessageReceived", "==", "null", ")", "{", "lastMessageReceived", "=", "new", "Date", "(", ")", ";", "getOmemoStoreBackend", "(", ")", ".", "setDateOfLastReceivedMessage", "(", "userDevice", ",", "device", ",", "lastMessageReceived", ")", ";", "}", "boolean", "stale", "=", "isStale", "(", "userDevice", ",", "device", ",", "lastDeviceIdPublication", ",", "maxAgeHours", ")", ";", "stale", "&=", "isStale", "(", "userDevice", ",", "device", ",", "lastMessageReceived", ",", "maxAgeHours", ")", ";", "if", "(", "stale", ")", "{", "deviceList", ".", "addInactiveDevice", "(", "deviceId", ")", ";", "}", "}", "return", "deviceList", ";", "}" ]
Return a copy of the given deviceList of user contact, but with stale devices marked as inactive. Never mark our own device as stale. If we haven't yet received a message from a device, store the current date as last date of message receipt to allow future decisions. A stale device is a device, from which we haven't received an OMEMO message from for more than "maxAgeMillis" milliseconds. @param userDevice our OmemoDevice. @param contact subjects BareJid. @param contactsDeviceList subjects deviceList. @return copy of subjects deviceList with stale devices marked as inactive.
[ "Return", "a", "copy", "of", "the", "given", "deviceList", "of", "user", "contact", "but", "with", "stale", "devices", "marked", "as", "inactive", ".", "Never", "mark", "our", "own", "device", "as", "stale", ".", "If", "we", "haven", "t", "yet", "received", "a", "message", "from", "a", "device", "store", "the", "current", "date", "as", "last", "date", "of", "message", "receipt", "to", "allow", "future", "decisions", "." ]
train
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-omemo/src/main/java/org/jivesoftware/smackx/omemo/OmemoService.java#L938-L968
apache/incubator-druid
extensions-core/histogram/src/main/java/org/apache/druid/query/aggregation/histogram/FixedBucketsHistogram.java
FixedBucketsHistogram.writeByteBufferSerdeHeader
private void writeByteBufferSerdeHeader(ByteBuffer buf, byte mode) { """ Write a serialization header containing the serde version byte and full/sparse encoding mode byte. This header is not needed when serializing the histogram for localized internal use within the buffer aggregator implementation. @param buf Destination buffer @param mode Full or sparse mode """ buf.put(SERIALIZATION_VERSION); buf.put(mode); }
java
private void writeByteBufferSerdeHeader(ByteBuffer buf, byte mode) { buf.put(SERIALIZATION_VERSION); buf.put(mode); }
[ "private", "void", "writeByteBufferSerdeHeader", "(", "ByteBuffer", "buf", ",", "byte", "mode", ")", "{", "buf", ".", "put", "(", "SERIALIZATION_VERSION", ")", ";", "buf", ".", "put", "(", "mode", ")", ";", "}" ]
Write a serialization header containing the serde version byte and full/sparse encoding mode byte. This header is not needed when serializing the histogram for localized internal use within the buffer aggregator implementation. @param buf Destination buffer @param mode Full or sparse mode
[ "Write", "a", "serialization", "header", "containing", "the", "serde", "version", "byte", "and", "full", "/", "sparse", "encoding", "mode", "byte", "." ]
train
https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/extensions-core/histogram/src/main/java/org/apache/druid/query/aggregation/histogram/FixedBucketsHistogram.java#L788-L792
alkacon/opencms-core
src-gwt/org/opencms/ade/containerpage/client/CmsContainerpageHandler.java
CmsContainerpageHandler.insertContextMenu
public void insertContextMenu(List<CmsContextMenuEntryBean> menuBeans, CmsUUID structureId) { """ Inserts the context menu.<p> @param menuBeans the menu beans from the server @param structureId the structure id of the resource for which the context menu entries should be generated """ List<I_CmsContextMenuEntry> menuEntries = transformEntries(menuBeans, structureId); m_editor.getContext().showMenu(menuEntries); }
java
public void insertContextMenu(List<CmsContextMenuEntryBean> menuBeans, CmsUUID structureId) { List<I_CmsContextMenuEntry> menuEntries = transformEntries(menuBeans, structureId); m_editor.getContext().showMenu(menuEntries); }
[ "public", "void", "insertContextMenu", "(", "List", "<", "CmsContextMenuEntryBean", ">", "menuBeans", ",", "CmsUUID", "structureId", ")", "{", "List", "<", "I_CmsContextMenuEntry", ">", "menuEntries", "=", "transformEntries", "(", "menuBeans", ",", "structureId", ")", ";", "m_editor", ".", "getContext", "(", ")", ".", "showMenu", "(", "menuEntries", ")", ";", "}" ]
Inserts the context menu.<p> @param menuBeans the menu beans from the server @param structureId the structure id of the resource for which the context menu entries should be generated
[ "Inserts", "the", "context", "menu", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/containerpage/client/CmsContainerpageHandler.java#L578-L582
elki-project/elki
elki-index/src/main/java/de/lmu/ifi/dbs/elki/index/tree/AbstractNode.java
AbstractNode.splitTo
public final void splitTo(AbstractNode<E> newNode, List<E> assignmentsToFirst, List<E> assignmentsToSecond) { """ Splits the entries of this node into a new node using the given assignments @param newNode Node to split to @param assignmentsToFirst the assignment to this node @param assignmentsToSecond the assignment to the new node """ assert (isLeaf() == newNode.isLeaf()); deleteAllEntries(); StringBuilder msg = LoggingConfiguration.DEBUG ? new StringBuilder(1000) : null; // assignments to this node for(E entry : assignmentsToFirst) { if(msg != null) { msg.append("n_").append(getPageID()).append(' ').append(entry).append('\n'); } addEntry(entry); } // assignments to the new node for(E entry : assignmentsToSecond) { if(msg != null) { msg.append("n_").append(newNode.getPageID()).append(' ').append(entry).append('\n'); } newNode.addEntry(entry); } if(msg != null) { Logging.getLogger(this.getClass()).fine(msg.toString()); } }
java
public final void splitTo(AbstractNode<E> newNode, List<E> assignmentsToFirst, List<E> assignmentsToSecond) { assert (isLeaf() == newNode.isLeaf()); deleteAllEntries(); StringBuilder msg = LoggingConfiguration.DEBUG ? new StringBuilder(1000) : null; // assignments to this node for(E entry : assignmentsToFirst) { if(msg != null) { msg.append("n_").append(getPageID()).append(' ').append(entry).append('\n'); } addEntry(entry); } // assignments to the new node for(E entry : assignmentsToSecond) { if(msg != null) { msg.append("n_").append(newNode.getPageID()).append(' ').append(entry).append('\n'); } newNode.addEntry(entry); } if(msg != null) { Logging.getLogger(this.getClass()).fine(msg.toString()); } }
[ "public", "final", "void", "splitTo", "(", "AbstractNode", "<", "E", ">", "newNode", ",", "List", "<", "E", ">", "assignmentsToFirst", ",", "List", "<", "E", ">", "assignmentsToSecond", ")", "{", "assert", "(", "isLeaf", "(", ")", "==", "newNode", ".", "isLeaf", "(", ")", ")", ";", "deleteAllEntries", "(", ")", ";", "StringBuilder", "msg", "=", "LoggingConfiguration", ".", "DEBUG", "?", "new", "StringBuilder", "(", "1000", ")", ":", "null", ";", "// assignments to this node", "for", "(", "E", "entry", ":", "assignmentsToFirst", ")", "{", "if", "(", "msg", "!=", "null", ")", "{", "msg", ".", "append", "(", "\"n_\"", ")", ".", "append", "(", "getPageID", "(", ")", ")", ".", "append", "(", "'", "'", ")", ".", "append", "(", "entry", ")", ".", "append", "(", "'", "'", ")", ";", "}", "addEntry", "(", "entry", ")", ";", "}", "// assignments to the new node", "for", "(", "E", "entry", ":", "assignmentsToSecond", ")", "{", "if", "(", "msg", "!=", "null", ")", "{", "msg", ".", "append", "(", "\"n_\"", ")", ".", "append", "(", "newNode", ".", "getPageID", "(", ")", ")", ".", "append", "(", "'", "'", ")", ".", "append", "(", "entry", ")", ".", "append", "(", "'", "'", ")", ";", "}", "newNode", ".", "addEntry", "(", "entry", ")", ";", "}", "if", "(", "msg", "!=", "null", ")", "{", "Logging", ".", "getLogger", "(", "this", ".", "getClass", "(", ")", ")", ".", "fine", "(", "msg", ".", "toString", "(", ")", ")", ";", "}", "}" ]
Splits the entries of this node into a new node using the given assignments @param newNode Node to split to @param assignmentsToFirst the assignment to this node @param assignmentsToSecond the assignment to the new node
[ "Splits", "the", "entries", "of", "this", "node", "into", "a", "new", "node", "using", "the", "given", "assignments" ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-index/src/main/java/de/lmu/ifi/dbs/elki/index/tree/AbstractNode.java#L332-L355
Viascom/groundwork
foxhttp/src/main/java/ch/viascom/groundwork/foxhttp/util/QueryBuilder.java
QueryBuilder.buildQuery
public static String buildQuery(Map<String, String> entries, String encoding) throws FoxHttpRequestException { """ Return a string of key/value pair's based on a map @param entries @param encoding @return @throws FoxHttpRequestException """ if (entries.size() > 0) { StringBuilder sb = new StringBuilder(); String dataString; try { for (Map.Entry<String, String> entry : entries.entrySet()) { sb.append(URLEncoder.encode(entry.getKey(), encoding)); sb.append("="); sb.append(URLEncoder.encode(entry.getValue(), encoding)); sb.append("&"); } sb.deleteCharAt(sb.lastIndexOf("&")); dataString = sb.toString(); } catch (UnsupportedEncodingException e) { throw new FoxHttpRequestException(e); } return dataString; } else { return ""; } }
java
public static String buildQuery(Map<String, String> entries, String encoding) throws FoxHttpRequestException { if (entries.size() > 0) { StringBuilder sb = new StringBuilder(); String dataString; try { for (Map.Entry<String, String> entry : entries.entrySet()) { sb.append(URLEncoder.encode(entry.getKey(), encoding)); sb.append("="); sb.append(URLEncoder.encode(entry.getValue(), encoding)); sb.append("&"); } sb.deleteCharAt(sb.lastIndexOf("&")); dataString = sb.toString(); } catch (UnsupportedEncodingException e) { throw new FoxHttpRequestException(e); } return dataString; } else { return ""; } }
[ "public", "static", "String", "buildQuery", "(", "Map", "<", "String", ",", "String", ">", "entries", ",", "String", "encoding", ")", "throws", "FoxHttpRequestException", "{", "if", "(", "entries", ".", "size", "(", ")", ">", "0", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "String", "dataString", ";", "try", "{", "for", "(", "Map", ".", "Entry", "<", "String", ",", "String", ">", "entry", ":", "entries", ".", "entrySet", "(", ")", ")", "{", "sb", ".", "append", "(", "URLEncoder", ".", "encode", "(", "entry", ".", "getKey", "(", ")", ",", "encoding", ")", ")", ";", "sb", ".", "append", "(", "\"=\"", ")", ";", "sb", ".", "append", "(", "URLEncoder", ".", "encode", "(", "entry", ".", "getValue", "(", ")", ",", "encoding", ")", ")", ";", "sb", ".", "append", "(", "\"&\"", ")", ";", "}", "sb", ".", "deleteCharAt", "(", "sb", ".", "lastIndexOf", "(", "\"&\"", ")", ")", ";", "dataString", "=", "sb", ".", "toString", "(", ")", ";", "}", "catch", "(", "UnsupportedEncodingException", "e", ")", "{", "throw", "new", "FoxHttpRequestException", "(", "e", ")", ";", "}", "return", "dataString", ";", "}", "else", "{", "return", "\"\"", ";", "}", "}" ]
Return a string of key/value pair's based on a map @param entries @param encoding @return @throws FoxHttpRequestException
[ "Return", "a", "string", "of", "key", "/", "value", "pair", "s", "based", "on", "a", "map" ]
train
https://github.com/Viascom/groundwork/blob/d3f7d0df65e2e75861fc7db938090683f2cdf919/foxhttp/src/main/java/ch/viascom/groundwork/foxhttp/util/QueryBuilder.java#L42-L62
qatools/properties
src/main/java/ru/qatools/properties/PropertyLoader.java
PropertyLoader.checkRequired
protected void checkRequired(String key, AnnotatedElement element) { """ Throws an exception if given element is required. @see #isRequired(AnnotatedElement) """ if (isRequired(element)) { throw new PropertyLoaderException(String.format("Required property <%s> doesn't exists", key)); } }
java
protected void checkRequired(String key, AnnotatedElement element) { if (isRequired(element)) { throw new PropertyLoaderException(String.format("Required property <%s> doesn't exists", key)); } }
[ "protected", "void", "checkRequired", "(", "String", "key", ",", "AnnotatedElement", "element", ")", "{", "if", "(", "isRequired", "(", "element", ")", ")", "{", "throw", "new", "PropertyLoaderException", "(", "String", ".", "format", "(", "\"Required property <%s> doesn't exists\"", ",", "key", ")", ")", ";", "}", "}" ]
Throws an exception if given element is required. @see #isRequired(AnnotatedElement)
[ "Throws", "an", "exception", "if", "given", "element", "is", "required", "." ]
train
https://github.com/qatools/properties/blob/ae50b460a6bb4fcb21afe888b2e86a7613cd2115/src/main/java/ru/qatools/properties/PropertyLoader.java#L220-L224
gallandarakhneorg/afc
core/maths/mathphysics/src/main/java/org/arakhne/afc/math/physics/MeasureUnitUtil.java
MeasureUnitUtil.getSmallestUnit
@Pure public static SpaceUnit getSmallestUnit(double amount, SpaceUnit unit) { """ Compute the smallest unit that permits to have a metric value with its integer part positive. @param amount is the amount expressed in the given unit. @param unit is the unit of the given amount. @return the smallest unit that permits to obtain the smallest positive mathematical integer that corresponds to the integer part of the given amount after its convertion to the selected unit. """ final double meters = toMeters(amount, unit); double v; final SpaceUnit[] units = SpaceUnit.values(); SpaceUnit u; for (int i = units.length - 1; i >= 0; --i) { u = units[i]; v = Math.floor(fromMeters(meters, u)); if (v > 0.) { return u; } } return unit; }
java
@Pure public static SpaceUnit getSmallestUnit(double amount, SpaceUnit unit) { final double meters = toMeters(amount, unit); double v; final SpaceUnit[] units = SpaceUnit.values(); SpaceUnit u; for (int i = units.length - 1; i >= 0; --i) { u = units[i]; v = Math.floor(fromMeters(meters, u)); if (v > 0.) { return u; } } return unit; }
[ "@", "Pure", "public", "static", "SpaceUnit", "getSmallestUnit", "(", "double", "amount", ",", "SpaceUnit", "unit", ")", "{", "final", "double", "meters", "=", "toMeters", "(", "amount", ",", "unit", ")", ";", "double", "v", ";", "final", "SpaceUnit", "[", "]", "units", "=", "SpaceUnit", ".", "values", "(", ")", ";", "SpaceUnit", "u", ";", "for", "(", "int", "i", "=", "units", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "--", "i", ")", "{", "u", "=", "units", "[", "i", "]", ";", "v", "=", "Math", ".", "floor", "(", "fromMeters", "(", "meters", ",", "u", ")", ")", ";", "if", "(", "v", ">", "0.", ")", "{", "return", "u", ";", "}", "}", "return", "unit", ";", "}" ]
Compute the smallest unit that permits to have a metric value with its integer part positive. @param amount is the amount expressed in the given unit. @param unit is the unit of the given amount. @return the smallest unit that permits to obtain the smallest positive mathematical integer that corresponds to the integer part of the given amount after its convertion to the selected unit.
[ "Compute", "the", "smallest", "unit", "that", "permits", "to", "have", "a", "metric", "value", "with", "its", "integer", "part", "positive", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/maths/mathphysics/src/main/java/org/arakhne/afc/math/physics/MeasureUnitUtil.java#L700-L714
jeremylong/DependencyCheck
core/src/main/java/org/owasp/dependencycheck/data/cpe/CpeMemoryIndex.java
CpeMemoryIndex.buildIndex
private void buildIndex(CveDB cve) throws IndexException { """ Builds the CPE Lucene Index based off of the data within the CveDB. @param cve the data base containing the CPE data @throws IndexException thrown if there is an issue creating the index """ try (Analyzer analyzer = createSearchingAnalyzer(); IndexWriter indexWriter = new IndexWriter(index, new IndexWriterConfig(analyzer))) { final FieldType ft = new FieldType(TextField.TYPE_STORED); //ignore term frequency ft.setIndexOptions(IndexOptions.DOCS); //ignore field length normalization ft.setOmitNorms(true); // Tip: reuse the Document and Fields for performance... // See "Re-use Document and Field instances" from // http://wiki.apache.org/lucene-java/ImproveIndexingSpeed final Document doc = new Document(); final Field v = new Field(Fields.VENDOR, Fields.VENDOR, ft); final Field p = new Field(Fields.PRODUCT, Fields.PRODUCT, ft); doc.add(v); doc.add(p); final Set<Pair<String, String>> data = cve.getVendorProductList(); for (Pair<String, String> pair : data) { if (pair.getLeft() != null && pair.getRight() != null) { v.setStringValue(pair.getLeft()); p.setStringValue(pair.getRight()); indexWriter.addDocument(doc); resetAnalyzers(); } } indexWriter.commit(); } catch (DatabaseException ex) { LOGGER.debug("", ex); throw new IndexException("Error reading CPE data", ex); } catch (IOException ex) { throw new IndexException("Unable to close an in-memory index", ex); } }
java
private void buildIndex(CveDB cve) throws IndexException { try (Analyzer analyzer = createSearchingAnalyzer(); IndexWriter indexWriter = new IndexWriter(index, new IndexWriterConfig(analyzer))) { final FieldType ft = new FieldType(TextField.TYPE_STORED); //ignore term frequency ft.setIndexOptions(IndexOptions.DOCS); //ignore field length normalization ft.setOmitNorms(true); // Tip: reuse the Document and Fields for performance... // See "Re-use Document and Field instances" from // http://wiki.apache.org/lucene-java/ImproveIndexingSpeed final Document doc = new Document(); final Field v = new Field(Fields.VENDOR, Fields.VENDOR, ft); final Field p = new Field(Fields.PRODUCT, Fields.PRODUCT, ft); doc.add(v); doc.add(p); final Set<Pair<String, String>> data = cve.getVendorProductList(); for (Pair<String, String> pair : data) { if (pair.getLeft() != null && pair.getRight() != null) { v.setStringValue(pair.getLeft()); p.setStringValue(pair.getRight()); indexWriter.addDocument(doc); resetAnalyzers(); } } indexWriter.commit(); } catch (DatabaseException ex) { LOGGER.debug("", ex); throw new IndexException("Error reading CPE data", ex); } catch (IOException ex) { throw new IndexException("Unable to close an in-memory index", ex); } }
[ "private", "void", "buildIndex", "(", "CveDB", "cve", ")", "throws", "IndexException", "{", "try", "(", "Analyzer", "analyzer", "=", "createSearchingAnalyzer", "(", ")", ";", "IndexWriter", "indexWriter", "=", "new", "IndexWriter", "(", "index", ",", "new", "IndexWriterConfig", "(", "analyzer", ")", ")", ")", "{", "final", "FieldType", "ft", "=", "new", "FieldType", "(", "TextField", ".", "TYPE_STORED", ")", ";", "//ignore term frequency", "ft", ".", "setIndexOptions", "(", "IndexOptions", ".", "DOCS", ")", ";", "//ignore field length normalization", "ft", ".", "setOmitNorms", "(", "true", ")", ";", "// Tip: reuse the Document and Fields for performance...", "// See \"Re-use Document and Field instances\" from", "// http://wiki.apache.org/lucene-java/ImproveIndexingSpeed", "final", "Document", "doc", "=", "new", "Document", "(", ")", ";", "final", "Field", "v", "=", "new", "Field", "(", "Fields", ".", "VENDOR", ",", "Fields", ".", "VENDOR", ",", "ft", ")", ";", "final", "Field", "p", "=", "new", "Field", "(", "Fields", ".", "PRODUCT", ",", "Fields", ".", "PRODUCT", ",", "ft", ")", ";", "doc", ".", "add", "(", "v", ")", ";", "doc", ".", "add", "(", "p", ")", ";", "final", "Set", "<", "Pair", "<", "String", ",", "String", ">", ">", "data", "=", "cve", ".", "getVendorProductList", "(", ")", ";", "for", "(", "Pair", "<", "String", ",", "String", ">", "pair", ":", "data", ")", "{", "if", "(", "pair", ".", "getLeft", "(", ")", "!=", "null", "&&", "pair", ".", "getRight", "(", ")", "!=", "null", ")", "{", "v", ".", "setStringValue", "(", "pair", ".", "getLeft", "(", ")", ")", ";", "p", ".", "setStringValue", "(", "pair", ".", "getRight", "(", ")", ")", ";", "indexWriter", ".", "addDocument", "(", "doc", ")", ";", "resetAnalyzers", "(", ")", ";", "}", "}", "indexWriter", ".", "commit", "(", ")", ";", "}", "catch", "(", "DatabaseException", "ex", ")", "{", "LOGGER", ".", "debug", "(", "\"\"", ",", "ex", ")", ";", "throw", "new", "IndexException", "(", "\"Error reading CPE data\"", ",", "ex", ")", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "throw", "new", "IndexException", "(", "\"Unable to close an in-memory index\"", ",", "ex", ")", ";", "}", "}" ]
Builds the CPE Lucene Index based off of the data within the CveDB. @param cve the data base containing the CPE data @throws IndexException thrown if there is an issue creating the index
[ "Builds", "the", "CPE", "Lucene", "Index", "based", "off", "of", "the", "data", "within", "the", "CveDB", "." ]
train
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/cpe/CpeMemoryIndex.java#L215-L252
MenoData/Time4J
base/src/main/java/net/time4j/engine/StartOfDay.java
StartOfDay.definedBy
public static <T extends UnixTime> StartOfDay definedBy(ChronoFunction<CalendarDate, Optional<T>> event) { """ /*[deutsch] <p>Liefert den Start eines Kalendertags, wie von der angegebenen Datumsfunktion bestimmt. </p> <p>Wenn die angegebene Funktion keinen Moment f&uuml;r ein Kalenderdatum ermitteln kann, wird eine Ausnahme geworfen. Diese Methode ist am besten f&uuml;r Kalender geeignet, deren Tage zu astronomischen Ereignissen wie einem Sonnenuntergang beginnen. Beispiel: </p> <pre> HijriCalendar hijri = HijriCalendar.ofUmalqura(1436, 10, 2); SolarTime mekkaTime = SolarTime.ofLocation(21.4225, 39.826111); ZonalOffset saudiArabia = ZonalOffset.ofHours(OffsetSign.AHEAD_OF_UTC, 3); StartOfDay startOfDay = StartOfDay.definedBy(mekkaTime.sunset()); // short after sunset (2015-07-17T19:05:40) System.out.println( hijri.atTime(19, 6).at(saudiArabia, startOfDay)); // 2015-07-17T19:06+03:00 // short before sunset (2015-07-17T19:05:40) System.out.println( hijri.minus(CalendarDays.ONE).atTime(19, 5).at(saudiArabia, startOfDay)); // 2015-07-17T19:05+03:00 </pre> @param <T> generic type parameter indicating the time of the event @param event function which yields the relevant moment for a given calendar day @return start of day @since 3.34/4.29 """ return new FunctionalStartOfDay<>(event); }
java
public static <T extends UnixTime> StartOfDay definedBy(ChronoFunction<CalendarDate, Optional<T>> event) { return new FunctionalStartOfDay<>(event); }
[ "public", "static", "<", "T", "extends", "UnixTime", ">", "StartOfDay", "definedBy", "(", "ChronoFunction", "<", "CalendarDate", ",", "Optional", "<", "T", ">", ">", "event", ")", "{", "return", "new", "FunctionalStartOfDay", "<>", "(", "event", ")", ";", "}" ]
/*[deutsch] <p>Liefert den Start eines Kalendertags, wie von der angegebenen Datumsfunktion bestimmt. </p> <p>Wenn die angegebene Funktion keinen Moment f&uuml;r ein Kalenderdatum ermitteln kann, wird eine Ausnahme geworfen. Diese Methode ist am besten f&uuml;r Kalender geeignet, deren Tage zu astronomischen Ereignissen wie einem Sonnenuntergang beginnen. Beispiel: </p> <pre> HijriCalendar hijri = HijriCalendar.ofUmalqura(1436, 10, 2); SolarTime mekkaTime = SolarTime.ofLocation(21.4225, 39.826111); ZonalOffset saudiArabia = ZonalOffset.ofHours(OffsetSign.AHEAD_OF_UTC, 3); StartOfDay startOfDay = StartOfDay.definedBy(mekkaTime.sunset()); // short after sunset (2015-07-17T19:05:40) System.out.println( hijri.atTime(19, 6).at(saudiArabia, startOfDay)); // 2015-07-17T19:06+03:00 // short before sunset (2015-07-17T19:05:40) System.out.println( hijri.minus(CalendarDays.ONE).atTime(19, 5).at(saudiArabia, startOfDay)); // 2015-07-17T19:05+03:00 </pre> @param <T> generic type parameter indicating the time of the event @param event function which yields the relevant moment for a given calendar day @return start of day @since 3.34/4.29
[ "/", "*", "[", "deutsch", "]", "<p", ">", "Liefert", "den", "Start", "eines", "Kalendertags", "wie", "von", "der", "angegebenen", "Datumsfunktion", "bestimmt", ".", "<", "/", "p", ">" ]
train
https://github.com/MenoData/Time4J/blob/08b2eda6b2dbb140b92011cf7071bb087edd46a5/base/src/main/java/net/time4j/engine/StartOfDay.java#L177-L181