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
lastaflute/lasta-di
src/main/java/org/lastaflute/di/util/LdiSrl.java
LdiSrl.substringLastFrontIgnoreCase
public static String substringLastFrontIgnoreCase(String str, String... delimiters) { """ Extract front sub-string from last-found delimiter ignoring case. <pre> substringLastFront("foo.bar/baz.qux", "A", "U") returns "foo.bar/baz.q" </pre> @param str The target string. (NotNull) @param delimiters The array of delimiters. (NotNull) @return The part of string. (NotNull: if delimiter not found, returns argument-plain string) """ assertStringNotNull(str); return doSubstringFirstRear(true, false, true, str, delimiters); }
java
public static String substringLastFrontIgnoreCase(String str, String... delimiters) { assertStringNotNull(str); return doSubstringFirstRear(true, false, true, str, delimiters); }
[ "public", "static", "String", "substringLastFrontIgnoreCase", "(", "String", "str", ",", "String", "...", "delimiters", ")", "{", "assertStringNotNull", "(", "str", ")", ";", "return", "doSubstringFirstRear", "(", "true", ",", "false", ",", "true", ",", "str", ",", "delimiters", ")", ";", "}" ]
Extract front sub-string from last-found delimiter ignoring case. <pre> substringLastFront("foo.bar/baz.qux", "A", "U") returns "foo.bar/baz.q" </pre> @param str The target string. (NotNull) @param delimiters The array of delimiters. (NotNull) @return The part of string. (NotNull: if delimiter not found, returns argument-plain string)
[ "Extract", "front", "sub", "-", "string", "from", "last", "-", "found", "delimiter", "ignoring", "case", ".", "<pre", ">", "substringLastFront", "(", "foo", ".", "bar", "/", "baz", ".", "qux", "A", "U", ")", "returns", "foo", ".", "bar", "/", "baz", ".", "q", "<", "/", "pre", ">" ]
train
https://github.com/lastaflute/lasta-di/blob/c4e123610c53a04cc836c5e456660e32d613447b/src/main/java/org/lastaflute/di/util/LdiSrl.java#L702-L705
apache/incubator-druid
extensions-core/hdfs-storage/src/main/java/org/apache/druid/storage/hdfs/HdfsDataSegmentPusher.java
HdfsDataSegmentPusher.getStorageDir
@Override public String getStorageDir(DataSegment segment, boolean useUniquePath) { """ Due to https://issues.apache.org/jira/browse/HDFS-13 ":" are not allowed in path names. So we format paths differently for HDFS. """ // This is only called by HdfsDataSegmentPusher.push(), which will always set useUniquePath to false since any // 'uniqueness' will be applied not to the directory but to the filename along with the shard number. This is done // to avoid performance issues due to excessive HDFS directories. Hence useUniquePath is ignored here and we // expect it to be false. Preconditions.checkArgument( !useUniquePath, "useUniquePath must be false for HdfsDataSegmentPusher.getStorageDir()" ); return JOINER.join( segment.getDataSource(), StringUtils.format( "%s_%s", segment.getInterval().getStart().toString(ISODateTimeFormat.basicDateTime()), segment.getInterval().getEnd().toString(ISODateTimeFormat.basicDateTime()) ), segment.getVersion().replace(':', '_') ); }
java
@Override public String getStorageDir(DataSegment segment, boolean useUniquePath) { // This is only called by HdfsDataSegmentPusher.push(), which will always set useUniquePath to false since any // 'uniqueness' will be applied not to the directory but to the filename along with the shard number. This is done // to avoid performance issues due to excessive HDFS directories. Hence useUniquePath is ignored here and we // expect it to be false. Preconditions.checkArgument( !useUniquePath, "useUniquePath must be false for HdfsDataSegmentPusher.getStorageDir()" ); return JOINER.join( segment.getDataSource(), StringUtils.format( "%s_%s", segment.getInterval().getStart().toString(ISODateTimeFormat.basicDateTime()), segment.getInterval().getEnd().toString(ISODateTimeFormat.basicDateTime()) ), segment.getVersion().replace(':', '_') ); }
[ "@", "Override", "public", "String", "getStorageDir", "(", "DataSegment", "segment", ",", "boolean", "useUniquePath", ")", "{", "// This is only called by HdfsDataSegmentPusher.push(), which will always set useUniquePath to false since any", "// 'uniqueness' will be applied not to the directory but to the filename along with the shard number. This is done", "// to avoid performance issues due to excessive HDFS directories. Hence useUniquePath is ignored here and we", "// expect it to be false.", "Preconditions", ".", "checkArgument", "(", "!", "useUniquePath", ",", "\"useUniquePath must be false for HdfsDataSegmentPusher.getStorageDir()\"", ")", ";", "return", "JOINER", ".", "join", "(", "segment", ".", "getDataSource", "(", ")", ",", "StringUtils", ".", "format", "(", "\"%s_%s\"", ",", "segment", ".", "getInterval", "(", ")", ".", "getStart", "(", ")", ".", "toString", "(", "ISODateTimeFormat", ".", "basicDateTime", "(", ")", ")", ",", "segment", ".", "getInterval", "(", ")", ".", "getEnd", "(", ")", ".", "toString", "(", "ISODateTimeFormat", ".", "basicDateTime", "(", ")", ")", ")", ",", "segment", ".", "getVersion", "(", ")", ".", "replace", "(", "'", "'", ",", "'", "'", ")", ")", ";", "}" ]
Due to https://issues.apache.org/jira/browse/HDFS-13 ":" are not allowed in path names. So we format paths differently for HDFS.
[ "Due", "to", "https", ":", "//", "issues", ".", "apache", ".", "org", "/", "jira", "/", "browse", "/", "HDFS", "-", "13", ":", "are", "not", "allowed", "in", "path", "names", ".", "So", "we", "format", "paths", "differently", "for", "HDFS", "." ]
train
https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/extensions-core/hdfs-storage/src/main/java/org/apache/druid/storage/hdfs/HdfsDataSegmentPusher.java#L187-L208
Azure/azure-sdk-for-java
batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/FilesImpl.java
FilesImpl.deleteFromTask
public void deleteFromTask(String jobId, String taskId, String filePath, Boolean recursive, FileDeleteFromTaskOptions fileDeleteFromTaskOptions) { """ Deletes the specified task file from the compute node where the task ran. @param jobId The ID of the job that contains the task. @param taskId The ID of the task whose file you want to delete. @param filePath The path to the task file or directory that you want to delete. @param recursive Whether to delete children of a directory. If the filePath parameter represents a directory instead of a file, you can set recursive to true to delete the directory and all of the files and subdirectories in it. If recursive is false then the directory must be empty or deletion will fail. @param fileDeleteFromTaskOptions Additional parameters for the operation @throws IllegalArgumentException thrown if parameters fail the validation @throws BatchErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent """ deleteFromTaskWithServiceResponseAsync(jobId, taskId, filePath, recursive, fileDeleteFromTaskOptions).toBlocking().single().body(); }
java
public void deleteFromTask(String jobId, String taskId, String filePath, Boolean recursive, FileDeleteFromTaskOptions fileDeleteFromTaskOptions) { deleteFromTaskWithServiceResponseAsync(jobId, taskId, filePath, recursive, fileDeleteFromTaskOptions).toBlocking().single().body(); }
[ "public", "void", "deleteFromTask", "(", "String", "jobId", ",", "String", "taskId", ",", "String", "filePath", ",", "Boolean", "recursive", ",", "FileDeleteFromTaskOptions", "fileDeleteFromTaskOptions", ")", "{", "deleteFromTaskWithServiceResponseAsync", "(", "jobId", ",", "taskId", ",", "filePath", ",", "recursive", ",", "fileDeleteFromTaskOptions", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Deletes the specified task file from the compute node where the task ran. @param jobId The ID of the job that contains the task. @param taskId The ID of the task whose file you want to delete. @param filePath The path to the task file or directory that you want to delete. @param recursive Whether to delete children of a directory. If the filePath parameter represents a directory instead of a file, you can set recursive to true to delete the directory and all of the files and subdirectories in it. If recursive is false then the directory must be empty or deletion will fail. @param fileDeleteFromTaskOptions Additional parameters for the operation @throws IllegalArgumentException thrown if parameters fail the validation @throws BatchErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
[ "Deletes", "the", "specified", "task", "file", "from", "the", "compute", "node", "where", "the", "task", "ran", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/FilesImpl.java#L243-L245
headius/invokebinder
src/main/java/com/headius/invokebinder/Signature.java
Signature.argName
public Signature argName(int index, String name) { """ Set the argument name at the given index. @param index the index at which to set the argument name @param name the name to set @return a new signature with the given name at the given index """ String[] argNames = Arrays.copyOf(argNames(), argNames().length); argNames[index] = name; return new Signature(type(), argNames); }
java
public Signature argName(int index, String name) { String[] argNames = Arrays.copyOf(argNames(), argNames().length); argNames[index] = name; return new Signature(type(), argNames); }
[ "public", "Signature", "argName", "(", "int", "index", ",", "String", "name", ")", "{", "String", "[", "]", "argNames", "=", "Arrays", ".", "copyOf", "(", "argNames", "(", ")", ",", "argNames", "(", ")", ".", "length", ")", ";", "argNames", "[", "index", "]", "=", "name", ";", "return", "new", "Signature", "(", "type", "(", ")", ",", "argNames", ")", ";", "}" ]
Set the argument name at the given index. @param index the index at which to set the argument name @param name the name to set @return a new signature with the given name at the given index
[ "Set", "the", "argument", "name", "at", "the", "given", "index", "." ]
train
https://github.com/headius/invokebinder/blob/ce6bfeb8e33265480daa7b797989dd915d51238d/src/main/java/com/headius/invokebinder/Signature.java#L612-L616
defei/codelogger-utils
src/main/java/org/codelogger/utils/StringUtils.java
StringUtils.countIgnoreCase
public static int countIgnoreCase(final String source, final String target) { """ Count how much target in souce string.</br>统计target在source中出现的次数。 @param source source string @param target target string @return the count of target in source string. """ if (isEmpty(source) || isEmpty(target)) { return 0; } return count(source.toLowerCase(), target.toLowerCase()); }
java
public static int countIgnoreCase(final String source, final String target) { if (isEmpty(source) || isEmpty(target)) { return 0; } return count(source.toLowerCase(), target.toLowerCase()); }
[ "public", "static", "int", "countIgnoreCase", "(", "final", "String", "source", ",", "final", "String", "target", ")", "{", "if", "(", "isEmpty", "(", "source", ")", "||", "isEmpty", "(", "target", ")", ")", "{", "return", "0", ";", "}", "return", "count", "(", "source", ".", "toLowerCase", "(", ")", ",", "target", ".", "toLowerCase", "(", ")", ")", ";", "}" ]
Count how much target in souce string.</br>统计target在source中出现的次数。 @param source source string @param target target string @return the count of target in source string.
[ "Count", "how", "much", "target", "in", "souce", "string", ".", "<", "/", "br", ">", "统计target在source中出现的次数。" ]
train
https://github.com/defei/codelogger-utils/blob/d906f5d217b783c7ae3e53442cd6fb87b20ecc0a/src/main/java/org/codelogger/utils/StringUtils.java#L492-L498
albfernandez/itext2
src/main/java/com/lowagie/text/Table.java
Table.insertTable
public void insertTable(Table aTable, Point aLocation) { """ To put a table within the existing table at the given position generateTable will of course re-arrange the widths of the columns. @param aTable the table you want to insert @param aLocation a <CODE>Point</CODE> """ if (aTable == null) { throw new NullPointerException("insertTable - table has null-value"); } if (aLocation == null) { throw new NullPointerException("insertTable - point has null-value"); } mTableInserted = true; aTable.complete(); if (aLocation.y > columns) { throw new IllegalArgumentException("insertTable -- wrong columnposition("+ aLocation.y + ") of location; max =" + columns); } int rowCount = aLocation.x + 1 - rows.size(); int i = 0; if ( rowCount > 0 ) { //create new rows ? for (; i < rowCount; i++) { rows.add(new Row(columns)); } } rows.get(aLocation.x).setElement(aTable,aLocation.y); setCurrentLocationToNextValidPosition(aLocation); }
java
public void insertTable(Table aTable, Point aLocation) { if (aTable == null) { throw new NullPointerException("insertTable - table has null-value"); } if (aLocation == null) { throw new NullPointerException("insertTable - point has null-value"); } mTableInserted = true; aTable.complete(); if (aLocation.y > columns) { throw new IllegalArgumentException("insertTable -- wrong columnposition("+ aLocation.y + ") of location; max =" + columns); } int rowCount = aLocation.x + 1 - rows.size(); int i = 0; if ( rowCount > 0 ) { //create new rows ? for (; i < rowCount; i++) { rows.add(new Row(columns)); } } rows.get(aLocation.x).setElement(aTable,aLocation.y); setCurrentLocationToNextValidPosition(aLocation); }
[ "public", "void", "insertTable", "(", "Table", "aTable", ",", "Point", "aLocation", ")", "{", "if", "(", "aTable", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"insertTable - table has null-value\"", ")", ";", "}", "if", "(", "aLocation", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"insertTable - point has null-value\"", ")", ";", "}", "mTableInserted", "=", "true", ";", "aTable", ".", "complete", "(", ")", ";", "if", "(", "aLocation", ".", "y", ">", "columns", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"insertTable -- wrong columnposition(\"", "+", "aLocation", ".", "y", "+", "\") of location; max =\"", "+", "columns", ")", ";", "}", "int", "rowCount", "=", "aLocation", ".", "x", "+", "1", "-", "rows", ".", "size", "(", ")", ";", "int", "i", "=", "0", ";", "if", "(", "rowCount", ">", "0", ")", "{", "//create new rows ?", "for", "(", ";", "i", "<", "rowCount", ";", "i", "++", ")", "{", "rows", ".", "add", "(", "new", "Row", "(", "columns", ")", ")", ";", "}", "}", "rows", ".", "get", "(", "aLocation", ".", "x", ")", ".", "setElement", "(", "aTable", ",", "aLocation", ".", "y", ")", ";", "setCurrentLocationToNextValidPosition", "(", "aLocation", ")", ";", "}" ]
To put a table within the existing table at the given position generateTable will of course re-arrange the widths of the columns. @param aTable the table you want to insert @param aLocation a <CODE>Point</CODE>
[ "To", "put", "a", "table", "within", "the", "existing", "table", "at", "the", "given", "position", "generateTable", "will", "of", "course", "re", "-", "arrange", "the", "widths", "of", "the", "columns", "." ]
train
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/Table.java#L820-L846
NoraUi/NoraUi
src/main/java/com/github/noraui/utils/Utilities.java
Utilities.findElement
public static WebElement findElement(Page page, String code, Object... args) { """ Find the first {@link WebElement} using the given method. This method is affected by the 'implicit wait' times in force at the time of execution. The findElement(..) invocation will return a matching row, or try again repeatedly until the configured timeout is reached. @param page is target page @param code Name of element on the web Page. @param args can be a index i @return the first {@link WebElement} using the given method """ return Context.getDriver().findElement(getLocator(page.getApplication(), page.getPageKey() + code, args)); }
java
public static WebElement findElement(Page page, String code, Object... args) { return Context.getDriver().findElement(getLocator(page.getApplication(), page.getPageKey() + code, args)); }
[ "public", "static", "WebElement", "findElement", "(", "Page", "page", ",", "String", "code", ",", "Object", "...", "args", ")", "{", "return", "Context", ".", "getDriver", "(", ")", ".", "findElement", "(", "getLocator", "(", "page", ".", "getApplication", "(", ")", ",", "page", ".", "getPageKey", "(", ")", "+", "code", ",", "args", ")", ")", ";", "}" ]
Find the first {@link WebElement} using the given method. This method is affected by the 'implicit wait' times in force at the time of execution. The findElement(..) invocation will return a matching row, or try again repeatedly until the configured timeout is reached. @param page is target page @param code Name of element on the web Page. @param args can be a index i @return the first {@link WebElement} using the given method
[ "Find", "the", "first", "{", "@link", "WebElement", "}", "using", "the", "given", "method", ".", "This", "method", "is", "affected", "by", "the", "implicit", "wait", "times", "in", "force", "at", "the", "time", "of", "execution", ".", "The", "findElement", "(", "..", ")", "invocation", "will", "return", "a", "matching", "row", "or", "try", "again", "repeatedly", "until", "the", "configured", "timeout", "is", "reached", "." ]
train
https://github.com/NoraUi/NoraUi/blob/5f491a3339c7d3c20d7207760bdaf2acdb8f260c/src/main/java/com/github/noraui/utils/Utilities.java#L177-L179
b3dgs/lionengine
lionengine-game/src/main/java/com/b3dgs/lionengine/game/Configurer.java
Configurer.getDouble
public final double getDouble(String attribute, String... path) { """ Get a double in the xml tree. @param attribute The attribute to get as double. @param path The node path (child list) @return The double value. @throws LionEngineException If unable to read node. """ try { return Double.parseDouble(getNodeString(attribute, path)); } catch (final NumberFormatException exception) { throw new LionEngineException(exception, media); } }
java
public final double getDouble(String attribute, String... path) { try { return Double.parseDouble(getNodeString(attribute, path)); } catch (final NumberFormatException exception) { throw new LionEngineException(exception, media); } }
[ "public", "final", "double", "getDouble", "(", "String", "attribute", ",", "String", "...", "path", ")", "{", "try", "{", "return", "Double", ".", "parseDouble", "(", "getNodeString", "(", "attribute", ",", "path", ")", ")", ";", "}", "catch", "(", "final", "NumberFormatException", "exception", ")", "{", "throw", "new", "LionEngineException", "(", "exception", ",", "media", ")", ";", "}", "}" ]
Get a double in the xml tree. @param attribute The attribute to get as double. @param path The node path (child list) @return The double value. @throws LionEngineException If unable to read node.
[ "Get", "a", "double", "in", "the", "xml", "tree", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/Configurer.java#L253-L263
cycorp/api-suite
core-api/src/main/java/com/cyc/session/exception/UnsupportedCycOperationException.java
UnsupportedCycOperationException.fromThrowable
public static UnsupportedCycOperationException fromThrowable(String message, Throwable cause) { """ Converts a Throwable to a UnsupportedCycOperationException with the specified detail message. If the Throwable is a UnsupportedCycOperationException and if the Throwable's message is identical to the one supplied, the Throwable will be passed through unmodified; otherwise, it will be wrapped in a new UnsupportedCycOperationException with the detail message. @param cause the Throwable to convert @param message the specified detail message @return a UnsupportedCycOperationException """ return (cause instanceof UnsupportedCycOperationException && Objects.equals(message, cause.getMessage())) ? (UnsupportedCycOperationException) cause : new UnsupportedCycOperationException(message, cause); }
java
public static UnsupportedCycOperationException fromThrowable(String message, Throwable cause) { return (cause instanceof UnsupportedCycOperationException && Objects.equals(message, cause.getMessage())) ? (UnsupportedCycOperationException) cause : new UnsupportedCycOperationException(message, cause); }
[ "public", "static", "UnsupportedCycOperationException", "fromThrowable", "(", "String", "message", ",", "Throwable", "cause", ")", "{", "return", "(", "cause", "instanceof", "UnsupportedCycOperationException", "&&", "Objects", ".", "equals", "(", "message", ",", "cause", ".", "getMessage", "(", ")", ")", ")", "?", "(", "UnsupportedCycOperationException", ")", "cause", ":", "new", "UnsupportedCycOperationException", "(", "message", ",", "cause", ")", ";", "}" ]
Converts a Throwable to a UnsupportedCycOperationException with the specified detail message. If the Throwable is a UnsupportedCycOperationException and if the Throwable's message is identical to the one supplied, the Throwable will be passed through unmodified; otherwise, it will be wrapped in a new UnsupportedCycOperationException with the detail message. @param cause the Throwable to convert @param message the specified detail message @return a UnsupportedCycOperationException
[ "Converts", "a", "Throwable", "to", "a", "UnsupportedCycOperationException", "with", "the", "specified", "detail", "message", ".", "If", "the", "Throwable", "is", "a", "UnsupportedCycOperationException", "and", "if", "the", "Throwable", "s", "message", "is", "identical", "to", "the", "one", "supplied", "the", "Throwable", "will", "be", "passed", "through", "unmodified", ";", "otherwise", "it", "will", "be", "wrapped", "in", "a", "new", "UnsupportedCycOperationException", "with", "the", "detail", "message", "." ]
train
https://github.com/cycorp/api-suite/blob/1d52affabc4635e3715a059e38741712cbdbf2d5/core-api/src/main/java/com/cyc/session/exception/UnsupportedCycOperationException.java#L61-L65
Guichaguri/MinimalFTP
src/main/java/com/guichaguri/minimalftp/FTPConnection.java
FTPConnection.sendData
public void sendData(byte[] data) throws ResponseException { """ Sends an array of bytes through a data connection @param data The data to be sent @throws ResponseException When an error occurs """ if(con.isClosed()) return; Socket socket = null; try { socket = conHandler.createDataSocket(); dataConnections.add(socket); OutputStream out = socket.getOutputStream(); Utils.write(out, data, data.length, conHandler.isAsciiMode()); bytesTransferred += data.length; out.flush(); Utils.closeQuietly(out); Utils.closeQuietly(socket); } catch(SocketException ex) { throw new ResponseException(426, "Transfer aborted"); } catch(IOException ex) { throw new ResponseException(425, "An error occurred while transferring the data"); } finally { onUpdate(); if(socket != null) dataConnections.remove(socket); } }
java
public void sendData(byte[] data) throws ResponseException { if(con.isClosed()) return; Socket socket = null; try { socket = conHandler.createDataSocket(); dataConnections.add(socket); OutputStream out = socket.getOutputStream(); Utils.write(out, data, data.length, conHandler.isAsciiMode()); bytesTransferred += data.length; out.flush(); Utils.closeQuietly(out); Utils.closeQuietly(socket); } catch(SocketException ex) { throw new ResponseException(426, "Transfer aborted"); } catch(IOException ex) { throw new ResponseException(425, "An error occurred while transferring the data"); } finally { onUpdate(); if(socket != null) dataConnections.remove(socket); } }
[ "public", "void", "sendData", "(", "byte", "[", "]", "data", ")", "throws", "ResponseException", "{", "if", "(", "con", ".", "isClosed", "(", ")", ")", "return", ";", "Socket", "socket", "=", "null", ";", "try", "{", "socket", "=", "conHandler", ".", "createDataSocket", "(", ")", ";", "dataConnections", ".", "add", "(", "socket", ")", ";", "OutputStream", "out", "=", "socket", ".", "getOutputStream", "(", ")", ";", "Utils", ".", "write", "(", "out", ",", "data", ",", "data", ".", "length", ",", "conHandler", ".", "isAsciiMode", "(", ")", ")", ";", "bytesTransferred", "+=", "data", ".", "length", ";", "out", ".", "flush", "(", ")", ";", "Utils", ".", "closeQuietly", "(", "out", ")", ";", "Utils", ".", "closeQuietly", "(", "socket", ")", ";", "}", "catch", "(", "SocketException", "ex", ")", "{", "throw", "new", "ResponseException", "(", "426", ",", "\"Transfer aborted\"", ")", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "throw", "new", "ResponseException", "(", "425", ",", "\"An error occurred while transferring the data\"", ")", ";", "}", "finally", "{", "onUpdate", "(", ")", ";", "if", "(", "socket", "!=", "null", ")", "dataConnections", ".", "remove", "(", "socket", ")", ";", "}", "}" ]
Sends an array of bytes through a data connection @param data The data to be sent @throws ResponseException When an error occurs
[ "Sends", "an", "array", "of", "bytes", "through", "a", "data", "connection" ]
train
https://github.com/Guichaguri/MinimalFTP/blob/ddd81e26ec88079ee4c37fe53d8efe420996e9b1/src/main/java/com/guichaguri/minimalftp/FTPConnection.java#L236-L259
lightblueseas/swing-components
src/main/java/de/alpharogroup/swing/actions/OpenFileAction.java
OpenFileAction.onFileChoose
protected void onFileChoose(JFileChooser fileChooser, ActionEvent actionEvent) { """ Callback method to interact on file choose. @param fileChooser the file chooser @param actionEvent the action event """ final int returnVal = fileChooser.showOpenDialog(parent); if (returnVal == JFileChooser.APPROVE_OPTION) { final File file = fileChooser.getSelectedFile(); onApproveOption(file, actionEvent); } else { onCancel(actionEvent); } }
java
protected void onFileChoose(JFileChooser fileChooser, ActionEvent actionEvent) { final int returnVal = fileChooser.showOpenDialog(parent); if (returnVal == JFileChooser.APPROVE_OPTION) { final File file = fileChooser.getSelectedFile(); onApproveOption(file, actionEvent); } else { onCancel(actionEvent); } }
[ "protected", "void", "onFileChoose", "(", "JFileChooser", "fileChooser", ",", "ActionEvent", "actionEvent", ")", "{", "final", "int", "returnVal", "=", "fileChooser", ".", "showOpenDialog", "(", "parent", ")", ";", "if", "(", "returnVal", "==", "JFileChooser", ".", "APPROVE_OPTION", ")", "{", "final", "File", "file", "=", "fileChooser", ".", "getSelectedFile", "(", ")", ";", "onApproveOption", "(", "file", ",", "actionEvent", ")", ";", "}", "else", "{", "onCancel", "(", "actionEvent", ")", ";", "}", "}" ]
Callback method to interact on file choose. @param fileChooser the file chooser @param actionEvent the action event
[ "Callback", "method", "to", "interact", "on", "file", "choose", "." ]
train
https://github.com/lightblueseas/swing-components/blob/4045e85cabd8f0ce985cbfff134c3c9873930c79/src/main/java/de/alpharogroup/swing/actions/OpenFileAction.java#L105-L118
javalite/activejdbc
javalite-common/src/main/java/org/javalite/http/Http.java
Http.map2URLEncoded
public static String map2URLEncoded(Map params) { """ Converts a map to URL- encoded string. This is a convenience method which can be used in combination with {@link #post(String, byte[])}, {@link #put(String, String)} and others. It makes it easy to convert parameters to submit a string: <pre> key=value&key1=value1; </pre> @param params map with keys and values to be posted. This map is used to build a URL-encoded string, such that keys are names of parameters, and values are values of those parameters. This method will also URL-encode keys and content using UTF-8 encoding. <p> String representations of both keys and values are used. </p> @return URL-encided string like: <code>key=value&key1=value1;</code> """ StringBuilder stringBuilder = new StringBuilder(); try{ Set keySet = params.keySet(); Object[] keys = keySet.toArray(); for (int i = 0; i < keys.length; i++) { stringBuilder.append(encode(keys[i].toString(), "UTF-8")).append("=").append(encode(params.get(keys[i]).toString(), "UTF-8")); if(i < (keys.length - 1)){ stringBuilder.append("&"); } } }catch(Exception e){ throw new HttpException("failed to generate content from map", e); } return stringBuilder.toString(); }
java
public static String map2URLEncoded(Map params){ StringBuilder stringBuilder = new StringBuilder(); try{ Set keySet = params.keySet(); Object[] keys = keySet.toArray(); for (int i = 0; i < keys.length; i++) { stringBuilder.append(encode(keys[i].toString(), "UTF-8")).append("=").append(encode(params.get(keys[i]).toString(), "UTF-8")); if(i < (keys.length - 1)){ stringBuilder.append("&"); } } }catch(Exception e){ throw new HttpException("failed to generate content from map", e); } return stringBuilder.toString(); }
[ "public", "static", "String", "map2URLEncoded", "(", "Map", "params", ")", "{", "StringBuilder", "stringBuilder", "=", "new", "StringBuilder", "(", ")", ";", "try", "{", "Set", "keySet", "=", "params", ".", "keySet", "(", ")", ";", "Object", "[", "]", "keys", "=", "keySet", ".", "toArray", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "i", "++", ")", "{", "stringBuilder", ".", "append", "(", "encode", "(", "keys", "[", "i", "]", ".", "toString", "(", ")", ",", "\"UTF-8\"", ")", ")", ".", "append", "(", "\"=\"", ")", ".", "append", "(", "encode", "(", "params", ".", "get", "(", "keys", "[", "i", "]", ")", ".", "toString", "(", ")", ",", "\"UTF-8\"", ")", ")", ";", "if", "(", "i", "<", "(", "keys", ".", "length", "-", "1", ")", ")", "{", "stringBuilder", ".", "append", "(", "\"&\"", ")", ";", "}", "}", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "HttpException", "(", "\"failed to generate content from map\"", ",", "e", ")", ";", "}", "return", "stringBuilder", ".", "toString", "(", ")", ";", "}" ]
Converts a map to URL- encoded string. This is a convenience method which can be used in combination with {@link #post(String, byte[])}, {@link #put(String, String)} and others. It makes it easy to convert parameters to submit a string: <pre> key=value&key1=value1; </pre> @param params map with keys and values to be posted. This map is used to build a URL-encoded string, such that keys are names of parameters, and values are values of those parameters. This method will also URL-encode keys and content using UTF-8 encoding. <p> String representations of both keys and values are used. </p> @return URL-encided string like: <code>key=value&key1=value1;</code>
[ "Converts", "a", "map", "to", "URL", "-", "encoded", "string", ".", "This", "is", "a", "convenience", "method", "which", "can", "be", "used", "in", "combination", "with", "{", "@link", "#post", "(", "String", "byte", "[]", ")", "}", "{", "@link", "#put", "(", "String", "String", ")", "}", "and", "others", ".", "It", "makes", "it", "easy", "to", "convert", "parameters", "to", "submit", "a", "string", ":" ]
train
https://github.com/javalite/activejdbc/blob/ffcf5457cace19622a8f71e856cbbbe9e7dd5fcc/javalite-common/src/main/java/org/javalite/http/Http.java#L303-L318
ManfredTremmel/gwt-bean-validators
mt-bean-validators/src/main/java/de/knightsoftnet/validators/shared/impl/AlternateSizeValidator.java
AlternateSizeValidator.isValid
@Override public final boolean isValid(final Object pvalue, final ConstraintValidatorContext pcontext) { """ {@inheritDoc} check if given object is valid. @see javax.validation.ConstraintValidator#isValid(Object, javax.validation.ConstraintValidatorContext) """ String valueAsString = Objects.toString(pvalue, StringUtils.EMPTY); if (StringUtils.isEmpty(valueAsString)) { return true; } if (ignoreWhiteSpaces) { valueAsString = valueAsString.replaceAll("\\s", StringUtils.EMPTY); } if (ignoreMinus) { valueAsString = valueAsString.replaceAll("-", StringUtils.EMPTY); } if (ignoreSlashes) { valueAsString = valueAsString.replaceAll("/", StringUtils.EMPTY); } return StringUtils.length(valueAsString) == size1 || StringUtils.length(valueAsString) == size2; }
java
@Override public final boolean isValid(final Object pvalue, final ConstraintValidatorContext pcontext) { String valueAsString = Objects.toString(pvalue, StringUtils.EMPTY); if (StringUtils.isEmpty(valueAsString)) { return true; } if (ignoreWhiteSpaces) { valueAsString = valueAsString.replaceAll("\\s", StringUtils.EMPTY); } if (ignoreMinus) { valueAsString = valueAsString.replaceAll("-", StringUtils.EMPTY); } if (ignoreSlashes) { valueAsString = valueAsString.replaceAll("/", StringUtils.EMPTY); } return StringUtils.length(valueAsString) == size1 || StringUtils.length(valueAsString) == size2; }
[ "@", "Override", "public", "final", "boolean", "isValid", "(", "final", "Object", "pvalue", ",", "final", "ConstraintValidatorContext", "pcontext", ")", "{", "String", "valueAsString", "=", "Objects", ".", "toString", "(", "pvalue", ",", "StringUtils", ".", "EMPTY", ")", ";", "if", "(", "StringUtils", ".", "isEmpty", "(", "valueAsString", ")", ")", "{", "return", "true", ";", "}", "if", "(", "ignoreWhiteSpaces", ")", "{", "valueAsString", "=", "valueAsString", ".", "replaceAll", "(", "\"\\\\s\"", ",", "StringUtils", ".", "EMPTY", ")", ";", "}", "if", "(", "ignoreMinus", ")", "{", "valueAsString", "=", "valueAsString", ".", "replaceAll", "(", "\"-\"", ",", "StringUtils", ".", "EMPTY", ")", ";", "}", "if", "(", "ignoreSlashes", ")", "{", "valueAsString", "=", "valueAsString", ".", "replaceAll", "(", "\"/\"", ",", "StringUtils", ".", "EMPTY", ")", ";", "}", "return", "StringUtils", ".", "length", "(", "valueAsString", ")", "==", "size1", "||", "StringUtils", ".", "length", "(", "valueAsString", ")", "==", "size2", ";", "}" ]
{@inheritDoc} check if given object is valid. @see javax.validation.ConstraintValidator#isValid(Object, javax.validation.ConstraintValidatorContext)
[ "{", "@inheritDoc", "}", "check", "if", "given", "object", "is", "valid", "." ]
train
https://github.com/ManfredTremmel/gwt-bean-validators/blob/cff7a2c3d68c2d17bf9d3cc57c79cc16fa8b4d5c/mt-bean-validators/src/main/java/de/knightsoftnet/validators/shared/impl/AlternateSizeValidator.java#L79-L95
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/util/ModelSerializer.java
ModelSerializer.restoreComputationGraph
public static ComputationGraph restoreComputationGraph(@NonNull InputStream is, boolean loadUpdater) throws IOException { """ Load a computation graph from a InputStream @param is the inputstream to get the computation graph from @return the loaded computation graph @throws IOException """ checkInputStream(is); File tmpFile = null; try{ tmpFile = tempFileFromStream(is); return restoreComputationGraph(tmpFile, loadUpdater); } finally { if(tmpFile != null){ tmpFile.delete(); } } }
java
public static ComputationGraph restoreComputationGraph(@NonNull InputStream is, boolean loadUpdater) throws IOException { checkInputStream(is); File tmpFile = null; try{ tmpFile = tempFileFromStream(is); return restoreComputationGraph(tmpFile, loadUpdater); } finally { if(tmpFile != null){ tmpFile.delete(); } } }
[ "public", "static", "ComputationGraph", "restoreComputationGraph", "(", "@", "NonNull", "InputStream", "is", ",", "boolean", "loadUpdater", ")", "throws", "IOException", "{", "checkInputStream", "(", "is", ")", ";", "File", "tmpFile", "=", "null", ";", "try", "{", "tmpFile", "=", "tempFileFromStream", "(", "is", ")", ";", "return", "restoreComputationGraph", "(", "tmpFile", ",", "loadUpdater", ")", ";", "}", "finally", "{", "if", "(", "tmpFile", "!=", "null", ")", "{", "tmpFile", ".", "delete", "(", ")", ";", "}", "}", "}" ]
Load a computation graph from a InputStream @param is the inputstream to get the computation graph from @return the loaded computation graph @throws IOException
[ "Load", "a", "computation", "graph", "from", "a", "InputStream", "@param", "is", "the", "inputstream", "to", "get", "the", "computation", "graph", "from", "@return", "the", "loaded", "computation", "graph" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/util/ModelSerializer.java#L464-L477
xiancloud/xian
xian-core/src/main/java/info/xiancloud/core/message/UnitResponse.java
UnitResponse.createTimeout
public static UnitResponse createTimeout(Object dataOrException, String errMsg) { """ create a new timed out unit response. @param dataOrException the data or exception object. @param errMsg the error message. @return the newly created unit response object. """ return new UnitResponse().setCode(Group.CODE_TIME_OUT).setData(dataOrException).setMessage(errMsg); }
java
public static UnitResponse createTimeout(Object dataOrException, String errMsg) { return new UnitResponse().setCode(Group.CODE_TIME_OUT).setData(dataOrException).setMessage(errMsg); }
[ "public", "static", "UnitResponse", "createTimeout", "(", "Object", "dataOrException", ",", "String", "errMsg", ")", "{", "return", "new", "UnitResponse", "(", ")", ".", "setCode", "(", "Group", ".", "CODE_TIME_OUT", ")", ".", "setData", "(", "dataOrException", ")", ".", "setMessage", "(", "errMsg", ")", ";", "}" ]
create a new timed out unit response. @param dataOrException the data or exception object. @param errMsg the error message. @return the newly created unit response object.
[ "create", "a", "new", "timed", "out", "unit", "response", "." ]
train
https://github.com/xiancloud/xian/blob/1948e088545553d2745b2c86d8b5a64988bb850e/xian-core/src/main/java/info/xiancloud/core/message/UnitResponse.java#L188-L190
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/TimeZoneGenericNames.java
TimeZoneGenericNames.createGenericMatchInfo
private GenericMatchInfo createGenericMatchInfo(MatchInfo matchInfo) { """ Returns a <code>GenericMatchInfo</code> for the given <code>MatchInfo</code>. @param matchInfo the MatchInfo @return A GenericMatchInfo """ GenericNameType nameType = null; TimeType timeType = TimeType.UNKNOWN; switch (matchInfo.nameType()) { case LONG_STANDARD: nameType = GenericNameType.LONG; timeType = TimeType.STANDARD; break; case LONG_GENERIC: nameType = GenericNameType.LONG; break; case SHORT_STANDARD: nameType = GenericNameType.SHORT; timeType = TimeType.STANDARD; break; case SHORT_GENERIC: nameType = GenericNameType.SHORT; break; default: throw new IllegalArgumentException("Unexpected MatchInfo name type - " + matchInfo.nameType()); } String tzID = matchInfo.tzID(); if (tzID == null) { String mzID = matchInfo.mzID(); assert(mzID != null); tzID = _tznames.getReferenceZoneID(mzID, getTargetRegion()); } assert(tzID != null); GenericMatchInfo gmatch = new GenericMatchInfo(nameType, tzID, matchInfo.matchLength(), timeType); return gmatch; }
java
private GenericMatchInfo createGenericMatchInfo(MatchInfo matchInfo) { GenericNameType nameType = null; TimeType timeType = TimeType.UNKNOWN; switch (matchInfo.nameType()) { case LONG_STANDARD: nameType = GenericNameType.LONG; timeType = TimeType.STANDARD; break; case LONG_GENERIC: nameType = GenericNameType.LONG; break; case SHORT_STANDARD: nameType = GenericNameType.SHORT; timeType = TimeType.STANDARD; break; case SHORT_GENERIC: nameType = GenericNameType.SHORT; break; default: throw new IllegalArgumentException("Unexpected MatchInfo name type - " + matchInfo.nameType()); } String tzID = matchInfo.tzID(); if (tzID == null) { String mzID = matchInfo.mzID(); assert(mzID != null); tzID = _tznames.getReferenceZoneID(mzID, getTargetRegion()); } assert(tzID != null); GenericMatchInfo gmatch = new GenericMatchInfo(nameType, tzID, matchInfo.matchLength(), timeType); return gmatch; }
[ "private", "GenericMatchInfo", "createGenericMatchInfo", "(", "MatchInfo", "matchInfo", ")", "{", "GenericNameType", "nameType", "=", "null", ";", "TimeType", "timeType", "=", "TimeType", ".", "UNKNOWN", ";", "switch", "(", "matchInfo", ".", "nameType", "(", ")", ")", "{", "case", "LONG_STANDARD", ":", "nameType", "=", "GenericNameType", ".", "LONG", ";", "timeType", "=", "TimeType", ".", "STANDARD", ";", "break", ";", "case", "LONG_GENERIC", ":", "nameType", "=", "GenericNameType", ".", "LONG", ";", "break", ";", "case", "SHORT_STANDARD", ":", "nameType", "=", "GenericNameType", ".", "SHORT", ";", "timeType", "=", "TimeType", ".", "STANDARD", ";", "break", ";", "case", "SHORT_GENERIC", ":", "nameType", "=", "GenericNameType", ".", "SHORT", ";", "break", ";", "default", ":", "throw", "new", "IllegalArgumentException", "(", "\"Unexpected MatchInfo name type - \"", "+", "matchInfo", ".", "nameType", "(", ")", ")", ";", "}", "String", "tzID", "=", "matchInfo", ".", "tzID", "(", ")", ";", "if", "(", "tzID", "==", "null", ")", "{", "String", "mzID", "=", "matchInfo", ".", "mzID", "(", ")", ";", "assert", "(", "mzID", "!=", "null", ")", ";", "tzID", "=", "_tznames", ".", "getReferenceZoneID", "(", "mzID", ",", "getTargetRegion", "(", ")", ")", ";", "}", "assert", "(", "tzID", "!=", "null", ")", ";", "GenericMatchInfo", "gmatch", "=", "new", "GenericMatchInfo", "(", "nameType", ",", "tzID", ",", "matchInfo", ".", "matchLength", "(", ")", ",", "timeType", ")", ";", "return", "gmatch", ";", "}" ]
Returns a <code>GenericMatchInfo</code> for the given <code>MatchInfo</code>. @param matchInfo the MatchInfo @return A GenericMatchInfo
[ "Returns", "a", "<code", ">", "GenericMatchInfo<", "/", "code", ">", "for", "the", "given", "<code", ">", "MatchInfo<", "/", "code", ">", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/TimeZoneGenericNames.java#L796-L829
BlueBrain/bluima
modules/bluima_jsre/src/main/java/org/itc/irst/tcc/sre/util/Node.java
Node.dotProduct
public static double dotProduct(Node[] n1, Node[] n2) { """ Returns an iterator over the elements in this vector in proper sequence (optional operation). @return an iterator over the elements in this vector in proper sequence. """ // logger.info("n1 " + n1.length); // logger.info("n2 " + n2.length); double sum = 0; int i = 0, j = 0; while (i < n1.length && j < n2.length) { if (n1[i] == null) break; // logger.error("n1" + n1[i] + " " + i); if (n2[j] == null) break; // logger.error("n2" + n2[j] + " " + j); // logger.info(n1[i].index + " == " + n2[j].index); if (n1[i].index == n2[j].index) { // logger.info(n1[i].index + " == " + n2[j].index); sum += n1[i].value * n2[j].value; ++i; ++j; } else { if (n1[i].index > n2[j].index) { // logger.info(n1[i].index + " > " + n2[j].index); ++j; } else { // logger.info(n1[i].index + " <= " + n2[j].index); ++i; } } } return sum; }
java
public static double dotProduct(Node[] n1, Node[] n2) { // logger.info("n1 " + n1.length); // logger.info("n2 " + n2.length); double sum = 0; int i = 0, j = 0; while (i < n1.length && j < n2.length) { if (n1[i] == null) break; // logger.error("n1" + n1[i] + " " + i); if (n2[j] == null) break; // logger.error("n2" + n2[j] + " " + j); // logger.info(n1[i].index + " == " + n2[j].index); if (n1[i].index == n2[j].index) { // logger.info(n1[i].index + " == " + n2[j].index); sum += n1[i].value * n2[j].value; ++i; ++j; } else { if (n1[i].index > n2[j].index) { // logger.info(n1[i].index + " > " + n2[j].index); ++j; } else { // logger.info(n1[i].index + " <= " + n2[j].index); ++i; } } } return sum; }
[ "public", "static", "double", "dotProduct", "(", "Node", "[", "]", "n1", ",", "Node", "[", "]", "n2", ")", "{", "// logger.info(\"n1 \" + n1.length);", "// logger.info(\"n2 \" + n2.length);", "double", "sum", "=", "0", ";", "int", "i", "=", "0", ",", "j", "=", "0", ";", "while", "(", "i", "<", "n1", ".", "length", "&&", "j", "<", "n2", ".", "length", ")", "{", "if", "(", "n1", "[", "i", "]", "==", "null", ")", "break", ";", "// logger.error(\"n1\" + n1[i] + \" \" + i);", "if", "(", "n2", "[", "j", "]", "==", "null", ")", "break", ";", "// logger.error(\"n2\" + n2[j] + \" \" + j);", "// logger.info(n1[i].index + \" == \" + n2[j].index);", "if", "(", "n1", "[", "i", "]", ".", "index", "==", "n2", "[", "j", "]", ".", "index", ")", "{", "// logger.info(n1[i].index + \" == \" + n2[j].index);", "sum", "+=", "n1", "[", "i", "]", ".", "value", "*", "n2", "[", "j", "]", ".", "value", ";", "++", "i", ";", "++", "j", ";", "}", "else", "{", "if", "(", "n1", "[", "i", "]", ".", "index", ">", "n2", "[", "j", "]", ".", "index", ")", "{", "// logger.info(n1[i].index + \" > \" + n2[j].index);", "++", "j", ";", "}", "else", "{", "// logger.info(n1[i].index + \" <= \" + n2[j].index);", "++", "i", ";", "}", "}", "}", "return", "sum", ";", "}" ]
Returns an iterator over the elements in this vector in proper sequence (optional operation). @return an iterator over the elements in this vector in proper sequence.
[ "Returns", "an", "iterator", "over", "the", "elements", "in", "this", "vector", "in", "proper", "sequence", "(", "optional", "operation", ")", "." ]
train
https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_jsre/src/main/java/org/itc/irst/tcc/sre/util/Node.java#L46-L78
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp-chinese/src/main/java/org/ansj/library/SynonymsLibrary.java
SynonymsLibrary.insert
public static void insert(String key, String[] words) { """ 覆盖更新同义词 [中国, 中华, 我国] -> replace([中国,华夏]) -> [中国,华夏] @param words """ SmartForest<List<String>> synonyms = get(key); List<String> list = new ArrayList<>(); for (String word : words) { if (StringUtil.isBlank(word)) { continue; } list.add(word); } if (list.size() <= 1) { LOG.warn(Arrays.toString(words) + " not have any change because it less than 2 word"); return; } Set<String> set = findAllWords(key, words); for (String word : list) { set.remove(word); synonyms.add(word, list); } for (String word : set) { //删除所有 synonyms.remove(word); synonyms.getBranch(word).setParam(null); } }
java
public static void insert(String key, String[] words) { SmartForest<List<String>> synonyms = get(key); List<String> list = new ArrayList<>(); for (String word : words) { if (StringUtil.isBlank(word)) { continue; } list.add(word); } if (list.size() <= 1) { LOG.warn(Arrays.toString(words) + " not have any change because it less than 2 word"); return; } Set<String> set = findAllWords(key, words); for (String word : list) { set.remove(word); synonyms.add(word, list); } for (String word : set) { //删除所有 synonyms.remove(word); synonyms.getBranch(word).setParam(null); } }
[ "public", "static", "void", "insert", "(", "String", "key", ",", "String", "[", "]", "words", ")", "{", "SmartForest", "<", "List", "<", "String", ">>", "synonyms", "=", "get", "(", "key", ")", ";", "List", "<", "String", ">", "list", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "String", "word", ":", "words", ")", "{", "if", "(", "StringUtil", ".", "isBlank", "(", "word", ")", ")", "{", "continue", ";", "}", "list", ".", "add", "(", "word", ")", ";", "}", "if", "(", "list", ".", "size", "(", ")", "<=", "1", ")", "{", "LOG", ".", "warn", "(", "Arrays", ".", "toString", "(", "words", ")", "+", "\" not have any change because it less than 2 word\"", ")", ";", "return", ";", "}", "Set", "<", "String", ">", "set", "=", "findAllWords", "(", "key", ",", "words", ")", ";", "for", "(", "String", "word", ":", "list", ")", "{", "set", ".", "remove", "(", "word", ")", ";", "synonyms", ".", "add", "(", "word", ",", "list", ")", ";", "}", "for", "(", "String", "word", ":", "set", ")", "{", "//删除所有", "synonyms", ".", "remove", "(", "word", ")", ";", "synonyms", ".", "getBranch", "(", "word", ")", ".", "setParam", "(", "null", ")", ";", "}", "}" ]
覆盖更新同义词 [中国, 中华, 我国] -> replace([中国,华夏]) -> [中国,华夏] @param words
[ "覆盖更新同义词", "[", "中国", "中华", "我国", "]", "-", ">", "replace", "(", "[", "中国", "华夏", "]", ")", "-", ">", "[", "中国", "华夏", "]" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp-chinese/src/main/java/org/ansj/library/SynonymsLibrary.java#L184-L213
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/internal/common/I18N.java
I18N.writelnTo
public static void writelnTo(String html, Writer writer) throws IOException { """ Écrit un texte, puis un retour chariot, dans un flux en remplaçant dans le texte les clés entourées de deux '#' par leurs traductions dans la locale courante. @param html texte html avec éventuellement des #clé# @param writer flux @throws IOException e """ writeTo(html, writer); writer.write('\n'); }
java
public static void writelnTo(String html, Writer writer) throws IOException { writeTo(html, writer); writer.write('\n'); }
[ "public", "static", "void", "writelnTo", "(", "String", "html", ",", "Writer", "writer", ")", "throws", "IOException", "{", "writeTo", "(", "html", ",", "writer", ")", ";", "writer", ".", "write", "(", "'", "'", ")", ";", "}" ]
Écrit un texte, puis un retour chariot, dans un flux en remplaçant dans le texte les clés entourées de deux '#' par leurs traductions dans la locale courante. @param html texte html avec éventuellement des #clé# @param writer flux @throws IOException e
[ "Écrit", "un", "texte", "puis", "un", "retour", "chariot", "dans", "un", "flux", "en", "remplaçant", "dans", "le", "texte", "les", "clés", "entourées", "de", "deux", "#", "par", "leurs", "traductions", "dans", "la", "locale", "courante", "." ]
train
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/internal/common/I18N.java#L199-L202
moparisthebest/beehive
beehive-netui-tags/src/main/java/org/apache/beehive/netui/databinding/datagrid/api/rendering/DataGridTagModel.java
DataGridTagModel.formatMessage
public String formatMessage(String key, Object[] args) { """ Format a message given a resource string name <code>key</code> and a set of formatting arguments <code>args</code>. @param key the message key @param args the arguments used when formatting the message @return the formatted message """ assert _resourceProvider != null : "Received a null resource provider"; return _resourceProvider.formatMessage(key, args); }
java
public String formatMessage(String key, Object[] args) { assert _resourceProvider != null : "Received a null resource provider"; return _resourceProvider.formatMessage(key, args); }
[ "public", "String", "formatMessage", "(", "String", "key", ",", "Object", "[", "]", "args", ")", "{", "assert", "_resourceProvider", "!=", "null", ":", "\"Received a null resource provider\"", ";", "return", "_resourceProvider", ".", "formatMessage", "(", "key", ",", "args", ")", ";", "}" ]
Format a message given a resource string name <code>key</code> and a set of formatting arguments <code>args</code>. @param key the message key @param args the arguments used when formatting the message @return the formatted message
[ "Format", "a", "message", "given", "a", "resource", "string", "name", "<code", ">", "key<", "/", "code", ">", "and", "a", "set", "of", "formatting", "arguments", "<code", ">", "args<", "/", "code", ">", "." ]
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-tags/src/main/java/org/apache/beehive/netui/databinding/datagrid/api/rendering/DataGridTagModel.java#L353-L356
googleads/googleads-java-lib
modules/ads_lib_appengine/src/main/java/com/google/api/ads/common/lib/soap/jaxws/JaxWsSoapContextHandler.java
JaxWsSoapContextHandler.handleMessage
@Override public boolean handleMessage(SOAPMessageContext context) { """ Captures pertinent information from SOAP messages exchanged by the SOAP service this handler is attached to. Also responsible for placing custom (implicit) SOAP headers on outgoing messages. @see SOAPHandler#handleMessage(MessageContext) @param context the context of the SOAP message passing through this handler @return whether this SOAP interaction should continue """ if ((Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY)) { // Outbound message (request), so reset the last request and response builders. lastRequestInfo = new RequestInfo.Builder(); lastResponseInfo = new ResponseInfo.Builder(); SOAPMessage soapMessage = context.getMessage(); try { SOAPHeader soapHeader = soapMessage.getSOAPHeader(); if (soapHeader == null) { soapHeader = soapMessage.getSOAPPart().getEnvelope().addHeader(); } for (SOAPElement header : soapHeaders) { soapHeader.addChildElement(header); } } catch (SOAPException e) { throw new ServiceException("Error setting SOAP headers on outbound message.", e); } captureServiceAndOperationNames(context); } captureSoapXml(context); return true; }
java
@Override public boolean handleMessage(SOAPMessageContext context) { if ((Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY)) { // Outbound message (request), so reset the last request and response builders. lastRequestInfo = new RequestInfo.Builder(); lastResponseInfo = new ResponseInfo.Builder(); SOAPMessage soapMessage = context.getMessage(); try { SOAPHeader soapHeader = soapMessage.getSOAPHeader(); if (soapHeader == null) { soapHeader = soapMessage.getSOAPPart().getEnvelope().addHeader(); } for (SOAPElement header : soapHeaders) { soapHeader.addChildElement(header); } } catch (SOAPException e) { throw new ServiceException("Error setting SOAP headers on outbound message.", e); } captureServiceAndOperationNames(context); } captureSoapXml(context); return true; }
[ "@", "Override", "public", "boolean", "handleMessage", "(", "SOAPMessageContext", "context", ")", "{", "if", "(", "(", "Boolean", ")", "context", ".", "get", "(", "MessageContext", ".", "MESSAGE_OUTBOUND_PROPERTY", ")", ")", "{", "// Outbound message (request), so reset the last request and response builders.", "lastRequestInfo", "=", "new", "RequestInfo", ".", "Builder", "(", ")", ";", "lastResponseInfo", "=", "new", "ResponseInfo", ".", "Builder", "(", ")", ";", "SOAPMessage", "soapMessage", "=", "context", ".", "getMessage", "(", ")", ";", "try", "{", "SOAPHeader", "soapHeader", "=", "soapMessage", ".", "getSOAPHeader", "(", ")", ";", "if", "(", "soapHeader", "==", "null", ")", "{", "soapHeader", "=", "soapMessage", ".", "getSOAPPart", "(", ")", ".", "getEnvelope", "(", ")", ".", "addHeader", "(", ")", ";", "}", "for", "(", "SOAPElement", "header", ":", "soapHeaders", ")", "{", "soapHeader", ".", "addChildElement", "(", "header", ")", ";", "}", "}", "catch", "(", "SOAPException", "e", ")", "{", "throw", "new", "ServiceException", "(", "\"Error setting SOAP headers on outbound message.\"", ",", "e", ")", ";", "}", "captureServiceAndOperationNames", "(", "context", ")", ";", "}", "captureSoapXml", "(", "context", ")", ";", "return", "true", ";", "}" ]
Captures pertinent information from SOAP messages exchanged by the SOAP service this handler is attached to. Also responsible for placing custom (implicit) SOAP headers on outgoing messages. @see SOAPHandler#handleMessage(MessageContext) @param context the context of the SOAP message passing through this handler @return whether this SOAP interaction should continue
[ "Captures", "pertinent", "information", "from", "SOAP", "messages", "exchanged", "by", "the", "SOAP", "service", "this", "handler", "is", "attached", "to", ".", "Also", "responsible", "for", "placing", "custom", "(", "implicit", ")", "SOAP", "headers", "on", "outgoing", "messages", "." ]
train
https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/modules/ads_lib_appengine/src/main/java/com/google/api/ads/common/lib/soap/jaxws/JaxWsSoapContextHandler.java#L70-L93
ronmamo/reflections
src/main/java/org/reflections/vfs/Vfs.java
Vfs.fromURL
public static Dir fromURL(final URL url, final UrlType... urlTypes) { """ tries to create a Dir from the given url, using the given urlTypes """ return fromURL(url, Lists.<UrlType>newArrayList(urlTypes)); }
java
public static Dir fromURL(final URL url, final UrlType... urlTypes) { return fromURL(url, Lists.<UrlType>newArrayList(urlTypes)); }
[ "public", "static", "Dir", "fromURL", "(", "final", "URL", "url", ",", "final", "UrlType", "...", "urlTypes", ")", "{", "return", "fromURL", "(", "url", ",", "Lists", ".", "<", "UrlType", ">", "newArrayList", "(", "urlTypes", ")", ")", ";", "}" ]
tries to create a Dir from the given url, using the given urlTypes
[ "tries", "to", "create", "a", "Dir", "from", "the", "given", "url", "using", "the", "given", "urlTypes" ]
train
https://github.com/ronmamo/reflections/blob/084cf4a759a06d88e88753ac00397478c2e0ed52/src/main/java/org/reflections/vfs/Vfs.java#L118-L120
Azure/azure-sdk-for-java
containerservice/resource-manager/v2019_02_01/src/main/java/com/microsoft/azure/management/containerservice/v2019_02_01/implementation/ManagedClustersInner.java
ManagedClustersInner.listClusterAdminCredentialsAsync
public Observable<CredentialResultsInner> listClusterAdminCredentialsAsync(String resourceGroupName, String resourceName) { """ Gets cluster admin credential of a managed cluster. Gets cluster admin credential of the managed cluster with a specified resource group and name. @param resourceGroupName The name of the resource group. @param resourceName The name of the managed cluster resource. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the CredentialResultsInner object """ return listClusterAdminCredentialsWithServiceResponseAsync(resourceGroupName, resourceName).map(new Func1<ServiceResponse<CredentialResultsInner>, CredentialResultsInner>() { @Override public CredentialResultsInner call(ServiceResponse<CredentialResultsInner> response) { return response.body(); } }); }
java
public Observable<CredentialResultsInner> listClusterAdminCredentialsAsync(String resourceGroupName, String resourceName) { return listClusterAdminCredentialsWithServiceResponseAsync(resourceGroupName, resourceName).map(new Func1<ServiceResponse<CredentialResultsInner>, CredentialResultsInner>() { @Override public CredentialResultsInner call(ServiceResponse<CredentialResultsInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "CredentialResultsInner", ">", "listClusterAdminCredentialsAsync", "(", "String", "resourceGroupName", ",", "String", "resourceName", ")", "{", "return", "listClusterAdminCredentialsWithServiceResponseAsync", "(", "resourceGroupName", ",", "resourceName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "CredentialResultsInner", ">", ",", "CredentialResultsInner", ">", "(", ")", "{", "@", "Override", "public", "CredentialResultsInner", "call", "(", "ServiceResponse", "<", "CredentialResultsInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Gets cluster admin credential of a managed cluster. Gets cluster admin credential of the managed cluster with a specified resource group and name. @param resourceGroupName The name of the resource group. @param resourceName The name of the managed cluster resource. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the CredentialResultsInner object
[ "Gets", "cluster", "admin", "credential", "of", "a", "managed", "cluster", ".", "Gets", "cluster", "admin", "credential", "of", "the", "managed", "cluster", "with", "a", "specified", "resource", "group", "and", "name", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/containerservice/resource-manager/v2019_02_01/src/main/java/com/microsoft/azure/management/containerservice/v2019_02_01/implementation/ManagedClustersInner.java#L600-L607
Waikato/moa
moa/src/main/java/moa/classifiers/meta/AccuracyWeightedEnsemble.java
AccuracyWeightedEnsemble.computeCandidateWeight
protected double computeCandidateWeight(Classifier candidate, Instances chunk, int numFolds) { """ Computes the weight of a candidate classifier. @param candidate Candidate classifier. @param chunk Data chunk of examples. @param numFolds Number of folds in candidate classifier cross-validation. @param useMseR Determines whether to use the MSEr threshold. @return Candidate classifier weight. """ double candidateWeight = 0.0; Random random = new Random(1); Instances randData = new Instances(chunk); randData.randomize(random); if (randData.classAttribute().isNominal()) { randData.stratify(numFolds); } for (int n = 0; n < numFolds; n++) { Instances train = randData.trainCV(numFolds, n, random); Instances test = randData.testCV(numFolds, n); Classifier learner = candidate.copy(); for (int num = 0; num < train.numInstances(); num++) { learner.trainOnInstance(train.instance(num)); } candidateWeight += computeWeight(learner, test); } double resultWeight = candidateWeight / numFolds; if (Double.isInfinite(resultWeight)) { return Double.MAX_VALUE; } else { return resultWeight; } }
java
protected double computeCandidateWeight(Classifier candidate, Instances chunk, int numFolds) { double candidateWeight = 0.0; Random random = new Random(1); Instances randData = new Instances(chunk); randData.randomize(random); if (randData.classAttribute().isNominal()) { randData.stratify(numFolds); } for (int n = 0; n < numFolds; n++) { Instances train = randData.trainCV(numFolds, n, random); Instances test = randData.testCV(numFolds, n); Classifier learner = candidate.copy(); for (int num = 0; num < train.numInstances(); num++) { learner.trainOnInstance(train.instance(num)); } candidateWeight += computeWeight(learner, test); } double resultWeight = candidateWeight / numFolds; if (Double.isInfinite(resultWeight)) { return Double.MAX_VALUE; } else { return resultWeight; } }
[ "protected", "double", "computeCandidateWeight", "(", "Classifier", "candidate", ",", "Instances", "chunk", ",", "int", "numFolds", ")", "{", "double", "candidateWeight", "=", "0.0", ";", "Random", "random", "=", "new", "Random", "(", "1", ")", ";", "Instances", "randData", "=", "new", "Instances", "(", "chunk", ")", ";", "randData", ".", "randomize", "(", "random", ")", ";", "if", "(", "randData", ".", "classAttribute", "(", ")", ".", "isNominal", "(", ")", ")", "{", "randData", ".", "stratify", "(", "numFolds", ")", ";", "}", "for", "(", "int", "n", "=", "0", ";", "n", "<", "numFolds", ";", "n", "++", ")", "{", "Instances", "train", "=", "randData", ".", "trainCV", "(", "numFolds", ",", "n", ",", "random", ")", ";", "Instances", "test", "=", "randData", ".", "testCV", "(", "numFolds", ",", "n", ")", ";", "Classifier", "learner", "=", "candidate", ".", "copy", "(", ")", ";", "for", "(", "int", "num", "=", "0", ";", "num", "<", "train", ".", "numInstances", "(", ")", ";", "num", "++", ")", "{", "learner", ".", "trainOnInstance", "(", "train", ".", "instance", "(", "num", ")", ")", ";", "}", "candidateWeight", "+=", "computeWeight", "(", "learner", ",", "test", ")", ";", "}", "double", "resultWeight", "=", "candidateWeight", "/", "numFolds", ";", "if", "(", "Double", ".", "isInfinite", "(", "resultWeight", ")", ")", "{", "return", "Double", ".", "MAX_VALUE", ";", "}", "else", "{", "return", "resultWeight", ";", "}", "}" ]
Computes the weight of a candidate classifier. @param candidate Candidate classifier. @param chunk Data chunk of examples. @param numFolds Number of folds in candidate classifier cross-validation. @param useMseR Determines whether to use the MSEr threshold. @return Candidate classifier weight.
[ "Computes", "the", "weight", "of", "a", "candidate", "classifier", "." ]
train
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/classifiers/meta/AccuracyWeightedEnsemble.java#L247-L276
eduarddrenth/ConfigurableReports
src/main/java/com/vectorprint/report/itext/DefaultElementProducer.java
DefaultElementProducer.notDelayedStyle
private boolean notDelayedStyle(Chunk c, String gt, Collection<? extends BaseStyler> stylers) { """ register advanced stylers together with data(part) with the EventHelper to do the styling later @param c @param data @param stylers @return @see PageHelper#onGenericTag(com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document, com.itextpdf.text.Rectangle, java.lang.String) """ if (stylers == null) { return true; } try { Collection<Advanced> a = new ArrayList<>(stylers.size()); for (Advanced adv : StyleHelper.getStylers(stylers, Advanced.class)) { Advanced.EVENTMODE mode = adv.getEventmode(); if (Advanced.EVENTMODE.ALL.equals(mode) || Advanced.EVENTMODE.TEXT.equals(mode)) { // remember data and chunk adv.addDelayedData(gt, c); a.add(adv); } } if (a.size() > 0) { styleHelper.delayedStyle(c, gt, a, ph); return false; } } catch (VectorPrintException ex) { log.log(Level.SEVERE, null, ex); } return true; }
java
private boolean notDelayedStyle(Chunk c, String gt, Collection<? extends BaseStyler> stylers) { if (stylers == null) { return true; } try { Collection<Advanced> a = new ArrayList<>(stylers.size()); for (Advanced adv : StyleHelper.getStylers(stylers, Advanced.class)) { Advanced.EVENTMODE mode = adv.getEventmode(); if (Advanced.EVENTMODE.ALL.equals(mode) || Advanced.EVENTMODE.TEXT.equals(mode)) { // remember data and chunk adv.addDelayedData(gt, c); a.add(adv); } } if (a.size() > 0) { styleHelper.delayedStyle(c, gt, a, ph); return false; } } catch (VectorPrintException ex) { log.log(Level.SEVERE, null, ex); } return true; }
[ "private", "boolean", "notDelayedStyle", "(", "Chunk", "c", ",", "String", "gt", ",", "Collection", "<", "?", "extends", "BaseStyler", ">", "stylers", ")", "{", "if", "(", "stylers", "==", "null", ")", "{", "return", "true", ";", "}", "try", "{", "Collection", "<", "Advanced", ">", "a", "=", "new", "ArrayList", "<>", "(", "stylers", ".", "size", "(", ")", ")", ";", "for", "(", "Advanced", "adv", ":", "StyleHelper", ".", "getStylers", "(", "stylers", ",", "Advanced", ".", "class", ")", ")", "{", "Advanced", ".", "EVENTMODE", "mode", "=", "adv", ".", "getEventmode", "(", ")", ";", "if", "(", "Advanced", ".", "EVENTMODE", ".", "ALL", ".", "equals", "(", "mode", ")", "||", "Advanced", ".", "EVENTMODE", ".", "TEXT", ".", "equals", "(", "mode", ")", ")", "{", "// remember data and chunk", "adv", ".", "addDelayedData", "(", "gt", ",", "c", ")", ";", "a", ".", "add", "(", "adv", ")", ";", "}", "}", "if", "(", "a", ".", "size", "(", ")", ">", "0", ")", "{", "styleHelper", ".", "delayedStyle", "(", "c", ",", "gt", ",", "a", ",", "ph", ")", ";", "return", "false", ";", "}", "}", "catch", "(", "VectorPrintException", "ex", ")", "{", "log", ".", "log", "(", "Level", ".", "SEVERE", ",", "null", ",", "ex", ")", ";", "}", "return", "true", ";", "}" ]
register advanced stylers together with data(part) with the EventHelper to do the styling later @param c @param data @param stylers @return @see PageHelper#onGenericTag(com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document, com.itextpdf.text.Rectangle, java.lang.String)
[ "register", "advanced", "stylers", "together", "with", "data", "(", "part", ")", "with", "the", "EventHelper", "to", "do", "the", "styling", "later" ]
train
https://github.com/eduarddrenth/ConfigurableReports/blob/b5fb7a89e16d9b35f557f3bf620594f821fa1552/src/main/java/com/vectorprint/report/itext/DefaultElementProducer.java#L305-L327
looly/hutool
hutool-extra/src/main/java/cn/hutool/extra/template/engine/beetl/BeetlUtil.java
BeetlUtil.render
public static String render(Template template, Map<String, Object> bindingMap) { """ 渲染模板 @param template {@link Template} @param bindingMap 绑定参数 @return 渲染后的内容 """ template.binding(bindingMap); return template.render(); }
java
public static String render(Template template, Map<String, Object> bindingMap) { template.binding(bindingMap); return template.render(); }
[ "public", "static", "String", "render", "(", "Template", "template", ",", "Map", "<", "String", ",", "Object", ">", "bindingMap", ")", "{", "template", ".", "binding", "(", "bindingMap", ")", ";", "return", "template", ".", "render", "(", ")", ";", "}" ]
渲染模板 @param template {@link Template} @param bindingMap 绑定参数 @return 渲染后的内容
[ "渲染模板" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-extra/src/main/java/cn/hutool/extra/template/engine/beetl/BeetlUtil.java#L181-L184
alkacon/opencms-core
src/org/opencms/ui/CmsVaadinUtils.java
CmsVaadinUtils.updateComponentError
public static boolean updateComponentError(AbstractComponent component, ErrorMessage error) { """ Updates the component error of a component, but only if it differs from the currently set error.<p> @param component the component @param error the error @return true if the error was changed """ if (component.getComponentError() != error) { component.setComponentError(error); return true; } return false; }
java
public static boolean updateComponentError(AbstractComponent component, ErrorMessage error) { if (component.getComponentError() != error) { component.setComponentError(error); return true; } return false; }
[ "public", "static", "boolean", "updateComponentError", "(", "AbstractComponent", "component", ",", "ErrorMessage", "error", ")", "{", "if", "(", "component", ".", "getComponentError", "(", ")", "!=", "error", ")", "{", "component", ".", "setComponentError", "(", "error", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Updates the component error of a component, but only if it differs from the currently set error.<p> @param component the component @param error the error @return true if the error was changed
[ "Updates", "the", "component", "error", "of", "a", "component", "but", "only", "if", "it", "differs", "from", "the", "currently", "set", "error", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/CmsVaadinUtils.java#L1233-L1240
krummas/DrizzleJDBC
src/main/java/org/drizzle/jdbc/DrizzleResultSet.java
DrizzleResultSet.getTimestamp
public Timestamp getTimestamp(final int columnIndex, final Calendar cal) throws SQLException { """ Retrieves the value of the designated column in the current row of this <code>ResultSet</code> object as a <code>java.sql.Timestamp</code> object in the Java programming language. This method uses the given calendar to construct an appropriate millisecond value for the timestamp if the underlying database does not store timezone information. @param columnIndex the first column is 1, the second is 2, ... @param cal the <code>java.util.Calendar</code> object to use in constructing the timestamp @return the column value as a <code>java.sql.Timestamp</code> object; if the value is SQL <code>NULL</code>, the value returned is <code>null</code> in the Java programming language @throws java.sql.SQLException if the columnIndex is not valid; if a database access error occurs or this method is called on a closed result set @since 1.2 """ try { final Timestamp result = getValueObject(columnIndex).getTimestamp(cal); if (result == null) { return null; } return new Timestamp(result.getTime()); } catch (ParseException e) { throw SQLExceptionMapper.getSQLException("Could not parse as time"); } }
java
public Timestamp getTimestamp(final int columnIndex, final Calendar cal) throws SQLException { try { final Timestamp result = getValueObject(columnIndex).getTimestamp(cal); if (result == null) { return null; } return new Timestamp(result.getTime()); } catch (ParseException e) { throw SQLExceptionMapper.getSQLException("Could not parse as time"); } }
[ "public", "Timestamp", "getTimestamp", "(", "final", "int", "columnIndex", ",", "final", "Calendar", "cal", ")", "throws", "SQLException", "{", "try", "{", "final", "Timestamp", "result", "=", "getValueObject", "(", "columnIndex", ")", ".", "getTimestamp", "(", "cal", ")", ";", "if", "(", "result", "==", "null", ")", "{", "return", "null", ";", "}", "return", "new", "Timestamp", "(", "result", ".", "getTime", "(", ")", ")", ";", "}", "catch", "(", "ParseException", "e", ")", "{", "throw", "SQLExceptionMapper", ".", "getSQLException", "(", "\"Could not parse as time\"", ")", ";", "}", "}" ]
Retrieves the value of the designated column in the current row of this <code>ResultSet</code> object as a <code>java.sql.Timestamp</code> object in the Java programming language. This method uses the given calendar to construct an appropriate millisecond value for the timestamp if the underlying database does not store timezone information. @param columnIndex the first column is 1, the second is 2, ... @param cal the <code>java.util.Calendar</code> object to use in constructing the timestamp @return the column value as a <code>java.sql.Timestamp</code> object; if the value is SQL <code>NULL</code>, the value returned is <code>null</code> in the Java programming language @throws java.sql.SQLException if the columnIndex is not valid; if a database access error occurs or this method is called on a closed result set @since 1.2
[ "Retrieves", "the", "value", "of", "the", "designated", "column", "in", "the", "current", "row", "of", "this", "<code", ">", "ResultSet<", "/", "code", ">", "object", "as", "a", "<code", ">", "java", ".", "sql", ".", "Timestamp<", "/", "code", ">", "object", "in", "the", "Java", "programming", "language", ".", "This", "method", "uses", "the", "given", "calendar", "to", "construct", "an", "appropriate", "millisecond", "value", "for", "the", "timestamp", "if", "the", "underlying", "database", "does", "not", "store", "timezone", "information", "." ]
train
https://github.com/krummas/DrizzleJDBC/blob/716f31fd71f3cc289edf69844d8117deb86d98d6/src/main/java/org/drizzle/jdbc/DrizzleResultSet.java#L2160-L2170
line/centraldogma
server/src/main/java/com/linecorp/centraldogma/server/internal/metadata/MetadataService.java
MetadataService.replacePermissionAtPointer
private CompletableFuture<Revision> replacePermissionAtPointer(Author author, String projectName, JsonPointer path, Collection<Permission> permission, String commitSummary) { """ Replaces {@link Permission}s of the specified {@code path} with the specified {@code permission}. """ final Change<JsonNode> change = Change.ofJsonPatch(METADATA_JSON, new ReplaceOperation(path, Jackson.valueToTree(permission)).toJsonNode()); return metadataRepo.push(projectName, Project.REPO_DOGMA, author, commitSummary, change); }
java
private CompletableFuture<Revision> replacePermissionAtPointer(Author author, String projectName, JsonPointer path, Collection<Permission> permission, String commitSummary) { final Change<JsonNode> change = Change.ofJsonPatch(METADATA_JSON, new ReplaceOperation(path, Jackson.valueToTree(permission)).toJsonNode()); return metadataRepo.push(projectName, Project.REPO_DOGMA, author, commitSummary, change); }
[ "private", "CompletableFuture", "<", "Revision", ">", "replacePermissionAtPointer", "(", "Author", "author", ",", "String", "projectName", ",", "JsonPointer", "path", ",", "Collection", "<", "Permission", ">", "permission", ",", "String", "commitSummary", ")", "{", "final", "Change", "<", "JsonNode", ">", "change", "=", "Change", ".", "ofJsonPatch", "(", "METADATA_JSON", ",", "new", "ReplaceOperation", "(", "path", ",", "Jackson", ".", "valueToTree", "(", "permission", ")", ")", ".", "toJsonNode", "(", ")", ")", ";", "return", "metadataRepo", ".", "push", "(", "projectName", ",", "Project", ".", "REPO_DOGMA", ",", "author", ",", "commitSummary", ",", "change", ")", ";", "}" ]
Replaces {@link Permission}s of the specified {@code path} with the specified {@code permission}.
[ "Replaces", "{" ]
train
https://github.com/line/centraldogma/blob/b9e46c67fbc26628c2186ce2f46e7fb303c831e9/server/src/main/java/com/linecorp/centraldogma/server/internal/metadata/MetadataService.java#L571-L579
amaembo/streamex
src/main/java/one/util/streamex/StreamEx.java
StreamEx.forPairs
public void forPairs(BiConsumer<? super T, ? super T> action) { """ Performs an action for each adjacent pair of elements of this stream. <p> This is a <a href="package-summary.html#StreamOps">terminal</a> operation. <p> The behavior of this operation is explicitly non-deterministic. For parallel stream pipelines, this operation does <em>not</em> guarantee to respect the encounter order of the stream, as doing so would sacrifice the benefit of parallelism. For any given element, the action may be performed at whatever time and in whatever thread the library chooses. If the action accesses shared state, it is responsible for providing the required synchronization. @param action a non-interfering action to perform on the elements @since 0.2.2 """ pairMap((a, b) -> { action.accept(a, b); return null; }).reduce(null, selectFirst()); }
java
public void forPairs(BiConsumer<? super T, ? super T> action) { pairMap((a, b) -> { action.accept(a, b); return null; }).reduce(null, selectFirst()); }
[ "public", "void", "forPairs", "(", "BiConsumer", "<", "?", "super", "T", ",", "?", "super", "T", ">", "action", ")", "{", "pairMap", "(", "(", "a", ",", "b", ")", "->", "{", "action", ".", "accept", "(", "a", ",", "b", ")", ";", "return", "null", ";", "}", ")", ".", "reduce", "(", "null", ",", "selectFirst", "(", ")", ")", ";", "}" ]
Performs an action for each adjacent pair of elements of this stream. <p> This is a <a href="package-summary.html#StreamOps">terminal</a> operation. <p> The behavior of this operation is explicitly non-deterministic. For parallel stream pipelines, this operation does <em>not</em> guarantee to respect the encounter order of the stream, as doing so would sacrifice the benefit of parallelism. For any given element, the action may be performed at whatever time and in whatever thread the library chooses. If the action accesses shared state, it is responsible for providing the required synchronization. @param action a non-interfering action to perform on the elements @since 0.2.2
[ "Performs", "an", "action", "for", "each", "adjacent", "pair", "of", "elements", "of", "this", "stream", "." ]
train
https://github.com/amaembo/streamex/blob/936bbd1b7dfbcf64a3b990682bfc848213441d14/src/main/java/one/util/streamex/StreamEx.java#L1536-L1541
rundeck/rundeck
core/src/main/java/com/dtolabs/rundeck/core/authorization/providers/YamlProvider.java
YamlProvider.sourceFromStream
public static CacheableYamlSource sourceFromStream( final String identity, final InputStream stream, final Date modified, final ValidationSet validationSet ) { """ Source from a stream @param identity identity @param stream stream @param modified date the content was last modified, for caching purposes @param validationSet @return source """ return new CacheableYamlStreamSource(stream, identity, modified, validationSet); }
java
public static CacheableYamlSource sourceFromStream( final String identity, final InputStream stream, final Date modified, final ValidationSet validationSet ) { return new CacheableYamlStreamSource(stream, identity, modified, validationSet); }
[ "public", "static", "CacheableYamlSource", "sourceFromStream", "(", "final", "String", "identity", ",", "final", "InputStream", "stream", ",", "final", "Date", "modified", ",", "final", "ValidationSet", "validationSet", ")", "{", "return", "new", "CacheableYamlStreamSource", "(", "stream", ",", "identity", ",", "modified", ",", "validationSet", ")", ";", "}" ]
Source from a stream @param identity identity @param stream stream @param modified date the content was last modified, for caching purposes @param validationSet @return source
[ "Source", "from", "a", "stream" ]
train
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/authorization/providers/YamlProvider.java#L255-L263
innoq/LiQID
ldap-connector/src/main/java/com/innoq/ldap/connector/LdapHelper.java
LdapHelper.getUser
@Override public Node getUser(final String uid) { """ Returns an LDAP-User. @param uid the uid of the User. @see com.innoq.liqid.model.Node#getName @return the Node of that User, either filled (if User was found), or empty. """ try { String query = "(&(objectClass=" + userObjectClass + ")(" + userIdentifyer + "=" + uid + "))"; SearchResult searchResult; Attributes attributes; SearchControls controls = new SearchControls(); controls.setReturningAttributes(new String[]{LdapKeys.ASTERISK, LdapKeys.MODIFY_TIMESTAMP, LdapKeys.MODIFIERS_NAME, LdapKeys.ENTRY_UUID}); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration<SearchResult> results = ctx.search("", query, controls); queryCount++; if (results.hasMore()) { searchResult = results.next(); attributes = searchResult.getAttributes(); LdapUser user = new LdapUser(uid, this); user.setDn(searchResult.getNameInNamespace()); user = fillAttributesInUser((LdapUser) user, attributes); return user; } } catch (NamingException ex) { handleNamingException(instanceName + ":" + uid, ex); } return new LdapUser(); }
java
@Override public Node getUser(final String uid) { try { String query = "(&(objectClass=" + userObjectClass + ")(" + userIdentifyer + "=" + uid + "))"; SearchResult searchResult; Attributes attributes; SearchControls controls = new SearchControls(); controls.setReturningAttributes(new String[]{LdapKeys.ASTERISK, LdapKeys.MODIFY_TIMESTAMP, LdapKeys.MODIFIERS_NAME, LdapKeys.ENTRY_UUID}); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration<SearchResult> results = ctx.search("", query, controls); queryCount++; if (results.hasMore()) { searchResult = results.next(); attributes = searchResult.getAttributes(); LdapUser user = new LdapUser(uid, this); user.setDn(searchResult.getNameInNamespace()); user = fillAttributesInUser((LdapUser) user, attributes); return user; } } catch (NamingException ex) { handleNamingException(instanceName + ":" + uid, ex); } return new LdapUser(); }
[ "@", "Override", "public", "Node", "getUser", "(", "final", "String", "uid", ")", "{", "try", "{", "String", "query", "=", "\"(&(objectClass=\"", "+", "userObjectClass", "+", "\")(\"", "+", "userIdentifyer", "+", "\"=\"", "+", "uid", "+", "\"))\"", ";", "SearchResult", "searchResult", ";", "Attributes", "attributes", ";", "SearchControls", "controls", "=", "new", "SearchControls", "(", ")", ";", "controls", ".", "setReturningAttributes", "(", "new", "String", "[", "]", "{", "LdapKeys", ".", "ASTERISK", ",", "LdapKeys", ".", "MODIFY_TIMESTAMP", ",", "LdapKeys", ".", "MODIFIERS_NAME", ",", "LdapKeys", ".", "ENTRY_UUID", "}", ")", ";", "controls", ".", "setSearchScope", "(", "SearchControls", ".", "SUBTREE_SCOPE", ")", ";", "NamingEnumeration", "<", "SearchResult", ">", "results", "=", "ctx", ".", "search", "(", "\"\"", ",", "query", ",", "controls", ")", ";", "queryCount", "++", ";", "if", "(", "results", ".", "hasMore", "(", ")", ")", "{", "searchResult", "=", "results", ".", "next", "(", ")", ";", "attributes", "=", "searchResult", ".", "getAttributes", "(", ")", ";", "LdapUser", "user", "=", "new", "LdapUser", "(", "uid", ",", "this", ")", ";", "user", ".", "setDn", "(", "searchResult", ".", "getNameInNamespace", "(", ")", ")", ";", "user", "=", "fillAttributesInUser", "(", "(", "LdapUser", ")", "user", ",", "attributes", ")", ";", "return", "user", ";", "}", "}", "catch", "(", "NamingException", "ex", ")", "{", "handleNamingException", "(", "instanceName", "+", "\":\"", "+", "uid", ",", "ex", ")", ";", "}", "return", "new", "LdapUser", "(", ")", ";", "}" ]
Returns an LDAP-User. @param uid the uid of the User. @see com.innoq.liqid.model.Node#getName @return the Node of that User, either filled (if User was found), or empty.
[ "Returns", "an", "LDAP", "-", "User", "." ]
train
https://github.com/innoq/LiQID/blob/ae3de2c1fd78c40219780d510eba57c931901279/ldap-connector/src/main/java/com/innoq/ldap/connector/LdapHelper.java#L288-L312
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.getVpnProfilePackageUrlAsync
public Observable<String> getVpnProfilePackageUrlAsync(String resourceGroupName, String virtualNetworkGatewayName) { """ Gets pre-generated VPN profile for P2S client of the virtual network gateway in the specified resource group. The profile needs to be generated first using generateVpnProfile. @param resourceGroupName The name of the resource group. @param virtualNetworkGatewayName The name of the virtual network gateway. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request """ return getVpnProfilePackageUrlWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayName).map(new Func1<ServiceResponse<String>, String>() { @Override public String call(ServiceResponse<String> response) { return response.body(); } }); }
java
public Observable<String> getVpnProfilePackageUrlAsync(String resourceGroupName, String virtualNetworkGatewayName) { return getVpnProfilePackageUrlWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayName).map(new Func1<ServiceResponse<String>, String>() { @Override public String call(ServiceResponse<String> response) { return response.body(); } }); }
[ "public", "Observable", "<", "String", ">", "getVpnProfilePackageUrlAsync", "(", "String", "resourceGroupName", ",", "String", "virtualNetworkGatewayName", ")", "{", "return", "getVpnProfilePackageUrlWithServiceResponseAsync", "(", "resourceGroupName", ",", "virtualNetworkGatewayName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "String", ">", ",", "String", ">", "(", ")", "{", "@", "Override", "public", "String", "call", "(", "ServiceResponse", "<", "String", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Gets pre-generated VPN profile for P2S client of the virtual network gateway in the specified resource group. The profile needs to be generated first using generateVpnProfile. @param resourceGroupName The name of the resource group. @param virtualNetworkGatewayName The name of the virtual network gateway. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Gets", "pre", "-", "generated", "VPN", "profile", "for", "P2S", "client", "of", "the", "virtual", "network", "gateway", "in", "the", "specified", "resource", "group", ".", "The", "profile", "needs", "to", "be", "generated", "first", "using", "generateVpnProfile", "." ]
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#L1824-L1831
ahome-it/lienzo-core
src/main/java/com/ait/lienzo/client/core/util/Geometry.java
Geometry.getQuadrant
public static final Direction getQuadrant(final double cx, final double cy, final double x0, final double y0) { """ Returns the NESW quadrant the point is in. The delta from the center NE x > 0, y < 0 SE x > 0, y >= 0 SW x <= 0, y >= 0 NW x <= 0, y < 0 @param cx @param cy* @param x0 @param y0 @return """ if ((x0 > cx) && (y0 < cy)) { return Direction.NORTH_EAST; } if ((x0 > cx) && (y0 >= cy)) { return Direction.SOUTH_EAST; } if ((x0 <= cx) && (y0 >= cy)) { return Direction.SOUTH_WEST; } // if( x0 <= c.getX() && y0 < c.getY() ) return Direction.NORTH_WEST; }
java
public static final Direction getQuadrant(final double cx, final double cy, final double x0, final double y0) { if ((x0 > cx) && (y0 < cy)) { return Direction.NORTH_EAST; } if ((x0 > cx) && (y0 >= cy)) { return Direction.SOUTH_EAST; } if ((x0 <= cx) && (y0 >= cy)) { return Direction.SOUTH_WEST; } // if( x0 <= c.getX() && y0 < c.getY() ) return Direction.NORTH_WEST; }
[ "public", "static", "final", "Direction", "getQuadrant", "(", "final", "double", "cx", ",", "final", "double", "cy", ",", "final", "double", "x0", ",", "final", "double", "y0", ")", "{", "if", "(", "(", "x0", ">", "cx", ")", "&&", "(", "y0", "<", "cy", ")", ")", "{", "return", "Direction", ".", "NORTH_EAST", ";", "}", "if", "(", "(", "x0", ">", "cx", ")", "&&", "(", "y0", ">=", "cy", ")", ")", "{", "return", "Direction", ".", "SOUTH_EAST", ";", "}", "if", "(", "(", "x0", "<=", "cx", ")", "&&", "(", "y0", ">=", "cy", ")", ")", "{", "return", "Direction", ".", "SOUTH_WEST", ";", "}", "// if( x0 <= c.getX() && y0 < c.getY() )\r", "return", "Direction", ".", "NORTH_WEST", ";", "}" ]
Returns the NESW quadrant the point is in. The delta from the center NE x > 0, y < 0 SE x > 0, y >= 0 SW x <= 0, y >= 0 NW x <= 0, y < 0 @param cx @param cy* @param x0 @param y0 @return
[ "Returns", "the", "NESW", "quadrant", "the", "point", "is", "in", ".", "The", "delta", "from", "the", "center", "NE", "x", ">", "0", "y", "<", "0", "SE", "x", ">", "0", "y", ">", "=", "0", "SW", "x", "<", "=", "0", "y", ">", "=", "0", "NW", "x", "<", "=", "0", "y", "<", "0" ]
train
https://github.com/ahome-it/lienzo-core/blob/8e03723700dec366f77064d12fb8676d8cd6be99/src/main/java/com/ait/lienzo/client/core/util/Geometry.java#L1572-L1588
dita-ot/dita-ot
src/main/java/org/ditang/relaxng/defaults/Util.java
Util.clearUserInfo
private static URL clearUserInfo(String systemID) { """ Clears the user info from an url. @param systemID the url to be cleaned. @return the cleaned url, or null if the argument is not an URL. """ try { URL url = new URL(systemID); // Do not clear user info on "file" urls 'cause on Windows the drive will // have no ":"... if (!"file".equals(url.getProtocol())) { return attachUserInfo(url, null, null); } return url; } catch (MalformedURLException e) { return null; } }
java
private static URL clearUserInfo(String systemID) { try { URL url = new URL(systemID); // Do not clear user info on "file" urls 'cause on Windows the drive will // have no ":"... if (!"file".equals(url.getProtocol())) { return attachUserInfo(url, null, null); } return url; } catch (MalformedURLException e) { return null; } }
[ "private", "static", "URL", "clearUserInfo", "(", "String", "systemID", ")", "{", "try", "{", "URL", "url", "=", "new", "URL", "(", "systemID", ")", ";", "// Do not clear user info on \"file\" urls 'cause on Windows the drive will", "// have no \":\"...", "if", "(", "!", "\"file\"", ".", "equals", "(", "url", ".", "getProtocol", "(", ")", ")", ")", "{", "return", "attachUserInfo", "(", "url", ",", "null", ",", "null", ")", ";", "}", "return", "url", ";", "}", "catch", "(", "MalformedURLException", "e", ")", "{", "return", "null", ";", "}", "}" ]
Clears the user info from an url. @param systemID the url to be cleaned. @return the cleaned url, or null if the argument is not an URL.
[ "Clears", "the", "user", "info", "from", "an", "url", "." ]
train
https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/ditang/relaxng/defaults/Util.java#L362-L374
jillesvangurp/jsonj
src/main/java/com/github/jsonj/tools/JsonBuilder.java
JsonBuilder.putArray
public @Nonnull JsonBuilder putArray(String key, String... values) { """ Add a JsonArray to the object with the string values added. @param key key @param values one or more {@link String} values values that go in the array @return the builder """ JsonArray jjArray = new JsonArray(); for (String string : values) { jjArray.add(primitive(string)); } object.put(key, jjArray); return this; }
java
public @Nonnull JsonBuilder putArray(String key, String... values) { JsonArray jjArray = new JsonArray(); for (String string : values) { jjArray.add(primitive(string)); } object.put(key, jjArray); return this; }
[ "public", "@", "Nonnull", "JsonBuilder", "putArray", "(", "String", "key", ",", "String", "...", "values", ")", "{", "JsonArray", "jjArray", "=", "new", "JsonArray", "(", ")", ";", "for", "(", "String", "string", ":", "values", ")", "{", "jjArray", ".", "add", "(", "primitive", "(", "string", ")", ")", ";", "}", "object", ".", "put", "(", "key", ",", "jjArray", ")", ";", "return", "this", ";", "}" ]
Add a JsonArray to the object with the string values added. @param key key @param values one or more {@link String} values values that go in the array @return the builder
[ "Add", "a", "JsonArray", "to", "the", "object", "with", "the", "string", "values", "added", "." ]
train
https://github.com/jillesvangurp/jsonj/blob/1da0c44c5bdb60c0cd806c48d2da5a8a75bf84af/src/main/java/com/github/jsonj/tools/JsonBuilder.java#L125-L132
jcuda/jcuda
JCudaJava/src/main/java/jcuda/driver/JCudaDriver.java
JCudaDriver.cuGraphicsMapResources
public static int cuGraphicsMapResources(int count, CUgraphicsResource resources[], CUstream hStream) { """ Map graphics resources for access by CUDA. <pre> CUresult cuGraphicsMapResources ( unsigned int count, CUgraphicsResource* resources, CUstream hStream ) </pre> <div> <p>Map graphics resources for access by CUDA. Maps the <tt>count</tt> graphics resources in <tt>resources</tt> for access by CUDA. </p> <p>The resources in <tt>resources</tt> may be accessed by CUDA until they are unmapped. The graphics API from which <tt>resources</tt> were registered should not access any resources while they are mapped by CUDA. If an application does so, the results are undefined. </p> <p>This function provides the synchronization guarantee that any graphics calls issued before cuGraphicsMapResources() will complete before any subsequent CUDA work issued in <tt>stream</tt> begins. </p> <p>If <tt>resources</tt> includes any duplicate entries then CUDA_ERROR_INVALID_HANDLE is returned. If any of <tt>resources</tt> are presently mapped for access by CUDA then CUDA_ERROR_ALREADY_MAPPED is returned. </p> <div> <span>Note:</span> <p>Note that this function may also return error codes from previous, asynchronous launches. </p> </div> </p> </div> @param count Number of resources to map @param resources Resources to map for CUDA usage @param hStream Stream with which to synchronize @return CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_ALREADY_MAPPED, CUDA_ERROR_UNKNOWN @see JCudaDriver#cuGraphicsResourceGetMappedPointer @see JCudaDriver#cuGraphicsSubResourceGetMappedArray @see JCudaDriver#cuGraphicsUnmapResources """ return checkResult(cuGraphicsMapResourcesNative(count, resources, hStream)); }
java
public static int cuGraphicsMapResources(int count, CUgraphicsResource resources[], CUstream hStream) { return checkResult(cuGraphicsMapResourcesNative(count, resources, hStream)); }
[ "public", "static", "int", "cuGraphicsMapResources", "(", "int", "count", ",", "CUgraphicsResource", "resources", "[", "]", ",", "CUstream", "hStream", ")", "{", "return", "checkResult", "(", "cuGraphicsMapResourcesNative", "(", "count", ",", "resources", ",", "hStream", ")", ")", ";", "}" ]
Map graphics resources for access by CUDA. <pre> CUresult cuGraphicsMapResources ( unsigned int count, CUgraphicsResource* resources, CUstream hStream ) </pre> <div> <p>Map graphics resources for access by CUDA. Maps the <tt>count</tt> graphics resources in <tt>resources</tt> for access by CUDA. </p> <p>The resources in <tt>resources</tt> may be accessed by CUDA until they are unmapped. The graphics API from which <tt>resources</tt> were registered should not access any resources while they are mapped by CUDA. If an application does so, the results are undefined. </p> <p>This function provides the synchronization guarantee that any graphics calls issued before cuGraphicsMapResources() will complete before any subsequent CUDA work issued in <tt>stream</tt> begins. </p> <p>If <tt>resources</tt> includes any duplicate entries then CUDA_ERROR_INVALID_HANDLE is returned. If any of <tt>resources</tt> are presently mapped for access by CUDA then CUDA_ERROR_ALREADY_MAPPED is returned. </p> <div> <span>Note:</span> <p>Note that this function may also return error codes from previous, asynchronous launches. </p> </div> </p> </div> @param count Number of resources to map @param resources Resources to map for CUDA usage @param hStream Stream with which to synchronize @return CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_ALREADY_MAPPED, CUDA_ERROR_UNKNOWN @see JCudaDriver#cuGraphicsResourceGetMappedPointer @see JCudaDriver#cuGraphicsSubResourceGetMappedArray @see JCudaDriver#cuGraphicsUnmapResources
[ "Map", "graphics", "resources", "for", "access", "by", "CUDA", "." ]
train
https://github.com/jcuda/jcuda/blob/468528b5b9b37dfceb6ed83fcfd889e9b359f984/JCudaJava/src/main/java/jcuda/driver/JCudaDriver.java#L16094-L16097
Waikato/moa
moa/src/main/java/moa/clusterers/dstream/Dstream.java
Dstream.densityThresholdFunction
private double densityThresholdFunction(int tg, double cl, double decayFactor, int N) { """ Implements the function pi given in Definition 4.1 of Chen and Tu 2007 @param tg - the update time in the density grid's characteristic vector @param cl - user defined parameter which controls the threshold for sparse grids @param decayFactor - user defined parameter which is represented as lambda in Chen and Tu 2007 @param N - the number of density grids, defined after eq 2 in Chen and Tu 2007 """ return (cl * (1.0 - Math.pow(decayFactor, (this.getCurrTime()-tg+1.0))))/(N * (1.0 - decayFactor)); }
java
private double densityThresholdFunction(int tg, double cl, double decayFactor, int N) { return (cl * (1.0 - Math.pow(decayFactor, (this.getCurrTime()-tg+1.0))))/(N * (1.0 - decayFactor)); }
[ "private", "double", "densityThresholdFunction", "(", "int", "tg", ",", "double", "cl", ",", "double", "decayFactor", ",", "int", "N", ")", "{", "return", "(", "cl", "*", "(", "1.0", "-", "Math", ".", "pow", "(", "decayFactor", ",", "(", "this", ".", "getCurrTime", "(", ")", "-", "tg", "+", "1.0", ")", ")", ")", ")", "/", "(", "N", "*", "(", "1.0", "-", "decayFactor", ")", ")", ";", "}" ]
Implements the function pi given in Definition 4.1 of Chen and Tu 2007 @param tg - the update time in the density grid's characteristic vector @param cl - user defined parameter which controls the threshold for sparse grids @param decayFactor - user defined parameter which is represented as lambda in Chen and Tu 2007 @param N - the number of density grids, defined after eq 2 in Chen and Tu 2007
[ "Implements", "the", "function", "pi", "given", "in", "Definition", "4", ".", "1", "of", "Chen", "and", "Tu", "2007" ]
train
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/clusterers/dstream/Dstream.java#L1243-L1246
baidubce/bce-sdk-java
src/main/java/com/baidubce/services/bcc/BccClient.java
BccClient.purchaseReservedInstance
public void purchaseReservedInstance(String instanceId, int reservationLength, String reservationTimeUnit) { """ PurchaseReserved the instance with fixed duration. You can not purchaseReserved the instance which is resizing. This is an asynchronous interface, you can get the latest status by invoke {@link #getInstance(GetInstanceRequest)} @param instanceId The id of the instance. @param reservationLength The fixed duration to purchaseReserved,available is [1,2,3,4,5,6,7,8,9,12,24,36] @param reservationTimeUnit The timeUnit to renew the instance,only support "month" now. """ this.purchaseReservedInstance(new PurchaseReservedInstanceRequeset() .withInstanceId(instanceId) .withBilling(new Billing().withReservation(new Reservation() .withReservationLength(reservationLength) .withReservationTimeUnit(reservationTimeUnit)))); }
java
public void purchaseReservedInstance(String instanceId, int reservationLength, String reservationTimeUnit) { this.purchaseReservedInstance(new PurchaseReservedInstanceRequeset() .withInstanceId(instanceId) .withBilling(new Billing().withReservation(new Reservation() .withReservationLength(reservationLength) .withReservationTimeUnit(reservationTimeUnit)))); }
[ "public", "void", "purchaseReservedInstance", "(", "String", "instanceId", ",", "int", "reservationLength", ",", "String", "reservationTimeUnit", ")", "{", "this", ".", "purchaseReservedInstance", "(", "new", "PurchaseReservedInstanceRequeset", "(", ")", ".", "withInstanceId", "(", "instanceId", ")", ".", "withBilling", "(", "new", "Billing", "(", ")", ".", "withReservation", "(", "new", "Reservation", "(", ")", ".", "withReservationLength", "(", "reservationLength", ")", ".", "withReservationTimeUnit", "(", "reservationTimeUnit", ")", ")", ")", ")", ";", "}" ]
PurchaseReserved the instance with fixed duration. You can not purchaseReserved the instance which is resizing. This is an asynchronous interface, you can get the latest status by invoke {@link #getInstance(GetInstanceRequest)} @param instanceId The id of the instance. @param reservationLength The fixed duration to purchaseReserved,available is [1,2,3,4,5,6,7,8,9,12,24,36] @param reservationTimeUnit The timeUnit to renew the instance,only support "month" now.
[ "PurchaseReserved", "the", "instance", "with", "fixed", "duration", "." ]
train
https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/bcc/BccClient.java#L801-L807
attribyte/wpdb
src/main/java/org/attribyte/wp/db/DB.java
DB.createUser
public User createUser(final User user, final String userPass) throws SQLException { """ Creates a user. <p> If the {@code id} is &gt; 0, the user will be created with this id, otherwise it will be auto-generated. </p> @param user The user. @param userPass The {@code user_pass} string to use (probably the hash of a default username/password). @return The newly created user. @throws SQLException on database error. """ Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; String nicename = user.slug; if(nicename.length() > 49) { nicename = nicename.substring(0, 49); } String username = user.username.length() < 60 ? user.username : user.username.substring(0, 60); Timer.Context ctx = metrics.createUserTimer.time(); try { conn = connectionSupplier.getConnection(); if(user.id > 0L) { stmt = conn.prepareStatement(createUserWithIdSQL); stmt.setLong(1, user.id); stmt.setString(2, username); stmt.setString(3, Strings.nullToEmpty(userPass)); stmt.setString(4, nicename); stmt.setString(5, user.displayName()); stmt.setString(6, Strings.nullToEmpty(user.email)); stmt.setString(7, Strings.nullToEmpty(user.url)); stmt.executeUpdate(); return user; } else { stmt = conn.prepareStatement(createUserSQL, Statement.RETURN_GENERATED_KEYS); stmt.setString(1, username); stmt.setString(2, Strings.nullToEmpty(userPass)); stmt.setString(3, nicename); stmt.setString(4, user.displayName()); stmt.setString(5, Strings.nullToEmpty(user.email)); stmt.setString(6, Strings.nullToEmpty(user.url)); stmt.executeUpdate(); rs = stmt.getGeneratedKeys(); if(rs.next()) { return user.withId(rs.getLong(1)); } else { throw new SQLException("Problem creating user (no generated id)"); } } } finally { ctx.stop(); closeQuietly(conn, stmt, rs); } }
java
public User createUser(final User user, final String userPass) throws SQLException { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; String nicename = user.slug; if(nicename.length() > 49) { nicename = nicename.substring(0, 49); } String username = user.username.length() < 60 ? user.username : user.username.substring(0, 60); Timer.Context ctx = metrics.createUserTimer.time(); try { conn = connectionSupplier.getConnection(); if(user.id > 0L) { stmt = conn.prepareStatement(createUserWithIdSQL); stmt.setLong(1, user.id); stmt.setString(2, username); stmt.setString(3, Strings.nullToEmpty(userPass)); stmt.setString(4, nicename); stmt.setString(5, user.displayName()); stmt.setString(6, Strings.nullToEmpty(user.email)); stmt.setString(7, Strings.nullToEmpty(user.url)); stmt.executeUpdate(); return user; } else { stmt = conn.prepareStatement(createUserSQL, Statement.RETURN_GENERATED_KEYS); stmt.setString(1, username); stmt.setString(2, Strings.nullToEmpty(userPass)); stmt.setString(3, nicename); stmt.setString(4, user.displayName()); stmt.setString(5, Strings.nullToEmpty(user.email)); stmt.setString(6, Strings.nullToEmpty(user.url)); stmt.executeUpdate(); rs = stmt.getGeneratedKeys(); if(rs.next()) { return user.withId(rs.getLong(1)); } else { throw new SQLException("Problem creating user (no generated id)"); } } } finally { ctx.stop(); closeQuietly(conn, stmt, rs); } }
[ "public", "User", "createUser", "(", "final", "User", "user", ",", "final", "String", "userPass", ")", "throws", "SQLException", "{", "Connection", "conn", "=", "null", ";", "PreparedStatement", "stmt", "=", "null", ";", "ResultSet", "rs", "=", "null", ";", "String", "nicename", "=", "user", ".", "slug", ";", "if", "(", "nicename", ".", "length", "(", ")", ">", "49", ")", "{", "nicename", "=", "nicename", ".", "substring", "(", "0", ",", "49", ")", ";", "}", "String", "username", "=", "user", ".", "username", ".", "length", "(", ")", "<", "60", "?", "user", ".", "username", ":", "user", ".", "username", ".", "substring", "(", "0", ",", "60", ")", ";", "Timer", ".", "Context", "ctx", "=", "metrics", ".", "createUserTimer", ".", "time", "(", ")", ";", "try", "{", "conn", "=", "connectionSupplier", ".", "getConnection", "(", ")", ";", "if", "(", "user", ".", "id", ">", "0L", ")", "{", "stmt", "=", "conn", ".", "prepareStatement", "(", "createUserWithIdSQL", ")", ";", "stmt", ".", "setLong", "(", "1", ",", "user", ".", "id", ")", ";", "stmt", ".", "setString", "(", "2", ",", "username", ")", ";", "stmt", ".", "setString", "(", "3", ",", "Strings", ".", "nullToEmpty", "(", "userPass", ")", ")", ";", "stmt", ".", "setString", "(", "4", ",", "nicename", ")", ";", "stmt", ".", "setString", "(", "5", ",", "user", ".", "displayName", "(", ")", ")", ";", "stmt", ".", "setString", "(", "6", ",", "Strings", ".", "nullToEmpty", "(", "user", ".", "email", ")", ")", ";", "stmt", ".", "setString", "(", "7", ",", "Strings", ".", "nullToEmpty", "(", "user", ".", "url", ")", ")", ";", "stmt", ".", "executeUpdate", "(", ")", ";", "return", "user", ";", "}", "else", "{", "stmt", "=", "conn", ".", "prepareStatement", "(", "createUserSQL", ",", "Statement", ".", "RETURN_GENERATED_KEYS", ")", ";", "stmt", ".", "setString", "(", "1", ",", "username", ")", ";", "stmt", ".", "setString", "(", "2", ",", "Strings", ".", "nullToEmpty", "(", "userPass", ")", ")", ";", "stmt", ".", "setString", "(", "3", ",", "nicename", ")", ";", "stmt", ".", "setString", "(", "4", ",", "user", ".", "displayName", "(", ")", ")", ";", "stmt", ".", "setString", "(", "5", ",", "Strings", ".", "nullToEmpty", "(", "user", ".", "email", ")", ")", ";", "stmt", ".", "setString", "(", "6", ",", "Strings", ".", "nullToEmpty", "(", "user", ".", "url", ")", ")", ";", "stmt", ".", "executeUpdate", "(", ")", ";", "rs", "=", "stmt", ".", "getGeneratedKeys", "(", ")", ";", "if", "(", "rs", ".", "next", "(", ")", ")", "{", "return", "user", ".", "withId", "(", "rs", ".", "getLong", "(", "1", ")", ")", ";", "}", "else", "{", "throw", "new", "SQLException", "(", "\"Problem creating user (no generated id)\"", ")", ";", "}", "}", "}", "finally", "{", "ctx", ".", "stop", "(", ")", ";", "closeQuietly", "(", "conn", ",", "stmt", ",", "rs", ")", ";", "}", "}" ]
Creates a user. <p> If the {@code id} is &gt; 0, the user will be created with this id, otherwise it will be auto-generated. </p> @param user The user. @param userPass The {@code user_pass} string to use (probably the hash of a default username/password). @return The newly created user. @throws SQLException on database error.
[ "Creates", "a", "user", ".", "<p", ">", "If", "the", "{" ]
train
https://github.com/attribyte/wpdb/blob/b9adf6131dfb67899ebff770c9bfeb001cc42f30/src/main/java/org/attribyte/wp/db/DB.java#L312-L360
aws/aws-sdk-java
aws-java-sdk-sns/src/main/java/com/amazonaws/services/sns/util/SignatureChecker.java
SignatureChecker.verifySignature
public boolean verifySignature(Map<String, String> parsedMessage, PublicKey publicKey) { """ Validates the signature on a Simple Notification Service message. No Amazon-specific dependencies, just plain Java crypto @param parsedMessage A map of Simple Notification Service message. @param publicKey The Simple Notification Service public key, exactly as you'd see it when retrieved from the cert. @return True if the message was correctly validated, otherwise false. """ boolean valid = false; String version = parsedMessage.get(SIGNATURE_VERSION); if (version.equals("1")) { // construct the canonical signed string String type = parsedMessage.get(TYPE); String signature = parsedMessage.get(SIGNATURE); String signed; if (type.equals(NOTIFICATION_TYPE)) { signed = stringToSign(publishMessageValues(parsedMessage)); } else if (type.equals(SUBSCRIBE_TYPE)) { signed = stringToSign(subscribeMessageValues(parsedMessage)); } else if (type.equals(UNSUBSCRIBE_TYPE)) { signed = stringToSign(subscribeMessageValues(parsedMessage)); // no difference, for now } else { throw new RuntimeException("Cannot process message of type " + type); } valid = verifySignature(signed, signature, publicKey); } return valid; }
java
public boolean verifySignature(Map<String, String> parsedMessage, PublicKey publicKey) { boolean valid = false; String version = parsedMessage.get(SIGNATURE_VERSION); if (version.equals("1")) { // construct the canonical signed string String type = parsedMessage.get(TYPE); String signature = parsedMessage.get(SIGNATURE); String signed; if (type.equals(NOTIFICATION_TYPE)) { signed = stringToSign(publishMessageValues(parsedMessage)); } else if (type.equals(SUBSCRIBE_TYPE)) { signed = stringToSign(subscribeMessageValues(parsedMessage)); } else if (type.equals(UNSUBSCRIBE_TYPE)) { signed = stringToSign(subscribeMessageValues(parsedMessage)); // no difference, for now } else { throw new RuntimeException("Cannot process message of type " + type); } valid = verifySignature(signed, signature, publicKey); } return valid; }
[ "public", "boolean", "verifySignature", "(", "Map", "<", "String", ",", "String", ">", "parsedMessage", ",", "PublicKey", "publicKey", ")", "{", "boolean", "valid", "=", "false", ";", "String", "version", "=", "parsedMessage", ".", "get", "(", "SIGNATURE_VERSION", ")", ";", "if", "(", "version", ".", "equals", "(", "\"1\"", ")", ")", "{", "// construct the canonical signed string", "String", "type", "=", "parsedMessage", ".", "get", "(", "TYPE", ")", ";", "String", "signature", "=", "parsedMessage", ".", "get", "(", "SIGNATURE", ")", ";", "String", "signed", ";", "if", "(", "type", ".", "equals", "(", "NOTIFICATION_TYPE", ")", ")", "{", "signed", "=", "stringToSign", "(", "publishMessageValues", "(", "parsedMessage", ")", ")", ";", "}", "else", "if", "(", "type", ".", "equals", "(", "SUBSCRIBE_TYPE", ")", ")", "{", "signed", "=", "stringToSign", "(", "subscribeMessageValues", "(", "parsedMessage", ")", ")", ";", "}", "else", "if", "(", "type", ".", "equals", "(", "UNSUBSCRIBE_TYPE", ")", ")", "{", "signed", "=", "stringToSign", "(", "subscribeMessageValues", "(", "parsedMessage", ")", ")", ";", "// no difference, for now", "}", "else", "{", "throw", "new", "RuntimeException", "(", "\"Cannot process message of type \"", "+", "type", ")", ";", "}", "valid", "=", "verifySignature", "(", "signed", ",", "signature", ",", "publicKey", ")", ";", "}", "return", "valid", ";", "}" ]
Validates the signature on a Simple Notification Service message. No Amazon-specific dependencies, just plain Java crypto @param parsedMessage A map of Simple Notification Service message. @param publicKey The Simple Notification Service public key, exactly as you'd see it when retrieved from the cert. @return True if the message was correctly validated, otherwise false.
[ "Validates", "the", "signature", "on", "a", "Simple", "Notification", "Service", "message", ".", "No", "Amazon", "-", "specific", "dependencies", "just", "plain", "Java", "crypto" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-sns/src/main/java/com/amazonaws/services/sns/util/SignatureChecker.java#L111-L131
beangle/beangle3
commons/core/src/main/java/org/beangle/commons/lang/Strings.java
Strings.unCamel
public static String unCamel(String str, char seperator, boolean lowercase) { """ 将驼峰表示法转换为下划线小写表示 @param str a {@link java.lang.String} object. @param seperator a char. @param lowercase a boolean. @return a {@link java.lang.String} object. """ char[] ca = str.toCharArray(); if (3 > ca.length) { return lowercase ? str.toLowerCase() : str; } // about five seperator StringBuilder build = new StringBuilder(ca.length + 5); build.append(lowercase ? toLowerCase(ca[0]) : ca[0]); boolean lower1 = isLowerCase(ca[0]); int i = 1; while (i < ca.length - 1) { char cur = ca[i]; char next = ca[i + 1]; boolean upper2 = isUpperCase(cur); boolean lower3 = isLowerCase(next); if (lower1 && upper2 && lower3) { build.append(seperator); build.append(lowercase ? toLowerCase(cur) : cur); build.append(next); i += 2; } else { if (lowercase && upper2) { build.append(toLowerCase(cur)); } else { build.append(cur); } lower1 = !upper2; i++; } } if (i == ca.length - 1) { build.append(lowercase ? toLowerCase(ca[i]) : ca[i]); } return build.toString(); }
java
public static String unCamel(String str, char seperator, boolean lowercase) { char[] ca = str.toCharArray(); if (3 > ca.length) { return lowercase ? str.toLowerCase() : str; } // about five seperator StringBuilder build = new StringBuilder(ca.length + 5); build.append(lowercase ? toLowerCase(ca[0]) : ca[0]); boolean lower1 = isLowerCase(ca[0]); int i = 1; while (i < ca.length - 1) { char cur = ca[i]; char next = ca[i + 1]; boolean upper2 = isUpperCase(cur); boolean lower3 = isLowerCase(next); if (lower1 && upper2 && lower3) { build.append(seperator); build.append(lowercase ? toLowerCase(cur) : cur); build.append(next); i += 2; } else { if (lowercase && upper2) { build.append(toLowerCase(cur)); } else { build.append(cur); } lower1 = !upper2; i++; } } if (i == ca.length - 1) { build.append(lowercase ? toLowerCase(ca[i]) : ca[i]); } return build.toString(); }
[ "public", "static", "String", "unCamel", "(", "String", "str", ",", "char", "seperator", ",", "boolean", "lowercase", ")", "{", "char", "[", "]", "ca", "=", "str", ".", "toCharArray", "(", ")", ";", "if", "(", "3", ">", "ca", ".", "length", ")", "{", "return", "lowercase", "?", "str", ".", "toLowerCase", "(", ")", ":", "str", ";", "}", "// about five seperator", "StringBuilder", "build", "=", "new", "StringBuilder", "(", "ca", ".", "length", "+", "5", ")", ";", "build", ".", "append", "(", "lowercase", "?", "toLowerCase", "(", "ca", "[", "0", "]", ")", ":", "ca", "[", "0", "]", ")", ";", "boolean", "lower1", "=", "isLowerCase", "(", "ca", "[", "0", "]", ")", ";", "int", "i", "=", "1", ";", "while", "(", "i", "<", "ca", ".", "length", "-", "1", ")", "{", "char", "cur", "=", "ca", "[", "i", "]", ";", "char", "next", "=", "ca", "[", "i", "+", "1", "]", ";", "boolean", "upper2", "=", "isUpperCase", "(", "cur", ")", ";", "boolean", "lower3", "=", "isLowerCase", "(", "next", ")", ";", "if", "(", "lower1", "&&", "upper2", "&&", "lower3", ")", "{", "build", ".", "append", "(", "seperator", ")", ";", "build", ".", "append", "(", "lowercase", "?", "toLowerCase", "(", "cur", ")", ":", "cur", ")", ";", "build", ".", "append", "(", "next", ")", ";", "i", "+=", "2", ";", "}", "else", "{", "if", "(", "lowercase", "&&", "upper2", ")", "{", "build", ".", "append", "(", "toLowerCase", "(", "cur", ")", ")", ";", "}", "else", "{", "build", ".", "append", "(", "cur", ")", ";", "}", "lower1", "=", "!", "upper2", ";", "i", "++", ";", "}", "}", "if", "(", "i", "==", "ca", ".", "length", "-", "1", ")", "{", "build", ".", "append", "(", "lowercase", "?", "toLowerCase", "(", "ca", "[", "i", "]", ")", ":", "ca", "[", "i", "]", ")", ";", "}", "return", "build", ".", "toString", "(", ")", ";", "}" ]
将驼峰表示法转换为下划线小写表示 @param str a {@link java.lang.String} object. @param seperator a char. @param lowercase a boolean. @return a {@link java.lang.String} object.
[ "将驼峰表示法转换为下划线小写表示" ]
train
https://github.com/beangle/beangle3/blob/33df2873a5f38e28ac174a1d3b8144eb2f808e64/commons/core/src/main/java/org/beangle/commons/lang/Strings.java#L1142-L1175
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/security/KeyRep.java
KeyRep.readResolve
protected Object readResolve() throws ObjectStreamException { """ Resolve the Key object. <p> This method supports three Type/format combinations: <ul> <li> Type.SECRET/"RAW" - returns a SecretKeySpec object constructed using encoded key bytes and algorithm <li> Type.PUBLIC/"X.509" - gets a KeyFactory instance for the key algorithm, constructs an X509EncodedKeySpec with the encoded key bytes, and generates a public key from the spec <li> Type.PRIVATE/"PKCS#8" - gets a KeyFactory instance for the key algorithm, constructs a PKCS8EncodedKeySpec with the encoded key bytes, and generates a private key from the spec </ul> <p> @return the resolved Key object @exception ObjectStreamException if the Type/format combination is unrecognized, if the algorithm, key format, or encoded key bytes are unrecognized/invalid, of if the resolution of the key fails for any reason """ try { if (type == Type.SECRET && RAW.equals(format)) { return new SecretKeySpec(encoded, algorithm); } else if (type == Type.PUBLIC && X509.equals(format)) { KeyFactory f = KeyFactory.getInstance(algorithm); return f.generatePublic(new X509EncodedKeySpec(encoded)); } else if (type == Type.PRIVATE && PKCS8.equals(format)) { KeyFactory f = KeyFactory.getInstance(algorithm); return f.generatePrivate(new PKCS8EncodedKeySpec(encoded)); } else { throw new NotSerializableException ("unrecognized type/format combination: " + type + "/" + format); } } catch (NotSerializableException nse) { throw nse; } catch (Exception e) { NotSerializableException nse = new NotSerializableException ("java.security.Key: " + "[" + type + "] " + "[" + algorithm + "] " + "[" + format + "]"); nse.initCause(e); throw nse; } }
java
protected Object readResolve() throws ObjectStreamException { try { if (type == Type.SECRET && RAW.equals(format)) { return new SecretKeySpec(encoded, algorithm); } else if (type == Type.PUBLIC && X509.equals(format)) { KeyFactory f = KeyFactory.getInstance(algorithm); return f.generatePublic(new X509EncodedKeySpec(encoded)); } else if (type == Type.PRIVATE && PKCS8.equals(format)) { KeyFactory f = KeyFactory.getInstance(algorithm); return f.generatePrivate(new PKCS8EncodedKeySpec(encoded)); } else { throw new NotSerializableException ("unrecognized type/format combination: " + type + "/" + format); } } catch (NotSerializableException nse) { throw nse; } catch (Exception e) { NotSerializableException nse = new NotSerializableException ("java.security.Key: " + "[" + type + "] " + "[" + algorithm + "] " + "[" + format + "]"); nse.initCause(e); throw nse; } }
[ "protected", "Object", "readResolve", "(", ")", "throws", "ObjectStreamException", "{", "try", "{", "if", "(", "type", "==", "Type", ".", "SECRET", "&&", "RAW", ".", "equals", "(", "format", ")", ")", "{", "return", "new", "SecretKeySpec", "(", "encoded", ",", "algorithm", ")", ";", "}", "else", "if", "(", "type", "==", "Type", ".", "PUBLIC", "&&", "X509", ".", "equals", "(", "format", ")", ")", "{", "KeyFactory", "f", "=", "KeyFactory", ".", "getInstance", "(", "algorithm", ")", ";", "return", "f", ".", "generatePublic", "(", "new", "X509EncodedKeySpec", "(", "encoded", ")", ")", ";", "}", "else", "if", "(", "type", "==", "Type", ".", "PRIVATE", "&&", "PKCS8", ".", "equals", "(", "format", ")", ")", "{", "KeyFactory", "f", "=", "KeyFactory", ".", "getInstance", "(", "algorithm", ")", ";", "return", "f", ".", "generatePrivate", "(", "new", "PKCS8EncodedKeySpec", "(", "encoded", ")", ")", ";", "}", "else", "{", "throw", "new", "NotSerializableException", "(", "\"unrecognized type/format combination: \"", "+", "type", "+", "\"/\"", "+", "format", ")", ";", "}", "}", "catch", "(", "NotSerializableException", "nse", ")", "{", "throw", "nse", ";", "}", "catch", "(", "Exception", "e", ")", "{", "NotSerializableException", "nse", "=", "new", "NotSerializableException", "(", "\"java.security.Key: \"", "+", "\"[\"", "+", "type", "+", "\"] \"", "+", "\"[\"", "+", "algorithm", "+", "\"] \"", "+", "\"[\"", "+", "format", "+", "\"]\"", ")", ";", "nse", ".", "initCause", "(", "e", ")", ";", "throw", "nse", ";", "}", "}" ]
Resolve the Key object. <p> This method supports three Type/format combinations: <ul> <li> Type.SECRET/"RAW" - returns a SecretKeySpec object constructed using encoded key bytes and algorithm <li> Type.PUBLIC/"X.509" - gets a KeyFactory instance for the key algorithm, constructs an X509EncodedKeySpec with the encoded key bytes, and generates a public key from the spec <li> Type.PRIVATE/"PKCS#8" - gets a KeyFactory instance for the key algorithm, constructs a PKCS8EncodedKeySpec with the encoded key bytes, and generates a private key from the spec </ul> <p> @return the resolved Key object @exception ObjectStreamException if the Type/format combination is unrecognized, if the algorithm, key format, or encoded key bytes are unrecognized/invalid, of if the resolution of the key fails for any reason
[ "Resolve", "the", "Key", "object", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/security/KeyRep.java#L169-L195
cryptomator/webdav-nio-adapter
src/main/java/org/cryptomator/frontend/webdav/WebDavServer.java
WebDavServer.createWebDavServlet
public WebDavServletController createWebDavServlet(Path rootPath, String contextPath) { """ Creates a new WebDAV servlet (without starting it yet). @param rootPath The path to the directory which should be served as root resource. @param contextPath The servlet context path, i.e. the path of the root resource. @return The controller object for this new servlet """ WebDavServletComponent servletComp = servletFactory.create(rootPath, contextPath); return servletComp.servlet(); }
java
public WebDavServletController createWebDavServlet(Path rootPath, String contextPath) { WebDavServletComponent servletComp = servletFactory.create(rootPath, contextPath); return servletComp.servlet(); }
[ "public", "WebDavServletController", "createWebDavServlet", "(", "Path", "rootPath", ",", "String", "contextPath", ")", "{", "WebDavServletComponent", "servletComp", "=", "servletFactory", ".", "create", "(", "rootPath", ",", "contextPath", ")", ";", "return", "servletComp", ".", "servlet", "(", ")", ";", "}" ]
Creates a new WebDAV servlet (without starting it yet). @param rootPath The path to the directory which should be served as root resource. @param contextPath The servlet context path, i.e. the path of the root resource. @return The controller object for this new servlet
[ "Creates", "a", "new", "WebDAV", "servlet", "(", "without", "starting", "it", "yet", ")", "." ]
train
https://github.com/cryptomator/webdav-nio-adapter/blob/55b0d7dccea9a4ede0a30a95583d8f04c8a86d18/src/main/java/org/cryptomator/frontend/webdav/WebDavServer.java#L137-L140
box/box-android-sdk
box-content-sdk/src/main/java/com/box/androidsdk/content/requests/BoxHttpRequest.java
BoxHttpRequest.addHeader
public BoxHttpRequest addHeader(String key, String value) { """ Adds an HTTP header to the request. @param key the header key. @param value the header value. @return request with the updated header. """ mUrlConnection.addRequestProperty(key, value); return this; }
java
public BoxHttpRequest addHeader(String key, String value) { mUrlConnection.addRequestProperty(key, value); return this; }
[ "public", "BoxHttpRequest", "addHeader", "(", "String", "key", ",", "String", "value", ")", "{", "mUrlConnection", ".", "addRequestProperty", "(", "key", ",", "value", ")", ";", "return", "this", ";", "}" ]
Adds an HTTP header to the request. @param key the header key. @param value the header value. @return request with the updated header.
[ "Adds", "an", "HTTP", "header", "to", "the", "request", "." ]
train
https://github.com/box/box-android-sdk/blob/a621ad5ddebf23067fec27529130d72718fc0e88/box-content-sdk/src/main/java/com/box/androidsdk/content/requests/BoxHttpRequest.java#L49-L52
jbundle/jbundle
base/base/src/main/java/org/jbundle/base/field/event/CopySoundexHandler.java
CopySoundexHandler.syncClonedListener
public boolean syncClonedListener(BaseField field, FieldListener listener, boolean bInitCalled) { """ Set this cloned listener to the same state at this listener. @param field The field this new listener will be added to. @param The new listener to sync to this. @param Has the init method been called? @return True if I called init. """ if (!bInitCalled) ((CopySoundexHandler)listener).init(null, m_iFieldSeq); return super.syncClonedListener(field, listener, true); }
java
public boolean syncClonedListener(BaseField field, FieldListener listener, boolean bInitCalled) { if (!bInitCalled) ((CopySoundexHandler)listener).init(null, m_iFieldSeq); return super.syncClonedListener(field, listener, true); }
[ "public", "boolean", "syncClonedListener", "(", "BaseField", "field", ",", "FieldListener", "listener", ",", "boolean", "bInitCalled", ")", "{", "if", "(", "!", "bInitCalled", ")", "(", "(", "CopySoundexHandler", ")", "listener", ")", ".", "init", "(", "null", ",", "m_iFieldSeq", ")", ";", "return", "super", ".", "syncClonedListener", "(", "field", ",", "listener", ",", "true", ")", ";", "}" ]
Set this cloned listener to the same state at this listener. @param field The field this new listener will be added to. @param The new listener to sync to this. @param Has the init method been called? @return True if I called init.
[ "Set", "this", "cloned", "listener", "to", "the", "same", "state", "at", "this", "listener", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/field/event/CopySoundexHandler.java#L63-L68
OpenLiberty/open-liberty
dev/com.ibm.ws.jdbc/src/com/ibm/ws/rsadapter/impl/WSRdbManagedConnectionImpl.java
WSRdbManagedConnectionImpl.cacheStatement
public final void cacheStatement(Statement statement, StatementCacheKey key) { """ Returns the statement into the cache. The statement is closed if an error occurs attempting to cache it. This method will only called if statement caching was enabled at some point, although it might not be enabled anymore. @param statement the statement to return to the cache. @param key the statement cache key. """ if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) Tr.event(this, tc, "cacheStatement", AdapterUtil.toString(statement), key); // Add the statement to the cache. If there is no room in the cache, a statement from // the least recently used bucket will be cast out of the cache. Any statement cast // out of the cache must be closed. CacheMap cache = getStatementCache(); Object discardedStatement = cache == null ? statement : statementCache.add(key, statement); if (discardedStatement != null) destroyStatement(discardedStatement); }
java
public final void cacheStatement(Statement statement, StatementCacheKey key) { if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) Tr.event(this, tc, "cacheStatement", AdapterUtil.toString(statement), key); // Add the statement to the cache. If there is no room in the cache, a statement from // the least recently used bucket will be cast out of the cache. Any statement cast // out of the cache must be closed. CacheMap cache = getStatementCache(); Object discardedStatement = cache == null ? statement : statementCache.add(key, statement); if (discardedStatement != null) destroyStatement(discardedStatement); }
[ "public", "final", "void", "cacheStatement", "(", "Statement", "statement", ",", "StatementCacheKey", "key", ")", "{", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEventEnabled", "(", ")", ")", "Tr", ".", "event", "(", "this", ",", "tc", ",", "\"cacheStatement\"", ",", "AdapterUtil", ".", "toString", "(", "statement", ")", ",", "key", ")", ";", "// Add the statement to the cache. If there is no room in the cache, a statement from", "// the least recently used bucket will be cast out of the cache. Any statement cast", "// out of the cache must be closed. ", "CacheMap", "cache", "=", "getStatementCache", "(", ")", ";", "Object", "discardedStatement", "=", "cache", "==", "null", "?", "statement", ":", "statementCache", ".", "add", "(", "key", ",", "statement", ")", ";", "if", "(", "discardedStatement", "!=", "null", ")", "destroyStatement", "(", "discardedStatement", ")", ";", "}" ]
Returns the statement into the cache. The statement is closed if an error occurs attempting to cache it. This method will only called if statement caching was enabled at some point, although it might not be enabled anymore. @param statement the statement to return to the cache. @param key the statement cache key.
[ "Returns", "the", "statement", "into", "the", "cache", ".", "The", "statement", "is", "closed", "if", "an", "error", "occurs", "attempting", "to", "cache", "it", ".", "This", "method", "will", "only", "called", "if", "statement", "caching", "was", "enabled", "at", "some", "point", "although", "it", "might", "not", "be", "enabled", "anymore", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jdbc/src/com/ibm/ws/rsadapter/impl/WSRdbManagedConnectionImpl.java#L2244-L2257
structurizr/java
structurizr-core/src/com/structurizr/documentation/Arc42DocumentationTemplate.java
Arc42DocumentationTemplate.addContextAndScopeSection
public Section addContextAndScopeSection(SoftwareSystem softwareSystem, File... files) throws IOException { """ Adds a "Context and Scope" section relating to a {@link SoftwareSystem} from one or more files. @param softwareSystem the {@link SoftwareSystem} the documentation content relates to @param files one or more File objects that point to the documentation content @return a documentation {@link Section} @throws IOException if there is an error reading the files """ return addSection(softwareSystem, "Context and Scope", files); }
java
public Section addContextAndScopeSection(SoftwareSystem softwareSystem, File... files) throws IOException { return addSection(softwareSystem, "Context and Scope", files); }
[ "public", "Section", "addContextAndScopeSection", "(", "SoftwareSystem", "softwareSystem", ",", "File", "...", "files", ")", "throws", "IOException", "{", "return", "addSection", "(", "softwareSystem", ",", "\"Context and Scope\"", ",", "files", ")", ";", "}" ]
Adds a "Context and Scope" section relating to a {@link SoftwareSystem} from one or more files. @param softwareSystem the {@link SoftwareSystem} the documentation content relates to @param files one or more File objects that point to the documentation content @return a documentation {@link Section} @throws IOException if there is an error reading the files
[ "Adds", "a", "Context", "and", "Scope", "section", "relating", "to", "a", "{", "@link", "SoftwareSystem", "}", "from", "one", "or", "more", "files", "." ]
train
https://github.com/structurizr/java/blob/4b204f077877a24bcac363f5ecf0e129a0f9f4c5/structurizr-core/src/com/structurizr/documentation/Arc42DocumentationTemplate.java#L97-L99
maven-nar/nar-maven-plugin
src/main/java/com/github/maven_nar/cpptasks/CUtil.java
CUtil.getExecutableLocation
public static File getExecutableLocation(final String exeName) { """ Gets the parent directory for the executable file name using the current directory and system executable path @param exeName Name of executable such as "cl.exe" @return parent directory or null if not located """ // // must add current working directory to the // from of the path from the "path" environment variable final File currentDir = new File(System.getProperty("user.dir")); if (new File(currentDir, exeName).exists()) { return currentDir; } final File[] envPath = CUtil.getPathFromEnvironment("PATH", File.pathSeparator); for (final File element : envPath) { if (new File(element, exeName).exists()) { return element; } } return null; }
java
public static File getExecutableLocation(final String exeName) { // // must add current working directory to the // from of the path from the "path" environment variable final File currentDir = new File(System.getProperty("user.dir")); if (new File(currentDir, exeName).exists()) { return currentDir; } final File[] envPath = CUtil.getPathFromEnvironment("PATH", File.pathSeparator); for (final File element : envPath) { if (new File(element, exeName).exists()) { return element; } } return null; }
[ "public", "static", "File", "getExecutableLocation", "(", "final", "String", "exeName", ")", "{", "//", "// must add current working directory to the", "// from of the path from the \"path\" environment variable", "final", "File", "currentDir", "=", "new", "File", "(", "System", ".", "getProperty", "(", "\"user.dir\"", ")", ")", ";", "if", "(", "new", "File", "(", "currentDir", ",", "exeName", ")", ".", "exists", "(", ")", ")", "{", "return", "currentDir", ";", "}", "final", "File", "[", "]", "envPath", "=", "CUtil", ".", "getPathFromEnvironment", "(", "\"PATH\"", ",", "File", ".", "pathSeparator", ")", ";", "for", "(", "final", "File", "element", ":", "envPath", ")", "{", "if", "(", "new", "File", "(", "element", ",", "exeName", ")", ".", "exists", "(", ")", ")", "{", "return", "element", ";", "}", "}", "return", "null", ";", "}" ]
Gets the parent directory for the executable file name using the current directory and system executable path @param exeName Name of executable such as "cl.exe" @return parent directory or null if not located
[ "Gets", "the", "parent", "directory", "for", "the", "executable", "file", "name", "using", "the", "current", "directory", "and", "system", "executable", "path" ]
train
https://github.com/maven-nar/nar-maven-plugin/blob/3c622e2024296b4203431bbae3bde290a01dac00/src/main/java/com/github/maven_nar/cpptasks/CUtil.java#L125-L140
networknt/light-4j
utility/src/main/java/com/networknt/utility/StringUtils.java
StringUtils.containsIgnoreCase
public static boolean containsIgnoreCase(final CharSequence str, final CharSequence searchStr) { """ <p>Checks if CharSequence contains a search CharSequence irrespective of case, handling {@code null}. Case-insensitivity is defined as by {@link String#equalsIgnoreCase(String)}. <p>A {@code null} CharSequence will return {@code false}.</p> <pre> StringUtils.containsIgnoreCase(null, *) = false StringUtils.containsIgnoreCase(*, null) = false StringUtils.containsIgnoreCase("", "") = true StringUtils.containsIgnoreCase("abc", "") = true StringUtils.containsIgnoreCase("abc", "a") = true StringUtils.containsIgnoreCase("abc", "z") = false StringUtils.containsIgnoreCase("abc", "A") = true StringUtils.containsIgnoreCase("abc", "Z") = false </pre> @param str the CharSequence to check, may be null @param searchStr the CharSequence to find, may be null @return true if the CharSequence contains the search CharSequence irrespective of case or false if not or {@code null} string input @since 3.0 Changed signature from containsIgnoreCase(String, String) to containsIgnoreCase(CharSequence, CharSequence) """ if (str == null || searchStr == null) { return false; } final int len = searchStr.length(); final int max = str.length() - len; for (int i = 0; i <= max; i++) { if (CharSequenceUtils.regionMatches(str, true, i, searchStr, 0, len)) { return true; } } return false; }
java
public static boolean containsIgnoreCase(final CharSequence str, final CharSequence searchStr) { if (str == null || searchStr == null) { return false; } final int len = searchStr.length(); final int max = str.length() - len; for (int i = 0; i <= max; i++) { if (CharSequenceUtils.regionMatches(str, true, i, searchStr, 0, len)) { return true; } } return false; }
[ "public", "static", "boolean", "containsIgnoreCase", "(", "final", "CharSequence", "str", ",", "final", "CharSequence", "searchStr", ")", "{", "if", "(", "str", "==", "null", "||", "searchStr", "==", "null", ")", "{", "return", "false", ";", "}", "final", "int", "len", "=", "searchStr", ".", "length", "(", ")", ";", "final", "int", "max", "=", "str", ".", "length", "(", ")", "-", "len", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<=", "max", ";", "i", "++", ")", "{", "if", "(", "CharSequenceUtils", ".", "regionMatches", "(", "str", ",", "true", ",", "i", ",", "searchStr", ",", "0", ",", "len", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
<p>Checks if CharSequence contains a search CharSequence irrespective of case, handling {@code null}. Case-insensitivity is defined as by {@link String#equalsIgnoreCase(String)}. <p>A {@code null} CharSequence will return {@code false}.</p> <pre> StringUtils.containsIgnoreCase(null, *) = false StringUtils.containsIgnoreCase(*, null) = false StringUtils.containsIgnoreCase("", "") = true StringUtils.containsIgnoreCase("abc", "") = true StringUtils.containsIgnoreCase("abc", "a") = true StringUtils.containsIgnoreCase("abc", "z") = false StringUtils.containsIgnoreCase("abc", "A") = true StringUtils.containsIgnoreCase("abc", "Z") = false </pre> @param str the CharSequence to check, may be null @param searchStr the CharSequence to find, may be null @return true if the CharSequence contains the search CharSequence irrespective of case or false if not or {@code null} string input @since 3.0 Changed signature from containsIgnoreCase(String, String) to containsIgnoreCase(CharSequence, CharSequence)
[ "<p", ">", "Checks", "if", "CharSequence", "contains", "a", "search", "CharSequence", "irrespective", "of", "case", "handling", "{", "@code", "null", "}", ".", "Case", "-", "insensitivity", "is", "defined", "as", "by", "{", "@link", "String#equalsIgnoreCase", "(", "String", ")", "}", "." ]
train
https://github.com/networknt/light-4j/blob/2a60257c60663684c8f6dc8b5ea3cf184e534db6/utility/src/main/java/com/networknt/utility/StringUtils.java#L860-L872
before/quality-check
modules/quality-check/src/main/java/net/sf/qualitycheck/ConditionalCheck.java
ConditionalCheck.notEmpty
@ArgumentsChecked @Throws( { """ Ensures that a passed parameter of the calling method is not empty, using the passed expression to evaluate the emptiness. <p> We recommend to use the overloaded method {@link Check#notEmpty(boolean, String)} and pass as second argument the name of the parameter to enhance the exception message. @param condition condition must be {@code true}^ so that the check will be performed @param expression the result of the expression to verify the emptiness of a reference ({@code true} means empty, {@code false} means not empty) @throws IllegalNullArgumentException if the given argument {@code reference} is {@code null} @throws IllegalEmptyArgumentException if the given argument {@code reference} is empty """ IllegalNullArgumentException.class, IllegalEmptyArgumentException.class }) public static void notEmpty(final boolean condition, final boolean expression) { if (condition) { Check.notEmpty(expression); } }
java
@ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEmptyArgumentException.class }) public static void notEmpty(final boolean condition, final boolean expression) { if (condition) { Check.notEmpty(expression); } }
[ "@", "ArgumentsChecked", "@", "Throws", "(", "{", "IllegalNullArgumentException", ".", "class", ",", "IllegalEmptyArgumentException", ".", "class", "}", ")", "public", "static", "void", "notEmpty", "(", "final", "boolean", "condition", ",", "final", "boolean", "expression", ")", "{", "if", "(", "condition", ")", "{", "Check", ".", "notEmpty", "(", "expression", ")", ";", "}", "}" ]
Ensures that a passed parameter of the calling method is not empty, using the passed expression to evaluate the emptiness. <p> We recommend to use the overloaded method {@link Check#notEmpty(boolean, String)} and pass as second argument the name of the parameter to enhance the exception message. @param condition condition must be {@code true}^ so that the check will be performed @param expression the result of the expression to verify the emptiness of a reference ({@code true} means empty, {@code false} means not empty) @throws IllegalNullArgumentException if the given argument {@code reference} is {@code null} @throws IllegalEmptyArgumentException if the given argument {@code reference} is empty
[ "Ensures", "that", "a", "passed", "parameter", "of", "the", "calling", "method", "is", "not", "empty", "using", "the", "passed", "expression", "to", "evaluate", "the", "emptiness", "." ]
train
https://github.com/before/quality-check/blob/a75c32c39434ddb1f89bece57acae0536724c15a/modules/quality-check/src/main/java/net/sf/qualitycheck/ConditionalCheck.java#L1160-L1166
adamfisk/littleshoot-util
src/main/java/org/littleshoot/util/BeanUtils.java
BeanUtils.mapBean
public static Map<String, String> mapBean(final Object bean, final String exclude) { """ Creates a {@link Map} from all bean data get methods except the one specified to exclude. Note that "getClass" is always excluded. @param bean The bean with data to extract. @param exclude A method name to exclude. @return The map of bean data. """ final Set<String> excludes = new HashSet<String>(); if (!StringUtils.isBlank(exclude)) { excludes.add(exclude); } return mapBean(bean, excludes); }
java
public static Map<String, String> mapBean(final Object bean, final String exclude) { final Set<String> excludes = new HashSet<String>(); if (!StringUtils.isBlank(exclude)) { excludes.add(exclude); } return mapBean(bean, excludes); }
[ "public", "static", "Map", "<", "String", ",", "String", ">", "mapBean", "(", "final", "Object", "bean", ",", "final", "String", "exclude", ")", "{", "final", "Set", "<", "String", ">", "excludes", "=", "new", "HashSet", "<", "String", ">", "(", ")", ";", "if", "(", "!", "StringUtils", ".", "isBlank", "(", "exclude", ")", ")", "{", "excludes", ".", "add", "(", "exclude", ")", ";", "}", "return", "mapBean", "(", "bean", ",", "excludes", ")", ";", "}" ]
Creates a {@link Map} from all bean data get methods except the one specified to exclude. Note that "getClass" is always excluded. @param bean The bean with data to extract. @param exclude A method name to exclude. @return The map of bean data.
[ "Creates", "a", "{", "@link", "Map", "}", "from", "all", "bean", "data", "get", "methods", "except", "the", "one", "specified", "to", "exclude", ".", "Note", "that", "getClass", "is", "always", "excluded", "." ]
train
https://github.com/adamfisk/littleshoot-util/blob/3c0dc4955116b3382d6b0575d2f164b7508a4f73/src/main/java/org/littleshoot/util/BeanUtils.java#L50-L59
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/learning/NesterovsUpdater.java
NesterovsUpdater.applyUpdater
@Override public void applyUpdater(INDArray gradient, int iteration, int epoch) { """ Get the nesterov update @param gradient the gradient to get the update for @param iteration @return """ if (v == null) throw new IllegalStateException("Updater has not been initialized with view state"); double momentum = config.currentMomentum(iteration, epoch); double learningRate = config.getLearningRate(iteration, epoch); //reference https://cs231n.github.io/neural-networks-3/#sgd 2nd equation //DL4J default is negative step function thus we flipped the signs: // x += mu * v_prev + (-1 - mu) * v //i.e., we do params -= updatedGradient, not params += updatedGradient //v = mu * v - lr * gradient INDArray vPrev = v.dup(gradientReshapeOrder); v.muli(momentum).subi(gradient.dup(gradientReshapeOrder).muli(learningRate)); //Modify state array in-place /* Next line is equivalent to: INDArray ret = vPrev.muli(momentum).addi(v.mul(-momentum - 1)); gradient.assign(ret); */ Nd4j.getExecutioner().exec(new OldAddOp(vPrev.muli(momentum), v.mul(-momentum - 1), gradient)); }
java
@Override public void applyUpdater(INDArray gradient, int iteration, int epoch) { if (v == null) throw new IllegalStateException("Updater has not been initialized with view state"); double momentum = config.currentMomentum(iteration, epoch); double learningRate = config.getLearningRate(iteration, epoch); //reference https://cs231n.github.io/neural-networks-3/#sgd 2nd equation //DL4J default is negative step function thus we flipped the signs: // x += mu * v_prev + (-1 - mu) * v //i.e., we do params -= updatedGradient, not params += updatedGradient //v = mu * v - lr * gradient INDArray vPrev = v.dup(gradientReshapeOrder); v.muli(momentum).subi(gradient.dup(gradientReshapeOrder).muli(learningRate)); //Modify state array in-place /* Next line is equivalent to: INDArray ret = vPrev.muli(momentum).addi(v.mul(-momentum - 1)); gradient.assign(ret); */ Nd4j.getExecutioner().exec(new OldAddOp(vPrev.muli(momentum), v.mul(-momentum - 1), gradient)); }
[ "@", "Override", "public", "void", "applyUpdater", "(", "INDArray", "gradient", ",", "int", "iteration", ",", "int", "epoch", ")", "{", "if", "(", "v", "==", "null", ")", "throw", "new", "IllegalStateException", "(", "\"Updater has not been initialized with view state\"", ")", ";", "double", "momentum", "=", "config", ".", "currentMomentum", "(", "iteration", ",", "epoch", ")", ";", "double", "learningRate", "=", "config", ".", "getLearningRate", "(", "iteration", ",", "epoch", ")", ";", "//reference https://cs231n.github.io/neural-networks-3/#sgd 2nd equation", "//DL4J default is negative step function thus we flipped the signs:", "// x += mu * v_prev + (-1 - mu) * v", "//i.e., we do params -= updatedGradient, not params += updatedGradient", "//v = mu * v - lr * gradient", "INDArray", "vPrev", "=", "v", ".", "dup", "(", "gradientReshapeOrder", ")", ";", "v", ".", "muli", "(", "momentum", ")", ".", "subi", "(", "gradient", ".", "dup", "(", "gradientReshapeOrder", ")", ".", "muli", "(", "learningRate", ")", ")", ";", "//Modify state array in-place", "/*\n Next line is equivalent to:\n INDArray ret = vPrev.muli(momentum).addi(v.mul(-momentum - 1));\n gradient.assign(ret);\n */", "Nd4j", ".", "getExecutioner", "(", ")", ".", "exec", "(", "new", "OldAddOp", "(", "vPrev", ".", "muli", "(", "momentum", ")", ",", "v", ".", "mul", "(", "-", "momentum", "-", "1", ")", ",", "gradient", ")", ")", ";", "}" ]
Get the nesterov update @param gradient the gradient to get the update for @param iteration @return
[ "Get", "the", "nesterov", "update" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/learning/NesterovsUpdater.java#L68-L91
Baidu-AIP/java-sdk
src/main/java/com/baidu/aip/kg/AipKnowledgeGraphic.java
AipKnowledgeGraphic.createTask
public JSONObject createTask(String name, String templateContent, String inputMappingFile, String outputFile, String urlPattern, HashMap<String, String> options) { """ 创建任务接口 创建一个新的信息抽取任务 @param name - 任务名字 @param templateContent - json string 解析模板内容 @param inputMappingFile - 抓取结果映射文件的路径 @param outputFile - 输出文件名字 @param urlPattern - url pattern @param options - 可选参数对象,key: value都为string类型 options - options列表: limit_count 限制解析数量limit_count为0时进行全量任务,limit_count&gt;0时只解析limit_count数量的页面 @return JSONObject """ AipRequest request = new AipRequest(); preOperation(request); request.addBody("name", name); request.addBody("template_content", templateContent); request.addBody("input_mapping_file", inputMappingFile); request.addBody("output_file", outputFile); request.addBody("url_pattern", urlPattern); if (options != null) { request.addBody(options); } request.setUri(KnowledgeGraphicConsts.CREATE_TASK); postOperation(request); return requestServer(request); }
java
public JSONObject createTask(String name, String templateContent, String inputMappingFile, String outputFile, String urlPattern, HashMap<String, String> options) { AipRequest request = new AipRequest(); preOperation(request); request.addBody("name", name); request.addBody("template_content", templateContent); request.addBody("input_mapping_file", inputMappingFile); request.addBody("output_file", outputFile); request.addBody("url_pattern", urlPattern); if (options != null) { request.addBody(options); } request.setUri(KnowledgeGraphicConsts.CREATE_TASK); postOperation(request); return requestServer(request); }
[ "public", "JSONObject", "createTask", "(", "String", "name", ",", "String", "templateContent", ",", "String", "inputMappingFile", ",", "String", "outputFile", ",", "String", "urlPattern", ",", "HashMap", "<", "String", ",", "String", ">", "options", ")", "{", "AipRequest", "request", "=", "new", "AipRequest", "(", ")", ";", "preOperation", "(", "request", ")", ";", "request", ".", "addBody", "(", "\"name\"", ",", "name", ")", ";", "request", ".", "addBody", "(", "\"template_content\"", ",", "templateContent", ")", ";", "request", ".", "addBody", "(", "\"input_mapping_file\"", ",", "inputMappingFile", ")", ";", "request", ".", "addBody", "(", "\"output_file\"", ",", "outputFile", ")", ";", "request", ".", "addBody", "(", "\"url_pattern\"", ",", "urlPattern", ")", ";", "if", "(", "options", "!=", "null", ")", "{", "request", ".", "addBody", "(", "options", ")", ";", "}", "request", ".", "setUri", "(", "KnowledgeGraphicConsts", ".", "CREATE_TASK", ")", ";", "postOperation", "(", "request", ")", ";", "return", "requestServer", "(", "request", ")", ";", "}" ]
创建任务接口 创建一个新的信息抽取任务 @param name - 任务名字 @param templateContent - json string 解析模板内容 @param inputMappingFile - 抓取结果映射文件的路径 @param outputFile - 输出文件名字 @param urlPattern - url pattern @param options - 可选参数对象,key: value都为string类型 options - options列表: limit_count 限制解析数量limit_count为0时进行全量任务,limit_count&gt;0时只解析limit_count数量的页面 @return JSONObject
[ "创建任务接口", "创建一个新的信息抽取任务" ]
train
https://github.com/Baidu-AIP/java-sdk/blob/16bb8b7bb8f9bbcb7c8af62d0a67a1e79eecad90/src/main/java/com/baidu/aip/kg/AipKnowledgeGraphic.java#L42-L61
thymeleaf/thymeleaf-spring
thymeleaf-spring4/src/main/java/org/thymeleaf/spring4/view/AbstractThymeleafView.java
AbstractThymeleafView.setStaticVariables
public void setStaticVariables(final Map<String, ?> variables) { """ <p> Sets a set of static variables, which will be available at the context when this view is processed. </p> <p> This method <b>does not overwrite</b> the existing static variables, it simply adds the ones specify to any variables already registered. </p> <p> These static variables are added to the context before this view is processed, so that they can be referenced from the context like any other context variables, for example: {@code ${myStaticVar}}. </p> @param variables the set of variables to be added. """ if (variables != null) { if (this.staticVariables == null) { this.staticVariables = new HashMap<String, Object>(3, 1.0f); } this.staticVariables.putAll(variables); } }
java
public void setStaticVariables(final Map<String, ?> variables) { if (variables != null) { if (this.staticVariables == null) { this.staticVariables = new HashMap<String, Object>(3, 1.0f); } this.staticVariables.putAll(variables); } }
[ "public", "void", "setStaticVariables", "(", "final", "Map", "<", "String", ",", "?", ">", "variables", ")", "{", "if", "(", "variables", "!=", "null", ")", "{", "if", "(", "this", ".", "staticVariables", "==", "null", ")", "{", "this", ".", "staticVariables", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", "3", ",", "1.0f", ")", ";", "}", "this", ".", "staticVariables", ".", "putAll", "(", "variables", ")", ";", "}", "}" ]
<p> Sets a set of static variables, which will be available at the context when this view is processed. </p> <p> This method <b>does not overwrite</b> the existing static variables, it simply adds the ones specify to any variables already registered. </p> <p> These static variables are added to the context before this view is processed, so that they can be referenced from the context like any other context variables, for example: {@code ${myStaticVar}}. </p> @param variables the set of variables to be added.
[ "<p", ">", "Sets", "a", "set", "of", "static", "variables", "which", "will", "be", "available", "at", "the", "context", "when", "this", "view", "is", "processed", ".", "<", "/", "p", ">", "<p", ">", "This", "method", "<b", ">", "does", "not", "overwrite<", "/", "b", ">", "the", "existing", "static", "variables", "it", "simply", "adds", "the", "ones", "specify", "to", "any", "variables", "already", "registered", ".", "<", "/", "p", ">", "<p", ">", "These", "static", "variables", "are", "added", "to", "the", "context", "before", "this", "view", "is", "processed", "so", "that", "they", "can", "be", "referenced", "from", "the", "context", "like", "any", "other", "context", "variables", "for", "example", ":", "{", "@code", "$", "{", "myStaticVar", "}}", ".", "<", "/", "p", ">" ]
train
https://github.com/thymeleaf/thymeleaf-spring/blob/9aa15a19017a0938e57646e3deefb8a90ab78dcb/thymeleaf-spring4/src/main/java/org/thymeleaf/spring4/view/AbstractThymeleafView.java#L531-L538
Azure/azure-sdk-for-java
edgegateway/resource-manager/v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/implementation/SharesInner.java
SharesInner.getAsync
public Observable<ShareInner> getAsync(String deviceName, String name, String resourceGroupName) { """ Gets a share by name. @param deviceName The device name. @param name The share name. @param resourceGroupName The resource group name. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the ShareInner object """ return getWithServiceResponseAsync(deviceName, name, resourceGroupName).map(new Func1<ServiceResponse<ShareInner>, ShareInner>() { @Override public ShareInner call(ServiceResponse<ShareInner> response) { return response.body(); } }); }
java
public Observable<ShareInner> getAsync(String deviceName, String name, String resourceGroupName) { return getWithServiceResponseAsync(deviceName, name, resourceGroupName).map(new Func1<ServiceResponse<ShareInner>, ShareInner>() { @Override public ShareInner call(ServiceResponse<ShareInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "ShareInner", ">", "getAsync", "(", "String", "deviceName", ",", "String", "name", ",", "String", "resourceGroupName", ")", "{", "return", "getWithServiceResponseAsync", "(", "deviceName", ",", "name", ",", "resourceGroupName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "ShareInner", ">", ",", "ShareInner", ">", "(", ")", "{", "@", "Override", "public", "ShareInner", "call", "(", "ServiceResponse", "<", "ShareInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Gets a share by name. @param deviceName The device name. @param name The share name. @param resourceGroupName The resource group name. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the ShareInner object
[ "Gets", "a", "share", "by", "name", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/edgegateway/resource-manager/v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/implementation/SharesInner.java#L264-L271
lessthanoptimal/BoofCV
main/boofcv-geo/src/main/java/boofcv/alg/geo/MultiViewOps.java
MultiViewOps.rectifyHToAbsoluteQuadratic
public static void rectifyHToAbsoluteQuadratic(DMatrixRMaj H , DMatrixRMaj Q ) { """ Rectifying homography to dual absolute quadratic. <p>Q = H*I*H<sup>T</sup> = H(:,1:3)*H(:,1:3)'</p> <p>where I = diag(1 1 1 0)</p> @param H (Input) 4x4 rectifying homography. @param Q (Output) Absolute quadratic. Typically found in auto calibration. Not modified. """ int indexQ = 0; for (int rowA = 0; rowA < 4; rowA++) { for (int colB = 0; colB < 4; colB++) { int indexA = rowA*4; int indexB = colB*4; double sum = 0; for (int i = 0; i < 3; i++) { // sum += H.get(rowA,i)*H.get(colB,i); sum += H.data[indexA++]*H.data[indexB++]; } // Q.set(rowA,colB,sum); Q.data[indexQ++] = sum; } } }
java
public static void rectifyHToAbsoluteQuadratic(DMatrixRMaj H , DMatrixRMaj Q ) { int indexQ = 0; for (int rowA = 0; rowA < 4; rowA++) { for (int colB = 0; colB < 4; colB++) { int indexA = rowA*4; int indexB = colB*4; double sum = 0; for (int i = 0; i < 3; i++) { // sum += H.get(rowA,i)*H.get(colB,i); sum += H.data[indexA++]*H.data[indexB++]; } // Q.set(rowA,colB,sum); Q.data[indexQ++] = sum; } } }
[ "public", "static", "void", "rectifyHToAbsoluteQuadratic", "(", "DMatrixRMaj", "H", ",", "DMatrixRMaj", "Q", ")", "{", "int", "indexQ", "=", "0", ";", "for", "(", "int", "rowA", "=", "0", ";", "rowA", "<", "4", ";", "rowA", "++", ")", "{", "for", "(", "int", "colB", "=", "0", ";", "colB", "<", "4", ";", "colB", "++", ")", "{", "int", "indexA", "=", "rowA", "*", "4", ";", "int", "indexB", "=", "colB", "*", "4", ";", "double", "sum", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "3", ";", "i", "++", ")", "{", "//\t\t\t\t\tsum += H.get(rowA,i)*H.get(colB,i);", "sum", "+=", "H", ".", "data", "[", "indexA", "++", "]", "*", "H", ".", "data", "[", "indexB", "++", "]", ";", "}", "//\t\t\t\tQ.set(rowA,colB,sum);", "Q", ".", "data", "[", "indexQ", "++", "]", "=", "sum", ";", "}", "}", "}" ]
Rectifying homography to dual absolute quadratic. <p>Q = H*I*H<sup>T</sup> = H(:,1:3)*H(:,1:3)'</p> <p>where I = diag(1 1 1 0)</p> @param H (Input) 4x4 rectifying homography. @param Q (Output) Absolute quadratic. Typically found in auto calibration. Not modified.
[ "Rectifying", "homography", "to", "dual", "absolute", "quadratic", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/MultiViewOps.java#L1489-L1506
hyperledger/fabric-sdk-java
src/main/java/org/hyperledger/fabric/sdk/Channel.java
Channel.registerBlockListener
public String registerBlockListener(BlockingQueue<QueuedBlockEvent> blockEventQueue, long timeout, TimeUnit timeUnit) throws InvalidArgumentException { """ Register a Queued block listener. This queue should never block insertion of events. @param blockEventQueue the queue @param timeout The time that is waited on for event to be waited on the queue @param timeUnit the time unit for timeout. @return return a handle to ungregister the handler. @throws InvalidArgumentException """ if (shutdown) { throw new InvalidArgumentException(format("Channel %s has been shutdown.", name)); } if (null == blockEventQueue) { throw new InvalidArgumentException("BlockEventQueue parameter is null."); } if (timeout < 0L) { throw new InvalidArgumentException(format("Timeout parameter must be greater than 0 not %d", timeout)); } if (null == timeUnit) { throw new InvalidArgumentException("TimeUnit parameter must not be null."); } String handle = new BL(blockEventQueue, timeout, timeUnit).getHandle(); logger.trace(format("Register QueuedBlockEvent listener %s", handle)); return handle; }
java
public String registerBlockListener(BlockingQueue<QueuedBlockEvent> blockEventQueue, long timeout, TimeUnit timeUnit) throws InvalidArgumentException { if (shutdown) { throw new InvalidArgumentException(format("Channel %s has been shutdown.", name)); } if (null == blockEventQueue) { throw new InvalidArgumentException("BlockEventQueue parameter is null."); } if (timeout < 0L) { throw new InvalidArgumentException(format("Timeout parameter must be greater than 0 not %d", timeout)); } if (null == timeUnit) { throw new InvalidArgumentException("TimeUnit parameter must not be null."); } String handle = new BL(blockEventQueue, timeout, timeUnit).getHandle(); logger.trace(format("Register QueuedBlockEvent listener %s", handle)); return handle; }
[ "public", "String", "registerBlockListener", "(", "BlockingQueue", "<", "QueuedBlockEvent", ">", "blockEventQueue", ",", "long", "timeout", ",", "TimeUnit", "timeUnit", ")", "throws", "InvalidArgumentException", "{", "if", "(", "shutdown", ")", "{", "throw", "new", "InvalidArgumentException", "(", "format", "(", "\"Channel %s has been shutdown.\"", ",", "name", ")", ")", ";", "}", "if", "(", "null", "==", "blockEventQueue", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"BlockEventQueue parameter is null.\"", ")", ";", "}", "if", "(", "timeout", "<", "0L", ")", "{", "throw", "new", "InvalidArgumentException", "(", "format", "(", "\"Timeout parameter must be greater than 0 not %d\"", ",", "timeout", ")", ")", ";", "}", "if", "(", "null", "==", "timeUnit", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"TimeUnit parameter must not be null.\"", ")", ";", "}", "String", "handle", "=", "new", "BL", "(", "blockEventQueue", ",", "timeout", ",", "timeUnit", ")", ".", "getHandle", "(", ")", ";", "logger", ".", "trace", "(", "format", "(", "\"Register QueuedBlockEvent listener %s\"", ",", "handle", ")", ")", ";", "return", "handle", ";", "}" ]
Register a Queued block listener. This queue should never block insertion of events. @param blockEventQueue the queue @param timeout The time that is waited on for event to be waited on the queue @param timeUnit the time unit for timeout. @return return a handle to ungregister the handler. @throws InvalidArgumentException
[ "Register", "a", "Queued", "block", "listener", ".", "This", "queue", "should", "never", "block", "insertion", "of", "events", "." ]
train
https://github.com/hyperledger/fabric-sdk-java/blob/4a2d7b3408b8b0a1ed812aa36942c438159c37a0/src/main/java/org/hyperledger/fabric/sdk/Channel.java#L5543-L5567
KostyaSha/yet-another-docker-plugin
yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/steps/DockerShellStep.java
DockerShellStep.getEnvVars
protected static EnvVars getEnvVars(Run run, TaskListener listener) throws IOException, InterruptedException { """ Return all job related vars without executor vars. I.e. slave is running in osx, but docker image for shell is linux. """ final EnvVars envVars = run.getCharacteristicEnvVars(); // from run.getEnvironment(listener) but without computer vars for (EnvironmentContributor ec : EnvironmentContributor.all().reverseView()) { // job vars ec.buildEnvironmentFor(run.getParent(), envVars, listener); // build vars if (ec instanceof CoreEnvironmentContributor) { // exclude executor computer related vars envVars.put("BUILD_DISPLAY_NAME", run.getDisplayName()); String rootUrl = Jenkins.getInstance().getRootUrl(); if (rootUrl != null) { envVars.put("BUILD_URL", rootUrl + run.getUrl()); } // and remove useless job var from CoreEnvironmentContributor envVars.remove("JENKINS_HOME"); envVars.remove("HUDSON_HOME"); } else { ec.buildEnvironmentFor(run, envVars, listener); // build vars } } return envVars; }
java
protected static EnvVars getEnvVars(Run run, TaskListener listener) throws IOException, InterruptedException { final EnvVars envVars = run.getCharacteristicEnvVars(); // from run.getEnvironment(listener) but without computer vars for (EnvironmentContributor ec : EnvironmentContributor.all().reverseView()) { // job vars ec.buildEnvironmentFor(run.getParent(), envVars, listener); // build vars if (ec instanceof CoreEnvironmentContributor) { // exclude executor computer related vars envVars.put("BUILD_DISPLAY_NAME", run.getDisplayName()); String rootUrl = Jenkins.getInstance().getRootUrl(); if (rootUrl != null) { envVars.put("BUILD_URL", rootUrl + run.getUrl()); } // and remove useless job var from CoreEnvironmentContributor envVars.remove("JENKINS_HOME"); envVars.remove("HUDSON_HOME"); } else { ec.buildEnvironmentFor(run, envVars, listener); // build vars } } return envVars; }
[ "protected", "static", "EnvVars", "getEnvVars", "(", "Run", "run", ",", "TaskListener", "listener", ")", "throws", "IOException", ",", "InterruptedException", "{", "final", "EnvVars", "envVars", "=", "run", ".", "getCharacteristicEnvVars", "(", ")", ";", "// from run.getEnvironment(listener) but without computer vars", "for", "(", "EnvironmentContributor", "ec", ":", "EnvironmentContributor", ".", "all", "(", ")", ".", "reverseView", "(", ")", ")", "{", "// job vars", "ec", ".", "buildEnvironmentFor", "(", "run", ".", "getParent", "(", ")", ",", "envVars", ",", "listener", ")", ";", "// build vars", "if", "(", "ec", "instanceof", "CoreEnvironmentContributor", ")", "{", "// exclude executor computer related vars", "envVars", ".", "put", "(", "\"BUILD_DISPLAY_NAME\"", ",", "run", ".", "getDisplayName", "(", ")", ")", ";", "String", "rootUrl", "=", "Jenkins", ".", "getInstance", "(", ")", ".", "getRootUrl", "(", ")", ";", "if", "(", "rootUrl", "!=", "null", ")", "{", "envVars", ".", "put", "(", "\"BUILD_URL\"", ",", "rootUrl", "+", "run", ".", "getUrl", "(", ")", ")", ";", "}", "// and remove useless job var from CoreEnvironmentContributor", "envVars", ".", "remove", "(", "\"JENKINS_HOME\"", ")", ";", "envVars", ".", "remove", "(", "\"HUDSON_HOME\"", ")", ";", "}", "else", "{", "ec", ".", "buildEnvironmentFor", "(", "run", ",", "envVars", ",", "listener", ")", ";", "// build vars", "}", "}", "return", "envVars", ";", "}" ]
Return all job related vars without executor vars. I.e. slave is running in osx, but docker image for shell is linux.
[ "Return", "all", "job", "related", "vars", "without", "executor", "vars", ".", "I", ".", "e", ".", "slave", "is", "running", "in", "osx", "but", "docker", "image", "for", "shell", "is", "linux", "." ]
train
https://github.com/KostyaSha/yet-another-docker-plugin/blob/40b12e39ff94c3834cff7e028c3dd01c88e87d77/yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/steps/DockerShellStep.java#L306-L334
VoltDB/voltdb
third_party/java/src/com/google_voltpatches/common/util/concurrent/AbstractCheckedFuture.java
AbstractCheckedFuture.checkedGet
@CanIgnoreReturnValue @Override public V checkedGet(long timeout, TimeUnit unit) throws TimeoutException, X { """ {@inheritDoc} <p>This implementation calls {@link #get(long, TimeUnit)} and maps that method's standard exceptions (excluding {@link TimeoutException}, which is propagated) to instances of type {@code X} using {@link #mapException}. <p>In addition, if {@code get} throws an {@link InterruptedException}, this implementation will set the current thread's interrupt status before calling {@code mapException}. @throws X if {@link #get()} throws an {@link InterruptedException}, {@link CancellationException}, or {@link ExecutionException} """ try { return get(timeout, unit); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw mapException(e); } catch (CancellationException e) { throw mapException(e); } catch (ExecutionException e) { throw mapException(e); } }
java
@CanIgnoreReturnValue @Override public V checkedGet(long timeout, TimeUnit unit) throws TimeoutException, X { try { return get(timeout, unit); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw mapException(e); } catch (CancellationException e) { throw mapException(e); } catch (ExecutionException e) { throw mapException(e); } }
[ "@", "CanIgnoreReturnValue", "@", "Override", "public", "V", "checkedGet", "(", "long", "timeout", ",", "TimeUnit", "unit", ")", "throws", "TimeoutException", ",", "X", "{", "try", "{", "return", "get", "(", "timeout", ",", "unit", ")", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "Thread", ".", "currentThread", "(", ")", ".", "interrupt", "(", ")", ";", "throw", "mapException", "(", "e", ")", ";", "}", "catch", "(", "CancellationException", "e", ")", "{", "throw", "mapException", "(", "e", ")", ";", "}", "catch", "(", "ExecutionException", "e", ")", "{", "throw", "mapException", "(", "e", ")", ";", "}", "}" ]
{@inheritDoc} <p>This implementation calls {@link #get(long, TimeUnit)} and maps that method's standard exceptions (excluding {@link TimeoutException}, which is propagated) to instances of type {@code X} using {@link #mapException}. <p>In addition, if {@code get} throws an {@link InterruptedException}, this implementation will set the current thread's interrupt status before calling {@code mapException}. @throws X if {@link #get()} throws an {@link InterruptedException}, {@link CancellationException}, or {@link ExecutionException}
[ "{", "@inheritDoc", "}" ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/third_party/java/src/com/google_voltpatches/common/util/concurrent/AbstractCheckedFuture.java#L100-L113
FaritorKang/unmz-common-util
src/main/java/net/unmz/java/util/http/HttpUtils.java
HttpUtils.doPutResponse
public static HttpResponse doPutResponse(String host, String path, Map<String, String> headers, Map<String, String> queries) throws Exception { """ Put String @param host @param path @param headers @param queries @param body @return @throws Exception """ return doPutResponse(host, path, headers, queries, ""); }
java
public static HttpResponse doPutResponse(String host, String path, Map<String, String> headers, Map<String, String> queries) throws Exception { return doPutResponse(host, path, headers, queries, ""); }
[ "public", "static", "HttpResponse", "doPutResponse", "(", "String", "host", ",", "String", "path", ",", "Map", "<", "String", ",", "String", ">", "headers", ",", "Map", "<", "String", ",", "String", ">", "queries", ")", "throws", "Exception", "{", "return", "doPutResponse", "(", "host", ",", "path", ",", "headers", ",", "queries", ",", "\"\"", ")", ";", "}" ]
Put String @param host @param path @param headers @param queries @param body @return @throws Exception
[ "Put", "String" ]
train
https://github.com/FaritorKang/unmz-common-util/blob/2912b8889b85ed910d536f85b24b6fa68035814a/src/main/java/net/unmz/java/util/http/HttpUtils.java#L281-L285
rhuss/jolokia
agent/jvm/src/main/java/org/jolokia/jvmagent/client/command/AbstractBaseCommand.java
AbstractBaseCommand.checkAgentUrl
protected String checkAgentUrl(Object pVm, int delayInMs) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { """ Check whether an agent is registered by checking the existance of the system property {@link JvmAgent#JOLOKIA_AGENT_URL}. This can be used to check, whether a Jolokia agent has been already attached and started. ("start" will set this property, "stop" will remove it). @param pVm the {@link com.sun.tools.attach.VirtualMachine}, but typeless @param delayInMs wait that many ms before fetching the properties * @return the agent URL if it is was set by a previous 'start' command. """ if (delayInMs != 0) { try { Thread.sleep(delayInMs); } catch (InterruptedException e) { // just continue } } Properties systemProperties = getAgentSystemProperties(pVm); return systemProperties.getProperty(JvmAgent.JOLOKIA_AGENT_URL); }
java
protected String checkAgentUrl(Object pVm, int delayInMs) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { if (delayInMs != 0) { try { Thread.sleep(delayInMs); } catch (InterruptedException e) { // just continue } } Properties systemProperties = getAgentSystemProperties(pVm); return systemProperties.getProperty(JvmAgent.JOLOKIA_AGENT_URL); }
[ "protected", "String", "checkAgentUrl", "(", "Object", "pVm", ",", "int", "delayInMs", ")", "throws", "NoSuchMethodException", ",", "InvocationTargetException", ",", "IllegalAccessException", "{", "if", "(", "delayInMs", "!=", "0", ")", "{", "try", "{", "Thread", ".", "sleep", "(", "delayInMs", ")", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "// just continue", "}", "}", "Properties", "systemProperties", "=", "getAgentSystemProperties", "(", "pVm", ")", ";", "return", "systemProperties", ".", "getProperty", "(", "JvmAgent", ".", "JOLOKIA_AGENT_URL", ")", ";", "}" ]
Check whether an agent is registered by checking the existance of the system property {@link JvmAgent#JOLOKIA_AGENT_URL}. This can be used to check, whether a Jolokia agent has been already attached and started. ("start" will set this property, "stop" will remove it). @param pVm the {@link com.sun.tools.attach.VirtualMachine}, but typeless @param delayInMs wait that many ms before fetching the properties * @return the agent URL if it is was set by a previous 'start' command.
[ "Check", "whether", "an", "agent", "is", "registered", "by", "checking", "the", "existance", "of", "the", "system", "property", "{", "@link", "JvmAgent#JOLOKIA_AGENT_URL", "}", ".", "This", "can", "be", "used", "to", "check", "whether", "a", "Jolokia", "agent", "has", "been", "already", "attached", "and", "started", ".", "(", "start", "will", "set", "this", "property", "stop", "will", "remove", "it", ")", "." ]
train
https://github.com/rhuss/jolokia/blob/dc95e7bef859b1829776c5a84c8f7738f5d7d9c3/agent/jvm/src/main/java/org/jolokia/jvmagent/client/command/AbstractBaseCommand.java#L96-L106
apiman/apiman
common/plugin/src/main/java/io/apiman/common/plugin/PluginClassLoader.java
PluginClassLoader.extractResource
private URL extractResource(ZipEntry zipEntry) throws IOException { """ Extracts a resource from the plugin artifact ZIP and saves it to the work directory. If the resource has already been extracted (we're re-using the work directory) then this simply returns what is already there. @param zipEntry a ZIP file entry @throws IOException if an I/O error has occurred """ File resourceWorkDir = new File(workDir, "resources"); if (!resourceWorkDir.exists()) { resourceWorkDir.mkdirs(); } File resourceFile = new File(resourceWorkDir, zipEntry.getName()); if (!resourceFile.isFile()) { resourceFile.getParentFile().mkdirs(); File tmpFile = File.createTempFile("res", ".tmp", resourceWorkDir); tmpFile.deleteOnExit(); InputStream input = null; OutputStream output = null; try { input = this.pluginArtifactZip.getInputStream(zipEntry); output = new FileOutputStream(tmpFile); IOUtils.copy(input, output); output.flush(); tmpFile.renameTo(resourceFile); } catch (IOException e) { throw e; } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } } return resourceFile.toURI().toURL(); }
java
private URL extractResource(ZipEntry zipEntry) throws IOException { File resourceWorkDir = new File(workDir, "resources"); if (!resourceWorkDir.exists()) { resourceWorkDir.mkdirs(); } File resourceFile = new File(resourceWorkDir, zipEntry.getName()); if (!resourceFile.isFile()) { resourceFile.getParentFile().mkdirs(); File tmpFile = File.createTempFile("res", ".tmp", resourceWorkDir); tmpFile.deleteOnExit(); InputStream input = null; OutputStream output = null; try { input = this.pluginArtifactZip.getInputStream(zipEntry); output = new FileOutputStream(tmpFile); IOUtils.copy(input, output); output.flush(); tmpFile.renameTo(resourceFile); } catch (IOException e) { throw e; } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } } return resourceFile.toURI().toURL(); }
[ "private", "URL", "extractResource", "(", "ZipEntry", "zipEntry", ")", "throws", "IOException", "{", "File", "resourceWorkDir", "=", "new", "File", "(", "workDir", ",", "\"resources\"", ")", ";", "if", "(", "!", "resourceWorkDir", ".", "exists", "(", ")", ")", "{", "resourceWorkDir", ".", "mkdirs", "(", ")", ";", "}", "File", "resourceFile", "=", "new", "File", "(", "resourceWorkDir", ",", "zipEntry", ".", "getName", "(", ")", ")", ";", "if", "(", "!", "resourceFile", ".", "isFile", "(", ")", ")", "{", "resourceFile", ".", "getParentFile", "(", ")", ".", "mkdirs", "(", ")", ";", "File", "tmpFile", "=", "File", ".", "createTempFile", "(", "\"res\"", ",", "\".tmp\"", ",", "resourceWorkDir", ")", ";", "tmpFile", ".", "deleteOnExit", "(", ")", ";", "InputStream", "input", "=", "null", ";", "OutputStream", "output", "=", "null", ";", "try", "{", "input", "=", "this", ".", "pluginArtifactZip", ".", "getInputStream", "(", "zipEntry", ")", ";", "output", "=", "new", "FileOutputStream", "(", "tmpFile", ")", ";", "IOUtils", ".", "copy", "(", "input", ",", "output", ")", ";", "output", ".", "flush", "(", ")", ";", "tmpFile", ".", "renameTo", "(", "resourceFile", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "e", ";", "}", "finally", "{", "IOUtils", ".", "closeQuietly", "(", "input", ")", ";", "IOUtils", ".", "closeQuietly", "(", "output", ")", ";", "}", "}", "return", "resourceFile", ".", "toURI", "(", ")", ".", "toURL", "(", ")", ";", "}" ]
Extracts a resource from the plugin artifact ZIP and saves it to the work directory. If the resource has already been extracted (we're re-using the work directory) then this simply returns what is already there. @param zipEntry a ZIP file entry @throws IOException if an I/O error has occurred
[ "Extracts", "a", "resource", "from", "the", "plugin", "artifact", "ZIP", "and", "saves", "it", "to", "the", "work", "directory", ".", "If", "the", "resource", "has", "already", "been", "extracted", "(", "we", "re", "re", "-", "using", "the", "work", "directory", ")", "then", "this", "simply", "returns", "what", "is", "already", "there", "." ]
train
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/common/plugin/src/main/java/io/apiman/common/plugin/PluginClassLoader.java#L150-L176
threerings/nenya
core/src/main/java/com/threerings/resource/ResourceManager.java
ResourceManager.createFileResourceBundle
protected FileResourceBundle createFileResourceBundle ( File source, boolean delay, boolean unpack) { """ Creates an appropriate bundle for fetching resources from files. """ return new FileResourceBundle(source, delay, unpack); }
java
protected FileResourceBundle createFileResourceBundle ( File source, boolean delay, boolean unpack) { return new FileResourceBundle(source, delay, unpack); }
[ "protected", "FileResourceBundle", "createFileResourceBundle", "(", "File", "source", ",", "boolean", "delay", ",", "boolean", "unpack", ")", "{", "return", "new", "FileResourceBundle", "(", "source", ",", "delay", ",", "unpack", ")", ";", "}" ]
Creates an appropriate bundle for fetching resources from files.
[ "Creates", "an", "appropriate", "bundle", "for", "fetching", "resources", "from", "files", "." ]
train
https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/resource/ResourceManager.java#L841-L845
elki-project/elki
elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/gdbscan/COPACNeighborPredicate.java
COPACNeighborPredicate.instantiate
public COPACNeighborPredicate.Instance instantiate(Database database, Relation<V> relation) { """ Full instantiation method. @param database Database @param relation Vector relation @return Instance """ DistanceQuery<V> dq = database.getDistanceQuery(relation, EuclideanDistanceFunction.STATIC); KNNQuery<V> knnq = database.getKNNQuery(dq, settings.k); WritableDataStore<COPACModel> storage = DataStoreUtil.makeStorage(relation.getDBIDs(), DataStoreFactory.HINT_HOT | DataStoreFactory.HINT_TEMP, COPACModel.class); Duration time = LOG.newDuration(this.getClass().getName() + ".preprocessing-time").begin(); FiniteProgress progress = LOG.isVerbose() ? new FiniteProgress(this.getClass().getName(), relation.size(), LOG) : null; for(DBIDIter iditer = relation.iterDBIDs(); iditer.valid(); iditer.advance()) { DoubleDBIDList ref = knnq.getKNNForDBID(iditer, settings.k); storage.put(iditer, computeLocalModel(iditer, ref, relation)); LOG.incrementProcessed(progress); } LOG.ensureCompleted(progress); LOG.statistics(time.end()); return new Instance(relation.getDBIDs(), storage); }
java
public COPACNeighborPredicate.Instance instantiate(Database database, Relation<V> relation) { DistanceQuery<V> dq = database.getDistanceQuery(relation, EuclideanDistanceFunction.STATIC); KNNQuery<V> knnq = database.getKNNQuery(dq, settings.k); WritableDataStore<COPACModel> storage = DataStoreUtil.makeStorage(relation.getDBIDs(), DataStoreFactory.HINT_HOT | DataStoreFactory.HINT_TEMP, COPACModel.class); Duration time = LOG.newDuration(this.getClass().getName() + ".preprocessing-time").begin(); FiniteProgress progress = LOG.isVerbose() ? new FiniteProgress(this.getClass().getName(), relation.size(), LOG) : null; for(DBIDIter iditer = relation.iterDBIDs(); iditer.valid(); iditer.advance()) { DoubleDBIDList ref = knnq.getKNNForDBID(iditer, settings.k); storage.put(iditer, computeLocalModel(iditer, ref, relation)); LOG.incrementProcessed(progress); } LOG.ensureCompleted(progress); LOG.statistics(time.end()); return new Instance(relation.getDBIDs(), storage); }
[ "public", "COPACNeighborPredicate", ".", "Instance", "instantiate", "(", "Database", "database", ",", "Relation", "<", "V", ">", "relation", ")", "{", "DistanceQuery", "<", "V", ">", "dq", "=", "database", ".", "getDistanceQuery", "(", "relation", ",", "EuclideanDistanceFunction", ".", "STATIC", ")", ";", "KNNQuery", "<", "V", ">", "knnq", "=", "database", ".", "getKNNQuery", "(", "dq", ",", "settings", ".", "k", ")", ";", "WritableDataStore", "<", "COPACModel", ">", "storage", "=", "DataStoreUtil", ".", "makeStorage", "(", "relation", ".", "getDBIDs", "(", ")", ",", "DataStoreFactory", ".", "HINT_HOT", "|", "DataStoreFactory", ".", "HINT_TEMP", ",", "COPACModel", ".", "class", ")", ";", "Duration", "time", "=", "LOG", ".", "newDuration", "(", "this", ".", "getClass", "(", ")", ".", "getName", "(", ")", "+", "\".preprocessing-time\"", ")", ".", "begin", "(", ")", ";", "FiniteProgress", "progress", "=", "LOG", ".", "isVerbose", "(", ")", "?", "new", "FiniteProgress", "(", "this", ".", "getClass", "(", ")", ".", "getName", "(", ")", ",", "relation", ".", "size", "(", ")", ",", "LOG", ")", ":", "null", ";", "for", "(", "DBIDIter", "iditer", "=", "relation", ".", "iterDBIDs", "(", ")", ";", "iditer", ".", "valid", "(", ")", ";", "iditer", ".", "advance", "(", ")", ")", "{", "DoubleDBIDList", "ref", "=", "knnq", ".", "getKNNForDBID", "(", "iditer", ",", "settings", ".", "k", ")", ";", "storage", ".", "put", "(", "iditer", ",", "computeLocalModel", "(", "iditer", ",", "ref", ",", "relation", ")", ")", ";", "LOG", ".", "incrementProcessed", "(", "progress", ")", ";", "}", "LOG", ".", "ensureCompleted", "(", "progress", ")", ";", "LOG", ".", "statistics", "(", "time", ".", "end", "(", ")", ")", ";", "return", "new", "Instance", "(", "relation", ".", "getDBIDs", "(", ")", ",", "storage", ")", ";", "}" ]
Full instantiation method. @param database Database @param relation Vector relation @return Instance
[ "Full", "instantiation", "method", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/gdbscan/COPACNeighborPredicate.java#L115-L131
alkacon/opencms-core
src/org/opencms/security/CmsRoleManager.java
CmsRoleManager.hasRoleForResource
public boolean hasRoleForResource(CmsObject cms, CmsRole role, String resourceName) { """ Checks if the given context user has the given role for the given resource.<p> @param cms the opencms context @param role the role to check @param resourceName the name of the resource to check @return <code>true</code> if the given context user has the given role for the given resource """ CmsResource resource; try { resource = cms.readResource(resourceName, CmsResourceFilter.ALL); } catch (CmsException e) { // ignore return false; } return m_securityManager.hasRoleForResource( cms.getRequestContext(), cms.getRequestContext().getCurrentUser(), role, resource); }
java
public boolean hasRoleForResource(CmsObject cms, CmsRole role, String resourceName) { CmsResource resource; try { resource = cms.readResource(resourceName, CmsResourceFilter.ALL); } catch (CmsException e) { // ignore return false; } return m_securityManager.hasRoleForResource( cms.getRequestContext(), cms.getRequestContext().getCurrentUser(), role, resource); }
[ "public", "boolean", "hasRoleForResource", "(", "CmsObject", "cms", ",", "CmsRole", "role", ",", "String", "resourceName", ")", "{", "CmsResource", "resource", ";", "try", "{", "resource", "=", "cms", ".", "readResource", "(", "resourceName", ",", "CmsResourceFilter", ".", "ALL", ")", ";", "}", "catch", "(", "CmsException", "e", ")", "{", "// ignore", "return", "false", ";", "}", "return", "m_securityManager", ".", "hasRoleForResource", "(", "cms", ".", "getRequestContext", "(", ")", ",", "cms", ".", "getRequestContext", "(", ")", ".", "getCurrentUser", "(", ")", ",", "role", ",", "resource", ")", ";", "}" ]
Checks if the given context user has the given role for the given resource.<p> @param cms the opencms context @param role the role to check @param resourceName the name of the resource to check @return <code>true</code> if the given context user has the given role for the given resource
[ "Checks", "if", "the", "given", "context", "user", "has", "the", "given", "role", "for", "the", "given", "resource", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/security/CmsRoleManager.java#L479-L493
facebookarchive/hive-dwrf
hive-dwrf-shims/src/main/java/org/apache/hadoop/hive/ql/io/slice/Slice.java
Slice.getBytes
public void getBytes(int index, Slice destination, int destinationIndex, int length) { """ Transfers portion of data from this slice into the specified destination starting at the specified absolute {@code index}. @param destinationIndex the first index of the destination @param length the number of bytes to transfer @throws IndexOutOfBoundsException if the specified {@code index} is less than {@code 0}, if the specified {@code destinationIndex} is less than {@code 0}, if {@code index + length} is greater than {@code this.length()}, or if {@code destinationIndex + length} is greater than {@code destination.length()} """ destination.setBytes(destinationIndex, this, index, length); }
java
public void getBytes(int index, Slice destination, int destinationIndex, int length) { destination.setBytes(destinationIndex, this, index, length); }
[ "public", "void", "getBytes", "(", "int", "index", ",", "Slice", "destination", ",", "int", "destinationIndex", ",", "int", "length", ")", "{", "destination", ".", "setBytes", "(", "destinationIndex", ",", "this", ",", "index", ",", "length", ")", ";", "}" ]
Transfers portion of data from this slice into the specified destination starting at the specified absolute {@code index}. @param destinationIndex the first index of the destination @param length the number of bytes to transfer @throws IndexOutOfBoundsException if the specified {@code index} is less than {@code 0}, if the specified {@code destinationIndex} is less than {@code 0}, if {@code index + length} is greater than {@code this.length()}, or if {@code destinationIndex + length} is greater than {@code destination.length()}
[ "Transfers", "portion", "of", "data", "from", "this", "slice", "into", "the", "specified", "destination", "starting", "at", "the", "specified", "absolute", "{", "@code", "index", "}", "." ]
train
https://github.com/facebookarchive/hive-dwrf/blob/a7b4fcf28a57e006a2fc041d40cf7e5ad16e6b45/hive-dwrf-shims/src/main/java/org/apache/hadoop/hive/ql/io/slice/Slice.java#L320-L323
hawkular/hawkular-apm
server/api/src/main/java/org/hawkular/apm/server/api/utils/zipkin/SpanHttpDeriverUtil.java
SpanHttpDeriverUtil.getHttpStatusCodes
public static List<HttpCode> getHttpStatusCodes(List<BinaryAnnotation> binaryAnnotations) { """ Method returns list of http status codes. @param binaryAnnotations zipkin binary annotations @return http status codes """ if (binaryAnnotations == null) { return Collections.emptyList(); } List<HttpCode> httpCodes = new ArrayList<>(); for (BinaryAnnotation binaryAnnotation: binaryAnnotations) { if (Constants.ZIPKIN_BIN_ANNOTATION_HTTP_STATUS_CODE.equals(binaryAnnotation.getKey()) && binaryAnnotation.getValue() != null) { String strHttpCode = binaryAnnotation.getValue(); Integer httpCode = toInt(strHttpCode.trim()); if (httpCode != null) { String description = EnglishReasonPhraseCatalog.INSTANCE.getReason(httpCode, Locale.ENGLISH); httpCodes.add(new HttpCode(httpCode, description)); } } } return httpCodes; }
java
public static List<HttpCode> getHttpStatusCodes(List<BinaryAnnotation> binaryAnnotations) { if (binaryAnnotations == null) { return Collections.emptyList(); } List<HttpCode> httpCodes = new ArrayList<>(); for (BinaryAnnotation binaryAnnotation: binaryAnnotations) { if (Constants.ZIPKIN_BIN_ANNOTATION_HTTP_STATUS_CODE.equals(binaryAnnotation.getKey()) && binaryAnnotation.getValue() != null) { String strHttpCode = binaryAnnotation.getValue(); Integer httpCode = toInt(strHttpCode.trim()); if (httpCode != null) { String description = EnglishReasonPhraseCatalog.INSTANCE.getReason(httpCode, Locale.ENGLISH); httpCodes.add(new HttpCode(httpCode, description)); } } } return httpCodes; }
[ "public", "static", "List", "<", "HttpCode", ">", "getHttpStatusCodes", "(", "List", "<", "BinaryAnnotation", ">", "binaryAnnotations", ")", "{", "if", "(", "binaryAnnotations", "==", "null", ")", "{", "return", "Collections", ".", "emptyList", "(", ")", ";", "}", "List", "<", "HttpCode", ">", "httpCodes", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "BinaryAnnotation", "binaryAnnotation", ":", "binaryAnnotations", ")", "{", "if", "(", "Constants", ".", "ZIPKIN_BIN_ANNOTATION_HTTP_STATUS_CODE", ".", "equals", "(", "binaryAnnotation", ".", "getKey", "(", ")", ")", "&&", "binaryAnnotation", ".", "getValue", "(", ")", "!=", "null", ")", "{", "String", "strHttpCode", "=", "binaryAnnotation", ".", "getValue", "(", ")", ";", "Integer", "httpCode", "=", "toInt", "(", "strHttpCode", ".", "trim", "(", ")", ")", ";", "if", "(", "httpCode", "!=", "null", ")", "{", "String", "description", "=", "EnglishReasonPhraseCatalog", ".", "INSTANCE", ".", "getReason", "(", "httpCode", ",", "Locale", ".", "ENGLISH", ")", ";", "httpCodes", ".", "add", "(", "new", "HttpCode", "(", "httpCode", ",", "description", ")", ")", ";", "}", "}", "}", "return", "httpCodes", ";", "}" ]
Method returns list of http status codes. @param binaryAnnotations zipkin binary annotations @return http status codes
[ "Method", "returns", "list", "of", "http", "status", "codes", "." ]
train
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/server/api/src/main/java/org/hawkular/apm/server/api/utils/zipkin/SpanHttpDeriverUtil.java#L53-L75
Stratio/stratio-cassandra
src/java/org/apache/cassandra/repair/Differencer.java
Differencer.performStreamingRepair
void performStreamingRepair() { """ Starts sending/receiving our list of differences to/from the remote endpoint: creates a callback that will be called out of band once the streams complete. """ InetAddress local = FBUtilities.getBroadcastAddress(); // We can take anyone of the node as source or destination, however if one is localhost, we put at source to avoid a forwarding InetAddress src = r2.endpoint.equals(local) ? r2.endpoint : r1.endpoint; InetAddress dst = r2.endpoint.equals(local) ? r1.endpoint : r2.endpoint; SyncRequest request = new SyncRequest(desc, local, src, dst, differences); StreamingRepairTask task = new StreamingRepairTask(desc, request); task.run(); }
java
void performStreamingRepair() { InetAddress local = FBUtilities.getBroadcastAddress(); // We can take anyone of the node as source or destination, however if one is localhost, we put at source to avoid a forwarding InetAddress src = r2.endpoint.equals(local) ? r2.endpoint : r1.endpoint; InetAddress dst = r2.endpoint.equals(local) ? r1.endpoint : r2.endpoint; SyncRequest request = new SyncRequest(desc, local, src, dst, differences); StreamingRepairTask task = new StreamingRepairTask(desc, request); task.run(); }
[ "void", "performStreamingRepair", "(", ")", "{", "InetAddress", "local", "=", "FBUtilities", ".", "getBroadcastAddress", "(", ")", ";", "// We can take anyone of the node as source or destination, however if one is localhost, we put at source to avoid a forwarding", "InetAddress", "src", "=", "r2", ".", "endpoint", ".", "equals", "(", "local", ")", "?", "r2", ".", "endpoint", ":", "r1", ".", "endpoint", ";", "InetAddress", "dst", "=", "r2", ".", "endpoint", ".", "equals", "(", "local", ")", "?", "r1", ".", "endpoint", ":", "r2", ".", "endpoint", ";", "SyncRequest", "request", "=", "new", "SyncRequest", "(", "desc", ",", "local", ",", "src", ",", "dst", ",", "differences", ")", ";", "StreamingRepairTask", "task", "=", "new", "StreamingRepairTask", "(", "desc", ",", "request", ")", ";", "task", ".", "run", "(", ")", ";", "}" ]
Starts sending/receiving our list of differences to/from the remote endpoint: creates a callback that will be called out of band once the streams complete.
[ "Starts", "sending", "/", "receiving", "our", "list", "of", "differences", "to", "/", "from", "the", "remote", "endpoint", ":", "creates", "a", "callback", "that", "will", "be", "called", "out", "of", "band", "once", "the", "streams", "complete", "." ]
train
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/repair/Differencer.java#L82-L92
liferay/com-liferay-commerce
commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceWarehousePersistenceImpl.java
CommerceWarehousePersistenceImpl.countByG_A_C
@Override public int countByG_A_C(long groupId, boolean active, long commerceCountryId) { """ Returns the number of commerce warehouses where groupId = &#63; and active = &#63; and commerceCountryId = &#63;. @param groupId the group ID @param active the active @param commerceCountryId the commerce country ID @return the number of matching commerce warehouses """ FinderPath finderPath = FINDER_PATH_COUNT_BY_G_A_C; Object[] finderArgs = new Object[] { groupId, active, commerceCountryId }; Long count = (Long)finderCache.getResult(finderPath, finderArgs, this); if (count == null) { StringBundler query = new StringBundler(4); query.append(_SQL_COUNT_COMMERCEWAREHOUSE_WHERE); query.append(_FINDER_COLUMN_G_A_C_GROUPID_2); query.append(_FINDER_COLUMN_G_A_C_ACTIVE_2); query.append(_FINDER_COLUMN_G_A_C_COMMERCECOUNTRYID_2); String sql = query.toString(); Session session = null; try { session = openSession(); Query q = session.createQuery(sql); QueryPos qPos = QueryPos.getInstance(q); qPos.add(groupId); qPos.add(active); qPos.add(commerceCountryId); count = (Long)q.uniqueResult(); finderCache.putResult(finderPath, finderArgs, count); } catch (Exception e) { finderCache.removeResult(finderPath, finderArgs); throw processException(e); } finally { closeSession(session); } } return count.intValue(); }
java
@Override public int countByG_A_C(long groupId, boolean active, long commerceCountryId) { FinderPath finderPath = FINDER_PATH_COUNT_BY_G_A_C; Object[] finderArgs = new Object[] { groupId, active, commerceCountryId }; Long count = (Long)finderCache.getResult(finderPath, finderArgs, this); if (count == null) { StringBundler query = new StringBundler(4); query.append(_SQL_COUNT_COMMERCEWAREHOUSE_WHERE); query.append(_FINDER_COLUMN_G_A_C_GROUPID_2); query.append(_FINDER_COLUMN_G_A_C_ACTIVE_2); query.append(_FINDER_COLUMN_G_A_C_COMMERCECOUNTRYID_2); String sql = query.toString(); Session session = null; try { session = openSession(); Query q = session.createQuery(sql); QueryPos qPos = QueryPos.getInstance(q); qPos.add(groupId); qPos.add(active); qPos.add(commerceCountryId); count = (Long)q.uniqueResult(); finderCache.putResult(finderPath, finderArgs, count); } catch (Exception e) { finderCache.removeResult(finderPath, finderArgs); throw processException(e); } finally { closeSession(session); } } return count.intValue(); }
[ "@", "Override", "public", "int", "countByG_A_C", "(", "long", "groupId", ",", "boolean", "active", ",", "long", "commerceCountryId", ")", "{", "FinderPath", "finderPath", "=", "FINDER_PATH_COUNT_BY_G_A_C", ";", "Object", "[", "]", "finderArgs", "=", "new", "Object", "[", "]", "{", "groupId", ",", "active", ",", "commerceCountryId", "}", ";", "Long", "count", "=", "(", "Long", ")", "finderCache", ".", "getResult", "(", "finderPath", ",", "finderArgs", ",", "this", ")", ";", "if", "(", "count", "==", "null", ")", "{", "StringBundler", "query", "=", "new", "StringBundler", "(", "4", ")", ";", "query", ".", "append", "(", "_SQL_COUNT_COMMERCEWAREHOUSE_WHERE", ")", ";", "query", ".", "append", "(", "_FINDER_COLUMN_G_A_C_GROUPID_2", ")", ";", "query", ".", "append", "(", "_FINDER_COLUMN_G_A_C_ACTIVE_2", ")", ";", "query", ".", "append", "(", "_FINDER_COLUMN_G_A_C_COMMERCECOUNTRYID_2", ")", ";", "String", "sql", "=", "query", ".", "toString", "(", ")", ";", "Session", "session", "=", "null", ";", "try", "{", "session", "=", "openSession", "(", ")", ";", "Query", "q", "=", "session", ".", "createQuery", "(", "sql", ")", ";", "QueryPos", "qPos", "=", "QueryPos", ".", "getInstance", "(", "q", ")", ";", "qPos", ".", "add", "(", "groupId", ")", ";", "qPos", ".", "add", "(", "active", ")", ";", "qPos", ".", "add", "(", "commerceCountryId", ")", ";", "count", "=", "(", "Long", ")", "q", ".", "uniqueResult", "(", ")", ";", "finderCache", ".", "putResult", "(", "finderPath", ",", "finderArgs", ",", "count", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "finderCache", ".", "removeResult", "(", "finderPath", ",", "finderArgs", ")", ";", "throw", "processException", "(", "e", ")", ";", "}", "finally", "{", "closeSession", "(", "session", ")", ";", "}", "}", "return", "count", ".", "intValue", "(", ")", ";", "}" ]
Returns the number of commerce warehouses where groupId = &#63; and active = &#63; and commerceCountryId = &#63;. @param groupId the group ID @param active the active @param commerceCountryId the commerce country ID @return the number of matching commerce warehouses
[ "Returns", "the", "number", "of", "commerce", "warehouses", "where", "groupId", "=", "&#63", ";", "and", "active", "=", "&#63", ";", "and", "commerceCountryId", "=", "&#63", ";", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceWarehousePersistenceImpl.java#L2786-L2837
finmath/finmath-lib
src/main/java6/net/finmath/marketdata/model/curves/HazardCurve.java
HazardCurve.createHazardCurveFromSurvivalProbabilities
public static HazardCurve createHazardCurveFromSurvivalProbabilities( String name, LocalDate referenceDate, double[] times, double[] givenSurvivalProbabilities, boolean[] isParameter, InterpolationMethod interpolationMethod, ExtrapolationMethod extrapolationMethod, InterpolationEntity interpolationEntity) { """ Create a hazard curve from given times and given survival probabilities using given interpolation and extrapolation methods. @param name The name of this hazard curve. @param referenceDate The reference date for this curve, i.e., the date which defined t=0. @param times Array of times as doubles. @param givenSurvivalProbabilities Array of corresponding survival probabilities. @param isParameter Array of booleans specifying whether this point is served "as as parameter", e.g., whether it is calibrates (e.g. using CalibratedCurves). @param interpolationMethod The interpolation method used for the curve. @param extrapolationMethod The extrapolation method used for the curve. @param interpolationEntity The entity interpolated/extrapolated. @return A new hazard curve object. """ //We check that all input survival probabilities are in the range [0,1] for( int i = 0; i < givenSurvivalProbabilities.length; i++){ if(givenSurvivalProbabilities[i] < 0 || givenSurvivalProbabilities[i] > 1) { throw new IllegalArgumentException("Survival Probabilities must be between 0 and 1"); } } HazardCurve survivalProbabilities = new HazardCurve(name, referenceDate, interpolationMethod, extrapolationMethod, interpolationEntity); for(int timeIndex=0; timeIndex<times.length;timeIndex++) { survivalProbabilities.addSurvivalProbability(times[timeIndex], givenSurvivalProbabilities[timeIndex], isParameter != null && isParameter[timeIndex]); } return survivalProbabilities; }
java
public static HazardCurve createHazardCurveFromSurvivalProbabilities( String name, LocalDate referenceDate, double[] times, double[] givenSurvivalProbabilities, boolean[] isParameter, InterpolationMethod interpolationMethod, ExtrapolationMethod extrapolationMethod, InterpolationEntity interpolationEntity) { //We check that all input survival probabilities are in the range [0,1] for( int i = 0; i < givenSurvivalProbabilities.length; i++){ if(givenSurvivalProbabilities[i] < 0 || givenSurvivalProbabilities[i] > 1) { throw new IllegalArgumentException("Survival Probabilities must be between 0 and 1"); } } HazardCurve survivalProbabilities = new HazardCurve(name, referenceDate, interpolationMethod, extrapolationMethod, interpolationEntity); for(int timeIndex=0; timeIndex<times.length;timeIndex++) { survivalProbabilities.addSurvivalProbability(times[timeIndex], givenSurvivalProbabilities[timeIndex], isParameter != null && isParameter[timeIndex]); } return survivalProbabilities; }
[ "public", "static", "HazardCurve", "createHazardCurveFromSurvivalProbabilities", "(", "String", "name", ",", "LocalDate", "referenceDate", ",", "double", "[", "]", "times", ",", "double", "[", "]", "givenSurvivalProbabilities", ",", "boolean", "[", "]", "isParameter", ",", "InterpolationMethod", "interpolationMethod", ",", "ExtrapolationMethod", "extrapolationMethod", ",", "InterpolationEntity", "interpolationEntity", ")", "{", "//We check that all input survival probabilities are in the range [0,1]", "for", "(", "int", "i", "=", "0", ";", "i", "<", "givenSurvivalProbabilities", ".", "length", ";", "i", "++", ")", "{", "if", "(", "givenSurvivalProbabilities", "[", "i", "]", "<", "0", "||", "givenSurvivalProbabilities", "[", "i", "]", ">", "1", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Survival Probabilities must be between 0 and 1\"", ")", ";", "}", "}", "HazardCurve", "survivalProbabilities", "=", "new", "HazardCurve", "(", "name", ",", "referenceDate", ",", "interpolationMethod", ",", "extrapolationMethod", ",", "interpolationEntity", ")", ";", "for", "(", "int", "timeIndex", "=", "0", ";", "timeIndex", "<", "times", ".", "length", ";", "timeIndex", "++", ")", "{", "survivalProbabilities", ".", "addSurvivalProbability", "(", "times", "[", "timeIndex", "]", ",", "givenSurvivalProbabilities", "[", "timeIndex", "]", ",", "isParameter", "!=", "null", "&&", "isParameter", "[", "timeIndex", "]", ")", ";", "}", "return", "survivalProbabilities", ";", "}" ]
Create a hazard curve from given times and given survival probabilities using given interpolation and extrapolation methods. @param name The name of this hazard curve. @param referenceDate The reference date for this curve, i.e., the date which defined t=0. @param times Array of times as doubles. @param givenSurvivalProbabilities Array of corresponding survival probabilities. @param isParameter Array of booleans specifying whether this point is served "as as parameter", e.g., whether it is calibrates (e.g. using CalibratedCurves). @param interpolationMethod The interpolation method used for the curve. @param extrapolationMethod The extrapolation method used for the curve. @param interpolationEntity The entity interpolated/extrapolated. @return A new hazard curve object.
[ "Create", "a", "hazard", "curve", "from", "given", "times", "and", "given", "survival", "probabilities", "using", "given", "interpolation", "and", "extrapolation", "methods", "." ]
train
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/marketdata/model/curves/HazardCurve.java#L76-L95
OpenLiberty/open-liberty
dev/com.ibm.ws.microprofile.metrics_fat/fat/src/com/ibm/ws/microprofile/metrics/fat/utils/MetricsConnection.java
MetricsConnection.connection_administratorRole
public static MetricsConnection connection_administratorRole(LibertyServer server) { """ Creates a connection for private (authorized) docs endpoint using HTTPS and the Administrator role @param server - server to connect to @return """ return new MetricsConnection(server, METRICS_ENDPOINT).secure(true) .header("Authorization", "Basic " + Base64Coder.base64Encode(ADMINISTRATOR_USERNAME + ":" + ADMINISTRATOR_PASSWORD)); }
java
public static MetricsConnection connection_administratorRole(LibertyServer server) { return new MetricsConnection(server, METRICS_ENDPOINT).secure(true) .header("Authorization", "Basic " + Base64Coder.base64Encode(ADMINISTRATOR_USERNAME + ":" + ADMINISTRATOR_PASSWORD)); }
[ "public", "static", "MetricsConnection", "connection_administratorRole", "(", "LibertyServer", "server", ")", "{", "return", "new", "MetricsConnection", "(", "server", ",", "METRICS_ENDPOINT", ")", ".", "secure", "(", "true", ")", ".", "header", "(", "\"Authorization\"", ",", "\"Basic \"", "+", "Base64Coder", ".", "base64Encode", "(", "ADMINISTRATOR_USERNAME", "+", "\":\"", "+", "ADMINISTRATOR_PASSWORD", ")", ")", ";", "}" ]
Creates a connection for private (authorized) docs endpoint using HTTPS and the Administrator role @param server - server to connect to @return
[ "Creates", "a", "connection", "for", "private", "(", "authorized", ")", "docs", "endpoint", "using", "HTTPS", "and", "the", "Administrator", "role" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.microprofile.metrics_fat/fat/src/com/ibm/ws/microprofile/metrics/fat/utils/MetricsConnection.java#L201-L205
gallandarakhneorg/afc
core/maths/mathtree/src/main/java/org/arakhne/afc/math/tree/node/AbstractTreeNode.java
AbstractTreeNode.firePropertyParentChanged
protected final void firePropertyParentChanged(N oldParent, N newParent) { """ Fire the event for the changes node parents. @param oldParent is the previous parent node @param newParent is the current parent node """ firePropertyParentChanged(new TreeNodeParentChangedEvent(toN(), oldParent, newParent)); }
java
protected final void firePropertyParentChanged(N oldParent, N newParent) { firePropertyParentChanged(new TreeNodeParentChangedEvent(toN(), oldParent, newParent)); }
[ "protected", "final", "void", "firePropertyParentChanged", "(", "N", "oldParent", ",", "N", "newParent", ")", "{", "firePropertyParentChanged", "(", "new", "TreeNodeParentChangedEvent", "(", "toN", "(", ")", ",", "oldParent", ",", "newParent", ")", ")", ";", "}" ]
Fire the event for the changes node parents. @param oldParent is the previous parent node @param newParent is the current parent node
[ "Fire", "the", "event", "for", "the", "changes", "node", "parents", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/maths/mathtree/src/main/java/org/arakhne/afc/math/tree/node/AbstractTreeNode.java#L233-L235
vvakame/JsonPullParser
jsonpullparser-core/src/main/java/net/vvakame/util/jsonpullparser/JsonPullParser.java
JsonPullParser.newParser
public static JsonPullParser newParser(InputStream is, Charset charset) { """ Creates a new parser, using the given InputStream as its {@code JSON} feed. <p> Please call one of the {@code setSource(...)}'s before calling other methods. </p> @param is An InputStream serves as {@code JSON} feed. Cannot be null. @param charset The character set should be assumed in which in the stream are encoded. {@link #DEFAULT_CHARSET_NAME} is assumed if null is passed. @return {@link JsonPullParser} @throws IllegalArgumentException {@code null} has been passed in where not applicable. """ if (is == null) { throw new IllegalArgumentException("'is' must not be null."); } final Reader reader = new InputStreamReader(is, (charset == null) ? DEFAULT_CHARSET : charset); return newParser(reader); }
java
public static JsonPullParser newParser(InputStream is, Charset charset) { if (is == null) { throw new IllegalArgumentException("'is' must not be null."); } final Reader reader = new InputStreamReader(is, (charset == null) ? DEFAULT_CHARSET : charset); return newParser(reader); }
[ "public", "static", "JsonPullParser", "newParser", "(", "InputStream", "is", ",", "Charset", "charset", ")", "{", "if", "(", "is", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"'is' must not be null.\"", ")", ";", "}", "final", "Reader", "reader", "=", "new", "InputStreamReader", "(", "is", ",", "(", "charset", "==", "null", ")", "?", "DEFAULT_CHARSET", ":", "charset", ")", ";", "return", "newParser", "(", "reader", ")", ";", "}" ]
Creates a new parser, using the given InputStream as its {@code JSON} feed. <p> Please call one of the {@code setSource(...)}'s before calling other methods. </p> @param is An InputStream serves as {@code JSON} feed. Cannot be null. @param charset The character set should be assumed in which in the stream are encoded. {@link #DEFAULT_CHARSET_NAME} is assumed if null is passed. @return {@link JsonPullParser} @throws IllegalArgumentException {@code null} has been passed in where not applicable.
[ "Creates", "a", "new", "parser", "using", "the", "given", "InputStream", "as", "its", "{", "@code", "JSON", "}", "feed", "." ]
train
https://github.com/vvakame/JsonPullParser/blob/fce183ca66354723323a77f2ae8cb5222b5836bc/jsonpullparser-core/src/main/java/net/vvakame/util/jsonpullparser/JsonPullParser.java#L203-L211
citrusframework/citrus
modules/citrus-core/src/main/java/com/consol/citrus/xml/xpath/XPathUtils.java
XPathUtils.evaluateAsNumber
public static Double evaluateAsNumber(Node node, String xPathExpression, NamespaceContext nsContext) { """ Evaluate XPath expression with result type Number. @param node @param xPathExpression @param nsContext @return """ return (Double) evaluateExpression(node, xPathExpression, nsContext, XPathConstants.NUMBER); }
java
public static Double evaluateAsNumber(Node node, String xPathExpression, NamespaceContext nsContext) { return (Double) evaluateExpression(node, xPathExpression, nsContext, XPathConstants.NUMBER); }
[ "public", "static", "Double", "evaluateAsNumber", "(", "Node", "node", ",", "String", "xPathExpression", ",", "NamespaceContext", "nsContext", ")", "{", "return", "(", "Double", ")", "evaluateExpression", "(", "node", ",", "xPathExpression", ",", "nsContext", ",", "XPathConstants", ".", "NUMBER", ")", ";", "}" ]
Evaluate XPath expression with result type Number. @param node @param xPathExpression @param nsContext @return
[ "Evaluate", "XPath", "expression", "with", "result", "type", "Number", "." ]
train
https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/xml/xpath/XPathUtils.java#L245-L247
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/query/impl/IndexHeapMemoryCostUtil.java
IndexHeapMemoryCostUtil.estimateMapCost
public static long estimateMapCost(long size, boolean ordered, boolean usesCachedQueryableEntries) { """ Estimates the on-heap memory cost of a map backing an index. @param size the size of the map to estimate the cost of. @param ordered {@code true} if the index managing the map being estimated is ordered, {@code false} otherwise. @param usesCachedQueryableEntries {@code true} if queryable entries indexed by the associated index are cached, {@code false} otherwise. @return the estimated map cost. """ long mapCost; if (ordered) { mapCost = BASE_CONCURRENT_SKIP_LIST_MAP_COST + size * CONCURRENT_SKIP_LIST_MAP_ENTRY_COST; } else { mapCost = BASE_CONCURRENT_HASH_MAP_COST + size * CONCURRENT_HASH_MAP_ENTRY_COST; } long queryableEntriesCost; if (usesCachedQueryableEntries) { queryableEntriesCost = size * CACHED_QUERYABLE_ENTRY_COST; } else { queryableEntriesCost = size * QUERY_ENTRY_COST; } return mapCost + queryableEntriesCost; }
java
public static long estimateMapCost(long size, boolean ordered, boolean usesCachedQueryableEntries) { long mapCost; if (ordered) { mapCost = BASE_CONCURRENT_SKIP_LIST_MAP_COST + size * CONCURRENT_SKIP_LIST_MAP_ENTRY_COST; } else { mapCost = BASE_CONCURRENT_HASH_MAP_COST + size * CONCURRENT_HASH_MAP_ENTRY_COST; } long queryableEntriesCost; if (usesCachedQueryableEntries) { queryableEntriesCost = size * CACHED_QUERYABLE_ENTRY_COST; } else { queryableEntriesCost = size * QUERY_ENTRY_COST; } return mapCost + queryableEntriesCost; }
[ "public", "static", "long", "estimateMapCost", "(", "long", "size", ",", "boolean", "ordered", ",", "boolean", "usesCachedQueryableEntries", ")", "{", "long", "mapCost", ";", "if", "(", "ordered", ")", "{", "mapCost", "=", "BASE_CONCURRENT_SKIP_LIST_MAP_COST", "+", "size", "*", "CONCURRENT_SKIP_LIST_MAP_ENTRY_COST", ";", "}", "else", "{", "mapCost", "=", "BASE_CONCURRENT_HASH_MAP_COST", "+", "size", "*", "CONCURRENT_HASH_MAP_ENTRY_COST", ";", "}", "long", "queryableEntriesCost", ";", "if", "(", "usesCachedQueryableEntries", ")", "{", "queryableEntriesCost", "=", "size", "*", "CACHED_QUERYABLE_ENTRY_COST", ";", "}", "else", "{", "queryableEntriesCost", "=", "size", "*", "QUERY_ENTRY_COST", ";", "}", "return", "mapCost", "+", "queryableEntriesCost", ";", "}" ]
Estimates the on-heap memory cost of a map backing an index. @param size the size of the map to estimate the cost of. @param ordered {@code true} if the index managing the map being estimated is ordered, {@code false} otherwise. @param usesCachedQueryableEntries {@code true} if queryable entries indexed by the associated index are cached, {@code false} otherwise. @return the estimated map cost.
[ "Estimates", "the", "on", "-", "heap", "memory", "cost", "of", "a", "map", "backing", "an", "index", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/query/impl/IndexHeapMemoryCostUtil.java#L135-L151
icode/ameba
src/main/java/ameba/db/ebean/support/ModelResourceStructure.java
ModelResourceStructure.executeTx
protected void executeTx(final TxRunnable r, final TxRunnable errorHandler) throws Exception { """ <p>executeTx.</p> @param r a {@link ameba.db.ebean.support.ModelResourceStructure.TxRunnable} object. @param errorHandler error handler @throws java.lang.Exception if any. """ Transaction transaction = beginTransaction(); configureTransDefault(transaction); processTransactionError(transaction, t -> { try { r.run(t); t.commit(); } catch (Throwable e) { t.rollback(e); throw e; } finally { t.end(); } return null; }, errorHandler != null ? (TxCallable) t -> { errorHandler.run(t); return null; } : null); }
java
protected void executeTx(final TxRunnable r, final TxRunnable errorHandler) throws Exception { Transaction transaction = beginTransaction(); configureTransDefault(transaction); processTransactionError(transaction, t -> { try { r.run(t); t.commit(); } catch (Throwable e) { t.rollback(e); throw e; } finally { t.end(); } return null; }, errorHandler != null ? (TxCallable) t -> { errorHandler.run(t); return null; } : null); }
[ "protected", "void", "executeTx", "(", "final", "TxRunnable", "r", ",", "final", "TxRunnable", "errorHandler", ")", "throws", "Exception", "{", "Transaction", "transaction", "=", "beginTransaction", "(", ")", ";", "configureTransDefault", "(", "transaction", ")", ";", "processTransactionError", "(", "transaction", ",", "t", "->", "{", "try", "{", "r", ".", "run", "(", "t", ")", ";", "t", ".", "commit", "(", ")", ";", "}", "catch", "(", "Throwable", "e", ")", "{", "t", ".", "rollback", "(", "e", ")", ";", "throw", "e", ";", "}", "finally", "{", "t", ".", "end", "(", ")", ";", "}", "return", "null", ";", "}", ",", "errorHandler", "!=", "null", "?", "(", "TxCallable", ")", "t", "->", "{", "errorHandler", ".", "run", "(", "t", ")", ";", "return", "null", ";", "}", ":", "null", ")", ";", "}" ]
<p>executeTx.</p> @param r a {@link ameba.db.ebean.support.ModelResourceStructure.TxRunnable} object. @param errorHandler error handler @throws java.lang.Exception if any.
[ "<p", ">", "executeTx", ".", "<", "/", "p", ">" ]
train
https://github.com/icode/ameba/blob/9d4956e935898e41331b2745e400ef869cd265e0/src/main/java/ameba/db/ebean/support/ModelResourceStructure.java#L1096-L1114
lessthanoptimal/BoofCV
main/boofcv-io/src/main/java/boofcv/io/image/impl/ImplConvertRaster.java
ImplConvertRaster.bufferedToPlanar_U8
public static void bufferedToPlanar_U8(BufferedImage src, Planar<GrayU8> dst) { """ <p> Converts a buffered image into an planar image using the BufferedImage's RGB interface. </p> <p> This is much slower than working directly with the BufferedImage's internal raster and should be avoided if possible. </p> @param src Input image. @param dst Output image. """ final int width = src.getWidth(); final int height = src.getHeight(); if (dst.getNumBands() == 3) { byte[] band1 = dst.getBand(0).data; byte[] band2 = dst.getBand(1).data; byte[] band3 = dst.getBand(2).data; //CONCURRENT_BELOW BoofConcurrency.loopFor(0, height, y -> { for (int y = 0; y < height; y++) { int index = dst.startIndex + y * dst.stride; for (int x = 0; x < width; x++, index++) { int argb = src.getRGB(x, y); band1[index] = (byte) (argb >>> 16); band2[index] = (byte) (argb >>> 8); band3[index] = (byte) argb; } } //CONCURRENT_ABOVE }); } else { bufferedToGray(src, dst.getBand(0).data,dst.startIndex,dst.stride); GrayU8 band1 = dst.getBand(0); for (int i = 1; i < dst.getNumBands(); i++) { dst.getBand(i).setTo(band1); } } }
java
public static void bufferedToPlanar_U8(BufferedImage src, Planar<GrayU8> dst) { final int width = src.getWidth(); final int height = src.getHeight(); if (dst.getNumBands() == 3) { byte[] band1 = dst.getBand(0).data; byte[] band2 = dst.getBand(1).data; byte[] band3 = dst.getBand(2).data; //CONCURRENT_BELOW BoofConcurrency.loopFor(0, height, y -> { for (int y = 0; y < height; y++) { int index = dst.startIndex + y * dst.stride; for (int x = 0; x < width; x++, index++) { int argb = src.getRGB(x, y); band1[index] = (byte) (argb >>> 16); band2[index] = (byte) (argb >>> 8); band3[index] = (byte) argb; } } //CONCURRENT_ABOVE }); } else { bufferedToGray(src, dst.getBand(0).data,dst.startIndex,dst.stride); GrayU8 band1 = dst.getBand(0); for (int i = 1; i < dst.getNumBands(); i++) { dst.getBand(i).setTo(band1); } } }
[ "public", "static", "void", "bufferedToPlanar_U8", "(", "BufferedImage", "src", ",", "Planar", "<", "GrayU8", ">", "dst", ")", "{", "final", "int", "width", "=", "src", ".", "getWidth", "(", ")", ";", "final", "int", "height", "=", "src", ".", "getHeight", "(", ")", ";", "if", "(", "dst", ".", "getNumBands", "(", ")", "==", "3", ")", "{", "byte", "[", "]", "band1", "=", "dst", ".", "getBand", "(", "0", ")", ".", "data", ";", "byte", "[", "]", "band2", "=", "dst", ".", "getBand", "(", "1", ")", ".", "data", ";", "byte", "[", "]", "band3", "=", "dst", ".", "getBand", "(", "2", ")", ".", "data", ";", "//CONCURRENT_BELOW BoofConcurrency.loopFor(0, height, y -> {", "for", "(", "int", "y", "=", "0", ";", "y", "<", "height", ";", "y", "++", ")", "{", "int", "index", "=", "dst", ".", "startIndex", "+", "y", "*", "dst", ".", "stride", ";", "for", "(", "int", "x", "=", "0", ";", "x", "<", "width", ";", "x", "++", ",", "index", "++", ")", "{", "int", "argb", "=", "src", ".", "getRGB", "(", "x", ",", "y", ")", ";", "band1", "[", "index", "]", "=", "(", "byte", ")", "(", "argb", ">>>", "16", ")", ";", "band2", "[", "index", "]", "=", "(", "byte", ")", "(", "argb", ">>>", "8", ")", ";", "band3", "[", "index", "]", "=", "(", "byte", ")", "argb", ";", "}", "}", "//CONCURRENT_ABOVE });", "}", "else", "{", "bufferedToGray", "(", "src", ",", "dst", ".", "getBand", "(", "0", ")", ".", "data", ",", "dst", ".", "startIndex", ",", "dst", ".", "stride", ")", ";", "GrayU8", "band1", "=", "dst", ".", "getBand", "(", "0", ")", ";", "for", "(", "int", "i", "=", "1", ";", "i", "<", "dst", ".", "getNumBands", "(", ")", ";", "i", "++", ")", "{", "dst", ".", "getBand", "(", "i", ")", ".", "setTo", "(", "band1", ")", ";", "}", "}", "}" ]
<p> Converts a buffered image into an planar image using the BufferedImage's RGB interface. </p> <p> This is much slower than working directly with the BufferedImage's internal raster and should be avoided if possible. </p> @param src Input image. @param dst Output image.
[ "<p", ">", "Converts", "a", "buffered", "image", "into", "an", "planar", "image", "using", "the", "BufferedImage", "s", "RGB", "interface", ".", "<", "/", "p", ">", "<p", ">", "This", "is", "much", "slower", "than", "working", "directly", "with", "the", "BufferedImage", "s", "internal", "raster", "and", "should", "be", "avoided", "if", "possible", ".", "<", "/", "p", ">" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-io/src/main/java/boofcv/io/image/impl/ImplConvertRaster.java#L728-L757
phax/ph-css
ph-css/src/main/java/com/helger/css/reader/CSSReader.java
CSSReader.readFromFile
@Nullable public static CascadingStyleSheet readFromFile (@Nonnull final File aFile, @Nonnull final CSSReaderSettings aSettings) { """ Read the CSS from the passed File. @param aFile The file containing the CSS to be parsed. May not be <code>null</code>. @param aSettings The settings to be used for reading the CSS. May not be <code>null</code>. @return <code>null</code> if reading failed, the CSS declarations otherwise. @since 3.8.2 """ return readFromStream (new FileSystemResource (aFile), aSettings); }
java
@Nullable public static CascadingStyleSheet readFromFile (@Nonnull final File aFile, @Nonnull final CSSReaderSettings aSettings) { return readFromStream (new FileSystemResource (aFile), aSettings); }
[ "@", "Nullable", "public", "static", "CascadingStyleSheet", "readFromFile", "(", "@", "Nonnull", "final", "File", "aFile", ",", "@", "Nonnull", "final", "CSSReaderSettings", "aSettings", ")", "{", "return", "readFromStream", "(", "new", "FileSystemResource", "(", "aFile", ")", ",", "aSettings", ")", ";", "}" ]
Read the CSS from the passed File. @param aFile The file containing the CSS to be parsed. May not be <code>null</code>. @param aSettings The settings to be used for reading the CSS. May not be <code>null</code>. @return <code>null</code> if reading failed, the CSS declarations otherwise. @since 3.8.2
[ "Read", "the", "CSS", "from", "the", "passed", "File", "." ]
train
https://github.com/phax/ph-css/blob/c9da5bb4decc681de6e27ce31712aad4c00adafa/ph-css/src/main/java/com/helger/css/reader/CSSReader.java#L761-L765
lessthanoptimal/ejml
main/ejml-dsparse/src/org/ejml/sparse/csc/CommonOps_DSCC.java
CommonOps_DSCC.extractDiag
public static void extractDiag(DMatrixSparseCSC src, DMatrixRMaj dst ) { """ <p> Extracts the diagonal elements 'src' write it to the 'dst' vector. 'dst' can either be a row or column vector. <p> @param src Matrix whose diagonal elements are being extracted. Not modified. @param dst A vector the results will be written into. Modified. """ int N = Math.min(src.numRows, src.numCols); if( dst.getNumElements() != N || !(dst.numRows==1 || dst.numCols==1) ) { dst.reshape(N, 1); } for (int i = 0; i < N; i++) { dst.data[i] = src.unsafe_get(i, i); } }
java
public static void extractDiag(DMatrixSparseCSC src, DMatrixRMaj dst ) { int N = Math.min(src.numRows, src.numCols); if( dst.getNumElements() != N || !(dst.numRows==1 || dst.numCols==1) ) { dst.reshape(N, 1); } for (int i = 0; i < N; i++) { dst.data[i] = src.unsafe_get(i, i); } }
[ "public", "static", "void", "extractDiag", "(", "DMatrixSparseCSC", "src", ",", "DMatrixRMaj", "dst", ")", "{", "int", "N", "=", "Math", ".", "min", "(", "src", ".", "numRows", ",", "src", ".", "numCols", ")", ";", "if", "(", "dst", ".", "getNumElements", "(", ")", "!=", "N", "||", "!", "(", "dst", ".", "numRows", "==", "1", "||", "dst", ".", "numCols", "==", "1", ")", ")", "{", "dst", ".", "reshape", "(", "N", ",", "1", ")", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "N", ";", "i", "++", ")", "{", "dst", ".", "data", "[", "i", "]", "=", "src", ".", "unsafe_get", "(", "i", ",", "i", ")", ";", "}", "}" ]
<p> Extracts the diagonal elements 'src' write it to the 'dst' vector. 'dst' can either be a row or column vector. <p> @param src Matrix whose diagonal elements are being extracted. Not modified. @param dst A vector the results will be written into. Modified.
[ "<p", ">", "Extracts", "the", "diagonal", "elements", "src", "write", "it", "to", "the", "dst", "vector", ".", "dst", "can", "either", "be", "a", "row", "or", "column", "vector", ".", "<p", ">" ]
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-dsparse/src/org/ejml/sparse/csc/CommonOps_DSCC.java#L792-L802
baratine/baratine
kraken/src/main/java/com/caucho/v5/kraken/query/SelectQueryLocal.java
SelectQueryLocal.onFindAll
private Iterable<Cursor> onFindAll(EnvKelp envKelp, Iterable<RowCursor> rowIter) { """ /* private class FindAllResult extends Result.Wrapper<Iterable<RowCursor>,Iterable<Cursor>> { private EnvKelp _envKelp; FindAllResult(EnvKelp envKelp, Result<Iterable<Cursor>> result) { super(result); _envKelp = envKelp; } @Override public void complete(Iterable<RowCursor> rowIter) { if (rowIter == null) { getNext().complete(null); return; } getNext().complete(new CursorIterable(_envKelp, rowIter, _results)); } } """ if (rowIter == null) { return null; } return new CursorIterable(envKelp, rowIter, _results); }
java
private Iterable<Cursor> onFindAll(EnvKelp envKelp, Iterable<RowCursor> rowIter) { if (rowIter == null) { return null; } return new CursorIterable(envKelp, rowIter, _results); }
[ "private", "Iterable", "<", "Cursor", ">", "onFindAll", "(", "EnvKelp", "envKelp", ",", "Iterable", "<", "RowCursor", ">", "rowIter", ")", "{", "if", "(", "rowIter", "==", "null", ")", "{", "return", "null", ";", "}", "return", "new", "CursorIterable", "(", "envKelp", ",", "rowIter", ",", "_results", ")", ";", "}" ]
/* private class FindAllResult extends Result.Wrapper<Iterable<RowCursor>,Iterable<Cursor>> { private EnvKelp _envKelp; FindAllResult(EnvKelp envKelp, Result<Iterable<Cursor>> result) { super(result); _envKelp = envKelp; } @Override public void complete(Iterable<RowCursor> rowIter) { if (rowIter == null) { getNext().complete(null); return; } getNext().complete(new CursorIterable(_envKelp, rowIter, _results)); } }
[ "/", "*", "private", "class", "FindAllResult", "extends", "Result", ".", "Wrapper<Iterable<RowCursor", ">", "Iterable<Cursor", ">>", "{", "private", "EnvKelp", "_envKelp", ";" ]
train
https://github.com/baratine/baratine/blob/db34b45c03c5a5e930d8142acc72319125569fcf/kraken/src/main/java/com/caucho/v5/kraken/query/SelectQueryLocal.java#L420-L428
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/ICUBinary.java
ICUBinary.readHeader
public static int readHeader(ByteBuffer bytes, int dataFormat, Authenticate authenticate) throws IOException { """ Reads an ICU data header, checks the data format, and returns the data version. <p>Assumes that the ByteBuffer position is 0 on input. The buffer byte order is set according to the data. The buffer position is advanced past the header (including UDataInfo and comment). <p>See C++ ucmndata.h and unicode/udata.h. @return dataVersion @throws IOException if this is not a valid ICU data item of the expected dataFormat """ assert bytes != null && bytes.position() == 0; byte magic1 = bytes.get(2); byte magic2 = bytes.get(3); if (magic1 != MAGIC1 || magic2 != MAGIC2) { throw new IOException(MAGIC_NUMBER_AUTHENTICATION_FAILED_); } byte isBigEndian = bytes.get(8); byte charsetFamily = bytes.get(9); byte sizeofUChar = bytes.get(10); if (isBigEndian < 0 || 1 < isBigEndian || charsetFamily != CHAR_SET_ || sizeofUChar != CHAR_SIZE_) { throw new IOException(HEADER_AUTHENTICATION_FAILED_); } bytes.order(isBigEndian != 0 ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN); int headerSize = bytes.getChar(0); int sizeofUDataInfo = bytes.getChar(4); if (sizeofUDataInfo < 20 || headerSize < (sizeofUDataInfo + 4)) { throw new IOException("Internal Error: Header size error"); } // TODO: Change Authenticate to take int major, int minor, int milli, int micro // to avoid array allocation. byte[] formatVersion = new byte[] { bytes.get(16), bytes.get(17), bytes.get(18), bytes.get(19) }; if (bytes.get(12) != (byte)(dataFormat >> 24) || bytes.get(13) != (byte)(dataFormat >> 16) || bytes.get(14) != (byte)(dataFormat >> 8) || bytes.get(15) != (byte)dataFormat || (authenticate != null && !authenticate.isDataVersionAcceptable(formatVersion))) { throw new IOException(HEADER_AUTHENTICATION_FAILED_ + String.format("; data format %02x%02x%02x%02x, format version %d.%d.%d.%d", bytes.get(12), bytes.get(13), bytes.get(14), bytes.get(15), formatVersion[0] & 0xff, formatVersion[1] & 0xff, formatVersion[2] & 0xff, formatVersion[3] & 0xff)); } bytes.position(headerSize); return // dataVersion (bytes.get(20) << 24) | ((bytes.get(21) & 0xff) << 16) | ((bytes.get(22) & 0xff) << 8) | (bytes.get(23) & 0xff); }
java
public static int readHeader(ByteBuffer bytes, int dataFormat, Authenticate authenticate) throws IOException { assert bytes != null && bytes.position() == 0; byte magic1 = bytes.get(2); byte magic2 = bytes.get(3); if (magic1 != MAGIC1 || magic2 != MAGIC2) { throw new IOException(MAGIC_NUMBER_AUTHENTICATION_FAILED_); } byte isBigEndian = bytes.get(8); byte charsetFamily = bytes.get(9); byte sizeofUChar = bytes.get(10); if (isBigEndian < 0 || 1 < isBigEndian || charsetFamily != CHAR_SET_ || sizeofUChar != CHAR_SIZE_) { throw new IOException(HEADER_AUTHENTICATION_FAILED_); } bytes.order(isBigEndian != 0 ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN); int headerSize = bytes.getChar(0); int sizeofUDataInfo = bytes.getChar(4); if (sizeofUDataInfo < 20 || headerSize < (sizeofUDataInfo + 4)) { throw new IOException("Internal Error: Header size error"); } // TODO: Change Authenticate to take int major, int minor, int milli, int micro // to avoid array allocation. byte[] formatVersion = new byte[] { bytes.get(16), bytes.get(17), bytes.get(18), bytes.get(19) }; if (bytes.get(12) != (byte)(dataFormat >> 24) || bytes.get(13) != (byte)(dataFormat >> 16) || bytes.get(14) != (byte)(dataFormat >> 8) || bytes.get(15) != (byte)dataFormat || (authenticate != null && !authenticate.isDataVersionAcceptable(formatVersion))) { throw new IOException(HEADER_AUTHENTICATION_FAILED_ + String.format("; data format %02x%02x%02x%02x, format version %d.%d.%d.%d", bytes.get(12), bytes.get(13), bytes.get(14), bytes.get(15), formatVersion[0] & 0xff, formatVersion[1] & 0xff, formatVersion[2] & 0xff, formatVersion[3] & 0xff)); } bytes.position(headerSize); return // dataVersion (bytes.get(20) << 24) | ((bytes.get(21) & 0xff) << 16) | ((bytes.get(22) & 0xff) << 8) | (bytes.get(23) & 0xff); }
[ "public", "static", "int", "readHeader", "(", "ByteBuffer", "bytes", ",", "int", "dataFormat", ",", "Authenticate", "authenticate", ")", "throws", "IOException", "{", "assert", "bytes", "!=", "null", "&&", "bytes", ".", "position", "(", ")", "==", "0", ";", "byte", "magic1", "=", "bytes", ".", "get", "(", "2", ")", ";", "byte", "magic2", "=", "bytes", ".", "get", "(", "3", ")", ";", "if", "(", "magic1", "!=", "MAGIC1", "||", "magic2", "!=", "MAGIC2", ")", "{", "throw", "new", "IOException", "(", "MAGIC_NUMBER_AUTHENTICATION_FAILED_", ")", ";", "}", "byte", "isBigEndian", "=", "bytes", ".", "get", "(", "8", ")", ";", "byte", "charsetFamily", "=", "bytes", ".", "get", "(", "9", ")", ";", "byte", "sizeofUChar", "=", "bytes", ".", "get", "(", "10", ")", ";", "if", "(", "isBigEndian", "<", "0", "||", "1", "<", "isBigEndian", "||", "charsetFamily", "!=", "CHAR_SET_", "||", "sizeofUChar", "!=", "CHAR_SIZE_", ")", "{", "throw", "new", "IOException", "(", "HEADER_AUTHENTICATION_FAILED_", ")", ";", "}", "bytes", ".", "order", "(", "isBigEndian", "!=", "0", "?", "ByteOrder", ".", "BIG_ENDIAN", ":", "ByteOrder", ".", "LITTLE_ENDIAN", ")", ";", "int", "headerSize", "=", "bytes", ".", "getChar", "(", "0", ")", ";", "int", "sizeofUDataInfo", "=", "bytes", ".", "getChar", "(", "4", ")", ";", "if", "(", "sizeofUDataInfo", "<", "20", "||", "headerSize", "<", "(", "sizeofUDataInfo", "+", "4", ")", ")", "{", "throw", "new", "IOException", "(", "\"Internal Error: Header size error\"", ")", ";", "}", "// TODO: Change Authenticate to take int major, int minor, int milli, int micro", "// to avoid array allocation.", "byte", "[", "]", "formatVersion", "=", "new", "byte", "[", "]", "{", "bytes", ".", "get", "(", "16", ")", ",", "bytes", ".", "get", "(", "17", ")", ",", "bytes", ".", "get", "(", "18", ")", ",", "bytes", ".", "get", "(", "19", ")", "}", ";", "if", "(", "bytes", ".", "get", "(", "12", ")", "!=", "(", "byte", ")", "(", "dataFormat", ">>", "24", ")", "||", "bytes", ".", "get", "(", "13", ")", "!=", "(", "byte", ")", "(", "dataFormat", ">>", "16", ")", "||", "bytes", ".", "get", "(", "14", ")", "!=", "(", "byte", ")", "(", "dataFormat", ">>", "8", ")", "||", "bytes", ".", "get", "(", "15", ")", "!=", "(", "byte", ")", "dataFormat", "||", "(", "authenticate", "!=", "null", "&&", "!", "authenticate", ".", "isDataVersionAcceptable", "(", "formatVersion", ")", ")", ")", "{", "throw", "new", "IOException", "(", "HEADER_AUTHENTICATION_FAILED_", "+", "String", ".", "format", "(", "\"; data format %02x%02x%02x%02x, format version %d.%d.%d.%d\"", ",", "bytes", ".", "get", "(", "12", ")", ",", "bytes", ".", "get", "(", "13", ")", ",", "bytes", ".", "get", "(", "14", ")", ",", "bytes", ".", "get", "(", "15", ")", ",", "formatVersion", "[", "0", "]", "&", "0xff", ",", "formatVersion", "[", "1", "]", "&", "0xff", ",", "formatVersion", "[", "2", "]", "&", "0xff", ",", "formatVersion", "[", "3", "]", "&", "0xff", ")", ")", ";", "}", "bytes", ".", "position", "(", "headerSize", ")", ";", "return", "// dataVersion", "(", "bytes", ".", "get", "(", "20", ")", "<<", "24", ")", "|", "(", "(", "bytes", ".", "get", "(", "21", ")", "&", "0xff", ")", "<<", "16", ")", "|", "(", "(", "bytes", ".", "get", "(", "22", ")", "&", "0xff", ")", "<<", "8", ")", "|", "(", "bytes", ".", "get", "(", "23", ")", "&", "0xff", ")", ";", "}" ]
Reads an ICU data header, checks the data format, and returns the data version. <p>Assumes that the ByteBuffer position is 0 on input. The buffer byte order is set according to the data. The buffer position is advanced past the header (including UDataInfo and comment). <p>See C++ ucmndata.h and unicode/udata.h. @return dataVersion @throws IOException if this is not a valid ICU data item of the expected dataFormat
[ "Reads", "an", "ICU", "data", "header", "checks", "the", "data", "format", "and", "returns", "the", "data", "version", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/ICUBinary.java#L575-L621
landawn/AbacusUtil
src/com/landawn/abacus/util/FloatList.java
FloatList.allMatch
public <E extends Exception> boolean allMatch(Try.FloatPredicate<E> filter) throws E { """ Returns whether all elements of this List match the provided predicate. @param filter @return """ return allMatch(0, size(), filter); }
java
public <E extends Exception> boolean allMatch(Try.FloatPredicate<E> filter) throws E { return allMatch(0, size(), filter); }
[ "public", "<", "E", "extends", "Exception", ">", "boolean", "allMatch", "(", "Try", ".", "FloatPredicate", "<", "E", ">", "filter", ")", "throws", "E", "{", "return", "allMatch", "(", "0", ",", "size", "(", ")", ",", "filter", ")", ";", "}" ]
Returns whether all elements of this List match the provided predicate. @param filter @return
[ "Returns", "whether", "all", "elements", "of", "this", "List", "match", "the", "provided", "predicate", "." ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/FloatList.java#L905-L907
calrissian/mango
mango-json/src/main/java/org/calrissian/mango/json/mappings/JsonAttributeMappings.java
JsonAttributeMappings.toJsonString
public static String toJsonString(Collection<Attribute> attributeCollection, ObjectMapper objectMapper) throws JsonProcessingException { """ Re-expands a flattened json representation from a collection of attributes back into a raw nested json string. """ return objectMapper.writeValueAsString(toObject(attributeCollection)); }
java
public static String toJsonString(Collection<Attribute> attributeCollection, ObjectMapper objectMapper) throws JsonProcessingException { return objectMapper.writeValueAsString(toObject(attributeCollection)); }
[ "public", "static", "String", "toJsonString", "(", "Collection", "<", "Attribute", ">", "attributeCollection", ",", "ObjectMapper", "objectMapper", ")", "throws", "JsonProcessingException", "{", "return", "objectMapper", ".", "writeValueAsString", "(", "toObject", "(", "attributeCollection", ")", ")", ";", "}" ]
Re-expands a flattened json representation from a collection of attributes back into a raw nested json string.
[ "Re", "-", "expands", "a", "flattened", "json", "representation", "from", "a", "collection", "of", "attributes", "back", "into", "a", "raw", "nested", "json", "string", "." ]
train
https://github.com/calrissian/mango/blob/a95aa5e77af9aa0e629787228d80806560023452/mango-json/src/main/java/org/calrissian/mango/json/mappings/JsonAttributeMappings.java#L100-L102
undertow-io/undertow
core/src/main/java/io/undertow/websockets/core/protocol/version07/Base64.java
Base64.decodeFromFile
public static byte[] decodeFromFile(String filename) throws java.io.IOException { """ Convenience method for reading a base64-encoded file and decoding it. <p> As of v 2.3, if there is a error, the method will throw an java.io.IOException. <b>This is new to v2.3!</b> In earlier versions, it just returned false, but in retrospect that's a pretty poor way to handle it. </p> @param filename Filename for reading encoded data @return decoded byte array @throws java.io.IOException if there is an error @since 2.1 """ byte[] decodedData = null; Base64.InputStream bis = null; try { // Set up some useful variables Path file = Paths.get(filename); byte[] buffer; int length = 0; int numBytes; // Check for size of file if (Files.size(file) > Integer.MAX_VALUE) { throw new java.io.IOException("File is too big for this convenience method (" + Files.size(file) + " bytes)."); } // end if: file too big for int index buffer = new byte[(int) Files.size(file)]; // Open a stream bis = new Base64.InputStream(new java.io.BufferedInputStream(Files.newInputStream(file)), Base64.DECODE); // Read until done while ((numBytes = bis.read(buffer, length, 4096)) >= 0) { length += numBytes; } // end while // Save in a variable to return decodedData = new byte[length]; System.arraycopy(buffer, 0, decodedData, 0, length); } // end try catch (java.io.IOException e) { throw e; // Catch and release to execute finally{} } // end catch: java.io.IOException finally { try { bis.close(); } catch (Exception e) { } } // end finally return decodedData; }
java
public static byte[] decodeFromFile(String filename) throws java.io.IOException { byte[] decodedData = null; Base64.InputStream bis = null; try { // Set up some useful variables Path file = Paths.get(filename); byte[] buffer; int length = 0; int numBytes; // Check for size of file if (Files.size(file) > Integer.MAX_VALUE) { throw new java.io.IOException("File is too big for this convenience method (" + Files.size(file) + " bytes)."); } // end if: file too big for int index buffer = new byte[(int) Files.size(file)]; // Open a stream bis = new Base64.InputStream(new java.io.BufferedInputStream(Files.newInputStream(file)), Base64.DECODE); // Read until done while ((numBytes = bis.read(buffer, length, 4096)) >= 0) { length += numBytes; } // end while // Save in a variable to return decodedData = new byte[length]; System.arraycopy(buffer, 0, decodedData, 0, length); } // end try catch (java.io.IOException e) { throw e; // Catch and release to execute finally{} } // end catch: java.io.IOException finally { try { bis.close(); } catch (Exception e) { } } // end finally return decodedData; }
[ "public", "static", "byte", "[", "]", "decodeFromFile", "(", "String", "filename", ")", "throws", "java", ".", "io", ".", "IOException", "{", "byte", "[", "]", "decodedData", "=", "null", ";", "Base64", ".", "InputStream", "bis", "=", "null", ";", "try", "{", "// Set up some useful variables", "Path", "file", "=", "Paths", ".", "get", "(", "filename", ")", ";", "byte", "[", "]", "buffer", ";", "int", "length", "=", "0", ";", "int", "numBytes", ";", "// Check for size of file", "if", "(", "Files", ".", "size", "(", "file", ")", ">", "Integer", ".", "MAX_VALUE", ")", "{", "throw", "new", "java", ".", "io", ".", "IOException", "(", "\"File is too big for this convenience method (\"", "+", "Files", ".", "size", "(", "file", ")", "+", "\" bytes).\"", ")", ";", "}", "// end if: file too big for int index", "buffer", "=", "new", "byte", "[", "(", "int", ")", "Files", ".", "size", "(", "file", ")", "]", ";", "// Open a stream", "bis", "=", "new", "Base64", ".", "InputStream", "(", "new", "java", ".", "io", ".", "BufferedInputStream", "(", "Files", ".", "newInputStream", "(", "file", ")", ")", ",", "Base64", ".", "DECODE", ")", ";", "// Read until done", "while", "(", "(", "numBytes", "=", "bis", ".", "read", "(", "buffer", ",", "length", ",", "4096", ")", ")", ">=", "0", ")", "{", "length", "+=", "numBytes", ";", "}", "// end while", "// Save in a variable to return", "decodedData", "=", "new", "byte", "[", "length", "]", ";", "System", ".", "arraycopy", "(", "buffer", ",", "0", ",", "decodedData", ",", "0", ",", "length", ")", ";", "}", "// end try", "catch", "(", "java", ".", "io", ".", "IOException", "e", ")", "{", "throw", "e", ";", "// Catch and release to execute finally{}", "}", "// end catch: java.io.IOException", "finally", "{", "try", "{", "bis", ".", "close", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "}", "}", "// end finally", "return", "decodedData", ";", "}" ]
Convenience method for reading a base64-encoded file and decoding it. <p> As of v 2.3, if there is a error, the method will throw an java.io.IOException. <b>This is new to v2.3!</b> In earlier versions, it just returned false, but in retrospect that's a pretty poor way to handle it. </p> @param filename Filename for reading encoded data @return decoded byte array @throws java.io.IOException if there is an error @since 2.1
[ "Convenience", "method", "for", "reading", "a", "base64", "-", "encoded", "file", "and", "decoding", "it", "." ]
train
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/websockets/core/protocol/version07/Base64.java#L1355-L1396
codeprimate-software/cp-elements
src/main/java/org/cp/elements/lang/ClassUtils.java
ClassUtils.isAnnotationPresent
@NullSafe public static boolean isAnnotationPresent(Class<? extends Annotation> annotation, AnnotatedElement... members) { """ Determines whether the specified Annotation meta-data is present on the given "annotated" members, such as fields and methods. @param annotation the Annotation used in the detection for presence on the given members. @param members the members of a class type or object to inspect for the presence of the specified Annotation. @return a boolean value indicating whether the specified Annotation is present on any of the given members. @see java.lang.annotation.Annotation @see java.lang.reflect.AccessibleObject#isAnnotationPresent(Class) """ return stream(ArrayUtils.nullSafeArray(members, AnnotatedElement.class)) .anyMatch(member -> member != null && member.isAnnotationPresent(annotation)); }
java
@NullSafe public static boolean isAnnotationPresent(Class<? extends Annotation> annotation, AnnotatedElement... members) { return stream(ArrayUtils.nullSafeArray(members, AnnotatedElement.class)) .anyMatch(member -> member != null && member.isAnnotationPresent(annotation)); }
[ "@", "NullSafe", "public", "static", "boolean", "isAnnotationPresent", "(", "Class", "<", "?", "extends", "Annotation", ">", "annotation", ",", "AnnotatedElement", "...", "members", ")", "{", "return", "stream", "(", "ArrayUtils", ".", "nullSafeArray", "(", "members", ",", "AnnotatedElement", ".", "class", ")", ")", ".", "anyMatch", "(", "member", "->", "member", "!=", "null", "&&", "member", ".", "isAnnotationPresent", "(", "annotation", ")", ")", ";", "}" ]
Determines whether the specified Annotation meta-data is present on the given "annotated" members, such as fields and methods. @param annotation the Annotation used in the detection for presence on the given members. @param members the members of a class type or object to inspect for the presence of the specified Annotation. @return a boolean value indicating whether the specified Annotation is present on any of the given members. @see java.lang.annotation.Annotation @see java.lang.reflect.AccessibleObject#isAnnotationPresent(Class)
[ "Determines", "whether", "the", "specified", "Annotation", "meta", "-", "data", "is", "present", "on", "the", "given", "annotated", "members", "such", "as", "fields", "and", "methods", "." ]
train
https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/ClassUtils.java#L592-L596
j-a-w-r/jawr-main-repo
jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/IOUtils.java
IOUtils.copy
public static void copy(Reader reader, Writer writer) throws IOException { """ Writes all the contents of a Reader to a Writer. @param reader the reader to read from @param writer the writer to write to @throws java.io.IOException if an IOExcption occurs """ copy(reader, writer, false); }
java
public static void copy(Reader reader, Writer writer) throws IOException { copy(reader, writer, false); }
[ "public", "static", "void", "copy", "(", "Reader", "reader", ",", "Writer", "writer", ")", "throws", "IOException", "{", "copy", "(", "reader", ",", "writer", ",", "false", ")", ";", "}" ]
Writes all the contents of a Reader to a Writer. @param reader the reader to read from @param writer the writer to write to @throws java.io.IOException if an IOExcption occurs
[ "Writes", "all", "the", "contents", "of", "a", "Reader", "to", "a", "Writer", "." ]
train
https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/IOUtils.java#L42-L44
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/geom/FeatureShapes.java
FeatureShapes.removeShapesWithExclusion
public int removeShapesWithExclusion(String database, String table, GoogleMapShapeType excludedType) { """ Remove all map shapes in the database and table from the map, excluding shapes with the excluded type @param database GeoPackage database @param table table name @param excludedType Google Map Shape Type to exclude from map removal @return count of removed features @since 3.2.0 """ Set<GoogleMapShapeType> excludedTypes = new HashSet<>(); excludedTypes.add(excludedType); return removeShapesWithExclusions(database, table, excludedTypes); }
java
public int removeShapesWithExclusion(String database, String table, GoogleMapShapeType excludedType) { Set<GoogleMapShapeType> excludedTypes = new HashSet<>(); excludedTypes.add(excludedType); return removeShapesWithExclusions(database, table, excludedTypes); }
[ "public", "int", "removeShapesWithExclusion", "(", "String", "database", ",", "String", "table", ",", "GoogleMapShapeType", "excludedType", ")", "{", "Set", "<", "GoogleMapShapeType", ">", "excludedTypes", "=", "new", "HashSet", "<>", "(", ")", ";", "excludedTypes", ".", "add", "(", "excludedType", ")", ";", "return", "removeShapesWithExclusions", "(", "database", ",", "table", ",", "excludedTypes", ")", ";", "}" ]
Remove all map shapes in the database and table from the map, excluding shapes with the excluded type @param database GeoPackage database @param table table name @param excludedType Google Map Shape Type to exclude from map removal @return count of removed features @since 3.2.0
[ "Remove", "all", "map", "shapes", "in", "the", "database", "and", "table", "from", "the", "map", "excluding", "shapes", "with", "the", "excluded", "type" ]
train
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/geom/FeatureShapes.java#L373-L377
Azure/azure-sdk-for-java
redis/resource-manager/v2018_03_01/src/main/java/com/microsoft/azure/management/redis/v2018_03_01/implementation/LinkedServersInner.java
LinkedServersInner.getAsync
public Observable<RedisLinkedServerWithPropertiesInner> getAsync(String resourceGroupName, String name, String linkedServerName) { """ Gets the detailed information about a linked server of a redis cache (requires Premium SKU). @param resourceGroupName The name of the resource group. @param name The name of the redis cache. @param linkedServerName The name of the linked server. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the RedisLinkedServerWithPropertiesInner object """ return getWithServiceResponseAsync(resourceGroupName, name, linkedServerName).map(new Func1<ServiceResponse<RedisLinkedServerWithPropertiesInner>, RedisLinkedServerWithPropertiesInner>() { @Override public RedisLinkedServerWithPropertiesInner call(ServiceResponse<RedisLinkedServerWithPropertiesInner> response) { return response.body(); } }); }
java
public Observable<RedisLinkedServerWithPropertiesInner> getAsync(String resourceGroupName, String name, String linkedServerName) { return getWithServiceResponseAsync(resourceGroupName, name, linkedServerName).map(new Func1<ServiceResponse<RedisLinkedServerWithPropertiesInner>, RedisLinkedServerWithPropertiesInner>() { @Override public RedisLinkedServerWithPropertiesInner call(ServiceResponse<RedisLinkedServerWithPropertiesInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "RedisLinkedServerWithPropertiesInner", ">", "getAsync", "(", "String", "resourceGroupName", ",", "String", "name", ",", "String", "linkedServerName", ")", "{", "return", "getWithServiceResponseAsync", "(", "resourceGroupName", ",", "name", ",", "linkedServerName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "RedisLinkedServerWithPropertiesInner", ">", ",", "RedisLinkedServerWithPropertiesInner", ">", "(", ")", "{", "@", "Override", "public", "RedisLinkedServerWithPropertiesInner", "call", "(", "ServiceResponse", "<", "RedisLinkedServerWithPropertiesInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Gets the detailed information about a linked server of a redis cache (requires Premium SKU). @param resourceGroupName The name of the resource group. @param name The name of the redis cache. @param linkedServerName The name of the linked server. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the RedisLinkedServerWithPropertiesInner object
[ "Gets", "the", "detailed", "information", "about", "a", "linked", "server", "of", "a", "redis", "cache", "(", "requires", "Premium", "SKU", ")", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/redis/resource-manager/v2018_03_01/src/main/java/com/microsoft/azure/management/redis/v2018_03_01/implementation/LinkedServersInner.java#L407-L414
docusign/docusign-java-client
src/main/java/com/docusign/esign/api/UsersApi.java
UsersApi.updateSignature
public UserSignature updateSignature(String accountId, String userId, String signatureId, UserSignatureDefinition userSignatureDefinition, UsersApi.UpdateSignatureOptions options) throws ApiException { """ Updates the user signature for a specified user. Creates, or updates, the signature font and initials for the specified user. When creating a signature, you use this resource to create the signature name and then add the signature and initials images into the signature. ###### Note: This will also create a default signature for the user when one does not exist. The userId property specified in the endpoint must match the authenticated user&#39;s user ID and the user must be a member of the account. The &#x60;signatureId&#x60; parameter accepts a signature ID or a signature name. DocuSign recommends you use signature ID (&#x60;signatureId&#x60;), since some names contain characters that do not properly encode into a URL. If you use the user name, it is likely that the name includes spaces. In that case, URL encode the name before using it in the endpoint. For example encode \&quot;Bob Smith\&quot; as \&quot;Bob%20Smith\&quot;. @param accountId The external account number (int) or account ID Guid. (required) @param userId The user ID of the user being accessed. Generally this is the user ID of the authenticated user, but if the authenticated user is an Admin on the account, this may be another user the Admin user is accessing. (required) @param signatureId The ID of the signature being accessed. (required) @param userSignatureDefinition (optional) @param options for modifying the method behavior. @return UserSignature @throws ApiException if fails to make API call """ Object localVarPostBody = userSignatureDefinition; // verify the required parameter 'accountId' is set if (accountId == null) { throw new ApiException(400, "Missing the required parameter 'accountId' when calling updateSignature"); } // verify the required parameter 'userId' is set if (userId == null) { throw new ApiException(400, "Missing the required parameter 'userId' when calling updateSignature"); } // verify the required parameter 'signatureId' is set if (signatureId == null) { throw new ApiException(400, "Missing the required parameter 'signatureId' when calling updateSignature"); } // create path and map variables String localVarPath = "/v2/accounts/{accountId}/users/{userId}/signatures/{signatureId}".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "accountId" + "\\}", apiClient.escapeString(accountId.toString())) .replaceAll("\\{" + "userId" + "\\}", apiClient.escapeString(userId.toString())) .replaceAll("\\{" + "signatureId" + "\\}", apiClient.escapeString(signatureId.toString())); // query params java.util.List<Pair> localVarQueryParams = new java.util.ArrayList<Pair>(); java.util.Map<String, String> localVarHeaderParams = new java.util.HashMap<String, String>(); java.util.Map<String, Object> localVarFormParams = new java.util.HashMap<String, Object>(); if (options != null) { localVarQueryParams.addAll(apiClient.parameterToPairs("", "close_existing_signature", options.closeExistingSignature)); } final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] localVarContentTypes = { }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); String[] localVarAuthNames = new String[] { "docusignAccessCode" }; //{ }; GenericType<UserSignature> localVarReturnType = new GenericType<UserSignature>() {}; return apiClient.invokeAPI(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); }
java
public UserSignature updateSignature(String accountId, String userId, String signatureId, UserSignatureDefinition userSignatureDefinition, UsersApi.UpdateSignatureOptions options) throws ApiException { Object localVarPostBody = userSignatureDefinition; // verify the required parameter 'accountId' is set if (accountId == null) { throw new ApiException(400, "Missing the required parameter 'accountId' when calling updateSignature"); } // verify the required parameter 'userId' is set if (userId == null) { throw new ApiException(400, "Missing the required parameter 'userId' when calling updateSignature"); } // verify the required parameter 'signatureId' is set if (signatureId == null) { throw new ApiException(400, "Missing the required parameter 'signatureId' when calling updateSignature"); } // create path and map variables String localVarPath = "/v2/accounts/{accountId}/users/{userId}/signatures/{signatureId}".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "accountId" + "\\}", apiClient.escapeString(accountId.toString())) .replaceAll("\\{" + "userId" + "\\}", apiClient.escapeString(userId.toString())) .replaceAll("\\{" + "signatureId" + "\\}", apiClient.escapeString(signatureId.toString())); // query params java.util.List<Pair> localVarQueryParams = new java.util.ArrayList<Pair>(); java.util.Map<String, String> localVarHeaderParams = new java.util.HashMap<String, String>(); java.util.Map<String, Object> localVarFormParams = new java.util.HashMap<String, Object>(); if (options != null) { localVarQueryParams.addAll(apiClient.parameterToPairs("", "close_existing_signature", options.closeExistingSignature)); } final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] localVarContentTypes = { }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); String[] localVarAuthNames = new String[] { "docusignAccessCode" }; //{ }; GenericType<UserSignature> localVarReturnType = new GenericType<UserSignature>() {}; return apiClient.invokeAPI(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); }
[ "public", "UserSignature", "updateSignature", "(", "String", "accountId", ",", "String", "userId", ",", "String", "signatureId", ",", "UserSignatureDefinition", "userSignatureDefinition", ",", "UsersApi", ".", "UpdateSignatureOptions", "options", ")", "throws", "ApiException", "{", "Object", "localVarPostBody", "=", "userSignatureDefinition", ";", "// verify the required parameter 'accountId' is set", "if", "(", "accountId", "==", "null", ")", "{", "throw", "new", "ApiException", "(", "400", ",", "\"Missing the required parameter 'accountId' when calling updateSignature\"", ")", ";", "}", "// verify the required parameter 'userId' is set", "if", "(", "userId", "==", "null", ")", "{", "throw", "new", "ApiException", "(", "400", ",", "\"Missing the required parameter 'userId' when calling updateSignature\"", ")", ";", "}", "// verify the required parameter 'signatureId' is set", "if", "(", "signatureId", "==", "null", ")", "{", "throw", "new", "ApiException", "(", "400", ",", "\"Missing the required parameter 'signatureId' when calling updateSignature\"", ")", ";", "}", "// create path and map variables", "String", "localVarPath", "=", "\"/v2/accounts/{accountId}/users/{userId}/signatures/{signatureId}\"", ".", "replaceAll", "(", "\"\\\\{format\\\\}\"", ",", "\"json\"", ")", ".", "replaceAll", "(", "\"\\\\{\"", "+", "\"accountId\"", "+", "\"\\\\}\"", ",", "apiClient", ".", "escapeString", "(", "accountId", ".", "toString", "(", ")", ")", ")", ".", "replaceAll", "(", "\"\\\\{\"", "+", "\"userId\"", "+", "\"\\\\}\"", ",", "apiClient", ".", "escapeString", "(", "userId", ".", "toString", "(", ")", ")", ")", ".", "replaceAll", "(", "\"\\\\{\"", "+", "\"signatureId\"", "+", "\"\\\\}\"", ",", "apiClient", ".", "escapeString", "(", "signatureId", ".", "toString", "(", ")", ")", ")", ";", "// query params", "java", ".", "util", ".", "List", "<", "Pair", ">", "localVarQueryParams", "=", "new", "java", ".", "util", ".", "ArrayList", "<", "Pair", ">", "(", ")", ";", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "localVarHeaderParams", "=", "new", "java", ".", "util", ".", "HashMap", "<", "String", ",", "String", ">", "(", ")", ";", "java", ".", "util", ".", "Map", "<", "String", ",", "Object", ">", "localVarFormParams", "=", "new", "java", ".", "util", ".", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "if", "(", "options", "!=", "null", ")", "{", "localVarQueryParams", ".", "addAll", "(", "apiClient", ".", "parameterToPairs", "(", "\"\"", ",", "\"close_existing_signature\"", ",", "options", ".", "closeExistingSignature", ")", ")", ";", "}", "final", "String", "[", "]", "localVarAccepts", "=", "{", "\"application/json\"", "}", ";", "final", "String", "localVarAccept", "=", "apiClient", ".", "selectHeaderAccept", "(", "localVarAccepts", ")", ";", "final", "String", "[", "]", "localVarContentTypes", "=", "{", "}", ";", "final", "String", "localVarContentType", "=", "apiClient", ".", "selectHeaderContentType", "(", "localVarContentTypes", ")", ";", "String", "[", "]", "localVarAuthNames", "=", "new", "String", "[", "]", "{", "\"docusignAccessCode\"", "}", ";", "//{ };", "GenericType", "<", "UserSignature", ">", "localVarReturnType", "=", "new", "GenericType", "<", "UserSignature", ">", "(", ")", "{", "}", ";", "return", "apiClient", ".", "invokeAPI", "(", "localVarPath", ",", "\"PUT\"", ",", "localVarQueryParams", ",", "localVarPostBody", ",", "localVarHeaderParams", ",", "localVarFormParams", ",", "localVarAccept", ",", "localVarContentType", ",", "localVarAuthNames", ",", "localVarReturnType", ")", ";", "}" ]
Updates the user signature for a specified user. Creates, or updates, the signature font and initials for the specified user. When creating a signature, you use this resource to create the signature name and then add the signature and initials images into the signature. ###### Note: This will also create a default signature for the user when one does not exist. The userId property specified in the endpoint must match the authenticated user&#39;s user ID and the user must be a member of the account. The &#x60;signatureId&#x60; parameter accepts a signature ID or a signature name. DocuSign recommends you use signature ID (&#x60;signatureId&#x60;), since some names contain characters that do not properly encode into a URL. If you use the user name, it is likely that the name includes spaces. In that case, URL encode the name before using it in the endpoint. For example encode \&quot;Bob Smith\&quot; as \&quot;Bob%20Smith\&quot;. @param accountId The external account number (int) or account ID Guid. (required) @param userId The user ID of the user being accessed. Generally this is the user ID of the authenticated user, but if the authenticated user is an Admin on the account, this may be another user the Admin user is accessing. (required) @param signatureId The ID of the signature being accessed. (required) @param userSignatureDefinition (optional) @param options for modifying the method behavior. @return UserSignature @throws ApiException if fails to make API call
[ "Updates", "the", "user", "signature", "for", "a", "specified", "user", ".", "Creates", "or", "updates", "the", "signature", "font", "and", "initials", "for", "the", "specified", "user", ".", "When", "creating", "a", "signature", "you", "use", "this", "resource", "to", "create", "the", "signature", "name", "and", "then", "add", "the", "signature", "and", "initials", "images", "into", "the", "signature", ".", "######", "Note", ":", "This", "will", "also", "create", "a", "default", "signature", "for", "the", "user", "when", "one", "does", "not", "exist", ".", "The", "userId", "property", "specified", "in", "the", "endpoint", "must", "match", "the", "authenticated", "user&#39", ";", "s", "user", "ID", "and", "the", "user", "must", "be", "a", "member", "of", "the", "account", ".", "The", "&#x60", ";", "signatureId&#x60", ";", "parameter", "accepts", "a", "signature", "ID", "or", "a", "signature", "name", ".", "DocuSign", "recommends", "you", "use", "signature", "ID", "(", "&#x60", ";", "signatureId&#x60", ";", ")", "since", "some", "names", "contain", "characters", "that", "do", "not", "properly", "encode", "into", "a", "URL", ".", "If", "you", "use", "the", "user", "name", "it", "is", "likely", "that", "the", "name", "includes", "spaces", ".", "In", "that", "case", "URL", "encode", "the", "name", "before", "using", "it", "in", "the", "endpoint", ".", "For", "example", "encode", "\\", "&quot", ";", "Bob", "Smith", "\\", "&quot", ";", "as", "\\", "&quot", ";", "Bob%20Smith", "\\", "&quot", ";", "." ]
train
https://github.com/docusign/docusign-java-client/blob/17ae82ace0f023e98edf813be832950568212e34/src/main/java/com/docusign/esign/api/UsersApi.java#L1653-L1701
alkacon/opencms-core
src/org/opencms/gwt/CmsAliasHelper.java
CmsAliasHelper.checkValidAliasPath
protected String checkValidAliasPath(String path, Locale locale) { """ Checks whether a given string is a valid alias path.<p> @param path the path to check @param locale the locale to use for validation messages @return null if the string is a valid alias path, else an error message """ if (org.opencms.db.CmsAlias.ALIAS_PATTERN.matcher(path).matches()) { return null; } else { return Messages.get().getBundle(locale).key(Messages.ERR_ALIAS_INVALID_PATH_0); } }
java
protected String checkValidAliasPath(String path, Locale locale) { if (org.opencms.db.CmsAlias.ALIAS_PATTERN.matcher(path).matches()) { return null; } else { return Messages.get().getBundle(locale).key(Messages.ERR_ALIAS_INVALID_PATH_0); } }
[ "protected", "String", "checkValidAliasPath", "(", "String", "path", ",", "Locale", "locale", ")", "{", "if", "(", "org", ".", "opencms", ".", "db", ".", "CmsAlias", ".", "ALIAS_PATTERN", ".", "matcher", "(", "path", ")", ".", "matches", "(", ")", ")", "{", "return", "null", ";", "}", "else", "{", "return", "Messages", ".", "get", "(", ")", ".", "getBundle", "(", "locale", ")", ".", "key", "(", "Messages", ".", "ERR_ALIAS_INVALID_PATH_0", ")", ";", "}", "}" ]
Checks whether a given string is a valid alias path.<p> @param path the path to check @param locale the locale to use for validation messages @return null if the string is a valid alias path, else an error message
[ "Checks", "whether", "a", "given", "string", "is", "a", "valid", "alias", "path", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/gwt/CmsAliasHelper.java#L154-L161
beanshell/beanshell
src/main/java/bsh/org/objectweb/asm/ByteVector.java
ByteVector.putUTF8
public ByteVector putUTF8(final String stringValue) { """ Puts an UTF8 string into this byte vector. The byte vector is automatically enlarged if necessary. @param stringValue a String whose UTF8 encoded length must be less than 65536. @return this byte vector. """ int charLength = stringValue.length(); if (charLength > 65535) { throw new IllegalArgumentException(); } int currentLength = length; if (currentLength + 2 + charLength > data.length) { enlarge(2 + charLength); } byte[] currentData = data; // Optimistic algorithm: instead of computing the byte length and then serializing the string // (which requires two loops), we assume the byte length is equal to char length (which is the // most frequent case), and we start serializing the string right away. During the // serialization, if we find that this assumption is wrong, we continue with the general method. currentData[currentLength++] = (byte) (charLength >>> 8); currentData[currentLength++] = (byte) charLength; for (int i = 0; i < charLength; ++i) { char charValue = stringValue.charAt(i); if (charValue >= '\u0001' && charValue <= '\u007F') { currentData[currentLength++] = (byte) charValue; } else { length = currentLength; return encodeUTF8(stringValue, i, 65535); } } length = currentLength; return this; }
java
public ByteVector putUTF8(final String stringValue) { int charLength = stringValue.length(); if (charLength > 65535) { throw new IllegalArgumentException(); } int currentLength = length; if (currentLength + 2 + charLength > data.length) { enlarge(2 + charLength); } byte[] currentData = data; // Optimistic algorithm: instead of computing the byte length and then serializing the string // (which requires two loops), we assume the byte length is equal to char length (which is the // most frequent case), and we start serializing the string right away. During the // serialization, if we find that this assumption is wrong, we continue with the general method. currentData[currentLength++] = (byte) (charLength >>> 8); currentData[currentLength++] = (byte) charLength; for (int i = 0; i < charLength; ++i) { char charValue = stringValue.charAt(i); if (charValue >= '\u0001' && charValue <= '\u007F') { currentData[currentLength++] = (byte) charValue; } else { length = currentLength; return encodeUTF8(stringValue, i, 65535); } } length = currentLength; return this; }
[ "public", "ByteVector", "putUTF8", "(", "final", "String", "stringValue", ")", "{", "int", "charLength", "=", "stringValue", ".", "length", "(", ")", ";", "if", "(", "charLength", ">", "65535", ")", "{", "throw", "new", "IllegalArgumentException", "(", ")", ";", "}", "int", "currentLength", "=", "length", ";", "if", "(", "currentLength", "+", "2", "+", "charLength", ">", "data", ".", "length", ")", "{", "enlarge", "(", "2", "+", "charLength", ")", ";", "}", "byte", "[", "]", "currentData", "=", "data", ";", "// Optimistic algorithm: instead of computing the byte length and then serializing the string", "// (which requires two loops), we assume the byte length is equal to char length (which is the", "// most frequent case), and we start serializing the string right away. During the", "// serialization, if we find that this assumption is wrong, we continue with the general method.", "currentData", "[", "currentLength", "++", "]", "=", "(", "byte", ")", "(", "charLength", ">>>", "8", ")", ";", "currentData", "[", "currentLength", "++", "]", "=", "(", "byte", ")", "charLength", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "charLength", ";", "++", "i", ")", "{", "char", "charValue", "=", "stringValue", ".", "charAt", "(", "i", ")", ";", "if", "(", "charValue", ">=", "'", "'", "&&", "charValue", "<=", "'", "'", ")", "{", "currentData", "[", "currentLength", "++", "]", "=", "(", "byte", ")", "charValue", ";", "}", "else", "{", "length", "=", "currentLength", ";", "return", "encodeUTF8", "(", "stringValue", ",", "i", ",", "65535", ")", ";", "}", "}", "length", "=", "currentLength", ";", "return", "this", ";", "}" ]
Puts an UTF8 string into this byte vector. The byte vector is automatically enlarged if necessary. @param stringValue a String whose UTF8 encoded length must be less than 65536. @return this byte vector.
[ "Puts", "an", "UTF8", "string", "into", "this", "byte", "vector", ".", "The", "byte", "vector", "is", "automatically", "enlarged", "if", "necessary", "." ]
train
https://github.com/beanshell/beanshell/blob/fdddee3de948c9e6babb2d1337028f6fd0a2ba5c/src/main/java/bsh/org/objectweb/asm/ByteVector.java#L242-L269
nmdp-bioinformatics/ngs
range/src/main/java/org/nmdp/ngs/range/rtree/RangeGeometries.java
RangeGeometries.closedOpen
public static <N extends Number & Comparable<? super N>> Rectangle closedOpen(final N lower, final N upper) { """ Create and return a new rectangle geometry from the specified closed open range <code>[lower..upper)</code>. @param lower lower endpoint, must not be null @param upper upper endpoint, must not be null @return a new rectangle geometry from the specified closed range """ checkNotNull(lower); checkNotNull(upper); return range(Range.closedOpen(lower, upper)); }
java
public static <N extends Number & Comparable<? super N>> Rectangle closedOpen(final N lower, final N upper) { checkNotNull(lower); checkNotNull(upper); return range(Range.closedOpen(lower, upper)); }
[ "public", "static", "<", "N", "extends", "Number", "&", "Comparable", "<", "?", "super", "N", ">", ">", "Rectangle", "closedOpen", "(", "final", "N", "lower", ",", "final", "N", "upper", ")", "{", "checkNotNull", "(", "lower", ")", ";", "checkNotNull", "(", "upper", ")", ";", "return", "range", "(", "Range", ".", "closedOpen", "(", "lower", ",", "upper", ")", ")", ";", "}" ]
Create and return a new rectangle geometry from the specified closed open range <code>[lower..upper)</code>. @param lower lower endpoint, must not be null @param upper upper endpoint, must not be null @return a new rectangle geometry from the specified closed range
[ "Create", "and", "return", "a", "new", "rectangle", "geometry", "from", "the", "specified", "closed", "open", "range", "<code", ">", "[", "lower", "..", "upper", ")", "<", "/", "code", ">", "." ]
train
https://github.com/nmdp-bioinformatics/ngs/blob/277627e4311313a80f5dc110b3185b0d7af32bd0/range/src/main/java/org/nmdp/ngs/range/rtree/RangeGeometries.java#L91-L95
vlingo/vlingo-actors
src/main/java/io/vlingo/actors/World.java
World.actorFor
public Protocols actorFor(final Class<?>[] protocols, final Class<? extends Actor> type, final Object...parameters) { """ Answers a {@code Protocols} that provides one or more supported protocols for the newly created {@code Actor} according to {@code definition}. @param protocols the {@code Class<?>[]} array of protocols that the {@code Actor} supports @param type the {@code Class<? extends Actor>} of the {@code Actor} to create @param parameters the {@code Object[]} of constructor parameters @return {@code Protocols} """ if (isTerminated()) { throw new IllegalStateException("vlingo/actors: Stopped."); } return stage().actorFor(protocols, type, parameters); }
java
public Protocols actorFor(final Class<?>[] protocols, final Class<? extends Actor> type, final Object...parameters) { if (isTerminated()) { throw new IllegalStateException("vlingo/actors: Stopped."); } return stage().actorFor(protocols, type, parameters); }
[ "public", "Protocols", "actorFor", "(", "final", "Class", "<", "?", ">", "[", "]", "protocols", ",", "final", "Class", "<", "?", "extends", "Actor", ">", "type", ",", "final", "Object", "...", "parameters", ")", "{", "if", "(", "isTerminated", "(", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"vlingo/actors: Stopped.\"", ")", ";", "}", "return", "stage", "(", ")", ".", "actorFor", "(", "protocols", ",", "type", ",", "parameters", ")", ";", "}" ]
Answers a {@code Protocols} that provides one or more supported protocols for the newly created {@code Actor} according to {@code definition}. @param protocols the {@code Class<?>[]} array of protocols that the {@code Actor} supports @param type the {@code Class<? extends Actor>} of the {@code Actor} to create @param parameters the {@code Object[]} of constructor parameters @return {@code Protocols}
[ "Answers", "a", "{" ]
train
https://github.com/vlingo/vlingo-actors/blob/c7d046fd139c0490cf0fd2588d7dc2f792f13493/src/main/java/io/vlingo/actors/World.java#L136-L142
googleapis/google-cloud-java
google-cloud-clients/google-cloud-contrib/google-cloud-nio/src/main/java/com/google/cloud/storage/contrib/nio/UnixPath.java
UnixPath.getParent
@Nullable public UnixPath getParent() { """ Returns parent directory (including trailing separator) or {@code null} if no parent remains. @see java.nio.file.Path#getParent() """ if (path.isEmpty() || isRoot()) { return null; } int index = hasTrailingSeparator() ? path.lastIndexOf(SEPARATOR, path.length() - 2) : path.lastIndexOf(SEPARATOR); if (index == -1) { return isAbsolute() ? ROOT_PATH : null; } else { return new UnixPath(permitEmptyComponents, path.substring(0, index + 1)); } }
java
@Nullable public UnixPath getParent() { if (path.isEmpty() || isRoot()) { return null; } int index = hasTrailingSeparator() ? path.lastIndexOf(SEPARATOR, path.length() - 2) : path.lastIndexOf(SEPARATOR); if (index == -1) { return isAbsolute() ? ROOT_PATH : null; } else { return new UnixPath(permitEmptyComponents, path.substring(0, index + 1)); } }
[ "@", "Nullable", "public", "UnixPath", "getParent", "(", ")", "{", "if", "(", "path", ".", "isEmpty", "(", ")", "||", "isRoot", "(", ")", ")", "{", "return", "null", ";", "}", "int", "index", "=", "hasTrailingSeparator", "(", ")", "?", "path", ".", "lastIndexOf", "(", "SEPARATOR", ",", "path", ".", "length", "(", ")", "-", "2", ")", ":", "path", ".", "lastIndexOf", "(", "SEPARATOR", ")", ";", "if", "(", "index", "==", "-", "1", ")", "{", "return", "isAbsolute", "(", ")", "?", "ROOT_PATH", ":", "null", ";", "}", "else", "{", "return", "new", "UnixPath", "(", "permitEmptyComponents", ",", "path", ".", "substring", "(", "0", ",", "index", "+", "1", ")", ")", ";", "}", "}" ]
Returns parent directory (including trailing separator) or {@code null} if no parent remains. @see java.nio.file.Path#getParent()
[ "Returns", "parent", "directory", "(", "including", "trailing", "separator", ")", "or", "{", "@code", "null", "}", "if", "no", "parent", "remains", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-contrib/google-cloud-nio/src/main/java/com/google/cloud/storage/contrib/nio/UnixPath.java#L177-L191
google/error-prone-javac
src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/HtmlTree.java
HtmlTree.A_ID
public static HtmlTree A_ID(HtmlStyle styleClass, String id, Content body) { """ Generates an HTML anchor tag with a style class, id attribute and a body. @param styleClass stylesheet class for the tag @param id id for the anchor tag @param body body for the anchor tag @return an HtmlTree object """ HtmlTree htmltree = A_ID(id, body); if (styleClass != null) htmltree.addStyle(styleClass); return htmltree; }
java
public static HtmlTree A_ID(HtmlStyle styleClass, String id, Content body) { HtmlTree htmltree = A_ID(id, body); if (styleClass != null) htmltree.addStyle(styleClass); return htmltree; }
[ "public", "static", "HtmlTree", "A_ID", "(", "HtmlStyle", "styleClass", ",", "String", "id", ",", "Content", "body", ")", "{", "HtmlTree", "htmltree", "=", "A_ID", "(", "id", ",", "body", ")", ";", "if", "(", "styleClass", "!=", "null", ")", "htmltree", ".", "addStyle", "(", "styleClass", ")", ";", "return", "htmltree", ";", "}" ]
Generates an HTML anchor tag with a style class, id attribute and a body. @param styleClass stylesheet class for the tag @param id id for the anchor tag @param body body for the anchor tag @return an HtmlTree object
[ "Generates", "an", "HTML", "anchor", "tag", "with", "a", "style", "class", "id", "attribute", "and", "a", "body", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/HtmlTree.java#L275-L280
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/classify/Dataset.java
Dataset.readSVMLightFormat
public static Dataset<String, String> readSVMLightFormat(String filename) { """ Constructs a Dataset by reading in a file in SVM light format. """ return readSVMLightFormat(filename, new HashIndex<String>(), new HashIndex<String>()); }
java
public static Dataset<String, String> readSVMLightFormat(String filename) { return readSVMLightFormat(filename, new HashIndex<String>(), new HashIndex<String>()); }
[ "public", "static", "Dataset", "<", "String", ",", "String", ">", "readSVMLightFormat", "(", "String", "filename", ")", "{", "return", "readSVMLightFormat", "(", "filename", ",", "new", "HashIndex", "<", "String", ">", "(", ")", ",", "new", "HashIndex", "<", "String", ">", "(", ")", ")", ";", "}" ]
Constructs a Dataset by reading in a file in SVM light format.
[ "Constructs", "a", "Dataset", "by", "reading", "in", "a", "file", "in", "SVM", "light", "format", "." ]
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/classify/Dataset.java#L197-L199
MenoData/Time4J
base/src/main/java/net/time4j/tz/ZonalOffset.java
ZonalOffset.ofTotalSeconds
public static ZonalOffset ofTotalSeconds( int total, int fraction ) { """ /*[deutsch] <p>Konstruiert eine Verschiebung der lokalen Zeit relativ zur UTC-Zeitzone in integralen oder fraktionalen Sekunden. </p> <p>Hinweis: Fraktionale Verschiebungen werden im Zeitzonenkontext nicht verwendet, sondern nur dann, wenn ein {@code PlainTimestamp} zu einem {@code Moment} oder zur&uuml;ck konvertiert wird. </p> @param total total shift in seconds defined in range {@code -18 * 3600 <= total <= 18 * 3600} @param fraction fraction of second @return zonal offset in (sub-)second precision @throws IllegalArgumentException if any arguments are out of range or have different signs @see #getIntegralAmount() @see #getFractionalAmount() """ if (fraction != 0) { return new ZonalOffset(total, fraction); } else if (total == 0) { return UTC; } else if ((total % (15 * 60)) == 0) { // Viertelstundenintervall Integer value = Integer.valueOf(total); ZonalOffset result = OFFSET_CACHE.get(value); if (result == null) { result = new ZonalOffset(total, 0); OFFSET_CACHE.putIfAbsent(value, result); result = OFFSET_CACHE.get(value); } return result; } else { return new ZonalOffset(total, 0); } }
java
public static ZonalOffset ofTotalSeconds( int total, int fraction ) { if (fraction != 0) { return new ZonalOffset(total, fraction); } else if (total == 0) { return UTC; } else if ((total % (15 * 60)) == 0) { // Viertelstundenintervall Integer value = Integer.valueOf(total); ZonalOffset result = OFFSET_CACHE.get(value); if (result == null) { result = new ZonalOffset(total, 0); OFFSET_CACHE.putIfAbsent(value, result); result = OFFSET_CACHE.get(value); } return result; } else { return new ZonalOffset(total, 0); } }
[ "public", "static", "ZonalOffset", "ofTotalSeconds", "(", "int", "total", ",", "int", "fraction", ")", "{", "if", "(", "fraction", "!=", "0", ")", "{", "return", "new", "ZonalOffset", "(", "total", ",", "fraction", ")", ";", "}", "else", "if", "(", "total", "==", "0", ")", "{", "return", "UTC", ";", "}", "else", "if", "(", "(", "total", "%", "(", "15", "*", "60", ")", ")", "==", "0", ")", "{", "// Viertelstundenintervall", "Integer", "value", "=", "Integer", ".", "valueOf", "(", "total", ")", ";", "ZonalOffset", "result", "=", "OFFSET_CACHE", ".", "get", "(", "value", ")", ";", "if", "(", "result", "==", "null", ")", "{", "result", "=", "new", "ZonalOffset", "(", "total", ",", "0", ")", ";", "OFFSET_CACHE", ".", "putIfAbsent", "(", "value", ",", "result", ")", ";", "result", "=", "OFFSET_CACHE", ".", "get", "(", "value", ")", ";", "}", "return", "result", ";", "}", "else", "{", "return", "new", "ZonalOffset", "(", "total", ",", "0", ")", ";", "}", "}" ]
/*[deutsch] <p>Konstruiert eine Verschiebung der lokalen Zeit relativ zur UTC-Zeitzone in integralen oder fraktionalen Sekunden. </p> <p>Hinweis: Fraktionale Verschiebungen werden im Zeitzonenkontext nicht verwendet, sondern nur dann, wenn ein {@code PlainTimestamp} zu einem {@code Moment} oder zur&uuml;ck konvertiert wird. </p> @param total total shift in seconds defined in range {@code -18 * 3600 <= total <= 18 * 3600} @param fraction fraction of second @return zonal offset in (sub-)second precision @throws IllegalArgumentException if any arguments are out of range or have different signs @see #getIntegralAmount() @see #getFractionalAmount()
[ "/", "*", "[", "deutsch", "]", "<p", ">", "Konstruiert", "eine", "Verschiebung", "der", "lokalen", "Zeit", "relativ", "zur", "UTC", "-", "Zeitzone", "in", "integralen", "oder", "fraktionalen", "Sekunden", ".", "<", "/", "p", ">" ]
train
https://github.com/MenoData/Time4J/blob/08b2eda6b2dbb140b92011cf7071bb087edd46a5/base/src/main/java/net/time4j/tz/ZonalOffset.java#L485-L507
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/serializer/utils/URI.java
URI.initializeScheme
private void initializeScheme(String p_uriSpec) throws MalformedURIException { """ Initialize the scheme for this URI from a URI string spec. @param p_uriSpec the URI specification (cannot be null) @throws MalformedURIException if URI does not have a conformant scheme """ int uriSpecLen = p_uriSpec.length(); int index = 0; String scheme = null; char testChar = '\0'; while (index < uriSpecLen) { testChar = p_uriSpec.charAt(index); if (testChar == ':' || testChar == '/' || testChar == '?' || testChar == '#') { break; } index++; } scheme = p_uriSpec.substring(0, index); if (scheme.length() == 0) { throw new MalformedURIException(Utils.messages.createMessage(MsgKey.ER_NO_SCHEME_INURI, null)); //"No scheme found in URI."); } else { setScheme(scheme); } }
java
private void initializeScheme(String p_uriSpec) throws MalformedURIException { int uriSpecLen = p_uriSpec.length(); int index = 0; String scheme = null; char testChar = '\0'; while (index < uriSpecLen) { testChar = p_uriSpec.charAt(index); if (testChar == ':' || testChar == '/' || testChar == '?' || testChar == '#') { break; } index++; } scheme = p_uriSpec.substring(0, index); if (scheme.length() == 0) { throw new MalformedURIException(Utils.messages.createMessage(MsgKey.ER_NO_SCHEME_INURI, null)); //"No scheme found in URI."); } else { setScheme(scheme); } }
[ "private", "void", "initializeScheme", "(", "String", "p_uriSpec", ")", "throws", "MalformedURIException", "{", "int", "uriSpecLen", "=", "p_uriSpec", ".", "length", "(", ")", ";", "int", "index", "=", "0", ";", "String", "scheme", "=", "null", ";", "char", "testChar", "=", "'", "'", ";", "while", "(", "index", "<", "uriSpecLen", ")", "{", "testChar", "=", "p_uriSpec", ".", "charAt", "(", "index", ")", ";", "if", "(", "testChar", "==", "'", "'", "||", "testChar", "==", "'", "'", "||", "testChar", "==", "'", "'", "||", "testChar", "==", "'", "'", ")", "{", "break", ";", "}", "index", "++", ";", "}", "scheme", "=", "p_uriSpec", ".", "substring", "(", "0", ",", "index", ")", ";", "if", "(", "scheme", ".", "length", "(", ")", "==", "0", ")", "{", "throw", "new", "MalformedURIException", "(", "Utils", ".", "messages", ".", "createMessage", "(", "MsgKey", ".", "ER_NO_SCHEME_INURI", ",", "null", ")", ")", ";", "//\"No scheme found in URI.\");", "}", "else", "{", "setScheme", "(", "scheme", ")", ";", "}", "}" ]
Initialize the scheme for this URI from a URI string spec. @param p_uriSpec the URI specification (cannot be null) @throws MalformedURIException if URI does not have a conformant scheme
[ "Initialize", "the", "scheme", "for", "this", "URI", "from", "a", "URI", "string", "spec", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/serializer/utils/URI.java#L580-L611
jferard/fastods
fastods/src/main/java/com/github/jferard/fastods/odselement/OdsElements.java
OdsElements.writeStyles
public void writeStyles(final XMLUtil xmlUtil, final ZipUTF8Writer writer) throws IOException { """ Write the styles element to a writer. @param xmlUtil the xml util @param writer the writer @throws IOException if write fails """ this.logger.log(Level.FINER, "Writing odselement: stylesElement to zip file"); this.stylesElement.write(xmlUtil, writer); }
java
public void writeStyles(final XMLUtil xmlUtil, final ZipUTF8Writer writer) throws IOException { this.logger.log(Level.FINER, "Writing odselement: stylesElement to zip file"); this.stylesElement.write(xmlUtil, writer); }
[ "public", "void", "writeStyles", "(", "final", "XMLUtil", "xmlUtil", ",", "final", "ZipUTF8Writer", "writer", ")", "throws", "IOException", "{", "this", ".", "logger", ".", "log", "(", "Level", ".", "FINER", ",", "\"Writing odselement: stylesElement to zip file\"", ")", ";", "this", ".", "stylesElement", ".", "write", "(", "xmlUtil", ",", "writer", ")", ";", "}" ]
Write the styles element to a writer. @param xmlUtil the xml util @param writer the writer @throws IOException if write fails
[ "Write", "the", "styles", "element", "to", "a", "writer", "." ]
train
https://github.com/jferard/fastods/blob/a034d173083ffa602dc525699b97f753082eaef9/fastods/src/main/java/com/github/jferard/fastods/odselement/OdsElements.java#L424-L427