repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
18
188
func_name
stringlengths
7
127
whole_func_string
stringlengths
77
3.91k
language
stringclasses
1 value
func_code_string
stringlengths
77
3.91k
func_code_tokens
listlengths
20
745
func_documentation_string
stringlengths
61
1.98k
func_documentation_tokens
listlengths
1
477
split_name
stringclasses
1 value
func_code_url
stringlengths
111
288
j-a-w-r/jawr-main-repo
jawr-tools/jawr-bundle-processor/src/main/java/net/jawr/web/bundle/processor/BundleProcessor.java
BundleProcessor.initClassLoader
protected ClassLoader initClassLoader(String baseDirPath) throws MalformedURLException { File webAppClasses = new File(baseDirPath + WEB_INF_CLASSES_DIR_PATH); File[] webAppLibs = new File(baseDirPath + WEB_INF_LIB_DIR_PATH) .listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith(JAR_FILE_EXTENSION); } }); int length = webAppLibs != null ? webAppLibs.length + 1 : 1; URL[] urls = new URL[length]; urls[0] = webAppClasses.toURI().toURL(); for (int i = 1; i < length; i++) { urls[i] = webAppLibs[i - 1].toURI().toURL(); } ClassLoader webAppClassLoader = new JawrBundleProcessorCustomClassLoader( urls, getClass().getClassLoader()); Thread.currentThread().setContextClassLoader(webAppClassLoader); return webAppClassLoader; }
java
protected ClassLoader initClassLoader(String baseDirPath) throws MalformedURLException { File webAppClasses = new File(baseDirPath + WEB_INF_CLASSES_DIR_PATH); File[] webAppLibs = new File(baseDirPath + WEB_INF_LIB_DIR_PATH) .listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith(JAR_FILE_EXTENSION); } }); int length = webAppLibs != null ? webAppLibs.length + 1 : 1; URL[] urls = new URL[length]; urls[0] = webAppClasses.toURI().toURL(); for (int i = 1; i < length; i++) { urls[i] = webAppLibs[i - 1].toURI().toURL(); } ClassLoader webAppClassLoader = new JawrBundleProcessorCustomClassLoader( urls, getClass().getClassLoader()); Thread.currentThread().setContextClassLoader(webAppClassLoader); return webAppClassLoader; }
[ "protected", "ClassLoader", "initClassLoader", "(", "String", "baseDirPath", ")", "throws", "MalformedURLException", "{", "File", "webAppClasses", "=", "new", "File", "(", "baseDirPath", "+", "WEB_INF_CLASSES_DIR_PATH", ")", ";", "File", "[", "]", "webAppLibs", "=",...
Initialize the classloader @param baseDirPath the base directory path @return the class loader @throws MalformedURLException
[ "Initialize", "the", "classloader" ]
train
https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr-tools/jawr-bundle-processor/src/main/java/net/jawr/web/bundle/processor/BundleProcessor.java#L324-L348
deeplearning4j/deeplearning4j
nd4j/nd4j-parameter-server-parent/nd4j-parameter-server-node/src/main/java/org/nd4j/parameterserver/distributed/v2/ModelParameterServer.java
ModelParameterServer.configure
public void configure(@NonNull VoidConfiguration configuration, @NonNull Transport transport, boolean isMasterNode) { this.transport = transport; this.masterMode = isMasterNode; this.configuration = configuration; }
java
public void configure(@NonNull VoidConfiguration configuration, @NonNull Transport transport, boolean isMasterNode) { this.transport = transport; this.masterMode = isMasterNode; this.configuration = configuration; }
[ "public", "void", "configure", "(", "@", "NonNull", "VoidConfiguration", "configuration", ",", "@", "NonNull", "Transport", "transport", ",", "boolean", "isMasterNode", ")", "{", "this", ".", "transport", "=", "transport", ";", "this", ".", "masterMode", "=", ...
This method stores provided entities for MPS internal use @param configuration @param transport @param isMasterNode
[ "This", "method", "stores", "provided", "entities", "for", "MPS", "internal", "use" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-parameter-server-parent/nd4j-parameter-server-node/src/main/java/org/nd4j/parameterserver/distributed/v2/ModelParameterServer.java#L153-L157
Azure/azure-sdk-for-java
sql/resource-manager/v2015_05_01_preview/src/main/java/com/microsoft/azure/management/sql/v2015_05_01_preview/implementation/ManagedInstancesInner.java
ManagedInstancesInner.beginCreateOrUpdate
public ManagedInstanceInner beginCreateOrUpdate(String resourceGroupName, String managedInstanceName, ManagedInstanceInner parameters) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, managedInstanceName, parameters).toBlocking().single().body(); }
java
public ManagedInstanceInner beginCreateOrUpdate(String resourceGroupName, String managedInstanceName, ManagedInstanceInner parameters) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, managedInstanceName, parameters).toBlocking().single().body(); }
[ "public", "ManagedInstanceInner", "beginCreateOrUpdate", "(", "String", "resourceGroupName", ",", "String", "managedInstanceName", ",", "ManagedInstanceInner", "parameters", ")", "{", "return", "beginCreateOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "manag...
Creates or updates a managed instance. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param managedInstanceName The name of the managed instance. @param parameters The requested managed instance resource state. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the ManagedInstanceInner object if successful.
[ "Creates", "or", "updates", "a", "managed", "instance", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2015_05_01_preview/src/main/java/com/microsoft/azure/management/sql/v2015_05_01_preview/implementation/ManagedInstancesInner.java#L511-L513
apache/flink
flink-core/src/main/java/org/apache/flink/types/parser/BigDecParser.java
BigDecParser.parseField
public static final BigDecimal parseField(byte[] bytes, int startPos, int length, char delimiter) { if (length <= 0) { throw new NumberFormatException("Invalid input: Empty string"); } int i = 0; final byte delByte = (byte) delimiter; while (i < length && bytes[startPos + i] != delByte) { i++; } if (i > 0 && (Character.isWhitespace(bytes[startPos]) || Character.isWhitespace(bytes[startPos + i - 1]))) { throw new NumberFormatException("There is leading or trailing whitespace in the numeric field."); } final char[] chars = new char[i]; for (int j = 0; j < i; j++) { final byte b = bytes[startPos + j]; if ((b < '0' || b > '9') && b != '-' && b != '+' && b != '.' && b != 'E' && b != 'e') { throw new NumberFormatException(); } chars[j] = (char) bytes[startPos + j]; } return new BigDecimal(chars); }
java
public static final BigDecimal parseField(byte[] bytes, int startPos, int length, char delimiter) { if (length <= 0) { throw new NumberFormatException("Invalid input: Empty string"); } int i = 0; final byte delByte = (byte) delimiter; while (i < length && bytes[startPos + i] != delByte) { i++; } if (i > 0 && (Character.isWhitespace(bytes[startPos]) || Character.isWhitespace(bytes[startPos + i - 1]))) { throw new NumberFormatException("There is leading or trailing whitespace in the numeric field."); } final char[] chars = new char[i]; for (int j = 0; j < i; j++) { final byte b = bytes[startPos + j]; if ((b < '0' || b > '9') && b != '-' && b != '+' && b != '.' && b != 'E' && b != 'e') { throw new NumberFormatException(); } chars[j] = (char) bytes[startPos + j]; } return new BigDecimal(chars); }
[ "public", "static", "final", "BigDecimal", "parseField", "(", "byte", "[", "]", "bytes", ",", "int", "startPos", ",", "int", "length", ",", "char", "delimiter", ")", "{", "if", "(", "length", "<=", "0", ")", "{", "throw", "new", "NumberFormatException", ...
Static utility to parse a field of type BigDecimal from a byte sequence that represents text characters (such as when read from a file stream). @param bytes The bytes containing the text data that should be parsed. @param startPos The offset to start the parsing. @param length The length of the byte sequence (counting from the offset). @param delimiter The delimiter that terminates the field. @return The parsed value. @throws IllegalArgumentException Thrown when the value cannot be parsed because the text represents not a correct number.
[ "Static", "utility", "to", "parse", "a", "field", "of", "type", "BigDecimal", "from", "a", "byte", "sequence", "that", "represents", "text", "characters", "(", "such", "as", "when", "read", "from", "a", "file", "stream", ")", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/types/parser/BigDecParser.java#L104-L129
pravega/pravega
controller/src/main/java/io/pravega/controller/task/Stream/StreamTransactionMetadataTasks.java
StreamTransactionMetadataTasks.pingTxnBody
CompletableFuture<PingTxnStatus> pingTxnBody(final String scope, final String stream, final UUID txnId, final long lease, final OperationContext ctx) { if (!timeoutService.isRunning()) { return CompletableFuture.completedFuture(createStatus(Status.DISCONNECTED)); } log.debug("Txn={}, updating txn node in store and extending lease", txnId); return fenceTxnUpdateLease(scope, stream, txnId, lease, ctx); }
java
CompletableFuture<PingTxnStatus> pingTxnBody(final String scope, final String stream, final UUID txnId, final long lease, final OperationContext ctx) { if (!timeoutService.isRunning()) { return CompletableFuture.completedFuture(createStatus(Status.DISCONNECTED)); } log.debug("Txn={}, updating txn node in store and extending lease", txnId); return fenceTxnUpdateLease(scope, stream, txnId, lease, ctx); }
[ "CompletableFuture", "<", "PingTxnStatus", ">", "pingTxnBody", "(", "final", "String", "scope", ",", "final", "String", "stream", ",", "final", "UUID", "txnId", ",", "final", "long", "lease", ",", "final", "OperationContext", "ctx", ")", "{", "if", "(", "!",...
Ping a txn thereby updating its timeout to current time + lease. Post-condition: 1. If ping request completes successfully, then (a) txn timeout is set to lease + current time in timeout service, (b) txn version in timeout service equals version of txn node in store, (c) if txn's timeout was not previously tracked in timeout service of current process, then version of txn node in store is updated, thus fencing out other processes tracking timeout for this txn, (d) txn is present in the host-txn index of current host, 2. If process fails before responding to the client, then since txn is present in the host-txn index, some other controller process shall abort the txn after maxLeaseValue Store read/update operation is not invoked on receiving ping request for a txn that is being tracked in the timeout service. Otherwise, if the txn is not being tracked in the timeout service, txn node is read from the store and updated. @param scope scope name. @param stream stream name. @param txnId txn id. @param lease txn lease. @param ctx context. @return ping status.
[ "Ping", "a", "txn", "thereby", "updating", "its", "timeout", "to", "current", "time", "+", "lease", "." ]
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/controller/src/main/java/io/pravega/controller/task/Stream/StreamTransactionMetadataTasks.java#L418-L429
dasein-cloud/dasein-cloud-aws
src/main/java/org/dasein/cloud/aws/platform/RDS.java
RDS.getWindowString
private String getWindowString(TimeWindow window, boolean includeDays) { StringBuilder str = new StringBuilder(); if( includeDays ) { if( window.getStartDayOfWeek() == null ) { str.append("*"); } else { str.append(window.getStartDayOfWeek().getShortString()); } str.append(":"); } str.append(String.format("%02d:%02d", window.getStartHour(), window.getStartMinute())); str.append("-"); if( includeDays ) { if( window.getEndDayOfWeek() == null ) { str.append("*"); } else { str.append(window.getEndDayOfWeek().getShortString()); } str.append(":"); } str.append(String.format("%02d:%02d", window.getEndHour(), window.getEndMinute())); return str.toString(); }
java
private String getWindowString(TimeWindow window, boolean includeDays) { StringBuilder str = new StringBuilder(); if( includeDays ) { if( window.getStartDayOfWeek() == null ) { str.append("*"); } else { str.append(window.getStartDayOfWeek().getShortString()); } str.append(":"); } str.append(String.format("%02d:%02d", window.getStartHour(), window.getStartMinute())); str.append("-"); if( includeDays ) { if( window.getEndDayOfWeek() == null ) { str.append("*"); } else { str.append(window.getEndDayOfWeek().getShortString()); } str.append(":"); } str.append(String.format("%02d:%02d", window.getEndHour(), window.getEndMinute())); return str.toString(); }
[ "private", "String", "getWindowString", "(", "TimeWindow", "window", ",", "boolean", "includeDays", ")", "{", "StringBuilder", "str", "=", "new", "StringBuilder", "(", ")", ";", "if", "(", "includeDays", ")", "{", "if", "(", "window", ".", "getStartDayOfWeek",...
Formats a time window as hh24:mi-hh24:mi or ddd:hh24:mi-ddd:hh24:mi @param window @param includeDays must be false for PreferredBackupWindow parameter @return formatted time window text representation
[ "Formats", "a", "time", "window", "as", "hh24", ":", "mi", "-", "hh24", ":", "mi", "or", "ddd", ":", "hh24", ":", "mi", "-", "ddd", ":", "hh24", ":", "mi" ]
train
https://github.com/dasein-cloud/dasein-cloud-aws/blob/05098574197a1f573f77447cadc39a76bf00b99d/src/main/java/org/dasein/cloud/aws/platform/RDS.java#L173-L197
zaproxy/zaproxy
src/org/zaproxy/zap/extension/help/ExtensionHelp.java
ExtensionHelp.enableHelpKey
public static void enableHelpKey (Component component, String id) { if (component instanceof JComponent) { JComponent jComponent = (JComponent) component; if (componentsWithHelp == null) { componentsWithHelp = new WeakHashMap<>(); } componentsWithHelp.put(jComponent, id); } if (hb != null) { hb.enableHelp(component, id, hs); } }
java
public static void enableHelpKey (Component component, String id) { if (component instanceof JComponent) { JComponent jComponent = (JComponent) component; if (componentsWithHelp == null) { componentsWithHelp = new WeakHashMap<>(); } componentsWithHelp.put(jComponent, id); } if (hb != null) { hb.enableHelp(component, id, hs); } }
[ "public", "static", "void", "enableHelpKey", "(", "Component", "component", ",", "String", "id", ")", "{", "if", "(", "component", "instanceof", "JComponent", ")", "{", "JComponent", "jComponent", "=", "(", "JComponent", ")", "component", ";", "if", "(", "co...
Enables the help for the given component using the given help page ID. <p> The help page is shown when the help keyboard shortcut (F1) is pressed, while the component is focused. @param component the component that will have a help page assigned @param id the ID of the help page
[ "Enables", "the", "help", "for", "the", "given", "component", "using", "the", "given", "help", "page", "ID", ".", "<p", ">", "The", "help", "page", "is", "shown", "when", "the", "help", "keyboard", "shortcut", "(", "F1", ")", "is", "pressed", "while", ...
train
https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/extension/help/ExtensionHelp.java#L383-L395
pgjdbc/pgjdbc
pgjdbc/src/main/java/org/postgresql/core/Parser.java
Parser.parseBlockComment
public static int parseBlockComment(final char[] query, int offset) { if (offset + 1 < query.length && query[offset + 1] == '*') { // /* /* */ */ nest, according to SQL spec int level = 1; for (offset += 2; offset < query.length; ++offset) { switch (query[offset - 1]) { case '*': if (query[offset] == '/') { --level; ++offset; // don't parse / in */* twice } break; case '/': if (query[offset] == '*') { ++level; ++offset; // don't parse * in /*/ twice } break; default: break; } if (level == 0) { --offset; // reset position to last '/' char break; } } } return offset; }
java
public static int parseBlockComment(final char[] query, int offset) { if (offset + 1 < query.length && query[offset + 1] == '*') { // /* /* */ */ nest, according to SQL spec int level = 1; for (offset += 2; offset < query.length; ++offset) { switch (query[offset - 1]) { case '*': if (query[offset] == '/') { --level; ++offset; // don't parse / in */* twice } break; case '/': if (query[offset] == '*') { ++level; ++offset; // don't parse * in /*/ twice } break; default: break; } if (level == 0) { --offset; // reset position to last '/' char break; } } } return offset; }
[ "public", "static", "int", "parseBlockComment", "(", "final", "char", "[", "]", "query", ",", "int", "offset", ")", "{", "if", "(", "offset", "+", "1", "<", "query", ".", "length", "&&", "query", "[", "offset", "+", "1", "]", "==", "'", "'", ")", ...
Test if the <tt>/</tt> character at <tt>offset</tt> starts a block comment, and return the position of the last <tt>/</tt> character. @param query query @param offset start offset @return position of the last <tt>/</tt> character
[ "Test", "if", "the", "<tt", ">", "/", "<", "/", "tt", ">", "character", "at", "<tt", ">", "offset<", "/", "tt", ">", "starts", "a", "block", "comment", "and", "return", "the", "position", "of", "the", "last", "<tt", ">", "/", "<", "/", "tt", ">",...
train
https://github.com/pgjdbc/pgjdbc/blob/95ba7b261e39754674c5817695ae5ebf9a341fae/pgjdbc/src/main/java/org/postgresql/core/Parser.java#L523-L552
ManfredTremmel/gwt-bean-validators
mt-bean-validators/src/main/java/de/knightsoftnet/validators/shared/util/PhoneNumberUtil.java
PhoneNumberUtil.formatMs
public final String formatMs(final String pphoneNumber, final String pcountryCode) { return this.formatMs(this.parsePhoneNumber(pphoneNumber, pcountryCode)); }
java
public final String formatMs(final String pphoneNumber, final String pcountryCode) { return this.formatMs(this.parsePhoneNumber(pphoneNumber, pcountryCode)); }
[ "public", "final", "String", "formatMs", "(", "final", "String", "pphoneNumber", ",", "final", "String", "pcountryCode", ")", "{", "return", "this", ".", "formatMs", "(", "this", ".", "parsePhoneNumber", "(", "pphoneNumber", ",", "pcountryCode", ")", ")", ";",...
format phone number in Microsoft canonical address format. @param pphoneNumber phone number to format @param pcountryCode iso code of country @return formated phone number as String
[ "format", "phone", "number", "in", "Microsoft", "canonical", "address", "format", "." ]
train
https://github.com/ManfredTremmel/gwt-bean-validators/blob/cff7a2c3d68c2d17bf9d3cc57c79cc16fa8b4d5c/mt-bean-validators/src/main/java/de/knightsoftnet/validators/shared/util/PhoneNumberUtil.java#L1171-L1173
svenkubiak/mangooio
mangooio-core/src/main/java/io/mangoo/routing/bindings/Validator.java
Validator.validateNull
public void validateNull(Object object, String name, String message) { if (object != null) { addError(name, Optional.ofNullable(message).orElse(messages.get(Validation.NULL_KEY.name(), name))); } }
java
public void validateNull(Object object, String name, String message) { if (object != null) { addError(name, Optional.ofNullable(message).orElse(messages.get(Validation.NULL_KEY.name(), name))); } }
[ "public", "void", "validateNull", "(", "Object", "object", ",", "String", "name", ",", "String", "message", ")", "{", "if", "(", "object", "!=", "null", ")", "{", "addError", "(", "name", ",", "Optional", ".", "ofNullable", "(", "message", ")", ".", "o...
Validates a given object to be null @param object The object to check @param name The name of the field to display the error message @param message A custom error message instead of the default one
[ "Validates", "a", "given", "object", "to", "be", "null" ]
train
https://github.com/svenkubiak/mangooio/blob/b3beb6d09510dbbab0ed947d5069c463e1fda6e7/mangooio-core/src/main/java/io/mangoo/routing/bindings/Validator.java#L499-L503
box/box-java-sdk
src/main/java/com/box/sdk/BoxTrash.java
BoxTrash.restoreFolder
public BoxFolder.Info restoreFolder(String folderID) { URL url = RESTORE_FOLDER_URL_TEMPLATE.build(this.api.getBaseURL(), folderID); BoxAPIRequest request = new BoxAPIRequest(this.api, url, "POST"); JsonObject requestJSON = new JsonObject() .add("", ""); request.setBody(requestJSON.toString()); BoxJSONResponse response = (BoxJSONResponse) request.send(); JsonObject responseJSON = JsonObject.readFrom(response.getJSON()); BoxFolder restoredFolder = new BoxFolder(this.api, responseJSON.get("id").asString()); return restoredFolder.new Info(responseJSON); }
java
public BoxFolder.Info restoreFolder(String folderID) { URL url = RESTORE_FOLDER_URL_TEMPLATE.build(this.api.getBaseURL(), folderID); BoxAPIRequest request = new BoxAPIRequest(this.api, url, "POST"); JsonObject requestJSON = new JsonObject() .add("", ""); request.setBody(requestJSON.toString()); BoxJSONResponse response = (BoxJSONResponse) request.send(); JsonObject responseJSON = JsonObject.readFrom(response.getJSON()); BoxFolder restoredFolder = new BoxFolder(this.api, responseJSON.get("id").asString()); return restoredFolder.new Info(responseJSON); }
[ "public", "BoxFolder", ".", "Info", "restoreFolder", "(", "String", "folderID", ")", "{", "URL", "url", "=", "RESTORE_FOLDER_URL_TEMPLATE", ".", "build", "(", "this", ".", "api", ".", "getBaseURL", "(", ")", ",", "folderID", ")", ";", "BoxAPIRequest", "reque...
Restores a trashed folder back to its original location. @param folderID the ID of the trashed folder. @return info about the restored folder.
[ "Restores", "a", "trashed", "folder", "back", "to", "its", "original", "location", "." ]
train
https://github.com/box/box-java-sdk/blob/35b4ba69417f9d6a002c19dfaab57527750ef349/src/main/java/com/box/sdk/BoxTrash.java#L97-L108
jeremylong/DependencyCheck
core/src/main/java/org/owasp/dependencycheck/analyzer/CMakeAnalyzer.java
CMakeAnalyzer.analyzeSetVersionCommand
private void analyzeSetVersionCommand(Dependency dependency, Engine engine, String contents) { Dependency currentDep = dependency; final Matcher m = SET_VERSION.matcher(contents); int count = 0; while (m.find()) { count++; LOGGER.debug("Found project command match with {} groups: {}", m.groupCount(), m.group(0)); String product = m.group(1); final String version = m.group(2); LOGGER.debug("Group 1: {}", product); LOGGER.debug("Group 2: {}", version); final String aliasPrefix = "ALIASOF_"; if (product.startsWith(aliasPrefix)) { product = product.replaceFirst(aliasPrefix, ""); } if (count > 1) { //TODO - refactor so we do not assign to the parameter (checkstyle) currentDep = new Dependency(dependency.getActualFile()); currentDep.setEcosystem(DEPENDENCY_ECOSYSTEM); final String filePath = String.format("%s:%s", dependency.getFilePath(), product); currentDep.setFilePath(filePath); currentDep.setSha1sum(Checksum.getSHA1Checksum(filePath)); currentDep.setSha256sum(Checksum.getSHA256Checksum(filePath)); currentDep.setMd5sum(Checksum.getMD5Checksum(filePath)); engine.addDependency(currentDep); } final String source = currentDep.getFileName(); currentDep.addEvidence(EvidenceType.PRODUCT, source, "Product", product, Confidence.MEDIUM); currentDep.addEvidence(EvidenceType.VENDOR, source, "Vendor", product, Confidence.MEDIUM); currentDep.addEvidence(EvidenceType.VERSION, source, "Version", version, Confidence.MEDIUM); currentDep.setName(product); currentDep.setVersion(version); } LOGGER.debug("Found {} matches.", count); }
java
private void analyzeSetVersionCommand(Dependency dependency, Engine engine, String contents) { Dependency currentDep = dependency; final Matcher m = SET_VERSION.matcher(contents); int count = 0; while (m.find()) { count++; LOGGER.debug("Found project command match with {} groups: {}", m.groupCount(), m.group(0)); String product = m.group(1); final String version = m.group(2); LOGGER.debug("Group 1: {}", product); LOGGER.debug("Group 2: {}", version); final String aliasPrefix = "ALIASOF_"; if (product.startsWith(aliasPrefix)) { product = product.replaceFirst(aliasPrefix, ""); } if (count > 1) { //TODO - refactor so we do not assign to the parameter (checkstyle) currentDep = new Dependency(dependency.getActualFile()); currentDep.setEcosystem(DEPENDENCY_ECOSYSTEM); final String filePath = String.format("%s:%s", dependency.getFilePath(), product); currentDep.setFilePath(filePath); currentDep.setSha1sum(Checksum.getSHA1Checksum(filePath)); currentDep.setSha256sum(Checksum.getSHA256Checksum(filePath)); currentDep.setMd5sum(Checksum.getMD5Checksum(filePath)); engine.addDependency(currentDep); } final String source = currentDep.getFileName(); currentDep.addEvidence(EvidenceType.PRODUCT, source, "Product", product, Confidence.MEDIUM); currentDep.addEvidence(EvidenceType.VENDOR, source, "Vendor", product, Confidence.MEDIUM); currentDep.addEvidence(EvidenceType.VERSION, source, "Version", version, Confidence.MEDIUM); currentDep.setName(product); currentDep.setVersion(version); } LOGGER.debug("Found {} matches.", count); }
[ "private", "void", "analyzeSetVersionCommand", "(", "Dependency", "dependency", ",", "Engine", "engine", ",", "String", "contents", ")", "{", "Dependency", "currentDep", "=", "dependency", ";", "final", "Matcher", "m", "=", "SET_VERSION", ".", "matcher", "(", "c...
Extracts the version information from the contents. If more then one version is found additional dependencies are added to the dependency list. @param dependency the dependency being analyzed @param engine the dependency-check engine @param contents the version information
[ "Extracts", "the", "version", "information", "from", "the", "contents", ".", "If", "more", "then", "one", "version", "is", "found", "additional", "dependencies", "are", "added", "to", "the", "dependency", "list", "." ]
train
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/CMakeAnalyzer.java#L186-L223
b3log/latke
latke-core/src/main/java/org/b3log/latke/Latkes.java
Latkes.setLatkeProperty
public static void setLatkeProperty(final String key, final String value) { if (null == key) { LOGGER.log(Level.WARN, "latke.props can not set null key"); return; } if (null == value) { LOGGER.log(Level.WARN, "latke.props can not set null value"); return; } latkeProps.setProperty(key, value); }
java
public static void setLatkeProperty(final String key, final String value) { if (null == key) { LOGGER.log(Level.WARN, "latke.props can not set null key"); return; } if (null == value) { LOGGER.log(Level.WARN, "latke.props can not set null value"); return; } latkeProps.setProperty(key, value); }
[ "public", "static", "void", "setLatkeProperty", "(", "final", "String", "key", ",", "final", "String", "value", ")", "{", "if", "(", "null", "==", "key", ")", "{", "LOGGER", ".", "log", "(", "Level", ".", "WARN", ",", "\"latke.props can not set null key\"", ...
Sets latke.props with the specified key and value. @param key the specified key @param value the specified value
[ "Sets", "latke", ".", "props", "with", "the", "specified", "key", "and", "value", "." ]
train
https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/Latkes.java#L178-L191
sdl/odata
odata_api/src/main/java/com/sdl/odata/util/AnnotationsUtil.java
AnnotationsUtil.getAnnotation
public static <T extends Annotation> T getAnnotation(AnnotatedElement annotatedType, Class<T> annotationClass) { return getAnnotation(annotatedType, annotationClass, null); }
java
public static <T extends Annotation> T getAnnotation(AnnotatedElement annotatedType, Class<T> annotationClass) { return getAnnotation(annotatedType, annotationClass, null); }
[ "public", "static", "<", "T", "extends", "Annotation", ">", "T", "getAnnotation", "(", "AnnotatedElement", "annotatedType", ",", "Class", "<", "T", ">", "annotationClass", ")", "{", "return", "getAnnotation", "(", "annotatedType", ",", "annotationClass", ",", "n...
Small utility to easily get an annotation and will throw an exception if not provided. @param annotatedType The source type to tcheck the annotation on @param annotationClass The annotation to look for @param <T> The annotation subtype @return The annotation that was requested @throws ODataSystemException If unable to find the annotation or nullpointer in case null source was specified
[ "Small", "utility", "to", "easily", "get", "an", "annotation", "and", "will", "throw", "an", "exception", "if", "not", "provided", "." ]
train
https://github.com/sdl/odata/blob/eb747d73e9af0f4e59a25b82ed656e526a7e2189/odata_api/src/main/java/com/sdl/odata/util/AnnotationsUtil.java#L57-L59
Netflix/governator
governator-legacy/src/main/java/com/netflix/governator/guice/Grapher.java
Grapher.toFile
public void toFile(File file) throws Exception { PrintWriter out = new PrintWriter(file, "UTF-8"); try { out.write(graph()); } finally { Closeables.close(out, true); } }
java
public void toFile(File file) throws Exception { PrintWriter out = new PrintWriter(file, "UTF-8"); try { out.write(graph()); } finally { Closeables.close(out, true); } }
[ "public", "void", "toFile", "(", "File", "file", ")", "throws", "Exception", "{", "PrintWriter", "out", "=", "new", "PrintWriter", "(", "file", ",", "\"UTF-8\"", ")", ";", "try", "{", "out", ".", "write", "(", "graph", "(", ")", ")", ";", "}", "final...
Writes the "Dot" graph to a given file. @param file file to write to
[ "Writes", "the", "Dot", "graph", "to", "a", "given", "file", "." ]
train
https://github.com/Netflix/governator/blob/c1f4bb1518e759c61f2e9cad8a896ec6beba0294/governator-legacy/src/main/java/com/netflix/governator/guice/Grapher.java#L131-L139
lecousin/java-framework-core
net.lecousin.core/src/main/java/net/lecousin/framework/concurrent/synch/JoinPoint.java
JoinPoint.listenInlineOnAllDone
public static void listenInlineOnAllDone(Runnable listener, ISynchronizationPoint<?>... synchPoints) { JoinPoint<NoException> jp = new JoinPoint<>(); jp.addToJoin(synchPoints.length); Runnable jpr = new Runnable() { @Override public void run() { jp.joined(); } }; for (int i = 0; i < synchPoints.length; ++i) synchPoints[i].listenInline(jpr); jp.start(); jp.listenInline(listener); }
java
public static void listenInlineOnAllDone(Runnable listener, ISynchronizationPoint<?>... synchPoints) { JoinPoint<NoException> jp = new JoinPoint<>(); jp.addToJoin(synchPoints.length); Runnable jpr = new Runnable() { @Override public void run() { jp.joined(); } }; for (int i = 0; i < synchPoints.length; ++i) synchPoints[i].listenInline(jpr); jp.start(); jp.listenInline(listener); }
[ "public", "static", "void", "listenInlineOnAllDone", "(", "Runnable", "listener", ",", "ISynchronizationPoint", "<", "?", ">", "...", "synchPoints", ")", "{", "JoinPoint", "<", "NoException", ">", "jp", "=", "new", "JoinPoint", "<>", "(", ")", ";", "jp", "."...
Shortcut method to create a JoinPoint waiting for the given synchronization points, start the JoinPoint, and add the given listener to be called when the JoinPoint is unblocked. The JoinPoint is not unblocked until all synchronization points are unblocked. If any has error or is cancel, the error or cancellation reason is not given to the JoinPoint, in contrary of the method listenInline.
[ "Shortcut", "method", "to", "create", "a", "JoinPoint", "waiting", "for", "the", "given", "synchronization", "points", "start", "the", "JoinPoint", "and", "add", "the", "given", "listener", "to", "be", "called", "when", "the", "JoinPoint", "is", "unblocked", "...
train
https://github.com/lecousin/java-framework-core/blob/b0c893b44bfde2c03f90ea846a49ef5749d598f3/net.lecousin.core/src/main/java/net/lecousin/framework/concurrent/synch/JoinPoint.java#L291-L304
apache/incubator-gobblin
gobblin-core/src/main/java/org/apache/gobblin/state/ConstructState.java
ConstructState.addOverwriteProperties
public void addOverwriteProperties(Map<String, String> properties) { Map<String, String> previousOverwriteProps = getOverwritePropertiesMap(); previousOverwriteProps.putAll(properties); setProp(OVERWRITE_PROPS_KEY, serializeMap(previousOverwriteProps)); }
java
public void addOverwriteProperties(Map<String, String> properties) { Map<String, String> previousOverwriteProps = getOverwritePropertiesMap(); previousOverwriteProps.putAll(properties); setProp(OVERWRITE_PROPS_KEY, serializeMap(previousOverwriteProps)); }
[ "public", "void", "addOverwriteProperties", "(", "Map", "<", "String", ",", "String", ">", "properties", ")", "{", "Map", "<", "String", ",", "String", ">", "previousOverwriteProps", "=", "getOverwritePropertiesMap", "(", ")", ";", "previousOverwriteProps", ".", ...
Add a set of properties that will overwrite properties in the {@link WorkUnitState}. @param properties Properties to override.
[ "Add", "a", "set", "of", "properties", "that", "will", "overwrite", "properties", "in", "the", "{" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core/src/main/java/org/apache/gobblin/state/ConstructState.java#L61-L65
davetcc/tcMenu
tcMenuGenerator/src/main/java/com/thecoderscorner/menu/editorui/uimodel/UIMenuItem.java
UIMenuItem.safeIntFromProperty
protected int safeIntFromProperty(StringProperty strProp, String field, List<FieldError> errorsBuilder, int min, int max) { String s = strProp.get(); if (StringHelper.isStringEmptyOrNull(s)) { return 0; } int val = 0; try { val = Integer.valueOf(s); if(val < min || val > max) { errorsBuilder.add(new FieldError("Value must be between " + min + " and " + max, field)); } } catch (NumberFormatException e) { errorsBuilder.add(new FieldError("Value must be a number", field)); } return val; }
java
protected int safeIntFromProperty(StringProperty strProp, String field, List<FieldError> errorsBuilder, int min, int max) { String s = strProp.get(); if (StringHelper.isStringEmptyOrNull(s)) { return 0; } int val = 0; try { val = Integer.valueOf(s); if(val < min || val > max) { errorsBuilder.add(new FieldError("Value must be between " + min + " and " + max, field)); } } catch (NumberFormatException e) { errorsBuilder.add(new FieldError("Value must be a number", field)); } return val; }
[ "protected", "int", "safeIntFromProperty", "(", "StringProperty", "strProp", ",", "String", "field", ",", "List", "<", "FieldError", ">", "errorsBuilder", ",", "int", "min", ",", "int", "max", ")", "{", "String", "s", "=", "strProp", ".", "get", "(", ")", ...
Gets the integer value from a text field property and validates it again the conditions provided. It must be a number and within the ranges provided. @param strProp the property to convert @param field the field to report errors against @param errorsBuilder the list of errors recorded so far @param min the minimum value allowed @param max the maximum value allowed @return the integer value if all conditions are met
[ "Gets", "the", "integer", "value", "from", "a", "text", "field", "property", "and", "validates", "it", "again", "the", "conditions", "provided", ".", "It", "must", "be", "a", "number", "and", "within", "the", "ranges", "provided", "." ]
train
https://github.com/davetcc/tcMenu/blob/61546e4b982b25ceaff384073fe9ec1fff55e64a/tcMenuGenerator/src/main/java/com/thecoderscorner/menu/editorui/uimodel/UIMenuItem.java#L224-L241
EdwardRaff/JSAT
JSAT/src/jsat/linear/RowColumnOps.java
RowColumnOps.addRow
public static void addRow(Matrix A, int i, int start, int to, double c) { for(int j = start; j < to; j++) A.increment(i, j, c); }
java
public static void addRow(Matrix A, int i, int start, int to, double c) { for(int j = start; j < to; j++) A.increment(i, j, c); }
[ "public", "static", "void", "addRow", "(", "Matrix", "A", ",", "int", "i", ",", "int", "start", ",", "int", "to", ",", "double", "c", ")", "{", "for", "(", "int", "j", "=", "start", ";", "j", "<", "to", ";", "j", "++", ")", "A", ".", "increme...
Updates the values of row <tt>i</tt> in the given matrix to be A[i,:] = A[i,:]+ c @param A the matrix to perform he update on @param i the row to update @param start the first index of the row to update from (inclusive) @param to the last index of the row to update (exclusive) @param c the constant to add to each element
[ "Updates", "the", "values", "of", "row", "<tt", ">", "i<", "/", "tt", ">", "in", "the", "given", "matrix", "to", "be", "A", "[", "i", ":", "]", "=", "A", "[", "i", ":", "]", "+", "c" ]
train
https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/linear/RowColumnOps.java#L32-L36
datacleaner/AnalyzerBeans
core/src/main/java/org/eobjects/analyzer/result/renderer/RendererFactory.java
RendererFactory.isRendererMatch
private RendererSelection isRendererMatch(RendererBeanDescriptor<?> rendererDescriptor, Renderable renderable, RendererSelection bestMatch) { final Class<? extends Renderable> renderableType = rendererDescriptor.getRenderableType(); if (ReflectionUtils.is(renderable.getClass(), renderableType)) { if (bestMatch == null) { return isRendererCapable(rendererDescriptor, renderable, bestMatch); } else { int hierarchyDistance = ReflectionUtils.getHierarchyDistance(renderable.getClass(), renderableType); if (hierarchyDistance == 0) { // no hierarchy distance return isRendererCapable(rendererDescriptor, renderable, bestMatch); } if (hierarchyDistance <= bestMatch.getHierarchyDistance()) { // lower hierarchy distance than best match return isRendererCapable(rendererDescriptor, renderable, bestMatch); } } } return null; }
java
private RendererSelection isRendererMatch(RendererBeanDescriptor<?> rendererDescriptor, Renderable renderable, RendererSelection bestMatch) { final Class<? extends Renderable> renderableType = rendererDescriptor.getRenderableType(); if (ReflectionUtils.is(renderable.getClass(), renderableType)) { if (bestMatch == null) { return isRendererCapable(rendererDescriptor, renderable, bestMatch); } else { int hierarchyDistance = ReflectionUtils.getHierarchyDistance(renderable.getClass(), renderableType); if (hierarchyDistance == 0) { // no hierarchy distance return isRendererCapable(rendererDescriptor, renderable, bestMatch); } if (hierarchyDistance <= bestMatch.getHierarchyDistance()) { // lower hierarchy distance than best match return isRendererCapable(rendererDescriptor, renderable, bestMatch); } } } return null; }
[ "private", "RendererSelection", "isRendererMatch", "(", "RendererBeanDescriptor", "<", "?", ">", "rendererDescriptor", ",", "Renderable", "renderable", ",", "RendererSelection", "bestMatch", ")", "{", "final", "Class", "<", "?", "extends", "Renderable", ">", "renderab...
Checks if a particular renderer (descriptor) is a good match for a particular renderer. @param rendererDescriptor the renderer (descriptor) to check. @param renderable the renderable that needs rendering. @param bestMatchingDescriptor the currently "best matching" renderer (descriptor), or null if no other renderers matches yet. @return a {@link RendererSelection} object if the renderer is a match, or null if not.
[ "Checks", "if", "a", "particular", "renderer", "(", "descriptor", ")", "is", "a", "good", "match", "for", "a", "particular", "renderer", "." ]
train
https://github.com/datacleaner/AnalyzerBeans/blob/f82dae080d80d2a647b706a5fb22b3ea250613b3/core/src/main/java/org/eobjects/analyzer/result/renderer/RendererFactory.java#L164-L185
alkacon/opencms-core
src/org/opencms/xml/content/CmsXmlContentErrorHandler.java
CmsXmlContentErrorHandler.addError
public void addError(I_CmsXmlContentValue value, String message) { m_hasErrors = true; Locale locale = value.getLocale(); Map<String, String> localeErrors = getLocalIssueMap(m_errors, locale); localeErrors.put(value.getPath(), message); if (LOG.isDebugEnabled()) { LOG.debug( Messages.get().getBundle().key(Messages.LOG_XMLCONTENT_VALIDATION_ERR_2, value.getPath(), message)); } }
java
public void addError(I_CmsXmlContentValue value, String message) { m_hasErrors = true; Locale locale = value.getLocale(); Map<String, String> localeErrors = getLocalIssueMap(m_errors, locale); localeErrors.put(value.getPath(), message); if (LOG.isDebugEnabled()) { LOG.debug( Messages.get().getBundle().key(Messages.LOG_XMLCONTENT_VALIDATION_ERR_2, value.getPath(), message)); } }
[ "public", "void", "addError", "(", "I_CmsXmlContentValue", "value", ",", "String", "message", ")", "{", "m_hasErrors", "=", "true", ";", "Locale", "locale", "=", "value", ".", "getLocale", "(", ")", ";", "Map", "<", "String", ",", "String", ">", "localeErr...
Adds an error message to the internal list of errors, also raised the "has errors" flag.<p> @param value the value that contains the error @param message the error message to add
[ "Adds", "an", "error", "message", "to", "the", "internal", "list", "of", "errors", "also", "raised", "the", "has", "errors", "flag", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/content/CmsXmlContentErrorHandler.java#L78-L89
googleapis/google-http-java-client
google-http-client/src/main/java/com/google/api/client/util/SecurityUtils.java
SecurityUtils.loadPrivateKeyFromKeyStore
public static PrivateKey loadPrivateKeyFromKeyStore( KeyStore keyStore, InputStream keyStream, String storePass, String alias, String keyPass) throws IOException, GeneralSecurityException { loadKeyStore(keyStore, keyStream, storePass); return getPrivateKey(keyStore, alias, keyPass); }
java
public static PrivateKey loadPrivateKeyFromKeyStore( KeyStore keyStore, InputStream keyStream, String storePass, String alias, String keyPass) throws IOException, GeneralSecurityException { loadKeyStore(keyStore, keyStream, storePass); return getPrivateKey(keyStore, alias, keyPass); }
[ "public", "static", "PrivateKey", "loadPrivateKeyFromKeyStore", "(", "KeyStore", "keyStore", ",", "InputStream", "keyStream", ",", "String", "storePass", ",", "String", "alias", ",", "String", "keyPass", ")", "throws", "IOException", ",", "GeneralSecurityException", "...
Retrieves a private key from the specified key store stream and specified key store. @param keyStore key store @param keyStream input stream to the key store (closed at the end of this method in a finally block) @param storePass password protecting the key store file @param alias alias under which the key is stored @param keyPass password protecting the key @return key from the key store
[ "Retrieves", "a", "private", "key", "from", "the", "specified", "key", "store", "stream", "and", "specified", "key", "store", "." ]
train
https://github.com/googleapis/google-http-java-client/blob/0988ae4e0f26a80f579b6adb2b276dd8254928de/google-http-client/src/main/java/com/google/api/client/util/SecurityUtils.java#L108-L113
google/error-prone-javac
src/jdk.jdeps/share/classes/com/sun/tools/jdeps/InverseDepsAnalyzer.java
InverseDepsAnalyzer.inverseDependences
public Set<Deque<Archive>> inverseDependences() throws IOException { // create a new dependency finder to do the analysis DependencyFinder dependencyFinder = new DependencyFinder(configuration, DEFAULT_FILTER); try { // parse all archives in unnamed module to get compile-time dependences Stream<Archive> archives = Stream.concat(configuration.initialArchives().stream(), configuration.classPathArchives().stream()); if (apiOnly) { dependencyFinder.parseExportedAPIs(archives); } else { dependencyFinder.parse(archives); } Graph.Builder<Archive> builder = new Graph.Builder<>(); // include all target nodes targets().forEach(builder::addNode); // transpose the module graph configuration.getModules().values().stream() .forEach(m -> { builder.addNode(m); m.descriptor().requires().stream() .map(Requires::name) .map(configuration::findModule) // must be present .forEach(v -> builder.addEdge(v.get(), m)); }); // add the dependences from the analysis Map<Archive, Set<Archive>> dependences = dependencyFinder.dependences(); dependences.entrySet().stream() .forEach(e -> { Archive u = e.getKey(); builder.addNode(u); e.getValue().forEach(v -> builder.addEdge(v, u)); }); // transposed dependence graph. Graph<Archive> graph = builder.build(); trace("targets: %s%n", targets()); // Traverse from the targets and find all paths // rebuild a graph with all nodes that depends on targets // targets directly and indirectly return targets().stream() .map(t -> findPaths(graph, t)) .flatMap(Set::stream) .collect(Collectors.toSet()); } finally { dependencyFinder.shutdown(); } }
java
public Set<Deque<Archive>> inverseDependences() throws IOException { // create a new dependency finder to do the analysis DependencyFinder dependencyFinder = new DependencyFinder(configuration, DEFAULT_FILTER); try { // parse all archives in unnamed module to get compile-time dependences Stream<Archive> archives = Stream.concat(configuration.initialArchives().stream(), configuration.classPathArchives().stream()); if (apiOnly) { dependencyFinder.parseExportedAPIs(archives); } else { dependencyFinder.parse(archives); } Graph.Builder<Archive> builder = new Graph.Builder<>(); // include all target nodes targets().forEach(builder::addNode); // transpose the module graph configuration.getModules().values().stream() .forEach(m -> { builder.addNode(m); m.descriptor().requires().stream() .map(Requires::name) .map(configuration::findModule) // must be present .forEach(v -> builder.addEdge(v.get(), m)); }); // add the dependences from the analysis Map<Archive, Set<Archive>> dependences = dependencyFinder.dependences(); dependences.entrySet().stream() .forEach(e -> { Archive u = e.getKey(); builder.addNode(u); e.getValue().forEach(v -> builder.addEdge(v, u)); }); // transposed dependence graph. Graph<Archive> graph = builder.build(); trace("targets: %s%n", targets()); // Traverse from the targets and find all paths // rebuild a graph with all nodes that depends on targets // targets directly and indirectly return targets().stream() .map(t -> findPaths(graph, t)) .flatMap(Set::stream) .collect(Collectors.toSet()); } finally { dependencyFinder.shutdown(); } }
[ "public", "Set", "<", "Deque", "<", "Archive", ">", ">", "inverseDependences", "(", ")", "throws", "IOException", "{", "// create a new dependency finder to do the analysis", "DependencyFinder", "dependencyFinder", "=", "new", "DependencyFinder", "(", "configuration", ","...
Finds all inverse transitive dependencies using the given requires set as the targets, if non-empty. If the given requires set is empty, use the archives depending the packages specified in -regex or -p options.
[ "Finds", "all", "inverse", "transitive", "dependencies", "using", "the", "given", "requires", "set", "as", "the", "targets", "if", "non", "-", "empty", ".", "If", "the", "given", "requires", "set", "is", "empty", "use", "the", "archives", "depending", "the",...
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/InverseDepsAnalyzer.java#L125-L176
h2oai/h2o-3
h2o-algos/src/main/java/hex/deeplearning/Storage.java
Storage.toFrame
static Frame toFrame(Matrix m, Key key) { final int log_rows_per_chunk = Math.max(1, FileVec.DFLT_LOG2_CHUNK_SIZE - (int) Math.floor(Math.log(m.cols()) / Math.log(2.))); Vec v[] = new Vec[m.cols()]; for (int i = 0; i < m.cols(); ++i) { v[i] = makeCon(0, m.rows(), log_rows_per_chunk); } Frame f = new FrameFiller(m).doAll(new Frame(key, v, true))._fr; DKV.put(key, f); return f; }
java
static Frame toFrame(Matrix m, Key key) { final int log_rows_per_chunk = Math.max(1, FileVec.DFLT_LOG2_CHUNK_SIZE - (int) Math.floor(Math.log(m.cols()) / Math.log(2.))); Vec v[] = new Vec[m.cols()]; for (int i = 0; i < m.cols(); ++i) { v[i] = makeCon(0, m.rows(), log_rows_per_chunk); } Frame f = new FrameFiller(m).doAll(new Frame(key, v, true))._fr; DKV.put(key, f); return f; }
[ "static", "Frame", "toFrame", "(", "Matrix", "m", ",", "Key", "key", ")", "{", "final", "int", "log_rows_per_chunk", "=", "Math", ".", "max", "(", "1", ",", "FileVec", ".", "DFLT_LOG2_CHUNK_SIZE", "-", "(", "int", ")", "Math", ".", "floor", "(", "Math"...
Helper to convert a Matrix into a Frame @param m Matrix @param key Key for output Frame @return Reference to Frame (which is also in DKV)
[ "Helper", "to", "convert", "a", "Matrix", "into", "a", "Frame" ]
train
https://github.com/h2oai/h2o-3/blob/845eb49dfeaadf638b6e2f779d82fac996391fad/h2o-algos/src/main/java/hex/deeplearning/Storage.java#L251-L260
openxc/openxc-android
library/src/main/java/com/openxc/sources/trace/TraceVehicleDataSource.java
TraceVehicleDataSource.waitForNextRecord
private void waitForNextRecord(long startingTime, long timestamp) { if(mFirstTimestamp == 0) { mFirstTimestamp = timestamp; Log.d(TAG, "Storing " + timestamp + " as the first " + "timestamp of the trace file"); } long targetTime = startingTime + (timestamp - mFirstTimestamp); long sleepDuration = Math.max(targetTime - System.currentTimeMillis(), 0); try { Thread.sleep(sleepDuration); } catch(InterruptedException e) {} }
java
private void waitForNextRecord(long startingTime, long timestamp) { if(mFirstTimestamp == 0) { mFirstTimestamp = timestamp; Log.d(TAG, "Storing " + timestamp + " as the first " + "timestamp of the trace file"); } long targetTime = startingTime + (timestamp - mFirstTimestamp); long sleepDuration = Math.max(targetTime - System.currentTimeMillis(), 0); try { Thread.sleep(sleepDuration); } catch(InterruptedException e) {} }
[ "private", "void", "waitForNextRecord", "(", "long", "startingTime", ",", "long", "timestamp", ")", "{", "if", "(", "mFirstTimestamp", "==", "0", ")", "{", "mFirstTimestamp", "=", "timestamp", ";", "Log", ".", "d", "(", "TAG", ",", "\"Storing \"", "+", "ti...
Using the startingTime as the relative starting point, sleep this thread until the next timestamp would occur. @param startingTime the relative starting time in milliseconds @param timestamp the timestamp to wait for in milliseconds since the epoch
[ "Using", "the", "startingTime", "as", "the", "relative", "starting", "point", "sleep", "this", "thread", "until", "the", "next", "timestamp", "would", "occur", "." ]
train
https://github.com/openxc/openxc-android/blob/799adbdcd107a72fe89737bbf19c039dc2881665/library/src/main/java/com/openxc/sources/trace/TraceVehicleDataSource.java#L297-L308
arakelian/more-commons
src/main/java/com/arakelian/core/utils/XmlStreamReaderUtils.java
XmlStreamReaderUtils.requiredLongAttribute
public static long requiredLongAttribute(final XMLStreamReader reader, final String localName) throws XMLStreamException { return requiredLongAttribute(reader, null, localName); }
java
public static long requiredLongAttribute(final XMLStreamReader reader, final String localName) throws XMLStreamException { return requiredLongAttribute(reader, null, localName); }
[ "public", "static", "long", "requiredLongAttribute", "(", "final", "XMLStreamReader", "reader", ",", "final", "String", "localName", ")", "throws", "XMLStreamException", "{", "return", "requiredLongAttribute", "(", "reader", ",", "null", ",", "localName", ")", ";", ...
Returns the value of an attribute as a long. If the attribute is empty, this method throws an exception. @param reader <code>XMLStreamReader</code> that contains attribute values. @param localName local name of attribute (the namespace is ignored). @return value of attribute as long @throws XMLStreamException if attribute is empty.
[ "Returns", "the", "value", "of", "an", "attribute", "as", "a", "long", ".", "If", "the", "attribute", "is", "empty", "this", "method", "throws", "an", "exception", "." ]
train
https://github.com/arakelian/more-commons/blob/83c607044f64a7f6c005a67866c0ef7cb68d6e29/src/main/java/com/arakelian/core/utils/XmlStreamReaderUtils.java#L1260-L1263
osmdroid/osmdroid
osmdroid-android/src/main/java/org/osmdroid/views/overlay/TilesOverlay.java
TilesOverlay.protectDisplayedTilesForCache
public void protectDisplayedTilesForCache(final Canvas pCanvas, final Projection pProjection) { if (!setViewPort(pCanvas, pProjection)) { return; } TileSystem.getTileFromMercator(mViewPort, TileSystem.getTileSize(mProjection.getZoomLevel()), mProtectedTiles); final int tileZoomLevel = TileSystem.getInputTileZoomLevel(mProjection.getZoomLevel()); mTileProvider.getTileCache().getMapTileArea().set(tileZoomLevel, mProtectedTiles); mTileProvider.getTileCache().maintenance(); }
java
public void protectDisplayedTilesForCache(final Canvas pCanvas, final Projection pProjection) { if (!setViewPort(pCanvas, pProjection)) { return; } TileSystem.getTileFromMercator(mViewPort, TileSystem.getTileSize(mProjection.getZoomLevel()), mProtectedTiles); final int tileZoomLevel = TileSystem.getInputTileZoomLevel(mProjection.getZoomLevel()); mTileProvider.getTileCache().getMapTileArea().set(tileZoomLevel, mProtectedTiles); mTileProvider.getTileCache().maintenance(); }
[ "public", "void", "protectDisplayedTilesForCache", "(", "final", "Canvas", "pCanvas", ",", "final", "Projection", "pProjection", ")", "{", "if", "(", "!", "setViewPort", "(", "pCanvas", ",", "pProjection", ")", ")", "{", "return", ";", "}", "TileSystem", ".", ...
Populates the tile provider's memory cache with the list of displayed tiles @since 6.0.0
[ "Populates", "the", "tile", "provider", "s", "memory", "cache", "with", "the", "list", "of", "displayed", "tiles" ]
train
https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-android/src/main/java/org/osmdroid/views/overlay/TilesOverlay.java#L171-L179
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/io/grasslegacy/utils/Window.java
Window.snapToNextHigherInActiveRegionResolution
public static Point2D.Double snapToNextHigherInActiveRegionResolution( double x, double y, Window activeWindow ) { double minx = activeWindow.getRectangle().getBounds2D().getMinX(); double ewres = activeWindow.getWEResolution(); double xsnap = minx + (Math.ceil((x - minx) / ewres) * ewres); double miny = activeWindow.getRectangle().getBounds2D().getMinY(); double nsres = activeWindow.getNSResolution(); double ysnap = miny + (Math.ceil((y - miny) / nsres) * nsres); return new Point2D.Double(xsnap, ysnap); }
java
public static Point2D.Double snapToNextHigherInActiveRegionResolution( double x, double y, Window activeWindow ) { double minx = activeWindow.getRectangle().getBounds2D().getMinX(); double ewres = activeWindow.getWEResolution(); double xsnap = minx + (Math.ceil((x - minx) / ewres) * ewres); double miny = activeWindow.getRectangle().getBounds2D().getMinY(); double nsres = activeWindow.getNSResolution(); double ysnap = miny + (Math.ceil((y - miny) / nsres) * nsres); return new Point2D.Double(xsnap, ysnap); }
[ "public", "static", "Point2D", ".", "Double", "snapToNextHigherInActiveRegionResolution", "(", "double", "x", ",", "double", "y", ",", "Window", "activeWindow", ")", "{", "double", "minx", "=", "activeWindow", ".", "getRectangle", "(", ")", ".", "getBounds2D", "...
Moves the point given by X and Y to be on the grid of the active region. @param x the easting of the arbitrary point @param y the northing of the arbitrary point @param activeWindow the active window from which to take the grid @return the snapped point
[ "Moves", "the", "point", "given", "by", "X", "and", "Y", "to", "be", "on", "the", "grid", "of", "the", "active", "region", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/io/grasslegacy/utils/Window.java#L444-L456
liferay/com-liferay-commerce
commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPMeasurementUnitPersistenceImpl.java
CPMeasurementUnitPersistenceImpl.fetchByUUID_G
@Override public CPMeasurementUnit fetchByUUID_G(String uuid, long groupId) { return fetchByUUID_G(uuid, groupId, true); }
java
@Override public CPMeasurementUnit fetchByUUID_G(String uuid, long groupId) { return fetchByUUID_G(uuid, groupId, true); }
[ "@", "Override", "public", "CPMeasurementUnit", "fetchByUUID_G", "(", "String", "uuid", ",", "long", "groupId", ")", "{", "return", "fetchByUUID_G", "(", "uuid", ",", "groupId", ",", "true", ")", ";", "}" ]
Returns the cp measurement unit where uuid = &#63; and groupId = &#63; or returns <code>null</code> if it could not be found. Uses the finder cache. @param uuid the uuid @param groupId the group ID @return the matching cp measurement unit, or <code>null</code> if a matching cp measurement unit could not be found
[ "Returns", "the", "cp", "measurement", "unit", "where", "uuid", "=", "&#63", ";", "and", "groupId", "=", "&#63", ";", "or", "returns", "<code", ">", "null<", "/", "code", ">", "if", "it", "could", "not", "be", "found", ".", "Uses", "the", "finder", "...
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPMeasurementUnitPersistenceImpl.java#L703-L706
uoa-group-applications/morc
src/main/java/nz/ac/auckland/morc/MorcBuilder.java
MorcBuilder.predicateMultiplier
public Builder predicateMultiplier(int count, Predicate... predicates) { for (int i = 0; i < count; i++) { addPredicates(predicates); } return self(); }
java
public Builder predicateMultiplier(int count, Predicate... predicates) { for (int i = 0; i < count; i++) { addPredicates(predicates); } return self(); }
[ "public", "Builder", "predicateMultiplier", "(", "int", "count", ",", "Predicate", "...", "predicates", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "count", ";", "i", "++", ")", "{", "addPredicates", "(", "predicates", ")", ";", "}", "...
Expect a repeat of the same predicates multiple times @param count The number of times to repeat these predicates (separate responses) @param predicates The set of response validators/predicates that will be used to validate consecutive responses
[ "Expect", "a", "repeat", "of", "the", "same", "predicates", "multiple", "times" ]
train
https://github.com/uoa-group-applications/morc/blob/3add6308b1fbfc98187364ac73007c83012ea8ba/src/main/java/nz/ac/auckland/morc/MorcBuilder.java#L141-L147
lazy-koala/java-toolkit
fast-toolkit/src/main/java/com/thankjava/toolkit/core/utils/TimeUtil.java
TimeUtil.formatDate
public static String formatDate(TimeType timeType, Date date) { return getDateFormat(timeType).format(date); }
java
public static String formatDate(TimeType timeType, Date date) { return getDateFormat(timeType).format(date); }
[ "public", "static", "String", "formatDate", "(", "TimeType", "timeType", ",", "Date", "date", ")", "{", "return", "getDateFormat", "(", "timeType", ")", ".", "format", "(", "date", ")", ";", "}" ]
格式化日期 <p>Function: formatDate</p> <p>Description: </p> @param timeType @param date @return @author acexy@thankjava.com @date 2015年6月18日 上午10:01:09 @version 1.0
[ "格式化日期", "<p", ">", "Function", ":", "formatDate<", "/", "p", ">", "<p", ">", "Description", ":", "<", "/", "p", ">" ]
train
https://github.com/lazy-koala/java-toolkit/blob/f46055fae0cc73049597a3708e515f5c6582d27a/fast-toolkit/src/main/java/com/thankjava/toolkit/core/utils/TimeUtil.java#L86-L88
ironjacamar/ironjacamar
core/src/main/java/org/ironjacamar/core/connectionmanager/ccm/Context.java
Context.switchConnectionListener
void switchConnectionListener(Object c, ConnectionListener from, ConnectionListener to) { if (clToC != null && clToC.get(from) != null && clToC.get(to) != null) { clToC.get(from).remove(c); clToC.get(to).add(c); } }
java
void switchConnectionListener(Object c, ConnectionListener from, ConnectionListener to) { if (clToC != null && clToC.get(from) != null && clToC.get(to) != null) { clToC.get(from).remove(c); clToC.get(to).add(c); } }
[ "void", "switchConnectionListener", "(", "Object", "c", ",", "ConnectionListener", "from", ",", "ConnectionListener", "to", ")", "{", "if", "(", "clToC", "!=", "null", "&&", "clToC", ".", "get", "(", "from", ")", "!=", "null", "&&", "clToC", ".", "get", ...
Switch the connection listener for a connection @param c The connection @param from The from connection listener @param to The to connection listener
[ "Switch", "the", "connection", "listener", "for", "a", "connection" ]
train
https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/core/src/main/java/org/ironjacamar/core/connectionmanager/ccm/Context.java#L164-L171
apache/groovy
subprojects/groovy-datetime/src/main/java/org/apache/groovy/datetime/extensions/DateTimeExtensions.java
DateTimeExtensions.offsetFieldValue
private static int offsetFieldValue(ZoneOffset offset, TemporalField field) { int offsetSeconds = offset.getTotalSeconds(); int value = LocalTime.ofSecondOfDay(Math.abs(offsetSeconds)).get(field); return offsetSeconds < 0 ? value * -1 : value; }
java
private static int offsetFieldValue(ZoneOffset offset, TemporalField field) { int offsetSeconds = offset.getTotalSeconds(); int value = LocalTime.ofSecondOfDay(Math.abs(offsetSeconds)).get(field); return offsetSeconds < 0 ? value * -1 : value; }
[ "private", "static", "int", "offsetFieldValue", "(", "ZoneOffset", "offset", ",", "TemporalField", "field", ")", "{", "int", "offsetSeconds", "=", "offset", ".", "getTotalSeconds", "(", ")", ";", "int", "value", "=", "LocalTime", ".", "ofSecondOfDay", "(", "Ma...
Returns the value of the provided field for the ZoneOffset as if the ZoneOffset's hours/minutes/seconds were reckoned as a LocalTime.
[ "Returns", "the", "value", "of", "the", "provided", "field", "for", "the", "ZoneOffset", "as", "if", "the", "ZoneOffset", "s", "hours", "/", "minutes", "/", "seconds", "were", "reckoned", "as", "a", "LocalTime", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-datetime/src/main/java/org/apache/groovy/datetime/extensions/DateTimeExtensions.java#L1885-L1889
google/error-prone-javac
src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/util/Utils.java
Utils.makeComparatorForIndexUse
public Comparator<Doc> makeComparatorForIndexUse() { return new Utils.DocComparator<Doc>() { /** * Compare two given Doc entities, first sort on names, then on the kinds, * then on the parameters only if the type is an instance of ExecutableMemberDocs, * the parameters are compared and finally the fully qualified names. * * @param d1 - a Doc element. * @param d2 - a Doc element. * @return a negative integer, zero, or a positive integer as the first * argument is less than, equal to, or greater than the second. */ public int compare(Doc d1, Doc d2) { int result = compareNames(d1, d2); if (result != 0) { return result; } result = compareDocKinds(d1, d2); if (result != 0) { return result; } if (hasParameters(d1)) { Parameter[] param1 = ((ExecutableMemberDoc) d1).parameters(); Parameter[] param2 = ((ExecutableMemberDoc) d2).parameters(); result = compareParameters(false, param1, param2); if (result != 0) { return result; } result = compareParameters(true, param1, param2); if (result != 0) { return result; } } return compareFullyQualifiedNames(d1, d2); } }; }
java
public Comparator<Doc> makeComparatorForIndexUse() { return new Utils.DocComparator<Doc>() { /** * Compare two given Doc entities, first sort on names, then on the kinds, * then on the parameters only if the type is an instance of ExecutableMemberDocs, * the parameters are compared and finally the fully qualified names. * * @param d1 - a Doc element. * @param d2 - a Doc element. * @return a negative integer, zero, or a positive integer as the first * argument is less than, equal to, or greater than the second. */ public int compare(Doc d1, Doc d2) { int result = compareNames(d1, d2); if (result != 0) { return result; } result = compareDocKinds(d1, d2); if (result != 0) { return result; } if (hasParameters(d1)) { Parameter[] param1 = ((ExecutableMemberDoc) d1).parameters(); Parameter[] param2 = ((ExecutableMemberDoc) d2).parameters(); result = compareParameters(false, param1, param2); if (result != 0) { return result; } result = compareParameters(true, param1, param2); if (result != 0) { return result; } } return compareFullyQualifiedNames(d1, d2); } }; }
[ "public", "Comparator", "<", "Doc", ">", "makeComparatorForIndexUse", "(", ")", "{", "return", "new", "Utils", ".", "DocComparator", "<", "Doc", ">", "(", ")", "{", "/**\n * Compare two given Doc entities, first sort on names, then on the kinds,\n * th...
A comparator for index file presentations, and are sorted as follows: 1. sort on simple names of entities 2. if equal, then compare the DocKind ex: Package, Interface etc. 3a. if equal and if the type is of ExecutableMemberDoc(Constructor, Methods), a case insensitive comparison of parameter the type signatures 3b. if equal, case sensitive comparison of the type signatures 4. finally, if equal, compare the FQNs of the entities @return a comparator for index file use
[ "A", "comparator", "for", "index", "file", "presentations", "and", "are", "sorted", "as", "follows", ":", "1", ".", "sort", "on", "simple", "names", "of", "entities", "2", ".", "if", "equal", "then", "compare", "the", "DocKind", "ex", ":", "Package", "In...
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/util/Utils.java#L840-L876
hawkular/hawkular-commons
hawkular-command-gateway/hawkular-command-gateway-war/src/main/java/org/hawkular/cmdgw/command/ws/server/AbstractGatewayWebSocket.java
AbstractGatewayWebSocket.onMessage
@OnMessage public void onMessage(String nameAndJsonStr, Session session) { String requestClassName = "?"; try { // parse the JSON and get its message POJO BasicMessageWithExtraData<BasicMessage> request = new ApiDeserializer().deserialize(nameAndJsonStr); requestClassName = request.getBasicMessage().getClass().getName(); log.infoReceivedWsMessage(requestClassName, session.getId(), endpoint); handleRequest(session, request); } catch (Throwable t) { log.errorWsCommandExecutionFailure(requestClassName, session.getId(), endpoint, t); String errorMessage = "Failed to process message [" + requestClassName + "]"; sendErrorResponse(session, errorMessage, t); } }
java
@OnMessage public void onMessage(String nameAndJsonStr, Session session) { String requestClassName = "?"; try { // parse the JSON and get its message POJO BasicMessageWithExtraData<BasicMessage> request = new ApiDeserializer().deserialize(nameAndJsonStr); requestClassName = request.getBasicMessage().getClass().getName(); log.infoReceivedWsMessage(requestClassName, session.getId(), endpoint); handleRequest(session, request); } catch (Throwable t) { log.errorWsCommandExecutionFailure(requestClassName, session.getId(), endpoint, t); String errorMessage = "Failed to process message [" + requestClassName + "]"; sendErrorResponse(session, errorMessage, t); } }
[ "@", "OnMessage", "public", "void", "onMessage", "(", "String", "nameAndJsonStr", ",", "Session", "session", ")", "{", "String", "requestClassName", "=", "\"?\"", ";", "try", "{", "// parse the JSON and get its message POJO", "BasicMessageWithExtraData", "<", "BasicMess...
When a message is received from a WebSocket client, this method will lookup the {@link WsCommand} for the given request class and execute it. @param nameAndJsonStr the name of the API request followed by "=" followed then by the request's JSON data @param session the client session making the request
[ "When", "a", "message", "is", "received", "from", "a", "WebSocket", "client", "this", "method", "will", "lookup", "the", "{", "@link", "WsCommand", "}", "for", "the", "given", "request", "class", "and", "execute", "it", "." ]
train
https://github.com/hawkular/hawkular-commons/blob/e4a832862b3446d7f4d629bb05790f2df578e035/hawkular-command-gateway/hawkular-command-gateway-war/src/main/java/org/hawkular/cmdgw/command/ws/server/AbstractGatewayWebSocket.java#L140-L156
3redronin/mu-server
src/main/java/io/muserver/MediaTypeParser.java
MediaTypeParser.fromString
public static MediaType fromString(String value) { if (value == null) { throw new NullPointerException("value"); } List<ParameterizedHeaderWithValue> headerValues = ParameterizedHeaderWithValue.fromString(value); if (headerValues.isEmpty()) { throw new IllegalArgumentException("The value '" + value + "' did not contain a valid header value"); } ParameterizedHeaderWithValue v = headerValues.get(0); String[] split = v.value().split("/"); if (split.length != 2) { throw new IllegalArgumentException("Media types must be in the format 'type/subtype'; this is inavlid: '" + v.value() + "'"); } return new MediaType(split[0], split[1], v.parameters()); }
java
public static MediaType fromString(String value) { if (value == null) { throw new NullPointerException("value"); } List<ParameterizedHeaderWithValue> headerValues = ParameterizedHeaderWithValue.fromString(value); if (headerValues.isEmpty()) { throw new IllegalArgumentException("The value '" + value + "' did not contain a valid header value"); } ParameterizedHeaderWithValue v = headerValues.get(0); String[] split = v.value().split("/"); if (split.length != 2) { throw new IllegalArgumentException("Media types must be in the format 'type/subtype'; this is inavlid: '" + v.value() + "'"); } return new MediaType(split[0], split[1], v.parameters()); }
[ "public", "static", "MediaType", "fromString", "(", "String", "value", ")", "{", "if", "(", "value", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"value\"", ")", ";", "}", "List", "<", "ParameterizedHeaderWithValue", ">", "headerValue...
Converts a string such as "text/plain" into a MediaType object. @param value The value to parse @return A MediaType object
[ "Converts", "a", "string", "such", "as", "text", "/", "plain", "into", "a", "MediaType", "object", "." ]
train
https://github.com/3redronin/mu-server/blob/51598606a3082a121fbd785348ee9770b40308e6/src/main/java/io/muserver/MediaTypeParser.java#L22-L36
soi-toolkit/soi-toolkit-mule
tools/soitoolkit-generator/soitoolkit-generator-eclipse-plugin/soitoolkit-generator-plugin/src/soi_toolkit_generator_plugin/preferences/SoiToolkiGeneratorPreferencePage.java
SoiToolkiGeneratorPreferencePage.createFieldEditors
public void createFieldEditors() { addField(new DirectoryFieldEditor(PreferenceConstants.P_MAVEN_HOME, "&Maven home folder:", getFieldEditorParent())); addField(new DirectoryFieldEditor(PreferenceConstants.P_DEFAULT_ROOT_FOLDER, "Default root folder:", getFieldEditorParent())); // addField(new RadioGroupFieldEditor(PreferenceConstants.P_ECLIPSE_GOAL, "Maven Eclipse goal", 1, // new String[][] { { "eclipse:eclipse", "eclipse:eclipse" }, {"eclipse:m2eclipse", "eclipse:m2eclipse" } // }, getFieldEditorParent())); addField(new StringFieldEditor(PreferenceConstants.P_GROOVY_MODEL, "Custom Groovy model:", getFieldEditorParent())); addField(new StringFieldEditor(PreferenceConstants.P_SFTP_ROOT_FOLDER, "Default SFTP root folder:", getFieldEditorParent())); // addField( // new BooleanFieldEditor( // PreferenceConstants.P_BOOLEAN, // "&An example of a boolean preference", // getFieldEditorParent())); }
java
public void createFieldEditors() { addField(new DirectoryFieldEditor(PreferenceConstants.P_MAVEN_HOME, "&Maven home folder:", getFieldEditorParent())); addField(new DirectoryFieldEditor(PreferenceConstants.P_DEFAULT_ROOT_FOLDER, "Default root folder:", getFieldEditorParent())); // addField(new RadioGroupFieldEditor(PreferenceConstants.P_ECLIPSE_GOAL, "Maven Eclipse goal", 1, // new String[][] { { "eclipse:eclipse", "eclipse:eclipse" }, {"eclipse:m2eclipse", "eclipse:m2eclipse" } // }, getFieldEditorParent())); addField(new StringFieldEditor(PreferenceConstants.P_GROOVY_MODEL, "Custom Groovy model:", getFieldEditorParent())); addField(new StringFieldEditor(PreferenceConstants.P_SFTP_ROOT_FOLDER, "Default SFTP root folder:", getFieldEditorParent())); // addField( // new BooleanFieldEditor( // PreferenceConstants.P_BOOLEAN, // "&An example of a boolean preference", // getFieldEditorParent())); }
[ "public", "void", "createFieldEditors", "(", ")", "{", "addField", "(", "new", "DirectoryFieldEditor", "(", "PreferenceConstants", ".", "P_MAVEN_HOME", ",", "\"&Maven home folder:\"", ",", "getFieldEditorParent", "(", ")", ")", ")", ";", "addField", "(", "new", "D...
Creates the field editors. Field editors are abstractions of the common GUI blocks needed to manipulate various types of preferences. Each field editor knows how to save and restore itself.
[ "Creates", "the", "field", "editors", ".", "Field", "editors", "are", "abstractions", "of", "the", "common", "GUI", "blocks", "needed", "to", "manipulate", "various", "types", "of", "preferences", ".", "Each", "field", "editor", "knows", "how", "to", "save", ...
train
https://github.com/soi-toolkit/soi-toolkit-mule/blob/e891350dbf55e6307be94d193d056bdb785b37d3/tools/soitoolkit-generator/soitoolkit-generator-eclipse-plugin/soitoolkit-generator-plugin/src/soi_toolkit_generator_plugin/preferences/SoiToolkiGeneratorPreferencePage.java#L58-L77
threerings/nenya
core/src/main/java/com/threerings/media/util/MathUtil.java
MathUtil.floorDiv
public static int floorDiv (int dividend, int divisor) { return ((dividend >= 0) == (divisor >= 0)) ? dividend / divisor : (divisor >= 0 ? (dividend - divisor + 1) / divisor : (dividend - divisor - 1) / divisor); }
java
public static int floorDiv (int dividend, int divisor) { return ((dividend >= 0) == (divisor >= 0)) ? dividend / divisor : (divisor >= 0 ? (dividend - divisor + 1) / divisor : (dividend - divisor - 1) / divisor); }
[ "public", "static", "int", "floorDiv", "(", "int", "dividend", ",", "int", "divisor", ")", "{", "return", "(", "(", "dividend", ">=", "0", ")", "==", "(", "divisor", ">=", "0", ")", ")", "?", "dividend", "/", "divisor", ":", "(", "divisor", ">=", "...
Computes the floored division <code>dividend/divisor</code> which is useful when dividing potentially negative numbers into bins. <p> For example, the following numbers floorDiv 10 are: <pre> -15 -10 -8 -2 0 2 8 10 15 -2 -1 -1 -1 0 0 0 1 1 </pre>
[ "Computes", "the", "floored", "division", "<code", ">", "dividend", "/", "divisor<", "/", "code", ">", "which", "is", "useful", "when", "dividing", "potentially", "negative", "numbers", "into", "bins", "." ]
train
https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/media/util/MathUtil.java#L109-L114
ModeShape/modeshape
modeshape-jcr/src/main/java/org/modeshape/jcr/AbstractJcrNode.java
AbstractJcrNode.setProperty
final AbstractJcrProperty setProperty( Name name, Value[] values, int jcrPropertyType, boolean skipReferenceValidation ) throws VersionException, LockException, ConstraintViolationException, RepositoryException { return setProperty(name, values, jcrPropertyType, false, skipReferenceValidation, false, false); }
java
final AbstractJcrProperty setProperty( Name name, Value[] values, int jcrPropertyType, boolean skipReferenceValidation ) throws VersionException, LockException, ConstraintViolationException, RepositoryException { return setProperty(name, values, jcrPropertyType, false, skipReferenceValidation, false, false); }
[ "final", "AbstractJcrProperty", "setProperty", "(", "Name", "name", ",", "Value", "[", "]", "values", ",", "int", "jcrPropertyType", ",", "boolean", "skipReferenceValidation", ")", "throws", "VersionException", ",", "LockException", ",", "ConstraintViolationException", ...
Sets a multi valued property, skipping over protected ones. @param name the name of the property; may not be null @param values the values of the property; may not be null @param jcrPropertyType the expected property type; may be {@link PropertyType#UNDEFINED} if the values should not be converted @param skipReferenceValidation indicates whether constraints on REFERENCE properties should be enforced @return the new JCR property object @throws VersionException if the node is checked out @throws LockException if the node is locked @throws ConstraintViolationException if the new value would violate the constraints on the property definition @throws RepositoryException if the named property does not exist, or if some other error occurred
[ "Sets", "a", "multi", "valued", "property", "skipping", "over", "protected", "ones", "." ]
train
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-jcr/src/main/java/org/modeshape/jcr/AbstractJcrNode.java#L1823-L1829
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/embeddings/loader/WordVectorSerializer.java
WordVectorSerializer.readSequenceVectors
public static <T extends SequenceElement> SequenceVectors<T> readSequenceVectors( @NonNull SequenceElementFactory<T> factory, @NonNull InputStream stream) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8")); // at first we load vectors configuration String line = reader.readLine(); VectorsConfiguration configuration = VectorsConfiguration.fromJson(new String(Base64.decodeBase64(line), "UTF-8")); AbstractCache<T> vocabCache = new AbstractCache.Builder<T>().build(); List<INDArray> rows = new ArrayList<>(); while ((line = reader.readLine()) != null) { if (line.isEmpty()) // skip empty line continue; ElementPair pair = ElementPair.fromEncodedJson(line); T element = factory.deserialize(pair.getObject()); rows.add(Nd4j.create(pair.getVector())); vocabCache.addToken(element); vocabCache.addWordToIndex(element.getIndex(), element.getLabel()); } reader.close(); InMemoryLookupTable<T> lookupTable = (InMemoryLookupTable<T>) new InMemoryLookupTable.Builder<T>() .vectorLength(rows.get(0).columns()).cache(vocabCache).build(); // fix: add vocab cache /* * INDArray syn0 = Nd4j.create(rows.size(), rows.get(0).columns()); for (int x = 0; x < rows.size(); x++) { * syn0.putRow(x, rows.get(x)); } */ INDArray syn0 = Nd4j.vstack(rows); lookupTable.setSyn0(syn0); SequenceVectors<T> vectors = new SequenceVectors.Builder<T>(configuration).vocabCache(vocabCache) .lookupTable(lookupTable).resetModel(false).build(); return vectors; }
java
public static <T extends SequenceElement> SequenceVectors<T> readSequenceVectors( @NonNull SequenceElementFactory<T> factory, @NonNull InputStream stream) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8")); // at first we load vectors configuration String line = reader.readLine(); VectorsConfiguration configuration = VectorsConfiguration.fromJson(new String(Base64.decodeBase64(line), "UTF-8")); AbstractCache<T> vocabCache = new AbstractCache.Builder<T>().build(); List<INDArray> rows = new ArrayList<>(); while ((line = reader.readLine()) != null) { if (line.isEmpty()) // skip empty line continue; ElementPair pair = ElementPair.fromEncodedJson(line); T element = factory.deserialize(pair.getObject()); rows.add(Nd4j.create(pair.getVector())); vocabCache.addToken(element); vocabCache.addWordToIndex(element.getIndex(), element.getLabel()); } reader.close(); InMemoryLookupTable<T> lookupTable = (InMemoryLookupTable<T>) new InMemoryLookupTable.Builder<T>() .vectorLength(rows.get(0).columns()).cache(vocabCache).build(); // fix: add vocab cache /* * INDArray syn0 = Nd4j.create(rows.size(), rows.get(0).columns()); for (int x = 0; x < rows.size(); x++) { * syn0.putRow(x, rows.get(x)); } */ INDArray syn0 = Nd4j.vstack(rows); lookupTable.setSyn0(syn0); SequenceVectors<T> vectors = new SequenceVectors.Builder<T>(configuration).vocabCache(vocabCache) .lookupTable(lookupTable).resetModel(false).build(); return vectors; }
[ "public", "static", "<", "T", "extends", "SequenceElement", ">", "SequenceVectors", "<", "T", ">", "readSequenceVectors", "(", "@", "NonNull", "SequenceElementFactory", "<", "T", ">", "factory", ",", "@", "NonNull", "InputStream", "stream", ")", "throws", "IOExc...
This method loads previously saved SequenceVectors model from InputStream @param factory @param stream @param <T> @return
[ "This", "method", "loads", "previously", "saved", "SequenceVectors", "model", "from", "InputStream" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/embeddings/loader/WordVectorSerializer.java#L2135-L2176
maxirosson/jdroid-android
jdroid-android-google-maps/src/main/java/com/jdroid/android/google/maps/GoogleRouteParser.java
GoogleRouteParser.decodePolyLine
private List<GeoLocation> decodePolyLine(String poly) { int len = poly.length(); int index = 0; List<GeoLocation> decoded = new ArrayList<>(); int lat = 0; int lng = 0; while (index < len) { int b; int shift = 0; int result = 0; do { b = poly.charAt(index++) - 63; result |= (b & 0x1f) << shift; shift += 5; } while (b >= 0x20); int dlat = (result & 1) != 0 ? ~(result >> 1) : (result >> 1); lat += dlat; shift = 0; result = 0; do { b = poly.charAt(index++) - 63; result |= (b & 0x1f) << shift; shift += 5; } while (b >= 0x20); int dlng = (result & 1) != 0 ? ~(result >> 1) : (result >> 1); lng += dlng; decoded.add(new GeoLocation(lat / 1E5, lng / 1E5)); } return decoded; }
java
private List<GeoLocation> decodePolyLine(String poly) { int len = poly.length(); int index = 0; List<GeoLocation> decoded = new ArrayList<>(); int lat = 0; int lng = 0; while (index < len) { int b; int shift = 0; int result = 0; do { b = poly.charAt(index++) - 63; result |= (b & 0x1f) << shift; shift += 5; } while (b >= 0x20); int dlat = (result & 1) != 0 ? ~(result >> 1) : (result >> 1); lat += dlat; shift = 0; result = 0; do { b = poly.charAt(index++) - 63; result |= (b & 0x1f) << shift; shift += 5; } while (b >= 0x20); int dlng = (result & 1) != 0 ? ~(result >> 1) : (result >> 1); lng += dlng; decoded.add(new GeoLocation(lat / 1E5, lng / 1E5)); } return decoded; }
[ "private", "List", "<", "GeoLocation", ">", "decodePolyLine", "(", "String", "poly", ")", "{", "int", "len", "=", "poly", ".", "length", "(", ")", ";", "int", "index", "=", "0", ";", "List", "<", "GeoLocation", ">", "decoded", "=", "new", "ArrayList", ...
Decode a polyline string into a list of GeoLocations. From https://developers.google.com/maps/documentation/directions/?hl=es#Limits @param poly polyline encoded string to decode. @return the list of GeoLocations represented by this polystring.
[ "Decode", "a", "polyline", "string", "into", "a", "list", "of", "GeoLocations", ".", "From", "https", ":", "//", "developers", ".", "google", ".", "com", "/", "maps", "/", "documentation", "/", "directions", "/", "?hl", "=", "es#Limits" ]
train
https://github.com/maxirosson/jdroid-android/blob/1ba9cae56a16fa36bdb2c9c04379853f0300707f/jdroid-android-google-maps/src/main/java/com/jdroid/android/google/maps/GoogleRouteParser.java#L55-L88
alkacon/opencms-core
src-modules/org/opencms/workplace/tools/database/CmsHtmlImportConverter.java
CmsHtmlImportConverter.printDocument
private void printDocument(Node node, Hashtable properties) { // if node is empty do nothing... (Recursion) if (node == null) { return; } // initialise local variables int type = node.getNodeType(); String name = node.getNodeName(); // detect node type switch (type) { case Node.DOCUMENT_NODE: printDocument(((Document)node).getDocumentElement(), properties); break; case Node.ELEMENT_NODE: // check if its the <head> node. Nothing inside the <head> node // must be // part of the output, but we must scan the content of this // node to get all // <meta> tags if (name.equals(NODE_HEAD)) { m_write = false; } // scan element node; if a block has to be removed or replaced, // break and discard child nodes transformStartElement(node, properties); // test if node has children NodeList children = node.getChildNodes(); if (children != null) { int len = children.getLength(); for (int i = 0; i < len; i++) { // recursively call printDocument with all child nodes printDocument(children.item(i), properties); } } break; case Node.TEXT_NODE: // replace subStrings in text nodes transformTextNode(node); break; default: break; } // end of recursion, add eventual endtags and suffixes switch (type) { case Node.ELEMENT_NODE: // analyse endtags and add them to output transformEndElement(node); if (node.getNodeName().equals(NODE_HEAD)) { m_write = true; } break; case Node.DOCUMENT_NODE: break; default: break; } }
java
private void printDocument(Node node, Hashtable properties) { // if node is empty do nothing... (Recursion) if (node == null) { return; } // initialise local variables int type = node.getNodeType(); String name = node.getNodeName(); // detect node type switch (type) { case Node.DOCUMENT_NODE: printDocument(((Document)node).getDocumentElement(), properties); break; case Node.ELEMENT_NODE: // check if its the <head> node. Nothing inside the <head> node // must be // part of the output, but we must scan the content of this // node to get all // <meta> tags if (name.equals(NODE_HEAD)) { m_write = false; } // scan element node; if a block has to be removed or replaced, // break and discard child nodes transformStartElement(node, properties); // test if node has children NodeList children = node.getChildNodes(); if (children != null) { int len = children.getLength(); for (int i = 0; i < len; i++) { // recursively call printDocument with all child nodes printDocument(children.item(i), properties); } } break; case Node.TEXT_NODE: // replace subStrings in text nodes transformTextNode(node); break; default: break; } // end of recursion, add eventual endtags and suffixes switch (type) { case Node.ELEMENT_NODE: // analyse endtags and add them to output transformEndElement(node); if (node.getNodeName().equals(NODE_HEAD)) { m_write = true; } break; case Node.DOCUMENT_NODE: break; default: break; } }
[ "private", "void", "printDocument", "(", "Node", "node", ",", "Hashtable", "properties", ")", "{", "// if node is empty do nothing... (Recursion)", "if", "(", "node", "==", "null", ")", "{", "return", ";", "}", "// initialise local variables", "int", "type", "=", ...
Private method to parse DOM and create user defined output.<p> @param node Node of DOM from HTML code @param properties the file properties
[ "Private", "method", "to", "parse", "DOM", "and", "create", "user", "defined", "output", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/tools/database/CmsHtmlImportConverter.java#L321-L384
Azure/azure-sdk-for-java
servicebus/data-plane/azure-servicebus/src/main/java/com/microsoft/azure/servicebus/management/ManagementClient.java
ManagementClient.deleteSubscription
public Void deleteSubscription(String topicPath, String subscriptionName) throws ServiceBusException, InterruptedException { return Utils.completeFuture(this.asyncClient.deleteSubscriptionAsync(topicPath, subscriptionName)); }
java
public Void deleteSubscription(String topicPath, String subscriptionName) throws ServiceBusException, InterruptedException { return Utils.completeFuture(this.asyncClient.deleteSubscriptionAsync(topicPath, subscriptionName)); }
[ "public", "Void", "deleteSubscription", "(", "String", "topicPath", ",", "String", "subscriptionName", ")", "throws", "ServiceBusException", ",", "InterruptedException", "{", "return", "Utils", ".", "completeFuture", "(", "this", ".", "asyncClient", ".", "deleteSubscr...
Deletes the subscription described by the topicPath and the subscriptionName. @param topicPath - The name of the topic. @param subscriptionName - The name of the subscription. @throws IllegalArgumentException - path is not null / empty / too long / invalid. @throws TimeoutException - The operation times out. The timeout period is initiated through ClientSettings.operationTimeout @throws AuthorizationFailedException - No sufficient permission to perform this operation. Please check ClientSettings.tokenProvider has correct details. @throws ServerBusyException - The server is busy. You should wait before you retry the operation. @throws ServiceBusException - An internal error or an unexpected exception occurred. @throws MessagingEntityNotFoundException - An entity with this name does not exist. @throws InterruptedException if the current thread was interrupted
[ "Deletes", "the", "subscription", "described", "by", "the", "topicPath", "and", "the", "subscriptionName", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/servicebus/data-plane/azure-servicebus/src/main/java/com/microsoft/azure/servicebus/management/ManagementClient.java#L598-L600
biojava/biojava
biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/AlignmentTools.java
AlignmentTools.replaceOptAln
public static AFPChain replaceOptAln(AFPChain afpChain, Atom[] ca1, Atom[] ca2, Map<Integer, Integer> alignment) throws StructureException { // Determine block lengths // Sort ca1 indices, then start a new block whenever ca2 indices aren't // increasing monotonically. Integer[] res1 = alignment.keySet().toArray(new Integer[0]); Arrays.sort(res1); List<Integer> blockLens = new ArrayList<Integer>(2); int optLength = 0; Integer lastRes = alignment.get(res1[0]); int blkLen = lastRes==null?0:1; for(int i=1;i<res1.length;i++) { Integer currRes = alignment.get(res1[i]); //res2 index assert(currRes != null);// could be converted to if statement if assertion doesn't hold; just modify below as well. if(lastRes<currRes) { blkLen++; } else { // CP! blockLens.add(blkLen); optLength+=blkLen; blkLen = 1; } lastRes = currRes; } blockLens.add(blkLen); optLength+=blkLen; // Create array structure for alignment int[][][] optAln = new int[blockLens.size()][][]; int pos1 = 0; //index into res1 for(int blk=0;blk<blockLens.size();blk++) { optAln[blk] = new int[2][]; blkLen = blockLens.get(blk); optAln[blk][0] = new int[blkLen]; optAln[blk][1] = new int[blkLen]; int pos = 0; //index into optAln while(pos<blkLen) { optAln[blk][0][pos]=res1[pos1]; Integer currRes = alignment.get(res1[pos1]); optAln[blk][1][pos]=currRes; pos++; pos1++; } } assert(pos1 == optLength); // Create length array int[] optLens = new int[blockLens.size()]; for(int i=0;i<blockLens.size();i++) { optLens[i] = blockLens.get(i); } return replaceOptAln(afpChain, ca1, ca2, blockLens.size(), optLens, optAln); }
java
public static AFPChain replaceOptAln(AFPChain afpChain, Atom[] ca1, Atom[] ca2, Map<Integer, Integer> alignment) throws StructureException { // Determine block lengths // Sort ca1 indices, then start a new block whenever ca2 indices aren't // increasing monotonically. Integer[] res1 = alignment.keySet().toArray(new Integer[0]); Arrays.sort(res1); List<Integer> blockLens = new ArrayList<Integer>(2); int optLength = 0; Integer lastRes = alignment.get(res1[0]); int blkLen = lastRes==null?0:1; for(int i=1;i<res1.length;i++) { Integer currRes = alignment.get(res1[i]); //res2 index assert(currRes != null);// could be converted to if statement if assertion doesn't hold; just modify below as well. if(lastRes<currRes) { blkLen++; } else { // CP! blockLens.add(blkLen); optLength+=blkLen; blkLen = 1; } lastRes = currRes; } blockLens.add(blkLen); optLength+=blkLen; // Create array structure for alignment int[][][] optAln = new int[blockLens.size()][][]; int pos1 = 0; //index into res1 for(int blk=0;blk<blockLens.size();blk++) { optAln[blk] = new int[2][]; blkLen = blockLens.get(blk); optAln[blk][0] = new int[blkLen]; optAln[blk][1] = new int[blkLen]; int pos = 0; //index into optAln while(pos<blkLen) { optAln[blk][0][pos]=res1[pos1]; Integer currRes = alignment.get(res1[pos1]); optAln[blk][1][pos]=currRes; pos++; pos1++; } } assert(pos1 == optLength); // Create length array int[] optLens = new int[blockLens.size()]; for(int i=0;i<blockLens.size();i++) { optLens[i] = blockLens.get(i); } return replaceOptAln(afpChain, ca1, ca2, blockLens.size(), optLens, optAln); }
[ "public", "static", "AFPChain", "replaceOptAln", "(", "AFPChain", "afpChain", ",", "Atom", "[", "]", "ca1", ",", "Atom", "[", "]", "ca2", ",", "Map", "<", "Integer", ",", "Integer", ">", "alignment", ")", "throws", "StructureException", "{", "// Determine bl...
Takes an AFPChain and replaces the optimal alignment based on an alignment map <p>Parameters are filled with defaults (often null) or sometimes calculated. <p>For a way to create a new AFPChain, see {@link AlignmentTools#createAFPChain(Atom[], Atom[], ResidueNumber[], ResidueNumber[])} @param afpChain The alignment to be modified @param alignment The new alignment, as a Map @throws StructureException if an error occurred during superposition @see AlignmentTools#createAFPChain(Atom[], Atom[], ResidueNumber[], ResidueNumber[])
[ "Takes", "an", "AFPChain", "and", "replaces", "the", "optimal", "alignment", "based", "on", "an", "alignment", "map" ]
train
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/AlignmentTools.java#L753-L807
gitblit/fathom
fathom-mailer/src/main/java/fathom/mailer/Mailer.java
Mailer.newTextMailRequest
public MailRequest newTextMailRequest(String requestId, String subject, String body) { return createMailRequest(requestId, false, subject, body); }
java
public MailRequest newTextMailRequest(String requestId, String subject, String body) { return createMailRequest(requestId, false, subject, body); }
[ "public", "MailRequest", "newTextMailRequest", "(", "String", "requestId", ",", "String", "subject", ",", "String", "body", ")", "{", "return", "createMailRequest", "(", "requestId", ",", "false", ",", "subject", ",", "body", ")", ";", "}" ]
Creates a plan text MailRequest with the specified subject and body. The request id is supplied. @param requestId @param subject @param body @return a text mail request
[ "Creates", "a", "plan", "text", "MailRequest", "with", "the", "specified", "subject", "and", "body", ".", "The", "request", "id", "is", "supplied", "." ]
train
https://github.com/gitblit/fathom/blob/f2f820eb16e9fea1e36ad4eda4ed51b35f056538/fathom-mailer/src/main/java/fathom/mailer/Mailer.java#L110-L112
BorderTech/wcomponents
wcomponents-core/src/main/java/com/github/bordertech/wcomponents/util/LookupTableHelper.java
LookupTableHelper.getContext
public static UIContext getContext(final String key, final Request request) { return (UIContext) request.getSessionAttribute(DATA_LIST_UIC_SESSION_KEY); }
java
public static UIContext getContext(final String key, final Request request) { return (UIContext) request.getSessionAttribute(DATA_LIST_UIC_SESSION_KEY); }
[ "public", "static", "UIContext", "getContext", "(", "final", "String", "key", ",", "final", "Request", "request", ")", "{", "return", "(", "UIContext", ")", "request", ".", "getSessionAttribute", "(", "DATA_LIST_UIC_SESSION_KEY", ")", ";", "}" ]
Retrieves the UIContext for the given data list. @param key the list key. @param request the current request being responded to. @return the UIContext for the given key.
[ "Retrieves", "the", "UIContext", "for", "the", "given", "data", "list", "." ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/util/LookupTableHelper.java#L47-L49
RestComm/sip-servlets
sip-servlets-examples/facebook-c2c/src/main/java/com/facebook/api/FacebookRestClient.java
FacebookRestClient.users_getInfo
public T users_getInfo(Collection<Integer> userIds, EnumSet<ProfileField> fields) throws FacebookException, IOException { // assertions test for invalid params assert (userIds != null); assert (fields != null); assert (!fields.isEmpty()); return this.callMethod(FacebookMethod.USERS_GET_INFO, new Pair<String, CharSequence>("uids", delimit(userIds)), new Pair<String, CharSequence>("fields", delimit(fields))); }
java
public T users_getInfo(Collection<Integer> userIds, EnumSet<ProfileField> fields) throws FacebookException, IOException { // assertions test for invalid params assert (userIds != null); assert (fields != null); assert (!fields.isEmpty()); return this.callMethod(FacebookMethod.USERS_GET_INFO, new Pair<String, CharSequence>("uids", delimit(userIds)), new Pair<String, CharSequence>("fields", delimit(fields))); }
[ "public", "T", "users_getInfo", "(", "Collection", "<", "Integer", ">", "userIds", ",", "EnumSet", "<", "ProfileField", ">", "fields", ")", "throws", "FacebookException", ",", "IOException", "{", "// assertions test for invalid params", "assert", "(", "userIds", "!=...
Retrieves the requested info fields for the requested set of users. @param userIds a collection of user IDs for which to fetch info @param fields a set of ProfileFields @return a T consisting of a list of users, with each user element containing the requested fields.
[ "Retrieves", "the", "requested", "info", "fields", "for", "the", "requested", "set", "of", "users", "." ]
train
https://github.com/RestComm/sip-servlets/blob/fd7011d2803ab1d205b140768a760c8c69e0c997/sip-servlets-examples/facebook-c2c/src/main/java/com/facebook/api/FacebookRestClient.java#L923-L933
Stratio/bdt
src/main/java/com/stratio/qa/specs/DcosSpec.java
DcosSpec.sendAppendRequest
@Then("^I add a new DCOS label with key '(.+?)' and value '(.+?)' to the service '(.+?)'?$") public void sendAppendRequest(String key, String value, String service) throws Exception { commonspec.runCommandAndGetResult("touch " + service + ".json && dcos marathon app show " + service + " > /dcos/" + service + ".json"); commonspec.runCommandAndGetResult("cat /dcos/" + service + ".json"); String configFile = commonspec.getRemoteSSHConnection().getResult(); String myValue = commonspec.getJSONPathString(configFile, ".labels", "0"); String myJson = commonspec.updateMarathonJson(commonspec.removeJSONPathElement(configFile, "$.labels")); String newValue = myValue.replaceFirst("\\{", "{\"" + key + "\": \"" + value + "\", "); newValue = "\"labels\":" + newValue; String myFinalJson = myJson.replaceFirst("\\{", "{" + newValue.replace("\\n", "\\\\n") + ","); if (myFinalJson.contains("uris")) { String test = myFinalJson.replaceAll("\"uris\"", "\"none\""); commonspec.runCommandAndGetResult("echo '" + test + "' > /dcos/final" + service + ".json"); } else { commonspec.runCommandAndGetResult("echo '" + myFinalJson + "' > /dcos/final" + service + ".json"); } commonspec.runCommandAndGetResult("dcos marathon app update " + service + " < /dcos/final" + service + ".json"); commonspec.setCommandExitStatus(commonspec.getRemoteSSHConnection().getExitStatus()); }
java
@Then("^I add a new DCOS label with key '(.+?)' and value '(.+?)' to the service '(.+?)'?$") public void sendAppendRequest(String key, String value, String service) throws Exception { commonspec.runCommandAndGetResult("touch " + service + ".json && dcos marathon app show " + service + " > /dcos/" + service + ".json"); commonspec.runCommandAndGetResult("cat /dcos/" + service + ".json"); String configFile = commonspec.getRemoteSSHConnection().getResult(); String myValue = commonspec.getJSONPathString(configFile, ".labels", "0"); String myJson = commonspec.updateMarathonJson(commonspec.removeJSONPathElement(configFile, "$.labels")); String newValue = myValue.replaceFirst("\\{", "{\"" + key + "\": \"" + value + "\", "); newValue = "\"labels\":" + newValue; String myFinalJson = myJson.replaceFirst("\\{", "{" + newValue.replace("\\n", "\\\\n") + ","); if (myFinalJson.contains("uris")) { String test = myFinalJson.replaceAll("\"uris\"", "\"none\""); commonspec.runCommandAndGetResult("echo '" + test + "' > /dcos/final" + service + ".json"); } else { commonspec.runCommandAndGetResult("echo '" + myFinalJson + "' > /dcos/final" + service + ".json"); } commonspec.runCommandAndGetResult("dcos marathon app update " + service + " < /dcos/final" + service + ".json"); commonspec.setCommandExitStatus(commonspec.getRemoteSSHConnection().getExitStatus()); }
[ "@", "Then", "(", "\"^I add a new DCOS label with key '(.+?)' and value '(.+?)' to the service '(.+?)'?$\"", ")", "public", "void", "sendAppendRequest", "(", "String", "key", ",", "String", "value", ",", "String", "service", ")", "throws", "Exception", "{", "commonspec", ...
A PUT request over the body value. @param key @param value @param service @throws Exception
[ "A", "PUT", "request", "over", "the", "body", "value", "." ]
train
https://github.com/Stratio/bdt/blob/55324d19e7497764ad3dd7139923e13eb9841d75/src/main/java/com/stratio/qa/specs/DcosSpec.java#L405-L426
baratine/baratine
core/src/main/java/com/caucho/v5/amp/manager/ServiceManagerAmpWrapper.java
ServiceManagerAmpWrapper.bind
@Override public ServiceRefAmp bind(ServiceRefAmp service, String address) { return delegate().bind(service, address); }
java
@Override public ServiceRefAmp bind(ServiceRefAmp service, String address) { return delegate().bind(service, address); }
[ "@", "Override", "public", "ServiceRefAmp", "bind", "(", "ServiceRefAmp", "service", ",", "String", "address", ")", "{", "return", "delegate", "(", ")", ".", "bind", "(", "service", ",", "address", ")", ";", "}" ]
/* @Override public <T> T createPinProxy(ServiceRefAmp actorRef, Class<T> api, Class<?>... apis) { return getDelegate().createPinProxy(actorRef, api, apis); }
[ "/", "*" ]
train
https://github.com/baratine/baratine/blob/db34b45c03c5a5e930d8142acc72319125569fcf/core/src/main/java/com/caucho/v5/amp/manager/ServiceManagerAmpWrapper.java#L158-L162
actframework/actframework
src/main/java/act/cli/ascii_table/impl/SimpleASCIITableImpl.java
SimpleASCIITableImpl.getRowLineBuf
private String getRowLineBuf(int colCount, List<Integer> colMaxLenList, String[][] data) { S.Buffer rowBuilder = S.buffer(); int colWidth; for (int i = 0 ; i < colCount ; i ++) { colWidth = colMaxLenList.get(i) + 3; for (int j = 0; j < colWidth ; j ++) { if (j==0) { rowBuilder.append("+"); } else if ((i+1 == colCount && j+1 == colWidth)) {//for last column close the border rowBuilder.append("-+"); } else { rowBuilder.append("-"); } } } return rowBuilder.append("\n").toString(); }
java
private String getRowLineBuf(int colCount, List<Integer> colMaxLenList, String[][] data) { S.Buffer rowBuilder = S.buffer(); int colWidth; for (int i = 0 ; i < colCount ; i ++) { colWidth = colMaxLenList.get(i) + 3; for (int j = 0; j < colWidth ; j ++) { if (j==0) { rowBuilder.append("+"); } else if ((i+1 == colCount && j+1 == colWidth)) {//for last column close the border rowBuilder.append("-+"); } else { rowBuilder.append("-"); } } } return rowBuilder.append("\n").toString(); }
[ "private", "String", "getRowLineBuf", "(", "int", "colCount", ",", "List", "<", "Integer", ">", "colMaxLenList", ",", "String", "[", "]", "[", "]", "data", ")", "{", "S", ".", "Buffer", "rowBuilder", "=", "S", ".", "buffer", "(", ")", ";", "int", "co...
Each string item rendering requires the border and a space on both sides. 12 3 12 3 12 34 +----- +-------- +------+ abc venkat last @param colCount @param colMaxLenList @param data @return
[ "Each", "string", "item", "rendering", "requires", "the", "border", "and", "a", "space", "on", "both", "sides", "." ]
train
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/cli/ascii_table/impl/SimpleASCIITableImpl.java#L338-L359
buschmais/jqa-maven3-plugin
src/main/java/com/buschmais/jqassistant/plugin/maven3/impl/scanner/MavenModelScannerPlugin.java
MavenModelScannerPlugin.addPlugins
private void addPlugins(BaseProfileDescriptor pomDescriptor, BuildBase build, ScannerContext scannerContext) { if (null == build) { return; } List<Plugin> plugins = build.getPlugins(); List<MavenPluginDescriptor> pluginDescriptors = createMavenPluginDescriptors(plugins, scannerContext); pomDescriptor.getPlugins().addAll(pluginDescriptors); }
java
private void addPlugins(BaseProfileDescriptor pomDescriptor, BuildBase build, ScannerContext scannerContext) { if (null == build) { return; } List<Plugin> plugins = build.getPlugins(); List<MavenPluginDescriptor> pluginDescriptors = createMavenPluginDescriptors(plugins, scannerContext); pomDescriptor.getPlugins().addAll(pluginDescriptors); }
[ "private", "void", "addPlugins", "(", "BaseProfileDescriptor", "pomDescriptor", ",", "BuildBase", "build", ",", "ScannerContext", "scannerContext", ")", "{", "if", "(", "null", "==", "build", ")", "{", "return", ";", "}", "List", "<", "Plugin", ">", "plugins",...
Adds information about plugins. @param pomDescriptor The descriptor for the current POM. @param build Information required to build the project. @param scannerContext The scanner context.
[ "Adds", "information", "about", "plugins", "." ]
train
https://github.com/buschmais/jqa-maven3-plugin/blob/6c6e2dca56de6d5b8ceeb2f28982fb6d7c98778f/src/main/java/com/buschmais/jqassistant/plugin/maven3/impl/scanner/MavenModelScannerPlugin.java#L524-L531
mojohaus/mrm
mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/digest/MD5DigestFileEntry.java
MD5DigestFileEntry.getContent
private byte[] getContent() throws IOException { InputStream is = null; try { MessageDigest digest = MessageDigest.getInstance( "MD5" ); digest.reset(); byte[] buffer = new byte[8192]; int read; try { is = entry.getInputStream(); while ( ( read = is.read( buffer ) ) > 0 ) { digest.update( buffer, 0, read ); } } catch ( IOException e ) { if ( is != null ) { throw e; } } final String md5 = StringUtils.leftPad( new BigInteger( 1, digest.digest() ).toString( 16 ), 32, "0" ); return md5.getBytes(); } catch ( NoSuchAlgorithmException e ) { IOException ioe = new IOException( "Unable to calculate hash" ); ioe.initCause( e ); throw ioe; } finally { IOUtils.closeQuietly( is ); } }
java
private byte[] getContent() throws IOException { InputStream is = null; try { MessageDigest digest = MessageDigest.getInstance( "MD5" ); digest.reset(); byte[] buffer = new byte[8192]; int read; try { is = entry.getInputStream(); while ( ( read = is.read( buffer ) ) > 0 ) { digest.update( buffer, 0, read ); } } catch ( IOException e ) { if ( is != null ) { throw e; } } final String md5 = StringUtils.leftPad( new BigInteger( 1, digest.digest() ).toString( 16 ), 32, "0" ); return md5.getBytes(); } catch ( NoSuchAlgorithmException e ) { IOException ioe = new IOException( "Unable to calculate hash" ); ioe.initCause( e ); throw ioe; } finally { IOUtils.closeQuietly( is ); } }
[ "private", "byte", "[", "]", "getContent", "(", ")", "throws", "IOException", "{", "InputStream", "is", "=", "null", ";", "try", "{", "MessageDigest", "digest", "=", "MessageDigest", ".", "getInstance", "(", "\"MD5\"", ")", ";", "digest", ".", "reset", "("...
Generates the digest. @return the digest. @throws IOException if the backing entry could not be read. @since 1.0
[ "Generates", "the", "digest", "." ]
train
https://github.com/mojohaus/mrm/blob/ecbe54a1866f210c10bf2e9274b63d4804d6a151/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/digest/MD5DigestFileEntry.java#L103-L141
nakamura5akihito/six-util
src/main/java/jp/go/aist/six/util/search/RelationalBinding.java
RelationalBinding.lessThanBinding
public static RelationalBinding lessThanBinding( final String property, final Object value ) { return (new RelationalBinding( property, Relation.LESS_THAN, value )); }
java
public static RelationalBinding lessThanBinding( final String property, final Object value ) { return (new RelationalBinding( property, Relation.LESS_THAN, value )); }
[ "public", "static", "RelationalBinding", "lessThanBinding", "(", "final", "String", "property", ",", "final", "Object", "value", ")", "{", "return", "(", "new", "RelationalBinding", "(", "property", ",", "Relation", ".", "LESS_THAN", ",", "value", ")", ")", ";...
Creates a 'LESS_THAN' binding. @param property the property. @param value the value to which the property should be related. @return a 'LESS_THAN' binding.
[ "Creates", "a", "LESS_THAN", "binding", "." ]
train
https://github.com/nakamura5akihito/six-util/blob/a6db388a345e220cea2b1fa6324d15c80c6278b6/src/main/java/jp/go/aist/six/util/search/RelationalBinding.java#L90-L96
pagehelper/Mybatis-PageHelper
src/main/java/com/github/pagehelper/parser/SqlServerParser.java
SqlServerParser.cloneOrderByElement
protected OrderByElement cloneOrderByElement(OrderByElement orig, String alias) { return cloneOrderByElement(orig, new Column(alias)); }
java
protected OrderByElement cloneOrderByElement(OrderByElement orig, String alias) { return cloneOrderByElement(orig, new Column(alias)); }
[ "protected", "OrderByElement", "cloneOrderByElement", "(", "OrderByElement", "orig", ",", "String", "alias", ")", "{", "return", "cloneOrderByElement", "(", "orig", ",", "new", "Column", "(", "alias", ")", ")", ";", "}" ]
复制 OrderByElement @param orig 原 OrderByElement @param alias 新 OrderByElement 的排序要素 @return 复制的新 OrderByElement
[ "复制", "OrderByElement" ]
train
https://github.com/pagehelper/Mybatis-PageHelper/blob/319750fd47cf75328ff321f38125fa15e954e60f/src/main/java/com/github/pagehelper/parser/SqlServerParser.java#L403-L405
radkovo/CSSBox
src/main/java/org/fit/cssbox/layout/FloatList.java
FloatList.getMaxYForOwner
public int getMaxYForOwner(BlockBox owner, boolean requireVisible) { int maxy = 0; for (int i = 0; i < size(); i++) { Box box = getBox(i); if ((!requireVisible || box.isDeclaredVisible()) && box.getContainingBlockBox() == owner) { int ny = box.bounds.y + box.bounds.height; //TODO: -1 here? if (ny > maxy) maxy = ny; } } return maxy; }
java
public int getMaxYForOwner(BlockBox owner, boolean requireVisible) { int maxy = 0; for (int i = 0; i < size(); i++) { Box box = getBox(i); if ((!requireVisible || box.isDeclaredVisible()) && box.getContainingBlockBox() == owner) { int ny = box.bounds.y + box.bounds.height; //TODO: -1 here? if (ny > maxy) maxy = ny; } } return maxy; }
[ "public", "int", "getMaxYForOwner", "(", "BlockBox", "owner", ",", "boolean", "requireVisible", ")", "{", "int", "maxy", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "size", "(", ")", ";", "i", "++", ")", "{", "Box", "box", "="...
Goes through all the boxes and computes the Y coordinate of the bottom edge of the lowest box. Only the boxes with the 'owner' containing block are taken into account. @param owner the owning block @return the maximal Y coordinate
[ "Goes", "through", "all", "the", "boxes", "and", "computes", "the", "Y", "coordinate", "of", "the", "bottom", "edge", "of", "the", "lowest", "box", ".", "Only", "the", "boxes", "with", "the", "owner", "containing", "block", "are", "taken", "into", "account...
train
https://github.com/radkovo/CSSBox/blob/38aaf8f22d233d7b4dbc12a56cdbc72b447bc559/src/main/java/org/fit/cssbox/layout/FloatList.java#L170-L183
lecho/hellocharts-android
hellocharts-library/src/lecho/lib/hellocharts/model/PointValue.java
PointValue.setTarget
public PointValue setTarget(float targetX, float targetY) { set(x, y); this.diffX = targetX - originX; this.diffY = targetY - originY; return this; }
java
public PointValue setTarget(float targetX, float targetY) { set(x, y); this.diffX = targetX - originX; this.diffY = targetY - originY; return this; }
[ "public", "PointValue", "setTarget", "(", "float", "targetX", ",", "float", "targetY", ")", "{", "set", "(", "x", ",", "y", ")", ";", "this", ".", "diffX", "=", "targetX", "-", "originX", ";", "this", ".", "diffY", "=", "targetY", "-", "originY", ";"...
Set target values that should be reached when data animation finish then call {@link Chart#startDataAnimation()}
[ "Set", "target", "values", "that", "should", "be", "reached", "when", "data", "animation", "finish", "then", "call", "{" ]
train
https://github.com/lecho/hellocharts-android/blob/c41419c9afa097452dee823c7eba0e5136aa96bd/hellocharts-library/src/lecho/lib/hellocharts/model/PointValue.java#L55-L60
jmxtrans/embedded-jmxtrans
src/main/java/org/jmxtrans/embedded/util/jmx/JmxUtils2.java
JmxUtils2.unregisterObject
public static void unregisterObject(ObjectName objectName, MBeanServer mbeanServer) { if (objectName == null) { return; } try { mbeanServer.unregisterMBean(objectName); } catch (Exception e) { logger.warn("Failure to unregister {}", objectName, e); } }
java
public static void unregisterObject(ObjectName objectName, MBeanServer mbeanServer) { if (objectName == null) { return; } try { mbeanServer.unregisterMBean(objectName); } catch (Exception e) { logger.warn("Failure to unregister {}", objectName, e); } }
[ "public", "static", "void", "unregisterObject", "(", "ObjectName", "objectName", ",", "MBeanServer", "mbeanServer", ")", "{", "if", "(", "objectName", "==", "null", ")", "{", "return", ";", "}", "try", "{", "mbeanServer", ".", "unregisterMBean", "(", "objectNa...
Try to unregister given <code>objectName</code>. If given <code>objectName</code> is <code>null</code>, nothing is done. If registration fails, a {@link Logger#warn(String)} message is emitted and <code>null</code> is returned. @param objectName objectName to unregister @param mbeanServer MBeanServer to which the objectName is unregistered
[ "Try", "to", "unregister", "given", "<code", ">", "objectName<", "/", "code", ">", "." ]
train
https://github.com/jmxtrans/embedded-jmxtrans/blob/17224389e7d8323284cabc2a5167fc03bed6d223/src/main/java/org/jmxtrans/embedded/util/jmx/JmxUtils2.java#L74-L83
alkacon/opencms-core
src/org/opencms/jsp/util/CmsJspContentAccessBean.java
CmsJspContentAccessBean.createImageDndAttr
protected static String createImageDndAttr(CmsUUID structureId, String imagePath, String locale) { String attrValue = structureId + "|" + imagePath + "|" + locale; String escapedAttrValue = CmsEncoder.escapeXml(attrValue); return ("data-imagednd=\"" + escapedAttrValue + "\""); }
java
protected static String createImageDndAttr(CmsUUID structureId, String imagePath, String locale) { String attrValue = structureId + "|" + imagePath + "|" + locale; String escapedAttrValue = CmsEncoder.escapeXml(attrValue); return ("data-imagednd=\"" + escapedAttrValue + "\""); }
[ "protected", "static", "String", "createImageDndAttr", "(", "CmsUUID", "structureId", ",", "String", "imagePath", ",", "String", "locale", ")", "{", "String", "attrValue", "=", "structureId", "+", "\"|\"", "+", "imagePath", "+", "\"|\"", "+", "locale", ";", "S...
Generates the HTML attribute "data-imagednd" that enables the ADE image drag and drop feature.<p> @param structureId the structure ID of the XML document to insert the image @param locale the locale to generate the image in @param imagePath the XML path to the image source node. @return the HTML attribute "data-imagednd" that enables the ADE image drag and drop feature
[ "Generates", "the", "HTML", "attribute", "data", "-", "imagednd", "that", "enables", "the", "ADE", "image", "drag", "and", "drop", "feature", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jsp/util/CmsJspContentAccessBean.java#L523-L528
alexvasilkov/GestureViews
library/src/main/java/com/alexvasilkov/gestures/animation/ViewPositionAnimator.java
ViewPositionAnimator.setState
public void setState(@FloatRange(from = 0f, to = 1f) float pos, boolean leaving, boolean animate) { if (!isActivated) { throw new IllegalStateException( "You should call enter(...) before calling setState(...)"); } stopAnimation(); position = pos < 0f ? 0f : (pos > 1f ? 1f : pos); isLeaving = leaving; if (animate) { startAnimationInternal(); } applyCurrentPosition(); }
java
public void setState(@FloatRange(from = 0f, to = 1f) float pos, boolean leaving, boolean animate) { if (!isActivated) { throw new IllegalStateException( "You should call enter(...) before calling setState(...)"); } stopAnimation(); position = pos < 0f ? 0f : (pos > 1f ? 1f : pos); isLeaving = leaving; if (animate) { startAnimationInternal(); } applyCurrentPosition(); }
[ "public", "void", "setState", "(", "@", "FloatRange", "(", "from", "=", "0f", ",", "to", "=", "1f", ")", "float", "pos", ",", "boolean", "leaving", ",", "boolean", "animate", ")", "{", "if", "(", "!", "isActivated", ")", "{", "throw", "new", "Illegal...
Stops current animation and sets position state to particular values. <p> Note, that once animator reaches {@code state = 0f} and {@code isLeaving = true} it will cleanup all internal stuff. So you will need to call {@link #enter(View, boolean)} or {@link #enter(ViewPosition, boolean)} again in order to continue using animator. @param pos Current position @param leaving Whether we we are in exiting direction ({@code true}) or in entering ({@code false}) @param animate Whether we should start animating from given position and in given direction
[ "Stops", "current", "animation", "and", "sets", "position", "state", "to", "particular", "values", ".", "<p", ">", "Note", "that", "once", "animator", "reaches", "{", "@code", "state", "=", "0f", "}", "and", "{", "@code", "isLeaving", "=", "true", "}", "...
train
https://github.com/alexvasilkov/GestureViews/blob/f0a4c266e31dcad23bd0d9013531bc1c501b9c9f/library/src/main/java/com/alexvasilkov/gestures/animation/ViewPositionAnimator.java#L484-L498
app55/app55-java
src/support/java/com/googlecode/openbeans/beancontext/BeanContextServicesSupport.java
BeanContextServicesSupport.releaseServiceWithoutCheck
private void releaseServiceWithoutCheck(BeanContextChild child, BCSSChild bcssChild, Object requestor, Object service, boolean callRevokedListener) { if (bcssChild.serviceRecords == null || bcssChild.serviceRecords.isEmpty()) { return; } synchronized (child) { // scan record for (Iterator iter = bcssChild.serviceRecords.iterator(); iter.hasNext();) { ServiceRecord rec = (ServiceRecord) iter.next(); if (rec.requestor == requestor && rec.service == service) { // release service rec.provider.releaseService(getBeanContextServicesPeer(), requestor, service); // call service revoked listener if (callRevokedListener && rec.revokedListener != null) { rec.revokedListener.serviceRevoked(new BeanContextServiceRevokedEvent(getBeanContextServicesPeer(), rec.serviceClass, true)); } // remove record iter.remove(); break; } } } }
java
private void releaseServiceWithoutCheck(BeanContextChild child, BCSSChild bcssChild, Object requestor, Object service, boolean callRevokedListener) { if (bcssChild.serviceRecords == null || bcssChild.serviceRecords.isEmpty()) { return; } synchronized (child) { // scan record for (Iterator iter = bcssChild.serviceRecords.iterator(); iter.hasNext();) { ServiceRecord rec = (ServiceRecord) iter.next(); if (rec.requestor == requestor && rec.service == service) { // release service rec.provider.releaseService(getBeanContextServicesPeer(), requestor, service); // call service revoked listener if (callRevokedListener && rec.revokedListener != null) { rec.revokedListener.serviceRevoked(new BeanContextServiceRevokedEvent(getBeanContextServicesPeer(), rec.serviceClass, true)); } // remove record iter.remove(); break; } } } }
[ "private", "void", "releaseServiceWithoutCheck", "(", "BeanContextChild", "child", ",", "BCSSChild", "bcssChild", ",", "Object", "requestor", ",", "Object", "service", ",", "boolean", "callRevokedListener", ")", "{", "if", "(", "bcssChild", ".", "serviceRecords", "=...
Releases a service without checking the membership of the child.
[ "Releases", "a", "service", "without", "checking", "the", "membership", "of", "the", "child", "." ]
train
https://github.com/app55/app55-java/blob/73e51d0f3141a859dfbd37ca9becef98477e553e/src/support/java/com/googlecode/openbeans/beancontext/BeanContextServicesSupport.java#L850-L879
jmapper-framework/jmapper-core
JMapper Framework/src/main/java/com/googlecode/jmapper/config/Error.java
Error.xmlAttributeExistent
public static void xmlAttributeExistent(String path, Attribute attribute, Class<?> aClass){ throw new XmlMappingAttributeExistException (MSG.INSTANCE.message(xmlMappingAttributeExistException2,attribute.getName(),aClass.getSimpleName(),path)); }
java
public static void xmlAttributeExistent(String path, Attribute attribute, Class<?> aClass){ throw new XmlMappingAttributeExistException (MSG.INSTANCE.message(xmlMappingAttributeExistException2,attribute.getName(),aClass.getSimpleName(),path)); }
[ "public", "static", "void", "xmlAttributeExistent", "(", "String", "path", ",", "Attribute", "attribute", ",", "Class", "<", "?", ">", "aClass", ")", "{", "throw", "new", "XmlMappingAttributeExistException", "(", "MSG", ".", "INSTANCE", ".", "message", "(", "x...
Thrown if attribute is present in the xml file. @param path xml path @param attribute attribute present @param aClass attribute's class
[ "Thrown", "if", "attribute", "is", "present", "in", "the", "xml", "file", "." ]
train
https://github.com/jmapper-framework/jmapper-core/blob/b48fd3527f35055b8b4a30f53a51136f183acc90/JMapper Framework/src/main/java/com/googlecode/jmapper/config/Error.java#L303-L305
artikcloud/artikcloud-java
src/main/java/cloud/artik/api/ExportApi.java
ExportApi.getExportHistory
public ExportHistoryResponse getExportHistory(String trialId, Integer count, Integer offset) throws ApiException { ApiResponse<ExportHistoryResponse> resp = getExportHistoryWithHttpInfo(trialId, count, offset); return resp.getData(); }
java
public ExportHistoryResponse getExportHistory(String trialId, Integer count, Integer offset) throws ApiException { ApiResponse<ExportHistoryResponse> resp = getExportHistoryWithHttpInfo(trialId, count, offset); return resp.getData(); }
[ "public", "ExportHistoryResponse", "getExportHistory", "(", "String", "trialId", ",", "Integer", "count", ",", "Integer", "offset", ")", "throws", "ApiException", "{", "ApiResponse", "<", "ExportHistoryResponse", ">", "resp", "=", "getExportHistoryWithHttpInfo", "(", ...
Get Export History Get the history of export requests. @param trialId Filter by trialId. (optional) @param count Pagination count. (optional) @param offset Pagination offset. (optional) @return ExportHistoryResponse @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
[ "Get", "Export", "History", "Get", "the", "history", "of", "export", "requests", "." ]
train
https://github.com/artikcloud/artikcloud-java/blob/412f447573e7796ab4f685c0bdd5eb76185a365c/src/main/java/cloud/artik/api/ExportApi.java#L247-L250
Nordstrom/JUnit-Foundation
src/main/java/com/nordstrom/automation/junit/RetryHandler.java
RetryHandler.isRetriable
static boolean isRetriable(final FrameworkMethod method, final Throwable thrown) { synchronized(retryAnalyzerLoader) { for (JUnitRetryAnalyzer analyzer : retryAnalyzerLoader) { if (analyzer.retry(method, thrown)) { return true; } } } return false; }
java
static boolean isRetriable(final FrameworkMethod method, final Throwable thrown) { synchronized(retryAnalyzerLoader) { for (JUnitRetryAnalyzer analyzer : retryAnalyzerLoader) { if (analyzer.retry(method, thrown)) { return true; } } } return false; }
[ "static", "boolean", "isRetriable", "(", "final", "FrameworkMethod", "method", ",", "final", "Throwable", "thrown", ")", "{", "synchronized", "(", "retryAnalyzerLoader", ")", "{", "for", "(", "JUnitRetryAnalyzer", "analyzer", ":", "retryAnalyzerLoader", ")", "{", ...
Determine if the specified failed test should be retried. @param method failed test method @param thrown exception for this failed test @return {@code true} if test should be retried; otherwise {@code false}
[ "Determine", "if", "the", "specified", "failed", "test", "should", "be", "retried", "." ]
train
https://github.com/Nordstrom/JUnit-Foundation/blob/f24d91f8677d262c27d18ef29ed633eaac717be5/src/main/java/com/nordstrom/automation/junit/RetryHandler.java#L129-L138
pietermartin/sqlg
sqlg-core/src/main/java/org/umlg/sqlg/sql/parse/GremlinParser.java
GremlinParser.parse
public SchemaTableTree parse(SchemaTable schemaTable, ReplacedStepTree replacedStepTree) { ReplacedStep<?, ?> rootReplacedStep = replacedStepTree.root().getReplacedStep(); Preconditions.checkArgument(!rootReplacedStep.isGraphStep(), "Expected VertexStep, found GraphStep"); Set<SchemaTableTree> schemaTableTrees = new HashSet<>(); //replacedSteps contains a fake label representing the incoming vertex for the SqlgVertexStepStrategy. SchemaTableTree rootSchemaTableTree = new SchemaTableTree(this.sqlgGraph, schemaTable, 0, replacedStepTree.getDepth()); rootSchemaTableTree.setOptionalLeftJoin(rootReplacedStep.isLeftJoin()); rootSchemaTableTree.setEmit(rootReplacedStep.isEmit()); rootSchemaTableTree.setUntilFirst(rootReplacedStep.isUntilFirst()); rootSchemaTableTree.initializeAliasColumnNameMaps(); rootSchemaTableTree.setStepType(schemaTable.isVertexTable() ? SchemaTableTree.STEP_TYPE.VERTEX_STEP : SchemaTableTree.STEP_TYPE.EDGE_VERTEX_STEP); schemaTableTrees.add(rootSchemaTableTree); replacedStepTree.walkReplacedSteps(schemaTableTrees); rootSchemaTableTree.removeNodesInvalidatedByHas(); rootSchemaTableTree.removeAllButDeepestAndAddCacheLeafNodes(replacedStepTree.getDepth()); rootSchemaTableTree.setLocalStep(true); return rootSchemaTableTree; }
java
public SchemaTableTree parse(SchemaTable schemaTable, ReplacedStepTree replacedStepTree) { ReplacedStep<?, ?> rootReplacedStep = replacedStepTree.root().getReplacedStep(); Preconditions.checkArgument(!rootReplacedStep.isGraphStep(), "Expected VertexStep, found GraphStep"); Set<SchemaTableTree> schemaTableTrees = new HashSet<>(); //replacedSteps contains a fake label representing the incoming vertex for the SqlgVertexStepStrategy. SchemaTableTree rootSchemaTableTree = new SchemaTableTree(this.sqlgGraph, schemaTable, 0, replacedStepTree.getDepth()); rootSchemaTableTree.setOptionalLeftJoin(rootReplacedStep.isLeftJoin()); rootSchemaTableTree.setEmit(rootReplacedStep.isEmit()); rootSchemaTableTree.setUntilFirst(rootReplacedStep.isUntilFirst()); rootSchemaTableTree.initializeAliasColumnNameMaps(); rootSchemaTableTree.setStepType(schemaTable.isVertexTable() ? SchemaTableTree.STEP_TYPE.VERTEX_STEP : SchemaTableTree.STEP_TYPE.EDGE_VERTEX_STEP); schemaTableTrees.add(rootSchemaTableTree); replacedStepTree.walkReplacedSteps(schemaTableTrees); rootSchemaTableTree.removeNodesInvalidatedByHas(); rootSchemaTableTree.removeAllButDeepestAndAddCacheLeafNodes(replacedStepTree.getDepth()); rootSchemaTableTree.setLocalStep(true); return rootSchemaTableTree; }
[ "public", "SchemaTableTree", "parse", "(", "SchemaTable", "schemaTable", ",", "ReplacedStepTree", "replacedStepTree", ")", "{", "ReplacedStep", "<", "?", ",", "?", ">", "rootReplacedStep", "=", "replacedStepTree", ".", "root", "(", ")", ".", "getReplacedStep", "("...
This is only called for vertex steps. Constructs the label paths from the given schemaTable to the leaf vertex labels for the gremlin query. For each path Sqlg will executeRegularQuery a sql query. The union of the queries is the result the gremlin query. The vertex labels can be calculated from the steps. @param schemaTable The schema and table @param replacedStepTree The original VertexSteps and HasSteps that were replaced @return a List of paths. Each path is itself a list of SchemaTables.
[ "This", "is", "only", "called", "for", "vertex", "steps", ".", "Constructs", "the", "label", "paths", "from", "the", "given", "schemaTable", "to", "the", "leaf", "vertex", "labels", "for", "the", "gremlin", "query", ".", "For", "each", "path", "Sqlg", "wil...
train
https://github.com/pietermartin/sqlg/blob/c1845a1b31328a5ffda646873b0369ee72af56a7/sqlg-core/src/main/java/org/umlg/sqlg/sql/parse/GremlinParser.java#L53-L71
matthewhorridge/owlapi-gwt
owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLDataIntersectionOfImpl_CustomFieldSerializer.java
OWLDataIntersectionOfImpl_CustomFieldSerializer.deserializeInstance
@Override public void deserializeInstance(SerializationStreamReader streamReader, OWLDataIntersectionOfImpl instance) throws SerializationException { deserialize(streamReader, instance); }
java
@Override public void deserializeInstance(SerializationStreamReader streamReader, OWLDataIntersectionOfImpl instance) throws SerializationException { deserialize(streamReader, instance); }
[ "@", "Override", "public", "void", "deserializeInstance", "(", "SerializationStreamReader", "streamReader", ",", "OWLDataIntersectionOfImpl", "instance", ")", "throws", "SerializationException", "{", "deserialize", "(", "streamReader", ",", "instance", ")", ";", "}" ]
Deserializes the content of the object from the {@link com.google.gwt.user.client.rpc.SerializationStreamReader}. @param streamReader the {@link com.google.gwt.user.client.rpc.SerializationStreamReader} to read the object's content from @param instance the object instance to deserialize @throws com.google.gwt.user.client.rpc.SerializationException if the deserialization operation is not successful
[ "Deserializes", "the", "content", "of", "the", "object", "from", "the", "{", "@link", "com", ".", "google", ".", "gwt", ".", "user", ".", "client", ".", "rpc", ".", "SerializationStreamReader", "}", "." ]
train
https://github.com/matthewhorridge/owlapi-gwt/blob/7ab975fb6cef3c8947099983551672a3b5d4e2fd/owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLDataIntersectionOfImpl_CustomFieldSerializer.java#L89-L92
Red5/red5-server-common
src/main/java/org/red5/server/util/HttpConnectionUtil.java
HttpConnectionUtil.getClient
public static final HttpClient getClient(int timeout) { HttpClientBuilder client = HttpClientBuilder.create(); // set the connection manager client.setConnectionManager(connectionManager); // dont retry client.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false)); // establish a connection within x seconds RequestConfig config = RequestConfig.custom().setSocketTimeout(timeout).build(); client.setDefaultRequestConfig(config); // no redirects client.disableRedirectHandling(); // set custom ua client.setUserAgent(userAgent); // set the proxy if the user has one set if ((System.getProperty("http.proxyHost") != null) && (System.getProperty("http.proxyPort") != null)) { HttpHost proxy = new HttpHost(System.getProperty("http.proxyHost").toString(), Integer.valueOf(System.getProperty("http.proxyPort"))); client.setProxy(proxy); } return client.build(); }
java
public static final HttpClient getClient(int timeout) { HttpClientBuilder client = HttpClientBuilder.create(); // set the connection manager client.setConnectionManager(connectionManager); // dont retry client.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false)); // establish a connection within x seconds RequestConfig config = RequestConfig.custom().setSocketTimeout(timeout).build(); client.setDefaultRequestConfig(config); // no redirects client.disableRedirectHandling(); // set custom ua client.setUserAgent(userAgent); // set the proxy if the user has one set if ((System.getProperty("http.proxyHost") != null) && (System.getProperty("http.proxyPort") != null)) { HttpHost proxy = new HttpHost(System.getProperty("http.proxyHost").toString(), Integer.valueOf(System.getProperty("http.proxyPort"))); client.setProxy(proxy); } return client.build(); }
[ "public", "static", "final", "HttpClient", "getClient", "(", "int", "timeout", ")", "{", "HttpClientBuilder", "client", "=", "HttpClientBuilder", ".", "create", "(", ")", ";", "// set the connection manager\r", "client", ".", "setConnectionManager", "(", "connectionMa...
Returns a client with all our selected properties / params. @param timeout - socket timeout to set @return client
[ "Returns", "a", "client", "with", "all", "our", "selected", "properties", "/", "params", "." ]
train
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/util/HttpConnectionUtil.java#L77-L96
apache/incubator-druid
server/src/main/java/org/apache/druid/curator/discovery/DiscoveryModule.java
DiscoveryModule.registerKey
public static void registerKey(Binder binder, Key<DruidNode> key) { DruidBinders.discoveryAnnouncementBinder(binder).addBinding().toInstance(new KeyHolder<>(key)); LifecycleModule.register(binder, ServiceAnnouncer.class); }
java
public static void registerKey(Binder binder, Key<DruidNode> key) { DruidBinders.discoveryAnnouncementBinder(binder).addBinding().toInstance(new KeyHolder<>(key)); LifecycleModule.register(binder, ServiceAnnouncer.class); }
[ "public", "static", "void", "registerKey", "(", "Binder", "binder", ",", "Key", "<", "DruidNode", ">", "key", ")", "{", "DruidBinders", ".", "discoveryAnnouncementBinder", "(", "binder", ")", ".", "addBinding", "(", ")", ".", "toInstance", "(", "new", "KeyHo...
Requests that the keyed DruidNode instance be injected and published as part of the lifecycle. That is, this module will announce the DruidNode instance returned by injector.getInstance(Key.get(DruidNode.class, annotation)) automatically. Announcement will happen in the ANNOUNCEMENTS stage of the Lifecycle @param binder the Binder to register with @param key The key to use in finding the DruidNode instance
[ "Requests", "that", "the", "keyed", "DruidNode", "instance", "be", "injected", "and", "published", "as", "part", "of", "the", "lifecycle", "." ]
train
https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/server/src/main/java/org/apache/druid/curator/discovery/DiscoveryModule.java#L142-L146
orbisgis/h2gis
h2gis-functions/src/main/java/org/h2gis/functions/io/shp/internal/SHPDriver.java
SHPDriver.initDriver
public void initDriver(File shpFile, ShapeType shapeType, DbaseFileHeader dbaseHeader) throws IOException { String path = shpFile.getAbsolutePath(); String nameWithoutExt = path.substring(0,path.lastIndexOf('.')); this.shpFile = new File(nameWithoutExt+".shp"); this.shxFile = new File(nameWithoutExt+".shx"); this.dbfFile = new File(nameWithoutExt+".dbf"); FileOutputStream shpFos = new FileOutputStream(shpFile); FileOutputStream shxFos = new FileOutputStream(shxFile); shapefileWriter = new ShapefileWriter(shpFos.getChannel(), shxFos.getChannel()); this.shapeType = shapeType; shapefileWriter.writeHeaders(shapeType); dbfDriver.initDriver(dbfFile, dbaseHeader); }
java
public void initDriver(File shpFile, ShapeType shapeType, DbaseFileHeader dbaseHeader) throws IOException { String path = shpFile.getAbsolutePath(); String nameWithoutExt = path.substring(0,path.lastIndexOf('.')); this.shpFile = new File(nameWithoutExt+".shp"); this.shxFile = new File(nameWithoutExt+".shx"); this.dbfFile = new File(nameWithoutExt+".dbf"); FileOutputStream shpFos = new FileOutputStream(shpFile); FileOutputStream shxFos = new FileOutputStream(shxFile); shapefileWriter = new ShapefileWriter(shpFos.getChannel(), shxFos.getChannel()); this.shapeType = shapeType; shapefileWriter.writeHeaders(shapeType); dbfDriver.initDriver(dbfFile, dbaseHeader); }
[ "public", "void", "initDriver", "(", "File", "shpFile", ",", "ShapeType", "shapeType", ",", "DbaseFileHeader", "dbaseHeader", ")", "throws", "IOException", "{", "String", "path", "=", "shpFile", ".", "getAbsolutePath", "(", ")", ";", "String", "nameWithoutExt", ...
Init Driver for Write mode @param shpFile @param shapeType @param dbaseHeader @throws IOException
[ "Init", "Driver", "for", "Write", "mode" ]
train
https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/io/shp/internal/SHPDriver.java#L109-L121
apache/incubator-atlas
repository/src/main/java/org/apache/atlas/repository/store/graph/v1/AtlasTypeDefGraphStoreV1.java
AtlasTypeDefGraphStoreV1.hasIncomingEdgesWithLabel
boolean hasIncomingEdgesWithLabel(AtlasVertex vertex, String label) throws AtlasBaseException { boolean foundEdges = false; Iterator<AtlasEdge> inEdges = vertex.getEdges(AtlasEdgeDirection.IN).iterator(); while (inEdges.hasNext()) { AtlasEdge edge = inEdges.next(); if (label.equals(edge.getLabel())) { foundEdges = true; break; } } return foundEdges; }
java
boolean hasIncomingEdgesWithLabel(AtlasVertex vertex, String label) throws AtlasBaseException { boolean foundEdges = false; Iterator<AtlasEdge> inEdges = vertex.getEdges(AtlasEdgeDirection.IN).iterator(); while (inEdges.hasNext()) { AtlasEdge edge = inEdges.next(); if (label.equals(edge.getLabel())) { foundEdges = true; break; } } return foundEdges; }
[ "boolean", "hasIncomingEdgesWithLabel", "(", "AtlasVertex", "vertex", ",", "String", "label", ")", "throws", "AtlasBaseException", "{", "boolean", "foundEdges", "=", "false", ";", "Iterator", "<", "AtlasEdge", ">", "inEdges", "=", "vertex", ".", "getEdges", "(", ...
Look to see if there are any IN edges with the supplied label @param vertex @param label @return @throws AtlasBaseException
[ "Look", "to", "see", "if", "there", "are", "any", "IN", "edges", "with", "the", "supplied", "label" ]
train
https://github.com/apache/incubator-atlas/blob/e0d2cdc27c32742ebecd24db4cca62dc04dcdf4b/repository/src/main/java/org/apache/atlas/repository/store/graph/v1/AtlasTypeDefGraphStoreV1.java#L252-L265
jenkinsci/jenkins
core/src/main/java/hudson/model/View.java
View.createViewFromXML
public static View createViewFromXML(String name, InputStream xml) throws IOException { try (InputStream in = new BufferedInputStream(xml)) { View v = (View) Jenkins.XSTREAM.fromXML(in); if (name != null) v.name = name; Jenkins.checkGoodName(v.name); return v; } catch(StreamException|ConversionException|Error e) {// mostly reflection errors throw new IOException("Unable to read",e); } }
java
public static View createViewFromXML(String name, InputStream xml) throws IOException { try (InputStream in = new BufferedInputStream(xml)) { View v = (View) Jenkins.XSTREAM.fromXML(in); if (name != null) v.name = name; Jenkins.checkGoodName(v.name); return v; } catch(StreamException|ConversionException|Error e) {// mostly reflection errors throw new IOException("Unable to read",e); } }
[ "public", "static", "View", "createViewFromXML", "(", "String", "name", ",", "InputStream", "xml", ")", "throws", "IOException", "{", "try", "(", "InputStream", "in", "=", "new", "BufferedInputStream", "(", "xml", ")", ")", "{", "View", "v", "=", "(", "Vie...
Instantiate View subtype from XML stream. @param name Alternative name to use or {@code null} to keep the one in xml.
[ "Instantiate", "View", "subtype", "from", "XML", "stream", "." ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/model/View.java#L1371-L1381
betfair/cougar
cougar-codegen-plugin/src/main/java/com/betfair/cougar/codegen/FileUtil.java
FileUtil.resourceToFile
public static void resourceToFile(String resourceName, File dest, Class src) { InputStream is = null; OutputStream os = null; try { is = src.getClassLoader().getResourceAsStream(resourceName); if (is == null) { throw new RuntimeException("Could not load resource: " + resourceName); } dest.getParentFile().mkdirs(); os = new FileOutputStream(dest); IOUtils.copy(is, os); } catch (Exception e) { throw new RuntimeException("Error copying resource '" + resourceName + "' to file '" + dest.getPath() + "': "+ e, e); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } }
java
public static void resourceToFile(String resourceName, File dest, Class src) { InputStream is = null; OutputStream os = null; try { is = src.getClassLoader().getResourceAsStream(resourceName); if (is == null) { throw new RuntimeException("Could not load resource: " + resourceName); } dest.getParentFile().mkdirs(); os = new FileOutputStream(dest); IOUtils.copy(is, os); } catch (Exception e) { throw new RuntimeException("Error copying resource '" + resourceName + "' to file '" + dest.getPath() + "': "+ e, e); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } }
[ "public", "static", "void", "resourceToFile", "(", "String", "resourceName", ",", "File", "dest", ",", "Class", "src", ")", "{", "InputStream", "is", "=", "null", ";", "OutputStream", "os", "=", "null", ";", "try", "{", "is", "=", "src", ".", "getClassLo...
Copy the given resource to the given file. @param resourceName name of resource to copy @param destination file
[ "Copy", "the", "given", "resource", "to", "the", "given", "file", "." ]
train
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-codegen-plugin/src/main/java/com/betfair/cougar/codegen/FileUtil.java#L34-L56
wanglinsong/testharness
src/main/java/com/tascape/qa/th/comm/MySqlCommunication.java
MySqlCommunication.restoreTable
public void restoreTable(String tableName, String tempTableName) throws SQLException { LOG.debug("Restore table {} from {}", tableName, tempTableName); try { this.setForeignKeyCheckEnabled(false); this.truncateTable(tableName); final String sql = "INSERT INTO " + tableName + " SELECT * FROM " + tempTableName + ";"; this.executeUpdate(sql); } finally { this.setForeignKeyCheckEnabled(true); } }
java
public void restoreTable(String tableName, String tempTableName) throws SQLException { LOG.debug("Restore table {} from {}", tableName, tempTableName); try { this.setForeignKeyCheckEnabled(false); this.truncateTable(tableName); final String sql = "INSERT INTO " + tableName + " SELECT * FROM " + tempTableName + ";"; this.executeUpdate(sql); } finally { this.setForeignKeyCheckEnabled(true); } }
[ "public", "void", "restoreTable", "(", "String", "tableName", ",", "String", "tempTableName", ")", "throws", "SQLException", "{", "LOG", ".", "debug", "(", "\"Restore table {} from {}\"", ",", "tableName", ",", "tempTableName", ")", ";", "try", "{", "this", ".",...
Restores table content. @param tableName table to be restored @param tempTableName temporary table name @throws SQLException for any issue
[ "Restores", "table", "content", "." ]
train
https://github.com/wanglinsong/testharness/blob/76f3e4546648e0720f6f87a58cb91a09cd36dfca/src/main/java/com/tascape/qa/th/comm/MySqlCommunication.java#L141-L151
codelibs/fess
src/main/java/org/codelibs/fess/mylasta/action/FessMessages.java
FessMessages.addErrorsInvalidHeaderForRequestFile
public FessMessages addErrorsInvalidHeaderForRequestFile(String property, String arg0) { assertPropertyNotNull(property); add(property, new UserMessage(ERRORS_invalid_header_for_request_file, arg0)); return this; }
java
public FessMessages addErrorsInvalidHeaderForRequestFile(String property, String arg0) { assertPropertyNotNull(property); add(property, new UserMessage(ERRORS_invalid_header_for_request_file, arg0)); return this; }
[ "public", "FessMessages", "addErrorsInvalidHeaderForRequestFile", "(", "String", "property", ",", "String", "arg0", ")", "{", "assertPropertyNotNull", "(", "property", ")", ";", "add", "(", "property", ",", "new", "UserMessage", "(", "ERRORS_invalid_header_for_request_f...
Add the created action message for the key 'errors.invalid_header_for_request_file' with parameters. <pre> message: Invalid header: {0} </pre> @param property The property name for the message. (NotNull) @param arg0 The parameter arg0 for message. (NotNull) @return this. (NotNull)
[ "Add", "the", "created", "action", "message", "for", "the", "key", "errors", ".", "invalid_header_for_request_file", "with", "parameters", ".", "<pre", ">", "message", ":", "Invalid", "header", ":", "{", "0", "}", "<", "/", "pre", ">" ]
train
https://github.com/codelibs/fess/blob/e5e4b722549d32a4958dfd94965b21937bfe64cf/src/main/java/org/codelibs/fess/mylasta/action/FessMessages.java#L1965-L1969
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/session/RaftSession.java
RaftSession.registerSequenceQuery
public void registerSequenceQuery(long sequence, Runnable query) { // Add a query to be run once the session's sequence number reaches the given sequence number. List<Runnable> queries = this.sequenceQueries.computeIfAbsent(sequence, v -> new LinkedList<Runnable>()); queries.add(query); }
java
public void registerSequenceQuery(long sequence, Runnable query) { // Add a query to be run once the session's sequence number reaches the given sequence number. List<Runnable> queries = this.sequenceQueries.computeIfAbsent(sequence, v -> new LinkedList<Runnable>()); queries.add(query); }
[ "public", "void", "registerSequenceQuery", "(", "long", "sequence", ",", "Runnable", "query", ")", "{", "// Add a query to be run once the session's sequence number reaches the given sequence number.", "List", "<", "Runnable", ">", "queries", "=", "this", ".", "sequenceQuerie...
Registers a causal session query. @param sequence The session sequence number at which to execute the query. @param query The query to execute.
[ "Registers", "a", "causal", "session", "query", "." ]
train
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/session/RaftSession.java#L305-L309
raydac/java-binary-block-parser
jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPUtils.java
JBBPUtils.unpackInt
public static int unpackInt(final byte[] array, final JBBPIntCounter position) { final int code = array[position.getAndIncrement()] & 0xFF; if (code < 0x80) { return code; } final int result; switch (code) { case 0x80: { result = ((array[position.getAndIncrement()] & 0xFF) << 8) | (array[position.getAndIncrement()] & 0xFF); } break; case 0x81: { result = ((array[position.getAndIncrement()] & 0xFF) << 24) | ((array[position.getAndIncrement()] & 0xFF) << 16) | ((array[position.getAndIncrement()] & 0xFF) << 8) | (array[position.getAndIncrement()] & 0xFF); } break; default: throw new IllegalArgumentException("Unsupported packed integer prefix [0x" + Integer.toHexString(code).toUpperCase(Locale.ENGLISH) + ']'); } return result; }
java
public static int unpackInt(final byte[] array, final JBBPIntCounter position) { final int code = array[position.getAndIncrement()] & 0xFF; if (code < 0x80) { return code; } final int result; switch (code) { case 0x80: { result = ((array[position.getAndIncrement()] & 0xFF) << 8) | (array[position.getAndIncrement()] & 0xFF); } break; case 0x81: { result = ((array[position.getAndIncrement()] & 0xFF) << 24) | ((array[position.getAndIncrement()] & 0xFF) << 16) | ((array[position.getAndIncrement()] & 0xFF) << 8) | (array[position.getAndIncrement()] & 0xFF); } break; default: throw new IllegalArgumentException("Unsupported packed integer prefix [0x" + Integer.toHexString(code).toUpperCase(Locale.ENGLISH) + ']'); } return result; }
[ "public", "static", "int", "unpackInt", "(", "final", "byte", "[", "]", "array", ",", "final", "JBBPIntCounter", "position", ")", "{", "final", "int", "code", "=", "array", "[", "position", ".", "getAndIncrement", "(", ")", "]", "&", "0xFF", ";", "if", ...
Unpack an integer value from defined position in a byte array. @param array the source byte array @param position the position of the first byte of packed value @return the unpacked value, the position will be increased
[ "Unpack", "an", "integer", "value", "from", "defined", "position", "in", "a", "byte", "array", "." ]
train
https://github.com/raydac/java-binary-block-parser/blob/6d98abcab01e0c72d525ebcc9e7b694f9ce49f5b/jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPUtils.java#L152-L175
ppiastucki/recast4j
detourcrowd/src/main/java/org/recast4j/detour/crowd/PathCorridor.java
PathCorridor.movePosition
public boolean movePosition(float[] npos, NavMeshQuery navquery, QueryFilter filter) { // Move along navmesh and update new position. Result<MoveAlongSurfaceResult> masResult = navquery.moveAlongSurface(m_path.get(0), m_pos, npos, filter); if (masResult.succeeded()) { m_path = mergeCorridorStartMoved(m_path, masResult.result.getVisited()); // Adjust the position to stay on top of the navmesh. vCopy(m_pos, masResult.result.getResultPos()); Result<Float> hr = navquery.getPolyHeight(m_path.get(0), masResult.result.getResultPos()); if (hr.succeeded()) { m_pos[1] = hr.result; } return true; } return false; }
java
public boolean movePosition(float[] npos, NavMeshQuery navquery, QueryFilter filter) { // Move along navmesh and update new position. Result<MoveAlongSurfaceResult> masResult = navquery.moveAlongSurface(m_path.get(0), m_pos, npos, filter); if (masResult.succeeded()) { m_path = mergeCorridorStartMoved(m_path, masResult.result.getVisited()); // Adjust the position to stay on top of the navmesh. vCopy(m_pos, masResult.result.getResultPos()); Result<Float> hr = navquery.getPolyHeight(m_path.get(0), masResult.result.getResultPos()); if (hr.succeeded()) { m_pos[1] = hr.result; } return true; } return false; }
[ "public", "boolean", "movePosition", "(", "float", "[", "]", "npos", ",", "NavMeshQuery", "navquery", ",", "QueryFilter", "filter", ")", "{", "// Move along navmesh and update new position.", "Result", "<", "MoveAlongSurfaceResult", ">", "masResult", "=", "navquery", ...
Moves the position from the current location to the desired location, adjusting the corridor as needed to reflect the change. Behavior: - The movement is constrained to the surface of the navigation mesh. - The corridor is automatically adjusted (shorted or lengthened) in order to remain valid. - The new position will be located in the adjusted corridor's first polygon. The expected use case is that the desired position will be 'near' the current corridor. What is considered 'near' depends on local polygon density, query search extents, etc. The resulting position will differ from the desired position if the desired position is not on the navigation mesh, or it can't be reached using a local search. @param npos The desired new position. [(x, y, z)] @param navquery The query object used to build the corridor. @param filter The filter to apply to the operation.
[ "Moves", "the", "position", "from", "the", "current", "location", "to", "the", "desired", "location", "adjusting", "the", "corridor", "as", "needed", "to", "reflect", "the", "change", "." ]
train
https://github.com/ppiastucki/recast4j/blob/a414dc34f16b87c95fb4e0f46c28a7830d421788/detourcrowd/src/main/java/org/recast4j/detour/crowd/PathCorridor.java#L384-L398
MenoData/Time4J
base/src/main/java/net/time4j/base/GregorianMath.java
GregorianMath.checkDate
public static void checkDate( int year, int month, int dayOfMonth ) { if (year < MIN_YEAR || year > MAX_YEAR) { throw new IllegalArgumentException( "YEAR out of range: " + year); } else if ((month < 1) || (month > 12)) { throw new IllegalArgumentException( "MONTH out of range: " + month); } else if ((dayOfMonth < 1) || (dayOfMonth > 31)) { throw new IllegalArgumentException( "DAY_OF_MONTH out of range: " + dayOfMonth); } else if (dayOfMonth > getLengthOfMonth(year, month)) { throw new IllegalArgumentException( "DAY_OF_MONTH exceeds month length in given year: " + toString(year, month, dayOfMonth)); } }
java
public static void checkDate( int year, int month, int dayOfMonth ) { if (year < MIN_YEAR || year > MAX_YEAR) { throw new IllegalArgumentException( "YEAR out of range: " + year); } else if ((month < 1) || (month > 12)) { throw new IllegalArgumentException( "MONTH out of range: " + month); } else if ((dayOfMonth < 1) || (dayOfMonth > 31)) { throw new IllegalArgumentException( "DAY_OF_MONTH out of range: " + dayOfMonth); } else if (dayOfMonth > getLengthOfMonth(year, month)) { throw new IllegalArgumentException( "DAY_OF_MONTH exceeds month length in given year: " + toString(year, month, dayOfMonth)); } }
[ "public", "static", "void", "checkDate", "(", "int", "year", ",", "int", "month", ",", "int", "dayOfMonth", ")", "{", "if", "(", "year", "<", "MIN_YEAR", "||", "year", ">", "MAX_YEAR", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"YEAR out ...
/*[deutsch] <p>&Uuml;berpr&uuml;ft die Bereichsgrenzen der Datumswerte nach den gregorianischen Kalenderregeln. </p> @param year proleptic iso year [(-999999999) - 999999999] @param month gregorian month (1-12) @param dayOfMonth day of month (1-31) @throws IllegalArgumentException if any argument is out of range @see #isValid(int, int, int)
[ "/", "*", "[", "deutsch", "]", "<p", ">", "&Uuml", ";", "berpr&uuml", ";", "ft", "die", "Bereichsgrenzen", "der", "Datumswerte", "nach", "den", "gregorianischen", "Kalenderregeln", ".", "<", "/", "p", ">" ]
train
https://github.com/MenoData/Time4J/blob/08b2eda6b2dbb140b92011cf7071bb087edd46a5/base/src/main/java/net/time4j/base/GregorianMath.java#L195-L216
Jasig/uPortal
uPortal-url/src/main/java/org/apereo/portal/url/UrlStringBuilder.java
UrlStringBuilder.setParameter
public UrlStringBuilder setParameter(String name, String... values) { this.setParameter(name, values != null ? Arrays.asList(values) : null); return this; }
java
public UrlStringBuilder setParameter(String name, String... values) { this.setParameter(name, values != null ? Arrays.asList(values) : null); return this; }
[ "public", "UrlStringBuilder", "setParameter", "(", "String", "name", ",", "String", "...", "values", ")", "{", "this", ".", "setParameter", "(", "name", ",", "values", "!=", "null", "?", "Arrays", ".", "asList", "(", "values", ")", ":", "null", ")", ";",...
Sets a URL parameter, replacing any existing parameter with the same name. @param name Parameter name, can not be null @param values Values for the parameter, null is valid @return this
[ "Sets", "a", "URL", "parameter", "replacing", "any", "existing", "parameter", "with", "the", "same", "name", "." ]
train
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-url/src/main/java/org/apereo/portal/url/UrlStringBuilder.java#L116-L119
graphql-java/graphql-java
src/main/java/graphql/language/NodeTraverser.java
NodeTraverser.postOrder
public Object postOrder(NodeVisitor nodeVisitor, Node root) { return postOrder(nodeVisitor, Collections.singleton(root)); }
java
public Object postOrder(NodeVisitor nodeVisitor, Node root) { return postOrder(nodeVisitor, Collections.singleton(root)); }
[ "public", "Object", "postOrder", "(", "NodeVisitor", "nodeVisitor", ",", "Node", "root", ")", "{", "return", "postOrder", "(", "nodeVisitor", ",", "Collections", ".", "singleton", "(", "root", ")", ")", ";", "}" ]
Version of {@link #postOrder(NodeVisitor, Collection)} with one root. @param nodeVisitor the visitor of the nodes @param root the root node @return the accumulation result of this traversal
[ "Version", "of", "{", "@link", "#postOrder", "(", "NodeVisitor", "Collection", ")", "}", "with", "one", "root", "." ]
train
https://github.com/graphql-java/graphql-java/blob/9214b6044317849388bd88a14b54fc1c18c9f29f/src/main/java/graphql/language/NodeTraverser.java#L128-L130
kuali/ojb-1.0.4
src/java/org/apache/ojb/broker/accesslayer/sql/SqlQueryStatement.java
SqlQueryStatement.ensureColumns
protected void ensureColumns(List columns, List existingColumns) { if (columns == null || columns.isEmpty()) { return; } Iterator iter = columns.iterator(); while (iter.hasNext()) { FieldHelper cf = (FieldHelper) iter.next(); if (!existingColumns.contains(cf.name)) { getAttributeInfo(cf.name, false, null, getQuery().getPathClasses()); } } }
java
protected void ensureColumns(List columns, List existingColumns) { if (columns == null || columns.isEmpty()) { return; } Iterator iter = columns.iterator(); while (iter.hasNext()) { FieldHelper cf = (FieldHelper) iter.next(); if (!existingColumns.contains(cf.name)) { getAttributeInfo(cf.name, false, null, getQuery().getPathClasses()); } } }
[ "protected", "void", "ensureColumns", "(", "List", "columns", ",", "List", "existingColumns", ")", "{", "if", "(", "columns", "==", "null", "||", "columns", ".", "isEmpty", "(", ")", ")", "{", "return", ";", "}", "Iterator", "iter", "=", "columns", ".", ...
Builds the Join for columns if they are not found among the existingColumns. @param columns the list of columns represented by Criteria.Field to ensure @param existingColumns the list of column names (String) that are already appended
[ "Builds", "the", "Join", "for", "columns", "if", "they", "are", "not", "found", "among", "the", "existingColumns", "." ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/accesslayer/sql/SqlQueryStatement.java#L480-L497
apache/incubator-gobblin
gobblin-runtime/src/main/java/org/apache/gobblin/runtime/job_catalog/NonObservingFSJobCatalog.java
NonObservingFSJobCatalog.remove
@Override public synchronized void remove(URI jobURI) { Preconditions.checkState(state() == State.RUNNING, String.format("%s is not running.", this.getClass().getName())); try { long startTime = System.currentTimeMillis(); JobSpec jobSpec = getJobSpec(jobURI); Path jobSpecPath = getPathForURI(this.jobConfDirPath, jobURI); if (fs.exists(jobSpecPath)) { fs.delete(jobSpecPath, false); this.mutableMetrics.updateRemoveJobTime(startTime); this.listeners.onDeleteJob(jobURI, jobSpec.getVersion()); } else { LOGGER.warn("No file with URI:" + jobSpecPath + " is found. Deletion failed."); } } catch (IOException e) { throw new RuntimeException("When removing a JobConf. file, issues unexpected happen:" + e.getMessage()); } catch (SpecNotFoundException e) { LOGGER.warn("No file with URI:" + jobURI + " is found. Deletion failed."); } }
java
@Override public synchronized void remove(URI jobURI) { Preconditions.checkState(state() == State.RUNNING, String.format("%s is not running.", this.getClass().getName())); try { long startTime = System.currentTimeMillis(); JobSpec jobSpec = getJobSpec(jobURI); Path jobSpecPath = getPathForURI(this.jobConfDirPath, jobURI); if (fs.exists(jobSpecPath)) { fs.delete(jobSpecPath, false); this.mutableMetrics.updateRemoveJobTime(startTime); this.listeners.onDeleteJob(jobURI, jobSpec.getVersion()); } else { LOGGER.warn("No file with URI:" + jobSpecPath + " is found. Deletion failed."); } } catch (IOException e) { throw new RuntimeException("When removing a JobConf. file, issues unexpected happen:" + e.getMessage()); } catch (SpecNotFoundException e) { LOGGER.warn("No file with URI:" + jobURI + " is found. Deletion failed."); } }
[ "@", "Override", "public", "synchronized", "void", "remove", "(", "URI", "jobURI", ")", "{", "Preconditions", ".", "checkState", "(", "state", "(", ")", "==", "State", ".", "RUNNING", ",", "String", ".", "format", "(", "\"%s is not running.\"", ",", "this", ...
Allow user to programmatically delete a new JobSpec. This method is designed to be reentrant. @param jobURI The relative Path that specified by user, need to make it into complete path.
[ "Allow", "user", "to", "programmatically", "delete", "a", "new", "JobSpec", ".", "This", "method", "is", "designed", "to", "be", "reentrant", "." ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/job_catalog/NonObservingFSJobCatalog.java#L103-L123
google/closure-compiler
src/com/google/javascript/jscomp/RemoveUnusedCode.java
RemoveUnusedCode.process
@Override public void process(Node externs, Node root) { checkState(compiler.getLifeCycleStage().isNormalized()); if (!allowRemovalOfExternProperties) { referencedPropertyNames.addAll(compiler.getExternProperties()); } traverseAndRemoveUnusedReferences(root); // This pass may remove definitions of getter or setter properties. GatherGettersAndSetterProperties.update(compiler, externs, root); }
java
@Override public void process(Node externs, Node root) { checkState(compiler.getLifeCycleStage().isNormalized()); if (!allowRemovalOfExternProperties) { referencedPropertyNames.addAll(compiler.getExternProperties()); } traverseAndRemoveUnusedReferences(root); // This pass may remove definitions of getter or setter properties. GatherGettersAndSetterProperties.update(compiler, externs, root); }
[ "@", "Override", "public", "void", "process", "(", "Node", "externs", ",", "Node", "root", ")", "{", "checkState", "(", "compiler", ".", "getLifeCycleStage", "(", ")", ".", "isNormalized", "(", ")", ")", ";", "if", "(", "!", "allowRemovalOfExternProperties",...
Traverses the root, removing all unused variables. Multiple traversals may occur to ensure all unused variables are removed.
[ "Traverses", "the", "root", "removing", "all", "unused", "variables", ".", "Multiple", "traversals", "may", "occur", "to", "ensure", "all", "unused", "variables", "are", "removed", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/RemoveUnusedCode.java#L242-L251
inkstand-io/scribble
scribble-file/src/main/java/io/inkstand/scribble/rules/TemporaryZipFile.java
TemporaryZipFile.addEntry
private void addEntry(final Path pathToFile, final URL resource) throws IOException { final Path parent = pathToFile.getParent(); if (parent != null) { addFolder(parent); } try (InputStream inputStream = resource.openStream()) { Files.copy(inputStream, pathToFile); } }
java
private void addEntry(final Path pathToFile, final URL resource) throws IOException { final Path parent = pathToFile.getParent(); if (parent != null) { addFolder(parent); } try (InputStream inputStream = resource.openStream()) { Files.copy(inputStream, pathToFile); } }
[ "private", "void", "addEntry", "(", "final", "Path", "pathToFile", ",", "final", "URL", "resource", ")", "throws", "IOException", "{", "final", "Path", "parent", "=", "pathToFile", ".", "getParent", "(", ")", ";", "if", "(", "parent", "!=", "null", ")", ...
Creates an entry under the specifeid path with the content from the provided resource. @param pathToFile the path to the file in the zip file. @param resource the resource providing the content for the file. Must not be null. @throws IOException
[ "Creates", "an", "entry", "under", "the", "specifeid", "path", "with", "the", "content", "from", "the", "provided", "resource", "." ]
train
https://github.com/inkstand-io/scribble/blob/66e67553bad4b1ff817e1715fd1d3dd833406744/scribble-file/src/main/java/io/inkstand/scribble/rules/TemporaryZipFile.java#L146-L155
Azure/azure-sdk-for-java
cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java
ModelsImpl.getIntentSuggestionsAsync
public Observable<List<IntentsSuggestionExample>> getIntentSuggestionsAsync(UUID appId, String versionId, UUID intentId, GetIntentSuggestionsOptionalParameter getIntentSuggestionsOptionalParameter) { return getIntentSuggestionsWithServiceResponseAsync(appId, versionId, intentId, getIntentSuggestionsOptionalParameter).map(new Func1<ServiceResponse<List<IntentsSuggestionExample>>, List<IntentsSuggestionExample>>() { @Override public List<IntentsSuggestionExample> call(ServiceResponse<List<IntentsSuggestionExample>> response) { return response.body(); } }); }
java
public Observable<List<IntentsSuggestionExample>> getIntentSuggestionsAsync(UUID appId, String versionId, UUID intentId, GetIntentSuggestionsOptionalParameter getIntentSuggestionsOptionalParameter) { return getIntentSuggestionsWithServiceResponseAsync(appId, versionId, intentId, getIntentSuggestionsOptionalParameter).map(new Func1<ServiceResponse<List<IntentsSuggestionExample>>, List<IntentsSuggestionExample>>() { @Override public List<IntentsSuggestionExample> call(ServiceResponse<List<IntentsSuggestionExample>> response) { return response.body(); } }); }
[ "public", "Observable", "<", "List", "<", "IntentsSuggestionExample", ">", ">", "getIntentSuggestionsAsync", "(", "UUID", "appId", ",", "String", "versionId", ",", "UUID", "intentId", ",", "GetIntentSuggestionsOptionalParameter", "getIntentSuggestionsOptionalParameter", ")"...
Suggests examples that would improve the accuracy of the intent model. @param appId The application ID. @param versionId The version ID. @param intentId The intent classifier ID. @param getIntentSuggestionsOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the List&lt;IntentsSuggestionExample&gt; object
[ "Suggests", "examples", "that", "would", "improve", "the", "accuracy", "of", "the", "intent", "model", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java#L5100-L5107
haraldk/TwelveMonkeys
sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/NetUtil.java
NetUtil.getBytesHttp
public static byte[] getBytesHttp(String pURL, int pTimeout) throws IOException { // Get the input stream from the url InputStream in = new BufferedInputStream(getInputStreamHttp(pURL, pTimeout), BUF_SIZE * 2); // Get all the bytes in loop ByteArrayOutputStream bytes = new ByteArrayOutputStream(); int count; byte[] buffer = new byte[BUF_SIZE]; try { while ((count = in.read(buffer)) != -1) { // NOTE: According to the J2SE API doc, read(byte[]) will read // at least 1 byte, or return -1, if end-of-file is reached. bytes.write(buffer, 0, count); } } finally { // Close the buffer in.close(); } return bytes.toByteArray(); }
java
public static byte[] getBytesHttp(String pURL, int pTimeout) throws IOException { // Get the input stream from the url InputStream in = new BufferedInputStream(getInputStreamHttp(pURL, pTimeout), BUF_SIZE * 2); // Get all the bytes in loop ByteArrayOutputStream bytes = new ByteArrayOutputStream(); int count; byte[] buffer = new byte[BUF_SIZE]; try { while ((count = in.read(buffer)) != -1) { // NOTE: According to the J2SE API doc, read(byte[]) will read // at least 1 byte, or return -1, if end-of-file is reached. bytes.write(buffer, 0, count); } } finally { // Close the buffer in.close(); } return bytes.toByteArray(); }
[ "public", "static", "byte", "[", "]", "getBytesHttp", "(", "String", "pURL", ",", "int", "pTimeout", ")", "throws", "IOException", "{", "// Get the input stream from the url", "InputStream", "in", "=", "new", "BufferedInputStream", "(", "getInputStreamHttp", "(", "p...
Gets the content from a given URL, with the given timeout. The timeout must be > 0. A timeout of zero is interpreted as an infinite timeout. Supports basic HTTP authentication, using a URL string similar to most browsers. <P/> <SMALL>Implementation note: If the timeout parameter is greater than 0, this method uses my own implementation of java.net.HttpURLConnection, that uses plain sockets, to create an HTTP connection to the given URL. The {@code read} methods called on the returned InputStream, will block only for the specified timeout. If the timeout expires, a java.io.InterruptedIOException is raised. <BR/> </SMALL> @param pURL the URL to get. @param pTimeout the specified timeout, in milliseconds. @return a byte array that is read from the socket connection, created from the given URL. @throws MalformedURLException if the url parameter specifies an unknown protocol, or does not form a valid URL. @throws UnknownHostException if the IP address for the given URL cannot be resolved. @throws FileNotFoundException if there is no file at the given URL. @throws IOException if an error occurs during transfer. @see #getBytesHttp(URL,int) @see java.net.Socket @see java.net.Socket#setSoTimeout(int) setSoTimeout @see java.io.InterruptedIOException @see <A href="http://www.w3.org/Protocols/rfc2616/rfc2616.html">RFC 2616</A>
[ "Gets", "the", "content", "from", "a", "given", "URL", "with", "the", "given", "timeout", ".", "The", "timeout", "must", "be", ">", "0", ".", "A", "timeout", "of", "zero", "is", "interpreted", "as", "an", "infinite", "timeout", ".", "Supports", "basic", ...
train
https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/NetUtil.java#L967-L989
Deep-Symmetry/beat-link
src/main/java/org/deepsymmetry/beatlink/Util.java
Util.bytesToNumberLittleEndian
@SuppressWarnings("SameParameterValue") public static long bytesToNumberLittleEndian(byte[] buffer, int start, int length) { long result = 0; for (int index = start + length - 1; index >= start; index--) { result = (result << 8) + unsign(buffer[index]); } return result; }
java
@SuppressWarnings("SameParameterValue") public static long bytesToNumberLittleEndian(byte[] buffer, int start, int length) { long result = 0; for (int index = start + length - 1; index >= start; index--) { result = (result << 8) + unsign(buffer[index]); } return result; }
[ "@", "SuppressWarnings", "(", "\"SameParameterValue\"", ")", "public", "static", "long", "bytesToNumberLittleEndian", "(", "byte", "[", "]", "buffer", ",", "int", "start", ",", "int", "length", ")", "{", "long", "result", "=", "0", ";", "for", "(", "int", ...
Reconstructs a number that is represented by more than one byte in a network packet in little-endian order, for the very few protocol values that are sent in this quirky way. @param buffer the byte array containing the packet data @param start the index of the first byte containing a numeric value @param length the number of bytes making up the value @return the reconstructed number
[ "Reconstructs", "a", "number", "that", "is", "represented", "by", "more", "than", "one", "byte", "in", "a", "network", "packet", "in", "little", "-", "endian", "order", "for", "the", "very", "few", "protocol", "values", "that", "are", "sent", "in", "this",...
train
https://github.com/Deep-Symmetry/beat-link/blob/f958a2a70e8a87a31a75326d7b4db77c2f0b4212/src/main/java/org/deepsymmetry/beatlink/Util.java#L259-L266
languagetool-org/languagetool
languagetool-core/src/main/java/org/languagetool/rules/patterns/PatternRuleMatcher.java
PatternRuleMatcher.matchPreservesCase
private boolean matchPreservesCase(List<Match> suggestionMatches, String msg) { if (suggestionMatches != null && !suggestionMatches.isEmpty()) { //PatternRule rule = (PatternRule) this.rule; int sugStart = msg.indexOf(SUGGESTION_START_TAG) + SUGGESTION_START_TAG.length(); for (Match sMatch : suggestionMatches) { if (!sMatch.isInMessageOnly() && sMatch.convertsCase() && msg.charAt(sugStart) == '\\') { return false; } } } return true; }
java
private boolean matchPreservesCase(List<Match> suggestionMatches, String msg) { if (suggestionMatches != null && !suggestionMatches.isEmpty()) { //PatternRule rule = (PatternRule) this.rule; int sugStart = msg.indexOf(SUGGESTION_START_TAG) + SUGGESTION_START_TAG.length(); for (Match sMatch : suggestionMatches) { if (!sMatch.isInMessageOnly() && sMatch.convertsCase() && msg.charAt(sugStart) == '\\') { return false; } } } return true; }
[ "private", "boolean", "matchPreservesCase", "(", "List", "<", "Match", ">", "suggestionMatches", ",", "String", "msg", ")", "{", "if", "(", "suggestionMatches", "!=", "null", "&&", "!", "suggestionMatches", ".", "isEmpty", "(", ")", ")", "{", "//PatternRule ru...
Checks if the suggestion starts with a match that is supposed to preserve case. If it does not, perform the default conversion to uppercase. @return true, if the match preserves the case of the token.
[ "Checks", "if", "the", "suggestion", "starts", "with", "a", "match", "that", "is", "supposed", "to", "preserve", "case", ".", "If", "it", "does", "not", "perform", "the", "default", "conversion", "to", "uppercase", "." ]
train
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-core/src/main/java/org/languagetool/rules/patterns/PatternRuleMatcher.java#L261-L273
spotify/styx
styx-common/src/main/java/com/spotify/styx/util/TimeUtil.java
TimeUtil.nextInstant
public static Instant nextInstant(Instant instant, Schedule schedule) { final ExecutionTime executionTime = ExecutionTime.forCron(cron(schedule)); final ZonedDateTime utcDateTime = instant.atZone(UTC); return executionTime.nextExecution(utcDateTime) .orElseThrow(IllegalArgumentException::new) // with unix cron, this should not happen .toInstant(); }
java
public static Instant nextInstant(Instant instant, Schedule schedule) { final ExecutionTime executionTime = ExecutionTime.forCron(cron(schedule)); final ZonedDateTime utcDateTime = instant.atZone(UTC); return executionTime.nextExecution(utcDateTime) .orElseThrow(IllegalArgumentException::new) // with unix cron, this should not happen .toInstant(); }
[ "public", "static", "Instant", "nextInstant", "(", "Instant", "instant", ",", "Schedule", "schedule", ")", "{", "final", "ExecutionTime", "executionTime", "=", "ExecutionTime", ".", "forCron", "(", "cron", "(", "schedule", ")", ")", ";", "final", "ZonedDateTime"...
Gets the next execution instant for a {@link Schedule}, relative to a given instant. <p>e.g. an hourly schedule has a next execution instant at 14:00 relative to 13:22. @param instant The instant to calculate the next execution instant relative to @param schedule The schedule of executions @return an instant at the next execution time
[ "Gets", "the", "next", "execution", "instant", "for", "a", "{", "@link", "Schedule", "}", "relative", "to", "a", "given", "instant", "." ]
train
https://github.com/spotify/styx/blob/0d63999beeb93a17447e3bbccaa62175b74cf6e4/styx-common/src/main/java/com/spotify/styx/util/TimeUtil.java#L108-L115
ManfredTremmel/gwt-bean-validators
mt-bean-validators/src/main/java/de/knightsoftnet/validators/shared/impl/IsinValidator.java
IsinValidator.isValid
@Override public final boolean isValid(final Object pvalue, final ConstraintValidatorContext pcontext) { final String valueAsString = Objects.toString(pvalue, null); if (StringUtils.isEmpty(valueAsString)) { return true; } if (valueAsString.length() != ISIN_LENGTH) { // ISIN size is wrong, but that's handled by size annotation return true; } // calculate and check checksum (ISIN) return CHECK_ISIN.isValid(valueAsString); }
java
@Override public final boolean isValid(final Object pvalue, final ConstraintValidatorContext pcontext) { final String valueAsString = Objects.toString(pvalue, null); if (StringUtils.isEmpty(valueAsString)) { return true; } if (valueAsString.length() != ISIN_LENGTH) { // ISIN size is wrong, but that's handled by size annotation return true; } // calculate and check checksum (ISIN) return CHECK_ISIN.isValid(valueAsString); }
[ "@", "Override", "public", "final", "boolean", "isValid", "(", "final", "Object", "pvalue", ",", "final", "ConstraintValidatorContext", "pcontext", ")", "{", "final", "String", "valueAsString", "=", "Objects", ".", "toString", "(", "pvalue", ",", "null", ")", ...
{@inheritDoc} check if given string is a valid isin. @see javax.validation.ConstraintValidator#isValid(java.lang.Object, javax.validation.ConstraintValidatorContext)
[ "{", "@inheritDoc", "}", "check", "if", "given", "string", "is", "a", "valid", "isin", "." ]
train
https://github.com/ManfredTremmel/gwt-bean-validators/blob/cff7a2c3d68c2d17bf9d3cc57c79cc16fa8b4d5c/mt-bean-validators/src/main/java/de/knightsoftnet/validators/shared/impl/IsinValidator.java#L61-L73
bigdata-mx/factura-electronica
src/main/java/mx/bigdata/sat/security/PrivateKeyLoader.java
PrivateKeyLoader.setPrivateKey
public void setPrivateKey(String privateKeyLocation, String keyPassword) { InputStream privateKeyInputStream = null; try { privateKeyInputStream = new FileInputStream(privateKeyLocation); }catch (FileNotFoundException fnfe){ throw new KeyException("La ubicación del archivo de la llave privada es incorrecta", fnfe.getCause()); } this.setPrivateKey(privateKeyInputStream, keyPassword); }
java
public void setPrivateKey(String privateKeyLocation, String keyPassword) { InputStream privateKeyInputStream = null; try { privateKeyInputStream = new FileInputStream(privateKeyLocation); }catch (FileNotFoundException fnfe){ throw new KeyException("La ubicación del archivo de la llave privada es incorrecta", fnfe.getCause()); } this.setPrivateKey(privateKeyInputStream, keyPassword); }
[ "public", "void", "setPrivateKey", "(", "String", "privateKeyLocation", ",", "String", "keyPassword", ")", "{", "InputStream", "privateKeyInputStream", "=", "null", ";", "try", "{", "privateKeyInputStream", "=", "new", "FileInputStream", "(", "privateKeyLocation", ")"...
@param privateKeyLocation private key located in filesystem @param keyPassword private key password @throws KeyException thrown when any security exception occurs
[ "@param", "privateKeyLocation", "private", "key", "located", "in", "filesystem", "@param", "keyPassword", "private", "key", "password" ]
train
https://github.com/bigdata-mx/factura-electronica/blob/ca9b06039075bc3b06e64b080c3545c937e35003/src/main/java/mx/bigdata/sat/security/PrivateKeyLoader.java#L44-L55
awslabs/jsii
packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiEngine.java
JsiiEngine.findEnumValue
@SuppressWarnings({ "unchecked", "rawtypes" }) public Enum<?> findEnumValue(final String enumRef) { int sep = enumRef.lastIndexOf('/'); if (sep == -1) { throw new JsiiException("Malformed enum reference: " + enumRef); } String typeName = enumRef.substring(0, sep); String valueName = enumRef.substring(sep + 1); try { Class klass = resolveJavaClass(typeName); return Enum.valueOf(klass, valueName); } catch (final ClassNotFoundException e) { throw new JsiiException("Unable to resolve enum type " + typeName, e); } }
java
@SuppressWarnings({ "unchecked", "rawtypes" }) public Enum<?> findEnumValue(final String enumRef) { int sep = enumRef.lastIndexOf('/'); if (sep == -1) { throw new JsiiException("Malformed enum reference: " + enumRef); } String typeName = enumRef.substring(0, sep); String valueName = enumRef.substring(sep + 1); try { Class klass = resolveJavaClass(typeName); return Enum.valueOf(klass, valueName); } catch (final ClassNotFoundException e) { throw new JsiiException("Unable to resolve enum type " + typeName, e); } }
[ "@", "SuppressWarnings", "(", "{", "\"unchecked\"", ",", "\"rawtypes\"", "}", ")", "public", "Enum", "<", "?", ">", "findEnumValue", "(", "final", "String", "enumRef", ")", "{", "int", "sep", "=", "enumRef", ".", "lastIndexOf", "(", "'", "'", ")", ";", ...
Given a jsii enum ref in the form "fqn/member" returns the Java enum value for it. @param enumRef The jsii enum ref. @return The java enum value.
[ "Given", "a", "jsii", "enum", "ref", "in", "the", "form", "fqn", "/", "member", "returns", "the", "Java", "enum", "value", "for", "it", "." ]
train
https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiEngine.java#L264-L279
LearnLib/automatalib
util/src/main/java/net/automatalib/util/automata/minimizer/hopcroft/HopcroftMinimization.java
HopcroftMinimization.minimizeMealy
public static <S, I, T, O, A extends MealyMachine<S, I, T, O> & InputAlphabetHolder<I>> CompactMealy<I, O> minimizeMealy(A mealy) { return minimizeMealy(mealy, PruningMode.PRUNE_AFTER); }
java
public static <S, I, T, O, A extends MealyMachine<S, I, T, O> & InputAlphabetHolder<I>> CompactMealy<I, O> minimizeMealy(A mealy) { return minimizeMealy(mealy, PruningMode.PRUNE_AFTER); }
[ "public", "static", "<", "S", ",", "I", ",", "T", ",", "O", ",", "A", "extends", "MealyMachine", "<", "S", ",", "I", ",", "T", ",", "O", ">", "&", "InputAlphabetHolder", "<", "I", ">", ">", "CompactMealy", "<", "I", ",", "O", ">", "minimizeMealy"...
Minimizes the given Mealy machine. The result is returned in the form of a {@link CompactMealy}, using the alphabet obtained via <code>mealy.{@link InputAlphabetHolder#getInputAlphabet() getInputAlphabet()}</code>. Pruning (see above) is performed after computing state equivalences. @param mealy the Mealy machine to minimize @return a minimized version of the specified Mealy machine
[ "Minimizes", "the", "given", "Mealy", "machine", ".", "The", "result", "is", "returned", "in", "the", "form", "of", "a", "{", "@link", "CompactMealy", "}", "using", "the", "alphabet", "obtained", "via", "<code", ">", "mealy", ".", "{", "@link", "InputAlpha...
train
https://github.com/LearnLib/automatalib/blob/8a462ec52f6eaab9f8996e344f2163a72cb8aa6e/util/src/main/java/net/automatalib/util/automata/minimizer/hopcroft/HopcroftMinimization.java#L103-L105
Azure/azure-sdk-for-java
kusto/resource-manager/v2018_09_07_preview/src/main/java/com/microsoft/azure/management/kusto/v2018_09_07_preview/implementation/DatabasesInner.java
DatabasesInner.addPrincipals
public DatabasePrincipalListResultInner addPrincipals(String resourceGroupName, String clusterName, String databaseName) { return addPrincipalsWithServiceResponseAsync(resourceGroupName, clusterName, databaseName).toBlocking().single().body(); }
java
public DatabasePrincipalListResultInner addPrincipals(String resourceGroupName, String clusterName, String databaseName) { return addPrincipalsWithServiceResponseAsync(resourceGroupName, clusterName, databaseName).toBlocking().single().body(); }
[ "public", "DatabasePrincipalListResultInner", "addPrincipals", "(", "String", "resourceGroupName", ",", "String", "clusterName", ",", "String", "databaseName", ")", "{", "return", "addPrincipalsWithServiceResponseAsync", "(", "resourceGroupName", ",", "clusterName", ",", "d...
Add Database principals permissions. @param resourceGroupName The name of the resource group containing the Kusto cluster. @param clusterName The name of the Kusto cluster. @param databaseName The name of the database in the Kusto cluster. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the DatabasePrincipalListResultInner object if successful.
[ "Add", "Database", "principals", "permissions", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/kusto/resource-manager/v2018_09_07_preview/src/main/java/com/microsoft/azure/management/kusto/v2018_09_07_preview/implementation/DatabasesInner.java#L1045-L1047
b3dgs/lionengine
lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/HandlablesImpl.java
HandlablesImpl.removeSuperClass
private void removeSuperClass(Object object, Class<?> type) { for (final Class<?> types : type.getInterfaces()) { remove(types, object); } final Class<?> parent = type.getSuperclass(); if (parent != null) { removeSuperClass(object, parent); } }
java
private void removeSuperClass(Object object, Class<?> type) { for (final Class<?> types : type.getInterfaces()) { remove(types, object); } final Class<?> parent = type.getSuperclass(); if (parent != null) { removeSuperClass(object, parent); } }
[ "private", "void", "removeSuperClass", "(", "Object", "object", ",", "Class", "<", "?", ">", "type", ")", "{", "for", "(", "final", "Class", "<", "?", ">", "types", ":", "type", ".", "getInterfaces", "(", ")", ")", "{", "remove", "(", "types", ",", ...
Remove object parent super type. @param object The current object to check. @param type The current class level to check.
[ "Remove", "object", "parent", "super", "type", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/HandlablesImpl.java#L158-L169
s1ck/gdl
src/main/java/org/s1ck/gdl/GDLLoader.java
GDLLoader.getEdgeCache
Map<String, Edge> getEdgeCache(boolean includeUserDefined, boolean includeAutoGenerated) { return getCache(userEdgeCache, autoEdgeCache, includeUserDefined, includeAutoGenerated); }
java
Map<String, Edge> getEdgeCache(boolean includeUserDefined, boolean includeAutoGenerated) { return getCache(userEdgeCache, autoEdgeCache, includeUserDefined, includeAutoGenerated); }
[ "Map", "<", "String", ",", "Edge", ">", "getEdgeCache", "(", "boolean", "includeUserDefined", ",", "boolean", "includeAutoGenerated", ")", "{", "return", "getCache", "(", "userEdgeCache", ",", "autoEdgeCache", ",", "includeUserDefined", ",", "includeAutoGenerated", ...
Returns a cache containing a mapping from variables to edges. @param includeUserDefined include user-defined variables @param includeAutoGenerated include auto-generated variables @return immutable edge cache
[ "Returns", "a", "cache", "containing", "a", "mapping", "from", "variables", "to", "edges", "." ]
train
https://github.com/s1ck/gdl/blob/c89b0f83526661823ad3392f338dbf7dc3e3f834/src/main/java/org/s1ck/gdl/GDLLoader.java#L260-L262
alibaba/vlayout
vlayout/src/main/java/com/alibaba/android/vlayout/layout/MarginLayoutHelper.java
MarginLayoutHelper.setPadding
public void setPadding(int leftPadding, int topPadding, int rightPadding, int bottomPadding) { mPaddingLeft = leftPadding; mPaddingRight = rightPadding; mPaddingTop = topPadding; mPaddingBottom = bottomPadding; }
java
public void setPadding(int leftPadding, int topPadding, int rightPadding, int bottomPadding) { mPaddingLeft = leftPadding; mPaddingRight = rightPadding; mPaddingTop = topPadding; mPaddingBottom = bottomPadding; }
[ "public", "void", "setPadding", "(", "int", "leftPadding", ",", "int", "topPadding", ",", "int", "rightPadding", ",", "int", "bottomPadding", ")", "{", "mPaddingLeft", "=", "leftPadding", ";", "mPaddingRight", "=", "rightPadding", ";", "mPaddingTop", "=", "topPa...
set paddings for this layoutHelper @param leftPadding left padding @param topPadding top padding @param rightPadding right padding @param bottomPadding bottom padding
[ "set", "paddings", "for", "this", "layoutHelper" ]
train
https://github.com/alibaba/vlayout/blob/8a5a51d9d2eeb91fed2ee331a4cf3496282452ce/vlayout/src/main/java/com/alibaba/android/vlayout/layout/MarginLayoutHelper.java#L55-L60
querydsl/querydsl
querydsl-mongodb/src/main/java/com/querydsl/mongodb/MongodbExpressions.java
MongodbExpressions.near
public static BooleanExpression near(Expression<Double[]> expr, double latVal, double longVal) { return Expressions.booleanOperation(MongodbOps.NEAR, expr, ConstantImpl.create(new Double[]{latVal, longVal})); }
java
public static BooleanExpression near(Expression<Double[]> expr, double latVal, double longVal) { return Expressions.booleanOperation(MongodbOps.NEAR, expr, ConstantImpl.create(new Double[]{latVal, longVal})); }
[ "public", "static", "BooleanExpression", "near", "(", "Expression", "<", "Double", "[", "]", ">", "expr", ",", "double", "latVal", ",", "double", "longVal", ")", "{", "return", "Expressions", ".", "booleanOperation", "(", "MongodbOps", ".", "NEAR", ",", "exp...
Finds the closest points relative to the given location and orders the results with decreasing proximity @param expr location @param latVal latitude @param longVal longitude @return predicate
[ "Finds", "the", "closest", "points", "relative", "to", "the", "given", "location", "and", "orders", "the", "results", "with", "decreasing", "proximity" ]
train
https://github.com/querydsl/querydsl/blob/2bf234caf78549813a1e0f44d9c30ecc5ef734e3/querydsl-mongodb/src/main/java/com/querydsl/mongodb/MongodbExpressions.java#L39-L41
timols/java-gitlab-api
src/main/java/org/gitlab/api/GitlabAPI.java
GitlabAPI.createRepositoryFile
public GitlabSimpleRepositoryFile createRepositoryFile(GitlabProject project, String path, String branchName, String commitMsg, String content) throws IOException { String tailUrl = GitlabProject.URL + "/" + project.getId() + "/repository/files/" + sanitizePath(path); GitlabHTTPRequestor requestor = dispatch(); return requestor .with("branch", branchName) .with("encoding", "base64") .with("commit_message", commitMsg) .with("content", content) .to(tailUrl, GitlabSimpleRepositoryFile.class); }
java
public GitlabSimpleRepositoryFile createRepositoryFile(GitlabProject project, String path, String branchName, String commitMsg, String content) throws IOException { String tailUrl = GitlabProject.URL + "/" + project.getId() + "/repository/files/" + sanitizePath(path); GitlabHTTPRequestor requestor = dispatch(); return requestor .with("branch", branchName) .with("encoding", "base64") .with("commit_message", commitMsg) .with("content", content) .to(tailUrl, GitlabSimpleRepositoryFile.class); }
[ "public", "GitlabSimpleRepositoryFile", "createRepositoryFile", "(", "GitlabProject", "project", ",", "String", "path", ",", "String", "branchName", ",", "String", "commitMsg", ",", "String", "content", ")", "throws", "IOException", "{", "String", "tailUrl", "=", "G...
Creates a new file in the repository @param project The Project @param path The file path inside the repository @param branchName The name of a repository branch @param commitMsg The commit message @param content The base64 encoded content of the file @throws IOException on gitlab api call error
[ "Creates", "a", "new", "file", "in", "the", "repository" ]
train
https://github.com/timols/java-gitlab-api/blob/f03eedf952cfbb40306be3bf9234dcf78fab029e/src/main/java/org/gitlab/api/GitlabAPI.java#L2207-L2217
OpenLiberty/open-liberty
dev/com.ibm.ws.security.wim.core/src/com/ibm/ws/security/wim/adapter/urbridge/URBridge.java
URBridge.setBaseEntry
private void setBaseEntry(Map<String, Object> configProps) throws WIMException { /* * Map<String, List<Map<String, Object>>> configMap = Nester.nest(configProps, BASE_ENTRY); * * for (Map<String, Object> entry : configMap.get(BASE_ENTRY)) { * baseEntryName = (String) entry.get(BASE_ENTRY_NAME); * } */ baseEntryName = (String) configProps.get(BASE_ENTRY); if (baseEntryName == null) { throw new WIMApplicationException(WIMMessageKey.MISSING_BASE_ENTRY, Tr.formatMessage(tc, WIMMessageKey.MISSING_BASE_ENTRY, WIMMessageHelper.generateMsgParms(reposId))); } }
java
private void setBaseEntry(Map<String, Object> configProps) throws WIMException { /* * Map<String, List<Map<String, Object>>> configMap = Nester.nest(configProps, BASE_ENTRY); * * for (Map<String, Object> entry : configMap.get(BASE_ENTRY)) { * baseEntryName = (String) entry.get(BASE_ENTRY_NAME); * } */ baseEntryName = (String) configProps.get(BASE_ENTRY); if (baseEntryName == null) { throw new WIMApplicationException(WIMMessageKey.MISSING_BASE_ENTRY, Tr.formatMessage(tc, WIMMessageKey.MISSING_BASE_ENTRY, WIMMessageHelper.generateMsgParms(reposId))); } }
[ "private", "void", "setBaseEntry", "(", "Map", "<", "String", ",", "Object", ">", "configProps", ")", "throws", "WIMException", "{", "/*\n * Map<String, List<Map<String, Object>>> configMap = Nester.nest(configProps, BASE_ENTRY);\n *\n * for (Map<String, Object> entry : configMap.get(B...
Set the baseEntryname from the configuration. The configuration should have only 1 baseEntry @param configProps Map containing the configuration information for the baseEntries. @throws WIMException Exception is thrown if no baseEntry is set.
[ "Set", "the", "baseEntryname", "from", "the", "configuration", ".", "The", "configuration", "should", "have", "only", "1", "baseEntry" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.wim.core/src/com/ibm/ws/security/wim/adapter/urbridge/URBridge.java#L293-L307
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/style/StyleUtilities.java
StyleUtilities.checkSameNameFeatureTypeStyle
public static String checkSameNameFeatureTypeStyle( List<FeatureTypeStyleWrapper> ftsWrapperList, String ftsName ) { int index = 1; String name = ftsName.trim(); for( int i = 0; i < ftsWrapperList.size(); i++ ) { FeatureTypeStyleWrapper ftsWrapper = ftsWrapperList.get(i); String tmpName = ftsWrapper.getName(); if (tmpName == null) { continue; } tmpName = tmpName.trim(); if (tmpName.equals(name)) { // name exists, change the name of the entering if (name.endsWith(")")) { name = name.trim().replaceFirst("\\([0-9]+\\)$", "(" + (index++) + ")"); } else { name = name + " (" + (index++) + ")"; } // start again i = 0; } if (index == 1000) { // something odd is going on throw new RuntimeException(); } } return name; }
java
public static String checkSameNameFeatureTypeStyle( List<FeatureTypeStyleWrapper> ftsWrapperList, String ftsName ) { int index = 1; String name = ftsName.trim(); for( int i = 0; i < ftsWrapperList.size(); i++ ) { FeatureTypeStyleWrapper ftsWrapper = ftsWrapperList.get(i); String tmpName = ftsWrapper.getName(); if (tmpName == null) { continue; } tmpName = tmpName.trim(); if (tmpName.equals(name)) { // name exists, change the name of the entering if (name.endsWith(")")) { name = name.trim().replaceFirst("\\([0-9]+\\)$", "(" + (index++) + ")"); } else { name = name + " (" + (index++) + ")"; } // start again i = 0; } if (index == 1000) { // something odd is going on throw new RuntimeException(); } } return name; }
[ "public", "static", "String", "checkSameNameFeatureTypeStyle", "(", "List", "<", "FeatureTypeStyleWrapper", ">", "ftsWrapperList", ",", "String", "ftsName", ")", "{", "int", "index", "=", "1", ";", "String", "name", "=", "ftsName", ".", "trim", "(", ")", ";", ...
Checks if the list of {@link FeatureTypeStyleWrapper}s supplied contains one with the supplied name. <p>If the rule is contained it adds an index to the name. @param ftsWrapperList the list of featureTypeStyles to check. @param ftsName the name of the featureTypeStyle to find. @return the new name of the featureTypeStyle.
[ "Checks", "if", "the", "list", "of", "{", "@link", "FeatureTypeStyleWrapper", "}", "s", "supplied", "contains", "one", "with", "the", "supplied", "name", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/style/StyleUtilities.java#L794-L821