repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
204
func_name
stringlengths
5
103
whole_func_string
stringlengths
87
3.44k
language
stringclasses
1 value
func_code_string
stringlengths
87
3.44k
func_code_tokens
listlengths
21
714
func_documentation_string
stringlengths
61
1.95k
func_documentation_tokens
listlengths
1
482
split_name
stringclasses
1 value
func_code_url
stringlengths
102
309
google/truth
core/src/main/java/com/google/common/truth/MathUtil.java
MathUtil.equalWithinTolerance
public static boolean equalWithinTolerance(double left, double right, double tolerance) { return Math.abs(left - right) <= Math.abs(tolerance); }
java
public static boolean equalWithinTolerance(double left, double right, double tolerance) { return Math.abs(left - right) <= Math.abs(tolerance); }
[ "public", "static", "boolean", "equalWithinTolerance", "(", "double", "left", ",", "double", "right", ",", "double", "tolerance", ")", "{", "return", "Math", ".", "abs", "(", "left", "-", "right", ")", "<=", "Math", ".", "abs", "(", "tolerance", ")", ";"...
Returns true iff {@code left} and {@code right} are finite values within {@code tolerance} of each other. Note that both this method and {@link #notEqualWithinTolerance} returns false if either {@code left} or {@code right} is infinite or NaN.
[ "Returns", "true", "iff", "{" ]
train
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/core/src/main/java/com/google/common/truth/MathUtil.java#L30-L32
CenturyLinkCloud/mdw
mdw-common/src/com/centurylink/mdw/dataaccess/file/VersionControlGit.java
VersionControlGit.sparseCheckout
public void sparseCheckout(String branch, String path) throws Exception { fetch(); // in case the branch is not known locally hardReset(); checkout(branch); pull(branch); // pull before delete or next pull may add non-path items back // delete non-path items List<File> preserveList = new ArrayList<File>(); preserveList.add(new File(localDir + "/.git")); preserveList.add(new File(localDir + "/" + path)); new Delete(localDir, true).run(); }
java
public void sparseCheckout(String branch, String path) throws Exception { fetch(); // in case the branch is not known locally hardReset(); checkout(branch); pull(branch); // pull before delete or next pull may add non-path items back // delete non-path items List<File> preserveList = new ArrayList<File>(); preserveList.add(new File(localDir + "/.git")); preserveList.add(new File(localDir + "/" + path)); new Delete(localDir, true).run(); }
[ "public", "void", "sparseCheckout", "(", "String", "branch", ",", "String", "path", ")", "throws", "Exception", "{", "fetch", "(", ")", ";", "// in case the branch is not known locally", "hardReset", "(", ")", ";", "checkout", "(", "branch", ")", ";", "pull", ...
Actually a workaround since JGit does not support sparse checkout: https://bugs.eclipse.org/bugs/show_bug.cgi?id=383772. Performs a HARD reset and FORCED checkout then deletes non-path items. Only to be used on server (not Designer).
[ "Actually", "a", "workaround", "since", "JGit", "does", "not", "support", "sparse", "checkout", ":", "https", ":", "//", "bugs", ".", "eclipse", ".", "org", "/", "bugs", "/", "show_bug", ".", "cgi?id", "=", "383772", ".", "Performs", "a", "HARD", "reset"...
train
https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/dataaccess/file/VersionControlGit.java#L365-L376
OpenLiberty/open-liberty
dev/com.ibm.ws.rest.handler/src/com/ibm/wsspi/rest/handler/helper/DefaultRoutingHelper.java
DefaultRoutingHelper.containsRoutingContext
public static boolean containsRoutingContext(RESTRequest request) { if (request.getHeader(RESTHandlerContainer.COLLECTIVE_HOST_NAMES) != null) { return true; } //No routing header found, so check query strings return getQueryParameterValue(request, RESTHandlerContainer.COLLECTIVE_HOST_NAMES) != null; }
java
public static boolean containsRoutingContext(RESTRequest request) { if (request.getHeader(RESTHandlerContainer.COLLECTIVE_HOST_NAMES) != null) { return true; } //No routing header found, so check query strings return getQueryParameterValue(request, RESTHandlerContainer.COLLECTIVE_HOST_NAMES) != null; }
[ "public", "static", "boolean", "containsRoutingContext", "(", "RESTRequest", "request", ")", "{", "if", "(", "request", ".", "getHeader", "(", "RESTHandlerContainer", ".", "COLLECTIVE_HOST_NAMES", ")", "!=", "null", ")", "{", "return", "true", ";", "}", "//No ro...
Quick check for multiple routing context, without actually fetching all pieces
[ "Quick", "check", "for", "multiple", "routing", "context", "without", "actually", "fetching", "all", "pieces" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.rest.handler/src/com/ibm/wsspi/rest/handler/helper/DefaultRoutingHelper.java#L106-L113
aoindustries/aocode-public
src/main/java/com/aoindustries/servlet/http/ServletUtil.java
ServletUtil.resourceExists
@Deprecated public static boolean resourceExists(ServletContext servletContext, HttpServletRequest request, String relativeUrlPath) throws MalformedURLException { return getResource(servletContext, request, relativeUrlPath)!=null; }
java
@Deprecated public static boolean resourceExists(ServletContext servletContext, HttpServletRequest request, String relativeUrlPath) throws MalformedURLException { return getResource(servletContext, request, relativeUrlPath)!=null; }
[ "@", "Deprecated", "public", "static", "boolean", "resourceExists", "(", "ServletContext", "servletContext", ",", "HttpServletRequest", "request", ",", "String", "relativeUrlPath", ")", "throws", "MalformedURLException", "{", "return", "getResource", "(", "servletContext"...
Checks if a resource with the possibly-relative path exists. @deprecated Use regular methods directly @see #getAbsoluteURL(javax.servlet.http.HttpServletRequest, java.lang.String) @see ServletContext#getResource(java.lang.String) @see ServletContextCache#getResource(java.lang.String) @see ServletContextCache#getResource(javax.servlet.ServletContext, java.lang.String)
[ "Checks", "if", "a", "resource", "with", "the", "possibly", "-", "relative", "path", "exists", "." ]
train
https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/servlet/http/ServletUtil.java#L204-L207
eclipse/hawkbit
hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/upload/FileTransferHandlerVaadinUpload.java
FileTransferHandlerVaadinUpload.updateProgress
@Override public void updateProgress(final long readBytes, final long contentLength) { if (readBytes > maxSize || contentLength > maxSize) { LOG.error("User tried to upload more than was allowed ({}).", maxSize); interruptUploadDueToFileSizeExceeded(maxSize); return; } if (isUploadInterrupted()) { // Upload interruption is delayed maybe another event is fired // before return; } publishUploadProgressEvent(fileUploadId, readBytes, contentLength); }
java
@Override public void updateProgress(final long readBytes, final long contentLength) { if (readBytes > maxSize || contentLength > maxSize) { LOG.error("User tried to upload more than was allowed ({}).", maxSize); interruptUploadDueToFileSizeExceeded(maxSize); return; } if (isUploadInterrupted()) { // Upload interruption is delayed maybe another event is fired // before return; } publishUploadProgressEvent(fileUploadId, readBytes, contentLength); }
[ "@", "Override", "public", "void", "updateProgress", "(", "final", "long", "readBytes", ",", "final", "long", "contentLength", ")", "{", "if", "(", "readBytes", ">", "maxSize", "||", "contentLength", ">", "maxSize", ")", "{", "LOG", ".", "error", "(", "\"U...
Reports progress in {@link Upload} variant. @see com.vaadin.ui.Upload.ProgressListener#updateProgress(long, long)
[ "Reports", "progress", "in", "{", "@link", "Upload", "}", "variant", "." ]
train
https://github.com/eclipse/hawkbit/blob/9884452ad42f3b4827461606d8a9215c8625a7fe/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/upload/FileTransferHandlerVaadinUpload.java#L147-L161
aNNiMON/Lightweight-Stream-API
stream/src/main/java/com/annimon/stream/IntStream.java
IntStream.scan
@NotNull public IntStream scan(final int identity, @NotNull final IntBinaryOperator accumulator) { Objects.requireNonNull(accumulator); return new IntStream(params, new IntScanIdentity(iterator, identity, accumulator)); }
java
@NotNull public IntStream scan(final int identity, @NotNull final IntBinaryOperator accumulator) { Objects.requireNonNull(accumulator); return new IntStream(params, new IntScanIdentity(iterator, identity, accumulator)); }
[ "@", "NotNull", "public", "IntStream", "scan", "(", "final", "int", "identity", ",", "@", "NotNull", "final", "IntBinaryOperator", "accumulator", ")", "{", "Objects", ".", "requireNonNull", "(", "accumulator", ")", ";", "return", "new", "IntStream", "(", "para...
Returns a {@code IntStream} produced by iterative application of a accumulation function to an initial element {@code identity} and next element of the current stream. Produces a {@code IntStream} consisting of {@code identity}, {@code acc(identity, value1)}, {@code acc(acc(identity, value1), value2)}, etc. <p>This is an intermediate operation. <p>Example: <pre> identity: 0 accumulator: (a, b) -&gt; a + b stream: [1, 2, 3, 4, 5] result: [0, 1, 3, 6, 10, 15] </pre> @param identity the initial value @param accumulator the accumulation function @return the new stream @throws NullPointerException if {@code accumulator} is null @since 1.1.6
[ "Returns", "a", "{", "@code", "IntStream", "}", "produced", "by", "iterative", "application", "of", "a", "accumulation", "function", "to", "an", "initial", "element", "{", "@code", "identity", "}", "and", "next", "element", "of", "the", "current", "stream", ...
train
https://github.com/aNNiMON/Lightweight-Stream-API/blob/f29fd57208c20252a4549b084d55ed082c3e58f0/stream/src/main/java/com/annimon/stream/IntStream.java#L733-L738
j256/ormlite-core
src/main/java/com/j256/ormlite/stmt/mapped/MappedRefresh.java
MappedRefresh.executeRefresh
public int executeRefresh(DatabaseConnection databaseConnection, T data, ObjectCache objectCache) throws SQLException { @SuppressWarnings("unchecked") ID id = (ID) idField.extractJavaFieldValue(data); // we don't care about the cache here T result = super.execute(databaseConnection, id, null); if (result == null) { return 0; } // copy each field from the result into the passed in object for (FieldType fieldType : resultsFieldTypes) { if (fieldType != idField) { fieldType.assignField(connectionSource, data, fieldType.extractJavaFieldValue(result), false, objectCache); } } return 1; }
java
public int executeRefresh(DatabaseConnection databaseConnection, T data, ObjectCache objectCache) throws SQLException { @SuppressWarnings("unchecked") ID id = (ID) idField.extractJavaFieldValue(data); // we don't care about the cache here T result = super.execute(databaseConnection, id, null); if (result == null) { return 0; } // copy each field from the result into the passed in object for (FieldType fieldType : resultsFieldTypes) { if (fieldType != idField) { fieldType.assignField(connectionSource, data, fieldType.extractJavaFieldValue(result), false, objectCache); } } return 1; }
[ "public", "int", "executeRefresh", "(", "DatabaseConnection", "databaseConnection", ",", "T", "data", ",", "ObjectCache", "objectCache", ")", "throws", "SQLException", "{", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "ID", "id", "=", "(", "ID", ")", "idF...
Execute our refresh query statement and then update all of the fields in data with the fields from the result. @return 1 if we found the object in the table by id or 0 if not.
[ "Execute", "our", "refresh", "query", "statement", "and", "then", "update", "all", "of", "the", "fields", "in", "data", "with", "the", "fields", "from", "the", "result", "." ]
train
https://github.com/j256/ormlite-core/blob/154d85bbb9614a0ea65a012251257831fb4fba21/src/main/java/com/j256/ormlite/stmt/mapped/MappedRefresh.java#L29-L46
liferay/com-liferay-commerce
commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDefinitionLinkPersistenceImpl.java
CPDefinitionLinkPersistenceImpl.removeByUuid_C
@Override public void removeByUuid_C(String uuid, long companyId) { for (CPDefinitionLink cpDefinitionLink : findByUuid_C(uuid, companyId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(cpDefinitionLink); } }
java
@Override public void removeByUuid_C(String uuid, long companyId) { for (CPDefinitionLink cpDefinitionLink : findByUuid_C(uuid, companyId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(cpDefinitionLink); } }
[ "@", "Override", "public", "void", "removeByUuid_C", "(", "String", "uuid", ",", "long", "companyId", ")", "{", "for", "(", "CPDefinitionLink", "cpDefinitionLink", ":", "findByUuid_C", "(", "uuid", ",", "companyId", ",", "QueryUtil", ".", "ALL_POS", ",", "Quer...
Removes all the cp definition links where uuid = &#63; and companyId = &#63; from the database. @param uuid the uuid @param companyId the company ID
[ "Removes", "all", "the", "cp", "definition", "links", "where", "uuid", "=", "&#63", ";", "and", "companyId", "=", "&#63", ";", "from", "the", "database", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDefinitionLinkPersistenceImpl.java#L1403-L1409
apache/incubator-shardingsphere
sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/antlr/rule/jaxb/loader/RuleDefinitionFileConstant.java
RuleDefinitionFileConstant.getFillerRuleDefinitionFileName
public static String getFillerRuleDefinitionFileName(final String rootDir, final DatabaseType databaseType) { return Joiner.on('/').join(rootDir, databaseType.name().toLowerCase(), FILLER_DEFINITION_FILE_NAME); }
java
public static String getFillerRuleDefinitionFileName(final String rootDir, final DatabaseType databaseType) { return Joiner.on('/').join(rootDir, databaseType.name().toLowerCase(), FILLER_DEFINITION_FILE_NAME); }
[ "public", "static", "String", "getFillerRuleDefinitionFileName", "(", "final", "String", "rootDir", ",", "final", "DatabaseType", "databaseType", ")", "{", "return", "Joiner", ".", "on", "(", "'", "'", ")", ".", "join", "(", "rootDir", ",", "databaseType", "."...
Get extractor rule definition file name. @param rootDir root dir @param databaseType database type @return extractor rule definition file name
[ "Get", "extractor", "rule", "definition", "file", "name", "." ]
train
https://github.com/apache/incubator-shardingsphere/blob/f88fd29fc345dfb31fdce12e9e96cbfa0fd2402d/sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/antlr/rule/jaxb/loader/RuleDefinitionFileConstant.java#L76-L78
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/FailoverGroupsInner.java
FailoverGroupsInner.createOrUpdateAsync
public Observable<FailoverGroupInner> createOrUpdateAsync(String resourceGroupName, String serverName, String failoverGroupName, FailoverGroupInner parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, failoverGroupName, parameters).map(new Func1<ServiceResponse<FailoverGroupInner>, FailoverGroupInner>() { @Override public FailoverGroupInner call(ServiceResponse<FailoverGroupInner> response) { return response.body(); } }); }
java
public Observable<FailoverGroupInner> createOrUpdateAsync(String resourceGroupName, String serverName, String failoverGroupName, FailoverGroupInner parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, failoverGroupName, parameters).map(new Func1<ServiceResponse<FailoverGroupInner>, FailoverGroupInner>() { @Override public FailoverGroupInner call(ServiceResponse<FailoverGroupInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "FailoverGroupInner", ">", "createOrUpdateAsync", "(", "String", "resourceGroupName", ",", "String", "serverName", ",", "String", "failoverGroupName", ",", "FailoverGroupInner", "parameters", ")", "{", "return", "createOrUpdateWithServiceRespons...
Creates or updates a failover group. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server containing the failover group. @param failoverGroupName The name of the failover group. @param parameters The failover group parameters. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Creates", "or", "updates", "a", "failover", "group", "." ]
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/FailoverGroupsInner.java#L255-L262
moparisthebest/beehive
beehive-netui-tags/src/main/java/org/apache/beehive/netui/tags/AbstractSimpleTag.java
AbstractSimpleTag.registerTagError
public void registerTagError(String message, Throwable e) throws JspException { ErrorHandling eh = getErrorHandling(); eh.registerTagError(message, getTagName(), this, e); }
java
public void registerTagError(String message, Throwable e) throws JspException { ErrorHandling eh = getErrorHandling(); eh.registerTagError(message, getTagName(), this, e); }
[ "public", "void", "registerTagError", "(", "String", "message", ",", "Throwable", "e", ")", "throws", "JspException", "{", "ErrorHandling", "eh", "=", "getErrorHandling", "(", ")", ";", "eh", ".", "registerTagError", "(", "message", ",", "getTagName", "(", ")"...
This will report an error from a tag. The error will contain a message. If error reporting is turned off, the message will be returned and the caller should throw a JspException to report the error. @param message - the message to register with the error @throws javax.servlet.jsp.JspException - if in-page error reporting is turned off this method will always throw a JspException.
[ "This", "will", "report", "an", "error", "from", "a", "tag", ".", "The", "error", "will", "contain", "a", "message", ".", "If", "error", "reporting", "is", "turned", "off", "the", "message", "will", "be", "returned", "and", "the", "caller", "should", "th...
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-tags/src/main/java/org/apache/beehive/netui/tags/AbstractSimpleTag.java#L179-L184
voldemort/voldemort
src/java/voldemort/store/metadata/MetadataStore.java
MetadataStore.addRebalancingState
public void addRebalancingState(final RebalanceTaskInfo stealInfo) { // acquire write lock writeLock.lock(); try { // Move into rebalancing state if(ByteUtils.getString(get(SERVER_STATE_KEY, null).get(0).getValue(), "UTF-8") .compareTo(VoldemortState.NORMAL_SERVER.toString()) == 0) { put(SERVER_STATE_KEY, VoldemortState.REBALANCING_MASTER_SERVER); initCache(SERVER_STATE_KEY); } // Add the steal information RebalancerState rebalancerState = getRebalancerState(); if(!rebalancerState.update(stealInfo)) { throw new VoldemortException("Could not add steal information " + stealInfo + " since a plan for the same donor node " + stealInfo.getDonorId() + " ( " + rebalancerState.find(stealInfo.getDonorId()) + " ) already exists"); } put(MetadataStore.REBALANCING_STEAL_INFO, rebalancerState); initCache(REBALANCING_STEAL_INFO); } finally { writeLock.unlock(); } }
java
public void addRebalancingState(final RebalanceTaskInfo stealInfo) { // acquire write lock writeLock.lock(); try { // Move into rebalancing state if(ByteUtils.getString(get(SERVER_STATE_KEY, null).get(0).getValue(), "UTF-8") .compareTo(VoldemortState.NORMAL_SERVER.toString()) == 0) { put(SERVER_STATE_KEY, VoldemortState.REBALANCING_MASTER_SERVER); initCache(SERVER_STATE_KEY); } // Add the steal information RebalancerState rebalancerState = getRebalancerState(); if(!rebalancerState.update(stealInfo)) { throw new VoldemortException("Could not add steal information " + stealInfo + " since a plan for the same donor node " + stealInfo.getDonorId() + " ( " + rebalancerState.find(stealInfo.getDonorId()) + " ) already exists"); } put(MetadataStore.REBALANCING_STEAL_INFO, rebalancerState); initCache(REBALANCING_STEAL_INFO); } finally { writeLock.unlock(); } }
[ "public", "void", "addRebalancingState", "(", "final", "RebalanceTaskInfo", "stealInfo", ")", "{", "// acquire write lock", "writeLock", ".", "lock", "(", ")", ";", "try", "{", "// Move into rebalancing state", "if", "(", "ByteUtils", ".", "getString", "(", "get", ...
Add the steal information to the rebalancer state @param stealInfo The steal information to add
[ "Add", "the", "steal", "information", "to", "the", "rebalancer", "state" ]
train
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/metadata/MetadataStore.java#L896-L921
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/UCharacterName.java
UCharacterName.getGroupChar
private synchronized int getGroupChar(String name, int choice) { for (int i = 0; i < m_groupcount_; i ++) { // populating the data set of grouptable int startgpstrindex = getGroupLengths(i, m_groupoffsets_, m_grouplengths_); // shift out to function int result = getGroupChar(startgpstrindex, m_grouplengths_, name, choice); if (result != -1) { return (m_groupinfo_[i * m_groupsize_] << GROUP_SHIFT_) | result; } } return -1; }
java
private synchronized int getGroupChar(String name, int choice) { for (int i = 0; i < m_groupcount_; i ++) { // populating the data set of grouptable int startgpstrindex = getGroupLengths(i, m_groupoffsets_, m_grouplengths_); // shift out to function int result = getGroupChar(startgpstrindex, m_grouplengths_, name, choice); if (result != -1) { return (m_groupinfo_[i * m_groupsize_] << GROUP_SHIFT_) | result; } } return -1; }
[ "private", "synchronized", "int", "getGroupChar", "(", "String", "name", ",", "int", "choice", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "m_groupcount_", ";", "i", "++", ")", "{", "// populating the data set of grouptable", "int", "startgpst...
Getting the character with the tokenized argument name @param name of the character @return character with the tokenized argument name or -1 if character is not found
[ "Getting", "the", "character", "with", "the", "tokenized", "argument", "name" ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/UCharacterName.java#L1213-L1230
Pi4J/pi4j
pi4j-device/src/main/java/com/pi4j/component/potentiometer/microchip/impl/MicrochipPotentiometerDeviceController.java
MicrochipPotentiometerDeviceController.getValue
public int getValue(final DeviceControllerChannel channel, final boolean nonVolatile) throws IOException { if (channel == null) { throw new RuntimeException("null-channel is not allowed. For devices " + "knowing just one wiper Channel.A is mandatory for " + "parameter 'channel'"); } // choose proper memory address (see TABLE 4-1) byte memAddr = nonVolatile ? channel.getNonVolatileMemoryAddress() : channel.getVolatileMemoryAddress(); // read current value int currentValue = read(memAddr); return currentValue; }
java
public int getValue(final DeviceControllerChannel channel, final boolean nonVolatile) throws IOException { if (channel == null) { throw new RuntimeException("null-channel is not allowed. For devices " + "knowing just one wiper Channel.A is mandatory for " + "parameter 'channel'"); } // choose proper memory address (see TABLE 4-1) byte memAddr = nonVolatile ? channel.getNonVolatileMemoryAddress() : channel.getVolatileMemoryAddress(); // read current value int currentValue = read(memAddr); return currentValue; }
[ "public", "int", "getValue", "(", "final", "DeviceControllerChannel", "channel", ",", "final", "boolean", "nonVolatile", ")", "throws", "IOException", "{", "if", "(", "channel", "==", "null", ")", "{", "throw", "new", "RuntimeException", "(", "\"null-channel is no...
Receives the current wiper's value from the device. @param channel Which wiper @param nonVolatile volatile or non-volatile value @return The wiper's value @throws IOException Thrown if communication fails or device returned a malformed result
[ "Receives", "the", "current", "wiper", "s", "value", "from", "the", "device", "." ]
train
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-device/src/main/java/com/pi4j/component/potentiometer/microchip/impl/MicrochipPotentiometerDeviceController.java#L205-L224
OpenLiberty/open-liberty
dev/com.ibm.ws.event/src/com/ibm/ws/event/internal/TopicBasedCache.java
TopicBasedCache.setStageTopics
synchronized void setStageTopics(String stageName, String[] topics) { for (String t : topics) { if (t.equals("*")) { wildcardStageTopics.put("", stageName); } else if (t.endsWith("/*")) { wildcardStageTopics.put(t.substring(0, t.length() - 1), stageName); } else { discreteStageTopics.put(t, stageName); } } // Clear the cache since it's no longer up to date clearTopicDataCache(); }
java
synchronized void setStageTopics(String stageName, String[] topics) { for (String t : topics) { if (t.equals("*")) { wildcardStageTopics.put("", stageName); } else if (t.endsWith("/*")) { wildcardStageTopics.put(t.substring(0, t.length() - 1), stageName); } else { discreteStageTopics.put(t, stageName); } } // Clear the cache since it's no longer up to date clearTopicDataCache(); }
[ "synchronized", "void", "setStageTopics", "(", "String", "stageName", ",", "String", "[", "]", "topics", ")", "{", "for", "(", "String", "t", ":", "topics", ")", "{", "if", "(", "t", ".", "equals", "(", "\"*\"", ")", ")", "{", "wildcardStageTopics", "....
Set the list of topics to be associated with the specified work stage. @param stageName the work stage name @param topics the topics associated with the work stage
[ "Set", "the", "list", "of", "topics", "to", "be", "associated", "with", "the", "specified", "work", "stage", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.event/src/com/ibm/ws/event/internal/TopicBasedCache.java#L95-L108
salesforce/Argus
ArgusCore/src/main/java/com/salesforce/dva/argus/service/alert/notifier/AuditNotifier.java
AuditNotifier.getTriggerDetails
protected String getTriggerDetails(Trigger trigger, NotificationContext context) { if (trigger != null) { String triggerString = trigger.toString(); triggerString = TemplateReplacer.applyTemplateChanges(context, triggerString); return triggerString.substring(triggerString.indexOf("{") + 1, triggerString.indexOf("}")); } else { return ""; } }
java
protected String getTriggerDetails(Trigger trigger, NotificationContext context) { if (trigger != null) { String triggerString = trigger.toString(); triggerString = TemplateReplacer.applyTemplateChanges(context, triggerString); return triggerString.substring(triggerString.indexOf("{") + 1, triggerString.indexOf("}")); } else { return ""; } }
[ "protected", "String", "getTriggerDetails", "(", "Trigger", "trigger", ",", "NotificationContext", "context", ")", "{", "if", "(", "trigger", "!=", "null", ")", "{", "String", "triggerString", "=", "trigger", ".", "toString", "(", ")", ";", "triggerString", "=...
Returns the trigger detail information. @param trigger The source trigger. @return The trigger detail information.
[ "Returns", "the", "trigger", "detail", "information", "." ]
train
https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/service/alert/notifier/AuditNotifier.java#L198-L207
baasbox/Android-SDK
library/src/main/java/com/baasbox/android/BaasACL.java
BaasACL.hasUserGrant
public boolean hasUserGrant(Grant grant,String username){ if (grant == null) throw new IllegalArgumentException("grant cannot be null"); if (username==null) throw new IllegalArgumentException("username cannot be null"); Set<String> users = userGrants.get(grant); return users!=null &&users.contains(username); }
java
public boolean hasUserGrant(Grant grant,String username){ if (grant == null) throw new IllegalArgumentException("grant cannot be null"); if (username==null) throw new IllegalArgumentException("username cannot be null"); Set<String> users = userGrants.get(grant); return users!=null &&users.contains(username); }
[ "public", "boolean", "hasUserGrant", "(", "Grant", "grant", ",", "String", "username", ")", "{", "if", "(", "grant", "==", "null", ")", "throw", "new", "IllegalArgumentException", "(", "\"grant cannot be null\"", ")", ";", "if", "(", "username", "==", "null", ...
Checks if the user with {@code username} has the specified {@code grant} @param grant a {@link com.baasbox.android.Grant} @param username a username @return
[ "Checks", "if", "the", "user", "with", "{" ]
train
https://github.com/baasbox/Android-SDK/blob/6bb2203246b885b2ad63a7bfaf37c83caf15e0d8/library/src/main/java/com/baasbox/android/BaasACL.java#L101-L106
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/nio/SerializationClassNameFilter.java
SerializationClassNameFilter.filter
public void filter(String className) throws SecurityException { if (blacklist.isListed(className)) { throw new SecurityException(format(DESERIALIZATION_ERROR, className)); } // if whitelisting is enabled (either explicit or as a default whitelist), force the whitelist check if (useDefaultWhitelist || !whitelist.isEmpty()) { if (whitelist.isListed(className) || (useDefaultWhitelist && DEFAULT_WHITELIST.isListed(className))) { return; } throw new SecurityException(format(DESERIALIZATION_ERROR, className)); } }
java
public void filter(String className) throws SecurityException { if (blacklist.isListed(className)) { throw new SecurityException(format(DESERIALIZATION_ERROR, className)); } // if whitelisting is enabled (either explicit or as a default whitelist), force the whitelist check if (useDefaultWhitelist || !whitelist.isEmpty()) { if (whitelist.isListed(className) || (useDefaultWhitelist && DEFAULT_WHITELIST.isListed(className))) { return; } throw new SecurityException(format(DESERIALIZATION_ERROR, className)); } }
[ "public", "void", "filter", "(", "String", "className", ")", "throws", "SecurityException", "{", "if", "(", "blacklist", ".", "isListed", "(", "className", ")", ")", "{", "throw", "new", "SecurityException", "(", "format", "(", "DESERIALIZATION_ERROR", ",", "c...
Throws {@link SecurityException} if the given class name appears on the blacklist or does not appear a whitelist. @param className class name to check @throws SecurityException if the classname is not allowed for deserialization
[ "Throws", "{", "@link", "SecurityException", "}", "if", "the", "given", "class", "name", "appears", "on", "the", "blacklist", "or", "does", "not", "appear", "a", "whitelist", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/nio/SerializationClassNameFilter.java#L53-L65
Ordinastie/MalisisCore
src/main/java/net/malisis/core/block/component/DirectionalComponent.java
DirectionalComponent.setDefaultState
@Override public IBlockState setDefaultState(Block block, IBlockState state) { return state.withProperty(getProperty(), EnumFacing.SOUTH); }
java
@Override public IBlockState setDefaultState(Block block, IBlockState state) { return state.withProperty(getProperty(), EnumFacing.SOUTH); }
[ "@", "Override", "public", "IBlockState", "setDefaultState", "(", "Block", "block", ",", "IBlockState", "state", ")", "{", "return", "state", ".", "withProperty", "(", "getProperty", "(", ")", ",", "EnumFacing", ".", "SOUTH", ")", ";", "}" ]
Sets the default value to use for the {@link IBlockState}. @param block the block @param state the state @return the i block state
[ "Sets", "the", "default", "value", "to", "use", "for", "the", "{", "@link", "IBlockState", "}", "." ]
train
https://github.com/Ordinastie/MalisisCore/blob/4f8e1fa462d5c372fc23414482ba9f429881cc54/src/main/java/net/malisis/core/block/component/DirectionalComponent.java#L118-L122
CenturyLinkCloud/clc-java-sdk
sdk/src/main/java/com/centurylink/cloud/sdk/server/services/dsl/GroupService.java
GroupService.updateGroup
private boolean updateGroup(String groupId, GroupConfig groupConfig) { return client .updateGroup( groupId, converter.createUpdateGroupRequest( groupConfig, groupConfig.getParentGroup() != null ? idByRef(groupConfig.getParentGroup()) : null, groupConfig.getCustomFields() == null || groupConfig.getCustomFields().size() == 0 ? null : client.getCustomFields()) ); }
java
private boolean updateGroup(String groupId, GroupConfig groupConfig) { return client .updateGroup( groupId, converter.createUpdateGroupRequest( groupConfig, groupConfig.getParentGroup() != null ? idByRef(groupConfig.getParentGroup()) : null, groupConfig.getCustomFields() == null || groupConfig.getCustomFields().size() == 0 ? null : client.getCustomFields()) ); }
[ "private", "boolean", "updateGroup", "(", "String", "groupId", ",", "GroupConfig", "groupConfig", ")", "{", "return", "client", ".", "updateGroup", "(", "groupId", ",", "converter", ".", "createUpdateGroupRequest", "(", "groupConfig", ",", "groupConfig", ".", "get...
Update group @param groupId group id to update @param groupConfig group config @return <tt>true</tt> if update was successful, <br/> <tt>false</tt> otherwise
[ "Update", "group" ]
train
https://github.com/CenturyLinkCloud/clc-java-sdk/blob/c026322f077dea71b1acf9f2d665253d79d9bf85/sdk/src/main/java/com/centurylink/cloud/sdk/server/services/dsl/GroupService.java#L356-L366
betfair/cougar
cougar-framework/socket-transport/src/main/java/com/betfair/cougar/transport/nio/ApplicationHealthMonitor.java
ApplicationHealthMonitor.startActiveMonitoring
private void startActiveMonitoring(final StatusAggregator aggregator) { log.info("Starting application health monitoring in ACTIVE mode"); ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = new Thread(r,"SocketTransport App Health Monitor"); t.setDaemon(true); return t; } }); executor.scheduleWithFixedDelay(new Runnable() { @Override public void run() { try { boolean healthy = !Status.FAIL.equals(aggregator.getStatus()); setStatus(healthy ? Status.OK : Status.FAIL); } catch (Exception e) { log.warn("Error whilst setting health status",e); } } }, monitorInterval, monitorInterval, TimeUnit.MILLISECONDS); }
java
private void startActiveMonitoring(final StatusAggregator aggregator) { log.info("Starting application health monitoring in ACTIVE mode"); ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = new Thread(r,"SocketTransport App Health Monitor"); t.setDaemon(true); return t; } }); executor.scheduleWithFixedDelay(new Runnable() { @Override public void run() { try { boolean healthy = !Status.FAIL.equals(aggregator.getStatus()); setStatus(healthy ? Status.OK : Status.FAIL); } catch (Exception e) { log.warn("Error whilst setting health status",e); } } }, monitorInterval, monitorInterval, TimeUnit.MILLISECONDS); }
[ "private", "void", "startActiveMonitoring", "(", "final", "StatusAggregator", "aggregator", ")", "{", "log", ".", "info", "(", "\"Starting application health monitoring in ACTIVE mode\"", ")", ";", "ScheduledExecutorService", "executor", "=", "Executors", ".", "newSingleThr...
Start a new thread and periodically poll all status aggregators for their current status </p> Calculate a new status where newStatus = healthy if all aggregator's status = healthy
[ "Start", "a", "new", "thread", "and", "periodically", "poll", "all", "status", "aggregators", "for", "their", "current", "status", "<", "/", "p", ">", "Calculate", "a", "new", "status", "where", "newStatus", "=", "healthy", "if", "all", "aggregator", "s", ...
train
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/socket-transport/src/main/java/com/betfair/cougar/transport/nio/ApplicationHealthMonitor.java#L132-L160
spotbugs/spotbugs
spotbugs/src/main/java/edu/umd/cs/findbugs/ba/CFG.java
CFG.getSuccessorWithEdgeType
public BasicBlock getSuccessorWithEdgeType(BasicBlock source, @Type int edgeType) { Edge edge = getOutgoingEdgeWithType(source, edgeType); return edge != null ? edge.getTarget() : null; }
java
public BasicBlock getSuccessorWithEdgeType(BasicBlock source, @Type int edgeType) { Edge edge = getOutgoingEdgeWithType(source, edgeType); return edge != null ? edge.getTarget() : null; }
[ "public", "BasicBlock", "getSuccessorWithEdgeType", "(", "BasicBlock", "source", ",", "@", "Type", "int", "edgeType", ")", "{", "Edge", "edge", "=", "getOutgoingEdgeWithType", "(", "source", ",", "edgeType", ")", ";", "return", "edge", "!=", "null", "?", "edge...
Get the first successor reachable from given edge type. @param source the source block @param edgeType the edge type leading to the successor @return the successor, or null if there is no outgoing edge with the specified edge type
[ "Get", "the", "first", "successor", "reachable", "from", "given", "edge", "type", "." ]
train
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/ba/CFG.java#L427-L430
briandilley/jsonrpc4j
src/main/java/com/googlecode/jsonrpc4j/JsonRpcBasicServer.java
JsonRpcBasicServer.findBestMethodUsingParamIndexes
private AMethodWithItsArgs findBestMethodUsingParamIndexes(Set<Method> methods, int paramCount, ArrayNode paramNodes) { int numParams = isNullNodeOrValue(paramNodes) ? 0 : paramNodes.size(); int bestParamNumDiff = Integer.MAX_VALUE; Set<Method> matchedMethods = collectMethodsMatchingParamCount(methods, paramCount, bestParamNumDiff); if (matchedMethods.isEmpty()) { return null; } Method bestMethod = getBestMatchingArgTypeMethod(paramNodes, numParams, matchedMethods); return new AMethodWithItsArgs(bestMethod, paramCount, paramNodes); }
java
private AMethodWithItsArgs findBestMethodUsingParamIndexes(Set<Method> methods, int paramCount, ArrayNode paramNodes) { int numParams = isNullNodeOrValue(paramNodes) ? 0 : paramNodes.size(); int bestParamNumDiff = Integer.MAX_VALUE; Set<Method> matchedMethods = collectMethodsMatchingParamCount(methods, paramCount, bestParamNumDiff); if (matchedMethods.isEmpty()) { return null; } Method bestMethod = getBestMatchingArgTypeMethod(paramNodes, numParams, matchedMethods); return new AMethodWithItsArgs(bestMethod, paramCount, paramNodes); }
[ "private", "AMethodWithItsArgs", "findBestMethodUsingParamIndexes", "(", "Set", "<", "Method", ">", "methods", ",", "int", "paramCount", ",", "ArrayNode", "paramNodes", ")", "{", "int", "numParams", "=", "isNullNodeOrValue", "(", "paramNodes", ")", "?", "0", ":", ...
Finds the {@link Method} from the supplied {@link Set} that best matches the rest of the arguments supplied and returns it as a {@link AMethodWithItsArgs} class. @param methods the {@link Method}s @param paramCount the number of expect parameters @param paramNodes the parameters for matching types @return the {@link AMethodWithItsArgs}
[ "Finds", "the", "{", "@link", "Method", "}", "from", "the", "supplied", "{", "@link", "Set", "}", "that", "best", "matches", "the", "rest", "of", "the", "arguments", "supplied", "and", "returns", "it", "as", "a", "{", "@link", "AMethodWithItsArgs", "}", ...
train
https://github.com/briandilley/jsonrpc4j/blob/d749762c9295b92d893677a8c7be2a14dd43b3bb/src/main/java/com/googlecode/jsonrpc4j/JsonRpcBasicServer.java#L659-L668
imsweb/naaccr-xml
src/main/java/com/imsweb/naaccrxml/sas/SasUtils.java
SasUtils.getFields
public static List<SasFieldInfo> getFields(String version, String recordType, File dictionary) { return getFields(recordType, Thread.currentThread().getContextClassLoader().getResourceAsStream("naaccr-xml-items-" + version + ".csv"), dictionary); }
java
public static List<SasFieldInfo> getFields(String version, String recordType, File dictionary) { return getFields(recordType, Thread.currentThread().getContextClassLoader().getResourceAsStream("naaccr-xml-items-" + version + ".csv"), dictionary); }
[ "public", "static", "List", "<", "SasFieldInfo", ">", "getFields", "(", "String", "version", ",", "String", "recordType", ",", "File", "dictionary", ")", "{", "return", "getFields", "(", "recordType", ",", "Thread", ".", "currentThread", "(", ")", ".", "getC...
Returns the fields information for the given parameters. @param version NAACCR version @param recordType record type @param dictionary user-defined dictionary in CSV format (see standard ones in docs folder) @return fields information
[ "Returns", "the", "fields", "information", "for", "the", "given", "parameters", "." ]
train
https://github.com/imsweb/naaccr-xml/blob/a3a501faa2a0c3411dd5248b2c1379f279131696/src/main/java/com/imsweb/naaccrxml/sas/SasUtils.java#L64-L66
pippo-java/pippo
pippo-controller-parent/pippo-spring/src/main/java/ro/pippo/spring/SpringControllerFactory.java
SpringControllerFactory.createBeanDefinition
protected BeanDefinition createBeanDefinition(Class<? extends Controller> controllerClass) { // optionally configure all bean properties, like scope, prototype/singleton, etc // return new RootBeanDefinition(beanClass); return new RootBeanDefinition(controllerClass, Autowire.BY_TYPE.value(), true); }
java
protected BeanDefinition createBeanDefinition(Class<? extends Controller> controllerClass) { // optionally configure all bean properties, like scope, prototype/singleton, etc // return new RootBeanDefinition(beanClass); return new RootBeanDefinition(controllerClass, Autowire.BY_TYPE.value(), true); }
[ "protected", "BeanDefinition", "createBeanDefinition", "(", "Class", "<", "?", "extends", "Controller", ">", "controllerClass", ")", "{", "// optionally configure all bean properties, like scope, prototype/singleton, etc", "// return new RootBeanDefinition(beanClass);", "return"...
Created a bean definition for a class. Optionally configure all bean properties, like scope, prototype/singleton, etc using: <p/> <pre> BeanDefinition definition = super.createBeanDefinition(beanClass); definition.setScope(BeanDefinition.SCOPE_SINGLETON); return definition; </pre> @param controllerClass @return
[ "Created", "a", "bean", "definition", "for", "a", "class", ".", "Optionally", "configure", "all", "bean", "properties", "like", "scope", "prototype", "/", "singleton", "etc", "using", ":", "<p", "/", ">", "<pre", ">", "BeanDefinition", "definition", "=", "su...
train
https://github.com/pippo-java/pippo/blob/cb5ccb453bffcc3cf386adc660674812d10b9726/pippo-controller-parent/pippo-spring/src/main/java/ro/pippo/spring/SpringControllerFactory.java#L81-L85
Impetus/Kundera
src/kundera-couchbase/src/main/java/com/impetus/client/couchbase/CouchbaseBucketUtils.java
CouchbaseBucketUtils.openBucket
public static Bucket openBucket(CouchbaseCluster cluster, String name, String password) { if (cluster == null) { throw new KunderaException("CouchbaseCluster object can't be null"); } try { Bucket bucket; if (password != null && !password.trim().isEmpty()) { bucket = cluster.openBucket(name, password); } else { bucket = cluster.openBucket(name); } LOGGER.debug("Bucket [" + name + "] is opened!"); return bucket; } catch (CouchbaseException ex) { LOGGER.error("Not able to open bucket [" + name + "].", ex); throw new KunderaException("Not able to open bucket [" + name + "].", ex); } }
java
public static Bucket openBucket(CouchbaseCluster cluster, String name, String password) { if (cluster == null) { throw new KunderaException("CouchbaseCluster object can't be null"); } try { Bucket bucket; if (password != null && !password.trim().isEmpty()) { bucket = cluster.openBucket(name, password); } else { bucket = cluster.openBucket(name); } LOGGER.debug("Bucket [" + name + "] is opened!"); return bucket; } catch (CouchbaseException ex) { LOGGER.error("Not able to open bucket [" + name + "].", ex); throw new KunderaException("Not able to open bucket [" + name + "].", ex); } }
[ "public", "static", "Bucket", "openBucket", "(", "CouchbaseCluster", "cluster", ",", "String", "name", ",", "String", "password", ")", "{", "if", "(", "cluster", "==", "null", ")", "{", "throw", "new", "KunderaException", "(", "\"CouchbaseCluster object can't be n...
Open bucket. @param cluster the cluster @param name the name @param password the password @return the bucket
[ "Open", "bucket", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-couchbase/src/main/java/com/impetus/client/couchbase/CouchbaseBucketUtils.java#L41-L67
webmetrics/browsermob-proxy
src/main/java/org/browsermob/proxy/jetty/util/LazyList.java
LazyList.getList
public static List getList(Object list, boolean nullForEmpty) { if (list==null) return nullForEmpty?null:Collections.EMPTY_LIST; if (list instanceof List) return (List)list; List l = new ArrayList(1); l.add(list); return l; }
java
public static List getList(Object list, boolean nullForEmpty) { if (list==null) return nullForEmpty?null:Collections.EMPTY_LIST; if (list instanceof List) return (List)list; List l = new ArrayList(1); l.add(list); return l; }
[ "public", "static", "List", "getList", "(", "Object", "list", ",", "boolean", "nullForEmpty", ")", "{", "if", "(", "list", "==", "null", ")", "return", "nullForEmpty", "?", "null", ":", "Collections", ".", "EMPTY_LIST", ";", "if", "(", "list", "instanceof"...
Get the real List from a LazyList. @param list A LazyList returned from LazyList.add(Object) or null @param nullForEmpty If true, null is returned instead of an empty list. @return The List of added items, which may be null, an EMPTY_LIST or a SingletonList.
[ "Get", "the", "real", "List", "from", "a", "LazyList", "." ]
train
https://github.com/webmetrics/browsermob-proxy/blob/a9252e62246ac33d55d51b993ba1159404e7d389/src/main/java/org/browsermob/proxy/jetty/util/LazyList.java#L225-L235
alkacon/opencms-core
src/org/opencms/db/generic/CmsUserDriver.java
CmsUserDriver.internalWriteOrgUnitProperty
protected void internalWriteOrgUnitProperty(CmsDbContext dbc, CmsResource resource, CmsProperty property) throws CmsException { CmsUUID projectId = ((dbc.getProjectId() == null) || dbc.getProjectId().isNullUUID()) ? dbc.currentProject().getUuid() : dbc.getProjectId(); // write the property m_driverManager.writePropertyObject(dbc, resource, property); resource.setState(CmsResource.STATE_UNCHANGED); m_driverManager.getVfsDriver(dbc).writeResource(dbc, projectId, resource, CmsDriverManager.NOTHING_CHANGED); // online persistence CmsProject project = dbc.currentProject(); dbc.getRequestContext().setCurrentProject(m_driverManager.readProject(dbc, CmsProject.ONLINE_PROJECT_ID)); try { m_driverManager.writePropertyObject(dbc, resource, property); // assume the resource is identical in both projects resource.setState(CmsResource.STATE_UNCHANGED); m_driverManager.getVfsDriver( dbc).writeResource(dbc, dbc.currentProject().getUuid(), resource, CmsDriverManager.NOTHING_CHANGED); } finally { dbc.getRequestContext().setCurrentProject(project); } }
java
protected void internalWriteOrgUnitProperty(CmsDbContext dbc, CmsResource resource, CmsProperty property) throws CmsException { CmsUUID projectId = ((dbc.getProjectId() == null) || dbc.getProjectId().isNullUUID()) ? dbc.currentProject().getUuid() : dbc.getProjectId(); // write the property m_driverManager.writePropertyObject(dbc, resource, property); resource.setState(CmsResource.STATE_UNCHANGED); m_driverManager.getVfsDriver(dbc).writeResource(dbc, projectId, resource, CmsDriverManager.NOTHING_CHANGED); // online persistence CmsProject project = dbc.currentProject(); dbc.getRequestContext().setCurrentProject(m_driverManager.readProject(dbc, CmsProject.ONLINE_PROJECT_ID)); try { m_driverManager.writePropertyObject(dbc, resource, property); // assume the resource is identical in both projects resource.setState(CmsResource.STATE_UNCHANGED); m_driverManager.getVfsDriver( dbc).writeResource(dbc, dbc.currentProject().getUuid(), resource, CmsDriverManager.NOTHING_CHANGED); } finally { dbc.getRequestContext().setCurrentProject(project); } }
[ "protected", "void", "internalWriteOrgUnitProperty", "(", "CmsDbContext", "dbc", ",", "CmsResource", "resource", ",", "CmsProperty", "property", ")", "throws", "CmsException", "{", "CmsUUID", "projectId", "=", "(", "(", "dbc", ".", "getProjectId", "(", ")", "==", ...
Writes a property for an organizational unit resource, online AND offline.<p> @param dbc the current database context @param resource the resource representing the organizational unit @param property the property to write @throws CmsException if something goes wrong
[ "Writes", "a", "property", "for", "an", "organizational", "unit", "resource", "online", "AND", "offline", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/generic/CmsUserDriver.java#L2924-L2946
SonarSource/sonarqube
server/sonar-process/src/main/java/org/sonar/process/FileUtils2.java
FileUtils2.deleteDirectory
public static void deleteDirectory(File directory) throws IOException { requireNonNull(directory, DIRECTORY_CAN_NOT_BE_NULL); if (!directory.exists()) { return; } Path path = directory.toPath(); if (Files.isSymbolicLink(path)) { throw new IOException(format("Directory '%s' is a symbolic link", directory)); } if (directory.isFile()) { throw new IOException(format("Directory '%s' is a file", directory)); } deleteDirectoryImpl(path); if (directory.exists()) { throw new IOException(format("Unable to delete directory '%s'", directory)); } }
java
public static void deleteDirectory(File directory) throws IOException { requireNonNull(directory, DIRECTORY_CAN_NOT_BE_NULL); if (!directory.exists()) { return; } Path path = directory.toPath(); if (Files.isSymbolicLink(path)) { throw new IOException(format("Directory '%s' is a symbolic link", directory)); } if (directory.isFile()) { throw new IOException(format("Directory '%s' is a file", directory)); } deleteDirectoryImpl(path); if (directory.exists()) { throw new IOException(format("Unable to delete directory '%s'", directory)); } }
[ "public", "static", "void", "deleteDirectory", "(", "File", "directory", ")", "throws", "IOException", "{", "requireNonNull", "(", "directory", ",", "DIRECTORY_CAN_NOT_BE_NULL", ")", ";", "if", "(", "!", "directory", ".", "exists", "(", ")", ")", "{", "return"...
Deletes a directory recursively. Does not support symbolic link to directories. @param directory directory to delete @throws IOException in case deletion is unsuccessful
[ "Deletes", "a", "directory", "recursively", ".", "Does", "not", "support", "symbolic", "link", "to", "directories", "." ]
train
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/server/sonar-process/src/main/java/org/sonar/process/FileUtils2.java#L98-L117
tempodb/tempodb-java
src/main/java/com/tempodb/Client.java
Client.readDataPoints
public Cursor<DataPoint> readDataPoints(Filter filter, Interval interval, Aggregation aggregation) { return readDataPoints(filter, interval, DateTimeZone.getDefault(), aggregation, null, null); }
java
public Cursor<DataPoint> readDataPoints(Filter filter, Interval interval, Aggregation aggregation) { return readDataPoints(filter, interval, DateTimeZone.getDefault(), aggregation, null, null); }
[ "public", "Cursor", "<", "DataPoint", ">", "readDataPoints", "(", "Filter", "filter", ",", "Interval", "interval", ",", "Aggregation", "aggregation", ")", "{", "return", "readDataPoints", "(", "filter", ",", "interval", ",", "DateTimeZone", ".", "getDefault", "(...
Returns a cursor of datapoints specified by a series filter. <p>This endpoint allows one to request multiple series and apply an aggregation function. The system default timezone is used for the returned DateTimes. @param filter The series filter @param interval An interval of time for the query (start/end datetimes) @param aggregation The aggregation for the read query. This is required. @return A Cursor of DataPoints. The cursor.iterator().next() may throw a {@link TempoDBException} if an error occurs while making a request. @see Aggregation @see Cursor @see Filter @since 1.0.0
[ "Returns", "a", "cursor", "of", "datapoints", "specified", "by", "a", "series", "filter", "." ]
train
https://github.com/tempodb/tempodb-java/blob/5733f204fe4c8dda48916ba1f67cf44f5a3f9c69/src/main/java/com/tempodb/Client.java#L764-L766
iipc/openwayback
wayback-core/src/main/java/org/archive/wayback/util/ByteOp.java
ByteOp.discardStreamCount
public static long discardStreamCount(InputStream is,int size) throws IOException { long count = 0; byte[] buffer = new byte[size]; int amt = 0; while((amt = is.read(buffer, 0, size)) != -1) { count += amt; } return count; }
java
public static long discardStreamCount(InputStream is,int size) throws IOException { long count = 0; byte[] buffer = new byte[size]; int amt = 0; while((amt = is.read(buffer, 0, size)) != -1) { count += amt; } return count; }
[ "public", "static", "long", "discardStreamCount", "(", "InputStream", "is", ",", "int", "size", ")", "throws", "IOException", "{", "long", "count", "=", "0", ";", "byte", "[", "]", "buffer", "=", "new", "byte", "[", "size", "]", ";", "int", "amt", "=",...
throw away all bytes from stream argument, and count how many bytes were discarded before reaching the end of the stream. @param is InputStream to read and discard @param size number of bytes to read at once from the stream @return the number of bytes discarded @throws IOException when is throws one
[ "throw", "away", "all", "bytes", "from", "stream", "argument", "and", "count", "how", "many", "bytes", "were", "discarded", "before", "reaching", "the", "end", "of", "the", "stream", "." ]
train
https://github.com/iipc/openwayback/blob/da74c3a59a5b5a5c365bd4702dcb45d263535794/wayback-core/src/main/java/org/archive/wayback/util/ByteOp.java#L113-L121
CloudSlang/cs-actions
cs-utilities/src/main/java/io/cloudslang/content/utilities/actions/FindTextInPdf.java
FindTextInPdf.execute
@Action(name = "Find Text in PDF", description = FIND_TEXT_IN_PDF_OPERATION_DESC, outputs = { @Output(value = RETURN_CODE, description = RETURN_CODE_DESC), @Output(value = RETURN_RESULT, description = FIND_TEXT_IN_PDF_RETURN_RESULT_DESC), @Output(value = EXCEPTION, description = EXCEPTION_DESC), }, responses = { @Response(text = SUCCESS, field = RETURN_CODE, value = ReturnCodes.SUCCESS, matchType = COMPARE_EQUAL, responseType = RESOLVED, description = SUCCESS_DESC), @Response(text = FAILURE, field = RETURN_CODE, value = ReturnCodes.FAILURE, matchType = COMPARE_EQUAL, responseType = ERROR, isOnFail = true, description = FAILURE_DESC) }) public Map<String, String> execute( @Param(value = TEXT, required = true, description = INITIAL_VALUE_DESC) String text, @Param(value = IGNORE_CASE, description = IGNORE_CASE_DESC) String ignoreCase, @Param(value = PATH_TO_FILE, required = true, description = DEFAULT_VALUE_DESC) String pathToFile, @Param(value = PASSWORD, description = PASSWORD_DESC, encrypted = true) String password) { try { final Path path = Paths.get(pathToFile); final String pdfPassword = defaultIfEmpty(password, EMPTY); final String pdfContent = PdfParseService.getPdfContent(path, pdfPassword).trim().replace(System.lineSeparator(), EMPTY); final boolean validIgnoreCase = BooleanUtilities.isValid(ignoreCase); if (!validIgnoreCase) { throw new RuntimeException(format("Invalid boolean value for ignoreCase parameter: %s", ignoreCase)); } return getSuccessResultsMap(PdfParseService.getOccurrences(pdfContent, text, toBoolean(ignoreCase))); } catch (Exception e) { return getFailureResultsMap(e); } }
java
@Action(name = "Find Text in PDF", description = FIND_TEXT_IN_PDF_OPERATION_DESC, outputs = { @Output(value = RETURN_CODE, description = RETURN_CODE_DESC), @Output(value = RETURN_RESULT, description = FIND_TEXT_IN_PDF_RETURN_RESULT_DESC), @Output(value = EXCEPTION, description = EXCEPTION_DESC), }, responses = { @Response(text = SUCCESS, field = RETURN_CODE, value = ReturnCodes.SUCCESS, matchType = COMPARE_EQUAL, responseType = RESOLVED, description = SUCCESS_DESC), @Response(text = FAILURE, field = RETURN_CODE, value = ReturnCodes.FAILURE, matchType = COMPARE_EQUAL, responseType = ERROR, isOnFail = true, description = FAILURE_DESC) }) public Map<String, String> execute( @Param(value = TEXT, required = true, description = INITIAL_VALUE_DESC) String text, @Param(value = IGNORE_CASE, description = IGNORE_CASE_DESC) String ignoreCase, @Param(value = PATH_TO_FILE, required = true, description = DEFAULT_VALUE_DESC) String pathToFile, @Param(value = PASSWORD, description = PASSWORD_DESC, encrypted = true) String password) { try { final Path path = Paths.get(pathToFile); final String pdfPassword = defaultIfEmpty(password, EMPTY); final String pdfContent = PdfParseService.getPdfContent(path, pdfPassword).trim().replace(System.lineSeparator(), EMPTY); final boolean validIgnoreCase = BooleanUtilities.isValid(ignoreCase); if (!validIgnoreCase) { throw new RuntimeException(format("Invalid boolean value for ignoreCase parameter: %s", ignoreCase)); } return getSuccessResultsMap(PdfParseService.getOccurrences(pdfContent, text, toBoolean(ignoreCase))); } catch (Exception e) { return getFailureResultsMap(e); } }
[ "@", "Action", "(", "name", "=", "\"Find Text in PDF\"", ",", "description", "=", "FIND_TEXT_IN_PDF_OPERATION_DESC", ",", "outputs", "=", "{", "@", "Output", "(", "value", "=", "RETURN_CODE", ",", "description", "=", "RETURN_CODE_DESC", ")", ",", "@", "Output", ...
This operation checks if a text input is found in a PDF file. @param text The text to be searched for in the PDF file. @param ignoreCase Whether to ignore if characters of the text are lowercase or uppercase. Valid values: "true", "false". Default Value: "false" @param pathToFile The full path to the PDF file. @param password The password for the PDF file. @return - a map containing the output of the operation. Keys present in the map are: returnResult - The number of occurrences of the text in the PDF file. returnCode - the return code of the operation. 0 if the operation goes to success, -1 if the operation goes to failure. exception - the exception message if the operation fails.
[ "This", "operation", "checks", "if", "a", "text", "input", "is", "found", "in", "a", "PDF", "file", "." ]
train
https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-utilities/src/main/java/io/cloudslang/content/utilities/actions/FindTextInPdf.java#L72-L102
Shusshu/Android-RecurrencePicker
library/src/main/java/be/billington/calendar/recurrencepicker/Utils.java
Utils.convertAlldayUtcToLocal
public static long convertAlldayUtcToLocal(Time recycle, long utcTime, String tz) { if (recycle == null) { recycle = new Time(); } recycle.timezone = Time.TIMEZONE_UTC; recycle.set(utcTime); recycle.timezone = tz; return recycle.normalize(true); }
java
public static long convertAlldayUtcToLocal(Time recycle, long utcTime, String tz) { if (recycle == null) { recycle = new Time(); } recycle.timezone = Time.TIMEZONE_UTC; recycle.set(utcTime); recycle.timezone = tz; return recycle.normalize(true); }
[ "public", "static", "long", "convertAlldayUtcToLocal", "(", "Time", "recycle", ",", "long", "utcTime", ",", "String", "tz", ")", "{", "if", "(", "recycle", "==", "null", ")", "{", "recycle", "=", "new", "Time", "(", ")", ";", "}", "recycle", ".", "time...
Convert given UTC time into current local time. This assumes it is for an allday event and will adjust the time to be on a midnight boundary. @param recycle Time object to recycle, otherwise null. @param utcTime Time to convert, in UTC. @param tz The time zone to convert this time to.
[ "Convert", "given", "UTC", "time", "into", "current", "local", "time", ".", "This", "assumes", "it", "is", "for", "an", "allday", "event", "and", "will", "adjust", "the", "time", "to", "be", "on", "a", "midnight", "boundary", "." ]
train
https://github.com/Shusshu/Android-RecurrencePicker/blob/4f0ae74482e4d46d57a8fb13b4b7980a8613f4af/library/src/main/java/be/billington/calendar/recurrencepicker/Utils.java#L461-L469
google/error-prone
check_api/src/main/java/com/google/errorprone/matchers/Matchers.java
Matchers.methodWithClassAndName
public static Matcher<MethodTree> methodWithClassAndName( final String className, final String methodName) { return new Matcher<MethodTree>() { @Override public boolean matches(MethodTree methodTree, VisitorState state) { return ASTHelpers.getSymbol(methodTree) .getEnclosingElement() .getQualifiedName() .contentEquals(className) && methodTree.getName().contentEquals(methodName); } }; }
java
public static Matcher<MethodTree> methodWithClassAndName( final String className, final String methodName) { return new Matcher<MethodTree>() { @Override public boolean matches(MethodTree methodTree, VisitorState state) { return ASTHelpers.getSymbol(methodTree) .getEnclosingElement() .getQualifiedName() .contentEquals(className) && methodTree.getName().contentEquals(methodName); } }; }
[ "public", "static", "Matcher", "<", "MethodTree", ">", "methodWithClassAndName", "(", "final", "String", "className", ",", "final", "String", "methodName", ")", "{", "return", "new", "Matcher", "<", "MethodTree", ">", "(", ")", "{", "@", "Override", "public", ...
Match a method declaration with a specific enclosing class and method name. @param className The fully-qualified name of the enclosing class, e.g. "com.google.common.base.Preconditions" @param methodName The name of the method to match, e.g., "checkNotNull"
[ "Match", "a", "method", "declaration", "with", "a", "specific", "enclosing", "class", "and", "method", "name", "." ]
train
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/matchers/Matchers.java#L948-L960
jronrun/benayn
benayn-ustyle/src/main/java/com/benayn/ustyle/string/Levenshtein.java
Levenshtein.longestCommonSubsequence
@SuppressWarnings("unchecked") public static <T extends Levenshtein> T longestCommonSubsequence(String baseTarget, String compareTarget) { return (T) new LongestCommonSubsequence(baseTarget).update(compareTarget); }
java
@SuppressWarnings("unchecked") public static <T extends Levenshtein> T longestCommonSubsequence(String baseTarget, String compareTarget) { return (T) new LongestCommonSubsequence(baseTarget).update(compareTarget); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "<", "T", "extends", "Levenshtein", ">", "T", "longestCommonSubsequence", "(", "String", "baseTarget", ",", "String", "compareTarget", ")", "{", "return", "(", "T", ")", "new", "LongestCommo...
Returns a new Longest Common Subsequence edit distance instance with compare target string @see LongestCommonSubsequence @param baseTarget @param compareTarget @return
[ "Returns", "a", "new", "Longest", "Common", "Subsequence", "edit", "distance", "instance", "with", "compare", "target", "string" ]
train
https://github.com/jronrun/benayn/blob/7585152e10e4cac07b4274c65f1c72ad7061ae69/benayn-ustyle/src/main/java/com/benayn/ustyle/string/Levenshtein.java#L160-L163
enioka/jqm
jqm-all/jqm-engine/src/main/java/com/enioka/jqm/tools/Helpers.java
Helpers.createDeliverable
static int createDeliverable(String path, String originalFileName, String fileFamily, Integer jobId, DbConn cnx) { QueryResult qr = cnx.runUpdate("deliverable_insert", fileFamily, path, jobId, originalFileName, UUID.randomUUID().toString()); return qr.getGeneratedId(); }
java
static int createDeliverable(String path, String originalFileName, String fileFamily, Integer jobId, DbConn cnx) { QueryResult qr = cnx.runUpdate("deliverable_insert", fileFamily, path, jobId, originalFileName, UUID.randomUUID().toString()); return qr.getGeneratedId(); }
[ "static", "int", "createDeliverable", "(", "String", "path", ",", "String", "originalFileName", ",", "String", "fileFamily", ",", "Integer", "jobId", ",", "DbConn", "cnx", ")", "{", "QueryResult", "qr", "=", "cnx", ".", "runUpdate", "(", "\"deliverable_insert\""...
Create a Deliverable inside the database that will track a file created by a JobInstance Must be called from inside a transaction @param path FilePath (relative to a root directory - cf. Node) @param originalFileName FileName @param fileFamily File family (may be null). E.g.: "daily report" @param jobId Job Instance ID @param cnx the DbConn to use.
[ "Create", "a", "Deliverable", "inside", "the", "database", "that", "will", "track", "a", "file", "created", "by", "a", "JobInstance", "Must", "be", "called", "from", "inside", "a", "transaction" ]
train
https://github.com/enioka/jqm/blob/391733b8e291404b97c714c3727a241c4a861f98/jqm-all/jqm-engine/src/main/java/com/enioka/jqm/tools/Helpers.java#L209-L213
threerings/narya
core/src/main/java/com/threerings/presents/server/net/PresentsConnectionManager.java
PresentsConnectionManager.postDatagram
protected boolean postDatagram (PresentsConnection conn, Message msg) throws Exception { _flattener.reset(); // flatten the message using the connection's sequencer DatagramSequencer sequencer = conn.getDatagramSequencer(); sequencer.writeDatagram(msg); // if the message is too big, we must fall back to sending it through the stream channel if (_flattener.size() > Client.MAX_DATAGRAM_SIZE) { return false; } // note the actual transport msg.noteActualTransport(Transport.UNRELIABLE_UNORDERED); // extract as a byte array byte[] data = _flattener.toByteArray(); // slap it on the queue _dataq.append(Tuple.newTuple(conn, data)); return true; }
java
protected boolean postDatagram (PresentsConnection conn, Message msg) throws Exception { _flattener.reset(); // flatten the message using the connection's sequencer DatagramSequencer sequencer = conn.getDatagramSequencer(); sequencer.writeDatagram(msg); // if the message is too big, we must fall back to sending it through the stream channel if (_flattener.size() > Client.MAX_DATAGRAM_SIZE) { return false; } // note the actual transport msg.noteActualTransport(Transport.UNRELIABLE_UNORDERED); // extract as a byte array byte[] data = _flattener.toByteArray(); // slap it on the queue _dataq.append(Tuple.newTuple(conn, data)); return true; }
[ "protected", "boolean", "postDatagram", "(", "PresentsConnection", "conn", ",", "Message", "msg", ")", "throws", "Exception", "{", "_flattener", ".", "reset", "(", ")", ";", "// flatten the message using the connection's sequencer", "DatagramSequencer", "sequencer", "=", ...
Helper function for {@link #postMessage}; handles posting the message as a datagram. @return true if the datagram was successfully posted, false if it was too big.
[ "Helper", "function", "for", "{", "@link", "#postMessage", "}", ";", "handles", "posting", "the", "message", "as", "a", "datagram", "." ]
train
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/server/net/PresentsConnectionManager.java#L318-L342
b3dgs/lionengine
lionengine-core/src/main/java/com/b3dgs/lionengine/UtilMath.java
UtilMath.getDistance
public static double getDistance(double x1, double y1, double x2, double y2) { final double x = x2 - x1; final double y = y2 - y1; return StrictMath.sqrt(x * x + y * y); }
java
public static double getDistance(double x1, double y1, double x2, double y2) { final double x = x2 - x1; final double y = y2 - y1; return StrictMath.sqrt(x * x + y * y); }
[ "public", "static", "double", "getDistance", "(", "double", "x1", ",", "double", "y1", ",", "double", "x2", ",", "double", "y2", ")", "{", "final", "double", "x", "=", "x2", "-", "x1", ";", "final", "double", "y", "=", "y2", "-", "y1", ";", "return...
Get distance of two points. @param x1 The point 1 x. @param y1 The point 1 y. @param x2 The point 2 x. @param y2 The point 2 y. @return The distance between them.
[ "Get", "distance", "of", "two", "points", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-core/src/main/java/com/b3dgs/lionengine/UtilMath.java#L176-L182
sniggle/simple-pgp
simple-pgp-java/src/main/java/me/sniggle/pgp/crypt/internal/BasePGPCommon.java
BasePGPCommon.findPrivateKey
protected PGPPrivateKey findPrivateKey(InputStream secretKey, String password, KeyFilter<PGPSecretKey> keyFilter) throws IOException, PGPException { LOGGER.trace("findPrivateKey(InputStream, String, KeyFilter<PGPSecretKey>)"); LOGGER.trace("Secret Key: {}, Password: {}, KeyFilter: {}", secretKey == null ? "not set" : "set", password == null ? "not set" : "********", keyFilter == null ? "not set" : "set"); return findPrivateKey(findSecretKey(secretKey, keyFilter), password); }
java
protected PGPPrivateKey findPrivateKey(InputStream secretKey, String password, KeyFilter<PGPSecretKey> keyFilter) throws IOException, PGPException { LOGGER.trace("findPrivateKey(InputStream, String, KeyFilter<PGPSecretKey>)"); LOGGER.trace("Secret Key: {}, Password: {}, KeyFilter: {}", secretKey == null ? "not set" : "set", password == null ? "not set" : "********", keyFilter == null ? "not set" : "set"); return findPrivateKey(findSecretKey(secretKey, keyFilter), password); }
[ "protected", "PGPPrivateKey", "findPrivateKey", "(", "InputStream", "secretKey", ",", "String", "password", ",", "KeyFilter", "<", "PGPSecretKey", ">", "keyFilter", ")", "throws", "IOException", ",", "PGPException", "{", "LOGGER", ".", "trace", "(", "\"findPrivateKe...
read a private key and unlock it with the given password @param secretKey the secret key stream @param password the password to use to unlock the private key @param keyFilter the filter ot find the appropriate key @return the appropriate private key or null if none matches the filter @throws IOException @throws PGPException
[ "read", "a", "private", "key", "and", "unlock", "it", "with", "the", "given", "password" ]
train
https://github.com/sniggle/simple-pgp/blob/2ab83e4d370b8189f767d8e4e4c7e6020e60fbe3/simple-pgp-java/src/main/java/me/sniggle/pgp/crypt/internal/BasePGPCommon.java#L245-L249
querydsl/querydsl
querydsl-core/src/main/java/com/querydsl/core/types/dsl/Expressions.java
Expressions.comparableTemplate
public static <T extends Comparable<?>> ComparableTemplate<T> comparableTemplate(Class<? extends T> cl, String template, Object... args) { return comparableTemplate(cl, createTemplate(template), ImmutableList.copyOf(args)); }
java
public static <T extends Comparable<?>> ComparableTemplate<T> comparableTemplate(Class<? extends T> cl, String template, Object... args) { return comparableTemplate(cl, createTemplate(template), ImmutableList.copyOf(args)); }
[ "public", "static", "<", "T", "extends", "Comparable", "<", "?", ">", ">", "ComparableTemplate", "<", "T", ">", "comparableTemplate", "(", "Class", "<", "?", "extends", "T", ">", "cl", ",", "String", "template", ",", "Object", "...", "args", ")", "{", ...
Create a new Template expression @param cl type of expression @param template template @param args template parameters @return template expression
[ "Create", "a", "new", "Template", "expression" ]
train
https://github.com/querydsl/querydsl/blob/2bf234caf78549813a1e0f44d9c30ecc5ef734e3/querydsl-core/src/main/java/com/querydsl/core/types/dsl/Expressions.java#L398-L401
oasp/oasp4j
modules/rest/src/main/java/io/oasp/module/rest/service/api/RequestParameters.java
RequestParameters.getList
public List<String> getList(String key) { List<String> list = this.parameters.get(key); if (list == null) { list = Collections.emptyList(); } return list; }
java
public List<String> getList(String key) { List<String> list = this.parameters.get(key); if (list == null) { list = Collections.emptyList(); } return list; }
[ "public", "List", "<", "String", ">", "getList", "(", "String", "key", ")", "{", "List", "<", "String", ">", "list", "=", "this", ".", "parameters", ".", "get", "(", "key", ")", ";", "if", "(", "list", "==", "null", ")", "{", "list", "=", "Collec...
Gets the {@link List} of all value for the parameter with with the given <code>key</code>. In general you should avoid multi-valued parameters (e.g. http://host/path?query=a&query=b). The JAX-RS API supports this exotic case as first citizen so we expose it here but only use it if you know exactly what you are doing. @param key is the {@link java.util.Map#get(Object) key} of the parameter to get. @return the {@link List} with all values of the requested parameter. Will be an {@link Collections#emptyList() empty list} if the parameter is not present.
[ "Gets", "the", "{", "@link", "List", "}", "of", "all", "value", "for", "the", "parameter", "with", "with", "the", "given", "<code", ">", "key<", "/", "code", ">", ".", "In", "general", "you", "should", "avoid", "multi", "-", "valued", "parameters", "("...
train
https://github.com/oasp/oasp4j/blob/03f90132699fad95e52ec8efa54aa391f8d3c7e4/modules/rest/src/main/java/io/oasp/module/rest/service/api/RequestParameters.java#L186-L193
ACRA/acra
acra-core/src/main/java/org/acra/collector/ReflectionCollector.java
ReflectionCollector.collectStaticGettersResults
private void collectStaticGettersResults(@NonNull Class<?> someClass, @NonNull JSONObject container) throws JSONException { final Method[] methods = someClass.getMethods(); for (final Method method : methods) { if (method.getParameterTypes().length == 0 && (method.getName().startsWith("get") || method.getName().startsWith("is")) && !"getClass".equals(method.getName())) { try { container.put(method.getName(), method.invoke(null, (Object[]) null)); } catch (@NonNull IllegalArgumentException ignored) { // NOOP } catch (@NonNull InvocationTargetException ignored) { // NOOP } catch (@NonNull IllegalAccessException ignored) { // NOOP } } } }
java
private void collectStaticGettersResults(@NonNull Class<?> someClass, @NonNull JSONObject container) throws JSONException { final Method[] methods = someClass.getMethods(); for (final Method method : methods) { if (method.getParameterTypes().length == 0 && (method.getName().startsWith("get") || method.getName().startsWith("is")) && !"getClass".equals(method.getName())) { try { container.put(method.getName(), method.invoke(null, (Object[]) null)); } catch (@NonNull IllegalArgumentException ignored) { // NOOP } catch (@NonNull InvocationTargetException ignored) { // NOOP } catch (@NonNull IllegalAccessException ignored) { // NOOP } } } }
[ "private", "void", "collectStaticGettersResults", "(", "@", "NonNull", "Class", "<", "?", ">", "someClass", ",", "@", "NonNull", "JSONObject", "container", ")", "throws", "JSONException", "{", "final", "Method", "[", "]", "methods", "=", "someClass", ".", "get...
Retrieves key/value pairs from static getters of a class (get*() or is*()). @param someClass the class to be inspected.
[ "Retrieves", "key", "/", "value", "pairs", "from", "static", "getters", "of", "a", "class", "(", "get", "*", "()", "or", "is", "*", "()", ")", "." ]
train
https://github.com/ACRA/acra/blob/bfa3235ab110328c5ab2f792ddf8ee87be4a32d1/acra-core/src/main/java/org/acra/collector/ReflectionCollector.java#L107-L124
Pi4J/pi4j
pi4j-core/src/main/java/com/pi4j/io/serial/impl/SerialImpl.java
SerialImpl.write
@Override public void write(byte[] data, int offset, int length) throws IllegalStateException, IOException{ // validate state if (isClosed()) { throw new IllegalStateException("Serial connection is not open; cannot 'write()'."); } // write serial data to transmit buffer com.pi4j.jni.Serial.write(fileDescriptor, data, offset, length); }
java
@Override public void write(byte[] data, int offset, int length) throws IllegalStateException, IOException{ // validate state if (isClosed()) { throw new IllegalStateException("Serial connection is not open; cannot 'write()'."); } // write serial data to transmit buffer com.pi4j.jni.Serial.write(fileDescriptor, data, offset, length); }
[ "@", "Override", "public", "void", "write", "(", "byte", "[", "]", "data", ",", "int", "offset", ",", "int", "length", ")", "throws", "IllegalStateException", ",", "IOException", "{", "// validate state", "if", "(", "isClosed", "(", ")", ")", "{", "throw",...
<p>Sends an array of bytes to the serial port/device identified by the given file descriptor.</p> @param data A ByteBuffer of data to be transmitted. @param offset The starting index (inclusive) in the array to send from. @param length The number of bytes from the byte array to transmit to the serial port. @throws IllegalStateException thrown if the serial port is not already open. @throws IOException thrown on any error.
[ "<p", ">", "Sends", "an", "array", "of", "bytes", "to", "the", "serial", "port", "/", "device", "identified", "by", "the", "given", "file", "descriptor", ".", "<", "/", "p", ">" ]
train
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/io/serial/impl/SerialImpl.java#L722-L731
Clivern/Racter
src/main/java/com/clivern/racter/senders/templates/ReceiptTemplate.java
ReceiptTemplate.setAdjustment
public void setAdjustment(String name, String amount) { HashMap<String, String> adjustment = new HashMap<String, String>(); adjustment.put("name", name); adjustment.put("amount", amount); this.adjustments.add(adjustment); }
java
public void setAdjustment(String name, String amount) { HashMap<String, String> adjustment = new HashMap<String, String>(); adjustment.put("name", name); adjustment.put("amount", amount); this.adjustments.add(adjustment); }
[ "public", "void", "setAdjustment", "(", "String", "name", ",", "String", "amount", ")", "{", "HashMap", "<", "String", ",", "String", ">", "adjustment", "=", "new", "HashMap", "<", "String", ",", "String", ">", "(", ")", ";", "adjustment", ".", "put", ...
Set Adjustment @param name the adjustment name @param amount the adjustment amount
[ "Set", "Adjustment" ]
train
https://github.com/Clivern/Racter/blob/bbde02f0c2a8a80653ad6b1607376d8408acd71c/src/main/java/com/clivern/racter/senders/templates/ReceiptTemplate.java#L186-L192
googleapis/google-cloud-java
google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/deprecated/ServiceAccount.java
ServiceAccount.of
public static ServiceAccount of(String email, String... scopes) { return of(email, Arrays.asList(scopes)); }
java
public static ServiceAccount of(String email, String... scopes) { return of(email, Arrays.asList(scopes)); }
[ "public", "static", "ServiceAccount", "of", "(", "String", "email", ",", "String", "...", "scopes", ")", "{", "return", "of", "(", "email", ",", "Arrays", ".", "asList", "(", "scopes", ")", ")", ";", "}" ]
Returns a {@code ServiceAccount} object for the provided email and scopes.
[ "Returns", "a", "{" ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/deprecated/ServiceAccount.java#L103-L105
Mozu/mozu-java
mozu-java-core/src/main/java/com/mozu/api/urls/platform/adminuser/TenantAdminUserAuthTicketUrl.java
TenantAdminUserAuthTicketUrl.createUserAuthTicketUrl
public static MozuUrl createUserAuthTicketUrl(String responseFields, Integer tenantId) { UrlFormatter formatter = new UrlFormatter("/api/platform/adminuser/authtickets/tenants?tenantId={tenantId}&responseFields={responseFields}"); formatter.formatUrl("responseFields", responseFields); formatter.formatUrl("tenantId", tenantId); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.HOME_POD) ; }
java
public static MozuUrl createUserAuthTicketUrl(String responseFields, Integer tenantId) { UrlFormatter formatter = new UrlFormatter("/api/platform/adminuser/authtickets/tenants?tenantId={tenantId}&responseFields={responseFields}"); formatter.formatUrl("responseFields", responseFields); formatter.formatUrl("tenantId", tenantId); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.HOME_POD) ; }
[ "public", "static", "MozuUrl", "createUserAuthTicketUrl", "(", "String", "responseFields", ",", "Integer", "tenantId", ")", "{", "UrlFormatter", "formatter", "=", "new", "UrlFormatter", "(", "\"/api/platform/adminuser/authtickets/tenants?tenantId={tenantId}&responseFields={respon...
Get Resource Url for CreateUserAuthTicket @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss. @param tenantId Unique identifier of the development or production tenant for which to generate the user authentication ticket. @return String Resource Url
[ "Get", "Resource", "Url", "for", "CreateUserAuthTicket" ]
train
https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-java-core/src/main/java/com/mozu/api/urls/platform/adminuser/TenantAdminUserAuthTicketUrl.java#L22-L28
UrielCh/ovh-java-sdk
ovh-java-sdk-newAccount/src/main/java/net/minidev/ovh/api/ApiOvhNewAccount.java
ApiOvhNewAccount.area_GET
public ArrayList<String> area_GET(OvhCountryEnum country) throws IOException { String qPath = "/newAccount/area"; StringBuilder sb = path(qPath); query(sb, "country", country); String resp = execN(qPath, "GET", sb.toString(), null); return convertTo(resp, t1); }
java
public ArrayList<String> area_GET(OvhCountryEnum country) throws IOException { String qPath = "/newAccount/area"; StringBuilder sb = path(qPath); query(sb, "country", country); String resp = execN(qPath, "GET", sb.toString(), null); return convertTo(resp, t1); }
[ "public", "ArrayList", "<", "String", ">", "area_GET", "(", "OvhCountryEnum", "country", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/newAccount/area\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ")", ";", "query", "(", "sb", "...
All available areas for a given country REST: GET /newAccount/area @param country [required]
[ "All", "available", "areas", "for", "a", "given", "country" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-newAccount/src/main/java/net/minidev/ovh/api/ApiOvhNewAccount.java#L150-L156
OpenLiberty/open-liberty
dev/com.ibm.ws.webcontainer.security/src/com/ibm/ws/webcontainer/security/internal/URLHandler.java
URLHandler.restoreHostNameToURL
@Sensitive protected String restoreHostNameToURL(@Sensitive String referrerURL, String url) { if ((referrerURL.startsWith("/")) || (referrerURL.length() == 0)) { int doubleSlash = url.indexOf("//"); int firstSingleSlash = url.indexOf("/", doubleSlash + 2); referrerURL = url.substring(0, firstSingleSlash) + referrerURL; } else { try { URL referrer = new URL(referrerURL); String referrerHost = referrer.getHost(); if ((referrerHost == null) || (referrerHost.length() == 0)) { URL currentURL = new URL(url); String currentHost = currentURL.getHost(); int doubleSlash = referrerURL.indexOf("//"); StringBuffer newURLBuf = new StringBuffer(referrerURL); newURLBuf.insert(doubleSlash + 2, currentHost); referrerURL = newURLBuf.toString(); } } catch (java.net.MalformedURLException e) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "restoreHostNameToURL", new Object[] { e }); } } } return referrerURL; }
java
@Sensitive protected String restoreHostNameToURL(@Sensitive String referrerURL, String url) { if ((referrerURL.startsWith("/")) || (referrerURL.length() == 0)) { int doubleSlash = url.indexOf("//"); int firstSingleSlash = url.indexOf("/", doubleSlash + 2); referrerURL = url.substring(0, firstSingleSlash) + referrerURL; } else { try { URL referrer = new URL(referrerURL); String referrerHost = referrer.getHost(); if ((referrerHost == null) || (referrerHost.length() == 0)) { URL currentURL = new URL(url); String currentHost = currentURL.getHost(); int doubleSlash = referrerURL.indexOf("//"); StringBuffer newURLBuf = new StringBuffer(referrerURL); newURLBuf.insert(doubleSlash + 2, currentHost); referrerURL = newURLBuf.toString(); } } catch (java.net.MalformedURLException e) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "restoreHostNameToURL", new Object[] { e }); } } } return referrerURL; }
[ "@", "Sensitive", "protected", "String", "restoreHostNameToURL", "(", "@", "Sensitive", "String", "referrerURL", ",", "String", "url", ")", "{", "if", "(", "(", "referrerURL", ".", "startsWith", "(", "\"/\"", ")", ")", "||", "(", "referrerURL", ".", "length"...
Updates the referrerURL with the host for the current request if one is missing. If referrerURL is relative or an empty String, use the host for the current request and append the referrerURL. Otherwise, inject into the referrer URL String the host for the current request. Note, this method does not handle the following scenarios: - either storeReq or URLString is null (could they ever be?) - URLString being incomplete, e.g. http://myhost.com (missing first /) @param referrerURL A valid URL string, potentially without host name, from the referrer URL cookie @param url A valid, fully qualified URL representing the current request @return
[ "Updates", "the", "referrerURL", "with", "the", "host", "for", "the", "current", "request", "if", "one", "is", "missing", ".", "If", "referrerURL", "is", "relative", "or", "an", "empty", "String", "use", "the", "host", "for", "the", "current", "request", "...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.webcontainer.security/src/com/ibm/ws/webcontainer/security/internal/URLHandler.java#L125-L150
foundation-runtime/service-directory
2.0/sd-core/src/main/java/com/cisco/oss/foundation/directory/utils/WebSocketSerializer.java
WebSocketSerializer.getResponseSerializer
public static ResponseSerializer getResponseSerializer(ResponseHeader header, Response response) throws JsonGenerationException, JsonMappingException, IOException{ final String s = serializeResponse(header, response); return new ResponseSerializer(){ @Override public String searializerAsString() { return s; } }; }
java
public static ResponseSerializer getResponseSerializer(ResponseHeader header, Response response) throws JsonGenerationException, JsonMappingException, IOException{ final String s = serializeResponse(header, response); return new ResponseSerializer(){ @Override public String searializerAsString() { return s; } }; }
[ "public", "static", "ResponseSerializer", "getResponseSerializer", "(", "ResponseHeader", "header", ",", "Response", "response", ")", "throws", "JsonGenerationException", ",", "JsonMappingException", ",", "IOException", "{", "final", "String", "s", "=", "serializeResponse...
Serialize the Response. @param header the ResponseHeader. @param response the Response. @return the ResponseSerializer. @throws JsonGenerationException @throws JsonMappingException @throws IOException
[ "Serialize", "the", "Response", "." ]
train
https://github.com/foundation-runtime/service-directory/blob/a7bdefe173dc99e75eff4a24e07e6407e62f2ed4/2.0/sd-core/src/main/java/com/cisco/oss/foundation/directory/utils/WebSocketSerializer.java#L54-L64
looly/hutool
hutool-core/src/main/java/cn/hutool/core/lang/Validator.java
Validator.validateLowerCase
public static <T extends CharSequence> T validateLowerCase(T value, String errorMsg) throws ValidateException { if (false == isLowerCase(value)) { throw new ValidateException(errorMsg); } return value; }
java
public static <T extends CharSequence> T validateLowerCase(T value, String errorMsg) throws ValidateException { if (false == isLowerCase(value)) { throw new ValidateException(errorMsg); } return value; }
[ "public", "static", "<", "T", "extends", "CharSequence", ">", "T", "validateLowerCase", "(", "T", "value", ",", "String", "errorMsg", ")", "throws", "ValidateException", "{", "if", "(", "false", "==", "isLowerCase", "(", "value", ")", ")", "{", "throw", "n...
验证字符串是否全部为小写字母 @param <T> 字符串类型 @param value 表单值 @param errorMsg 验证错误的信息 @return 验证后的值 @throws ValidateException 验证异常 @since 3.3.0
[ "验证字符串是否全部为小写字母" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/lang/Validator.java#L519-L524
Mozu/mozu-java
mozu-java-core/src/main/java/com/mozu/api/urls/event/EventNotificationUrl.java
EventNotificationUrl.getEventUrl
public static MozuUrl getEventUrl(String eventId, String responseFields) { UrlFormatter formatter = new UrlFormatter("/api/event/pull/{eventId}?responseFields={responseFields}"); formatter.formatUrl("eventId", eventId); formatter.formatUrl("responseFields", responseFields); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.HOME_POD) ; }
java
public static MozuUrl getEventUrl(String eventId, String responseFields) { UrlFormatter formatter = new UrlFormatter("/api/event/pull/{eventId}?responseFields={responseFields}"); formatter.formatUrl("eventId", eventId); formatter.formatUrl("responseFields", responseFields); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.HOME_POD) ; }
[ "public", "static", "MozuUrl", "getEventUrl", "(", "String", "eventId", ",", "String", "responseFields", ")", "{", "UrlFormatter", "formatter", "=", "new", "UrlFormatter", "(", "\"/api/event/pull/{eventId}?responseFields={responseFields}\"", ")", ";", "formatter", ".", ...
Get Resource Url for GetEvent @param eventId The unique identifier of the event being retrieved. An event is a notification about a create, read, update, or delete on an order, product, discount or category. @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss. @return String Resource Url
[ "Get", "Resource", "Url", "for", "GetEvent" ]
train
https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-java-core/src/main/java/com/mozu/api/urls/event/EventNotificationUrl.java#L42-L48
phax/ph-oton
ph-oton-uicore/src/main/java/com/helger/photon/uicore/page/handler/AbstractWebPageActionHandlerMultiDelete.java
AbstractWebPageActionHandlerMultiDelete.createDeleteToolbar
@Nonnull @OverrideOnDemand protected TOOLBAR_TYPE createDeleteToolbar (@Nonnull final WPECTYPE aWPEC, @Nonnull final FORM_TYPE aForm, @Nonnull final ICommonsList <DATATYPE> aSelectedObjects) { final Locale aDisplayLocale = aWPEC.getDisplayLocale (); final TOOLBAR_TYPE aToolbar = getUIHandler ().createToolbar (aWPEC); aToolbar.addHiddenField (CPageParam.PARAM_ACTION, aWPEC.getAction ()); aToolbar.addHiddenField (CPageParam.PARAM_SUBACTION, CPageParam.ACTION_SAVE); for (final DATATYPE aItem : aSelectedObjects) aToolbar.addHiddenField (getFieldName (), aItem.getID ()); // Yes button aToolbar.addSubmitButton (getDeleteToolbarSubmitButtonText (aDisplayLocale), getDeleteToolbarSubmitButtonIcon ()); // No button aToolbar.addButtonNo (aDisplayLocale); // Callback modifyDeleteToolbar (aWPEC, aToolbar); return aToolbar; }
java
@Nonnull @OverrideOnDemand protected TOOLBAR_TYPE createDeleteToolbar (@Nonnull final WPECTYPE aWPEC, @Nonnull final FORM_TYPE aForm, @Nonnull final ICommonsList <DATATYPE> aSelectedObjects) { final Locale aDisplayLocale = aWPEC.getDisplayLocale (); final TOOLBAR_TYPE aToolbar = getUIHandler ().createToolbar (aWPEC); aToolbar.addHiddenField (CPageParam.PARAM_ACTION, aWPEC.getAction ()); aToolbar.addHiddenField (CPageParam.PARAM_SUBACTION, CPageParam.ACTION_SAVE); for (final DATATYPE aItem : aSelectedObjects) aToolbar.addHiddenField (getFieldName (), aItem.getID ()); // Yes button aToolbar.addSubmitButton (getDeleteToolbarSubmitButtonText (aDisplayLocale), getDeleteToolbarSubmitButtonIcon ()); // No button aToolbar.addButtonNo (aDisplayLocale); // Callback modifyDeleteToolbar (aWPEC, aToolbar); return aToolbar; }
[ "@", "Nonnull", "@", "OverrideOnDemand", "protected", "TOOLBAR_TYPE", "createDeleteToolbar", "(", "@", "Nonnull", "final", "WPECTYPE", "aWPEC", ",", "@", "Nonnull", "final", "FORM_TYPE", "aForm", ",", "@", "Nonnull", "final", "ICommonsList", "<", "DATATYPE", ">", ...
Create toolbar for deleting an existing object @param aWPEC The web page execution context @param aForm The handled form. Never <code>null</code>. @param aSelectedObjects Selected objects. Never <code>null</code>. @return Never <code>null</code>.
[ "Create", "toolbar", "for", "deleting", "an", "existing", "object" ]
train
https://github.com/phax/ph-oton/blob/f3aaacbbc02a9f3e4f32fe8db8e4adf7b9c1d3ef/ph-oton-uicore/src/main/java/com/helger/photon/uicore/page/handler/AbstractWebPageActionHandlerMultiDelete.java#L132-L153
aspectran/aspectran
core/src/main/java/com/aspectran/core/support/i18n/message/AbstractMessageSource.java
AbstractMessageSource.resolveCodeWithoutArguments
protected String resolveCodeWithoutArguments(String code, Locale locale) { MessageFormat messageFormat = resolveCode(code, locale); if (messageFormat != null) { synchronized (messageFormat) { return messageFormat.format(new Object[0]); } } else { return null; } }
java
protected String resolveCodeWithoutArguments(String code, Locale locale) { MessageFormat messageFormat = resolveCode(code, locale); if (messageFormat != null) { synchronized (messageFormat) { return messageFormat.format(new Object[0]); } } else { return null; } }
[ "protected", "String", "resolveCodeWithoutArguments", "(", "String", "code", ",", "Locale", "locale", ")", "{", "MessageFormat", "messageFormat", "=", "resolveCode", "(", "code", ",", "locale", ")", ";", "if", "(", "messageFormat", "!=", "null", ")", "{", "syn...
Subclasses can override this method to resolve a message without arguments in an optimized fashion, i.e. to resolve without involving a MessageFormat. <p>The default implementation <i>does</i> use MessageFormat, through delegating to the {@link #resolveCode} method. Subclasses are encouraged to replace this with optimized resolution. <p>Unfortunately, {@code java.text.MessageFormat} is not implemented in an efficient fashion. In particular, it does not detect that a message pattern doesn't contain argument placeholders in the first place. Therefore, it is advisable to circumvent MessageFormat for messages without arguments. @param code the code of the message to resolve @param locale the Locale to resolve the code for (subclasses are encouraged to support internationalization) @return the message String, or {@code null} if not found @see #resolveCode #resolveCode @see java.text.MessageFormat
[ "Subclasses", "can", "override", "this", "method", "to", "resolve", "a", "message", "without", "arguments", "in", "an", "optimized", "fashion", "i", ".", "e", ".", "to", "resolve", "without", "involving", "a", "MessageFormat", ".", "<p", ">", "The", "default...
train
https://github.com/aspectran/aspectran/blob/2d758a2a28b71ee85b42823c12dc44674d7f2c70/core/src/main/java/com/aspectran/core/support/i18n/message/AbstractMessageSource.java#L259-L268
PistoiaHELM/HELM2NotationToolkit
src/main/java/org/helm/notation2/tools/ChangeObjects.java
ChangeObjects.deleteMonomerNotation
public final static void deleteMonomerNotation(int position, PolymerNotation polymer) throws NotationException { MonomerNotation monomerNotation = polymer.getPolymerElements().getListOfElements().get(position); if (polymer.getPolymerElements().getListOfElements().size() == 1) { throw new NotationException(monomerNotation.toString() + " can't be removed. Polymer has to have at least one Monomer Notation"); } polymer.getPolymerElements().getListOfElements().remove(monomerNotation); }
java
public final static void deleteMonomerNotation(int position, PolymerNotation polymer) throws NotationException { MonomerNotation monomerNotation = polymer.getPolymerElements().getListOfElements().get(position); if (polymer.getPolymerElements().getListOfElements().size() == 1) { throw new NotationException(monomerNotation.toString() + " can't be removed. Polymer has to have at least one Monomer Notation"); } polymer.getPolymerElements().getListOfElements().remove(monomerNotation); }
[ "public", "final", "static", "void", "deleteMonomerNotation", "(", "int", "position", ",", "PolymerNotation", "polymer", ")", "throws", "NotationException", "{", "MonomerNotation", "monomerNotation", "=", "polymer", ".", "getPolymerElements", "(", ")", ".", "getListOf...
method to delete a MonomerNotation at a specific position of the PolymerNotation @param position position of the to be deleted MonomerNotation @param polymer PolymerNotation @throws NotationException if the generated PolymerNotation has no elements after deleting the MonomerNotation
[ "method", "to", "delete", "a", "MonomerNotation", "at", "a", "specific", "position", "of", "the", "PolymerNotation" ]
train
https://github.com/PistoiaHELM/HELM2NotationToolkit/blob/ac5bb01fd5b4082134a8ef226bbe2ff0f60fcd38/src/main/java/org/helm/notation2/tools/ChangeObjects.java#L307-L314
UrielCh/ovh-java-sdk
ovh-java-sdk-xdsl/src/main/java/net/minidev/ovh/api/ApiOvhXdsl.java
ApiOvhXdsl.serviceName_resiliationTerms_GET
public OvhResiliationTerms serviceName_resiliationTerms_GET(String serviceName, Date resiliationDate) throws IOException { String qPath = "/xdsl/{serviceName}/resiliationTerms"; StringBuilder sb = path(qPath, serviceName); query(sb, "resiliationDate", resiliationDate); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhResiliationTerms.class); }
java
public OvhResiliationTerms serviceName_resiliationTerms_GET(String serviceName, Date resiliationDate) throws IOException { String qPath = "/xdsl/{serviceName}/resiliationTerms"; StringBuilder sb = path(qPath, serviceName); query(sb, "resiliationDate", resiliationDate); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhResiliationTerms.class); }
[ "public", "OvhResiliationTerms", "serviceName_resiliationTerms_GET", "(", "String", "serviceName", ",", "Date", "resiliationDate", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/xdsl/{serviceName}/resiliationTerms\"", ";", "StringBuilder", "sb", "=", "path",...
Get resiliation terms REST: GET /xdsl/{serviceName}/resiliationTerms @param resiliationDate [required] The desired resiliation date @param serviceName [required] The internal name of your XDSL offer
[ "Get", "resiliation", "terms" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-xdsl/src/main/java/net/minidev/ovh/api/ApiOvhXdsl.java#L1858-L1864
kite-sdk/kite
kite-data/kite-data-core/src/main/java/org/kitesdk/data/spi/filesystem/FileSystemDataset.java
FileSystemDataset.getDirectory
private static Path getDirectory(FileSystem fs, Path path) { try { if (!fs.exists(path) || fs.isDirectory(path)) { return path; } else { return path.getParent(); } } catch (IOException e) { throw new DatasetIOException("Cannot access path: " + path, e); } }
java
private static Path getDirectory(FileSystem fs, Path path) { try { if (!fs.exists(path) || fs.isDirectory(path)) { return path; } else { return path.getParent(); } } catch (IOException e) { throw new DatasetIOException("Cannot access path: " + path, e); } }
[ "private", "static", "Path", "getDirectory", "(", "FileSystem", "fs", ",", "Path", "path", ")", "{", "try", "{", "if", "(", "!", "fs", ".", "exists", "(", "path", ")", "||", "fs", ".", "isDirectory", "(", "path", ")", ")", "{", "return", "path", ";...
Returns the closest directory for the given {@code path}. @param fs a {@link FileSystem} to search @param path a {@link Path} to resolve @return the closest directory to {@link Path}
[ "Returns", "the", "closest", "directory", "for", "the", "given", "{", "@code", "path", "}", "." ]
train
https://github.com/kite-sdk/kite/blob/72bfb4b1a881af85808cd7f14bc3e15160a1e811/kite-data/kite-data-core/src/main/java/org/kitesdk/data/spi/filesystem/FileSystemDataset.java#L714-L725
jingwei/krati
krati-main/src/main/java/krati/core/array/entry/EntryValueInt.java
EntryValueInt.updateArrayFile
@Override public void updateArrayFile(DataWriter writer, long position) throws IOException { writer.writeInt(position, val); }
java
@Override public void updateArrayFile(DataWriter writer, long position) throws IOException { writer.writeInt(position, val); }
[ "@", "Override", "public", "void", "updateArrayFile", "(", "DataWriter", "writer", ",", "long", "position", ")", "throws", "IOException", "{", "writer", ".", "writeInt", "(", "position", ",", "val", ")", ";", "}" ]
Writes this EntryValue at a given position of a data writer. @param writer @param position @throws IOException
[ "Writes", "this", "EntryValue", "at", "a", "given", "position", "of", "a", "data", "writer", "." ]
train
https://github.com/jingwei/krati/blob/1ca0f994a7b0c8215b827eac9aaf95789ec08d21/krati-main/src/main/java/krati/core/array/entry/EntryValueInt.java#L94-L97
Stratio/deep-spark
deep-commons/src/main/java/com/stratio/deep/commons/config/ExtractorConfig.java
ExtractorConfig.getValue
public <W> W getValue(Class<W> clazz, String key) { if (values.get(key) == null) { return null; } else { try { return (W) values.get(key); } catch (ClassCastException e) { if (Number.class.isAssignableFrom(clazz)) { try { return (W) Utils.castNumberType(values.get(key), clazz); } catch (ClassCastException e1) { return null; } } else { throw e; } } } }
java
public <W> W getValue(Class<W> clazz, String key) { if (values.get(key) == null) { return null; } else { try { return (W) values.get(key); } catch (ClassCastException e) { if (Number.class.isAssignableFrom(clazz)) { try { return (W) Utils.castNumberType(values.get(key), clazz); } catch (ClassCastException e1) { return null; } } else { throw e; } } } }
[ "public", "<", "W", ">", "W", "getValue", "(", "Class", "<", "W", ">", "clazz", ",", "String", "key", ")", "{", "if", "(", "values", ".", "get", "(", "key", ")", "==", "null", ")", "{", "return", "null", ";", "}", "else", "{", "try", "{", "re...
Returns the cell value casted to the specified class. @param clazz the expected class @param key the key @return the cell value casted to the specified class
[ "Returns", "the", "cell", "value", "casted", "to", "the", "specified", "class", "." ]
train
https://github.com/Stratio/deep-spark/blob/b9621c9b7a6d996f80fce1d073d696a157bed095/deep-commons/src/main/java/com/stratio/deep/commons/config/ExtractorConfig.java#L243-L263
cesarferreira/AndroidQuickUtils
library/src/main/java/quickutils/core/adapters/BindableAdapter.java
BindableAdapter.newDropDownView
public View newDropDownView(LayoutInflater inflater, int position, ViewGroup container) { return newView(inflater, position, container); }
java
public View newDropDownView(LayoutInflater inflater, int position, ViewGroup container) { return newView(inflater, position, container); }
[ "public", "View", "newDropDownView", "(", "LayoutInflater", "inflater", ",", "int", "position", ",", "ViewGroup", "container", ")", "{", "return", "newView", "(", "inflater", ",", "position", ",", "container", ")", ";", "}" ]
Create a new instance of a drop-down view for the specified position.
[ "Create", "a", "new", "instance", "of", "a", "drop", "-", "down", "view", "for", "the", "specified", "position", "." ]
train
https://github.com/cesarferreira/AndroidQuickUtils/blob/73a91daedbb9f7be7986ea786fbc441c9e5a881c/library/src/main/java/quickutils/core/adapters/BindableAdapter.java#L59-L61
codeprimate-software/cp-elements
src/main/java/org/cp/elements/lang/factory/provider/PrototypeObjectFactory.java
PrototypeObjectFactory.postConstruct
@Override protected <T> T postConstruct(T object, final Object... args) { object = super.postConstruct(object, args); object = configure(object); object = initialize(object, args); return object; }
java
@Override protected <T> T postConstruct(T object, final Object... args) { object = super.postConstruct(object, args); object = configure(object); object = initialize(object, args); return object; }
[ "@", "Override", "protected", "<", "T", ">", "T", "postConstruct", "(", "T", "object", ",", "final", "Object", "...", "args", ")", "{", "object", "=", "super", ".", "postConstruct", "(", "object", ",", "args", ")", ";", "object", "=", "configure", "(",...
Overridden postConstruct method to perform post constructor (instantiation) configuration and initialization actions on the newly constructed object. @param <T> the Class type of created object. @param object the object created by this factory. @param args an array of Objects arguments used for post construction initialization and configuration if no constructor could be found with a signature matching the argument types. @return the object fully configured and initialized. @see #configure(Object) @see #initialize(Object, Object...)
[ "Overridden", "postConstruct", "method", "to", "perform", "post", "constructor", "(", "instantiation", ")", "configuration", "and", "initialization", "actions", "on", "the", "newly", "constructed", "object", "." ]
train
https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/factory/provider/PrototypeObjectFactory.java#L60-L67
knowm/XChart
xchart/src/main/java/org/knowm/xchart/internal/series/AxesChartSeriesNumericalNoErrorBars.java
AxesChartSeriesNumericalNoErrorBars.replaceData
public void replaceData(double[] newXData, double[] newYData, double[] newExtraValues) { // Sanity check if (newExtraValues != null && newExtraValues.length != newYData.length) { throw new IllegalArgumentException("error bars and Y-Axis sizes are not the same!!!"); } if (newXData.length != newYData.length) { throw new IllegalArgumentException("X and Y-Axis sizes are not the same!!!"); } xData = newXData; yData = newYData; extraValues = newExtraValues; setAllData(); calculateMinMax(); }
java
public void replaceData(double[] newXData, double[] newYData, double[] newExtraValues) { // Sanity check if (newExtraValues != null && newExtraValues.length != newYData.length) { throw new IllegalArgumentException("error bars and Y-Axis sizes are not the same!!!"); } if (newXData.length != newYData.length) { throw new IllegalArgumentException("X and Y-Axis sizes are not the same!!!"); } xData = newXData; yData = newYData; extraValues = newExtraValues; setAllData(); calculateMinMax(); }
[ "public", "void", "replaceData", "(", "double", "[", "]", "newXData", ",", "double", "[", "]", "newYData", ",", "double", "[", "]", "newExtraValues", ")", "{", "// Sanity check", "if", "(", "newExtraValues", "!=", "null", "&&", "newExtraValues", ".", "length...
This is an internal method which shouldn't be called from client code. Use XYChart.updateXYSeries or CategoryChart.updateXYSeries instead! @param newXData @param newYData @param newExtraValues
[ "This", "is", "an", "internal", "method", "which", "shouldn", "t", "be", "called", "from", "client", "code", ".", "Use", "XYChart", ".", "updateXYSeries", "or", "CategoryChart", ".", "updateXYSeries", "instead!" ]
train
https://github.com/knowm/XChart/blob/677a105753a855edf24782fab1bf1f5aec3e642b/xchart/src/main/java/org/knowm/xchart/internal/series/AxesChartSeriesNumericalNoErrorBars.java#L62-L79
adamfisk/littleshoot-util
src/main/java/org/littleshoot/util/SecurityUtils.java
SecurityUtils.signAndEncode
public static String signAndEncode(final String accessKey, final String canonicalString) { if (StringUtils.isBlank(accessKey)) { LOG.warn("Empty key!!"); throw new IllegalArgumentException("Empty key"); } // // Acquire an HMAC/SHA1 from the raw key bytes. final SecretKeySpec signingKey = new SecretKeySpec(accessKey.getBytes(), HMAC_SHA1_ALGORITHM); // Acquire the MAC instance and initialize with the signing key. final Mac mac; try { mac = Mac.getInstance(HMAC_SHA1_ALGORITHM); } catch (final NoSuchAlgorithmException e) { LOG.error("No SHA-1", e); throw new RuntimeException("Could not find sha1 algorithm", e); } try { mac.init(signingKey); } catch (final InvalidKeyException e) { LOG.error("Bad key", e); // also should not happen throw new RuntimeException("Could not initialize the MAC algorithm", e); } // Compute the HMAC on the digest, and set it. final String b64 = Base64.encodeBytes(mac.doFinal(canonicalString.getBytes())); return b64; }
java
public static String signAndEncode(final String accessKey, final String canonicalString) { if (StringUtils.isBlank(accessKey)) { LOG.warn("Empty key!!"); throw new IllegalArgumentException("Empty key"); } // // Acquire an HMAC/SHA1 from the raw key bytes. final SecretKeySpec signingKey = new SecretKeySpec(accessKey.getBytes(), HMAC_SHA1_ALGORITHM); // Acquire the MAC instance and initialize with the signing key. final Mac mac; try { mac = Mac.getInstance(HMAC_SHA1_ALGORITHM); } catch (final NoSuchAlgorithmException e) { LOG.error("No SHA-1", e); throw new RuntimeException("Could not find sha1 algorithm", e); } try { mac.init(signingKey); } catch (final InvalidKeyException e) { LOG.error("Bad key", e); // also should not happen throw new RuntimeException("Could not initialize the MAC algorithm", e); } // Compute the HMAC on the digest, and set it. final String b64 = Base64.encodeBytes(mac.doFinal(canonicalString.getBytes())); return b64; }
[ "public", "static", "String", "signAndEncode", "(", "final", "String", "accessKey", ",", "final", "String", "canonicalString", ")", "{", "if", "(", "StringUtils", ".", "isBlank", "(", "accessKey", ")", ")", "{", "LOG", ".", "warn", "(", "\"Empty key!!\"", ")...
Calculate the HMAC/SHA1 on a string. @param canonicalString Data to sign @param accessKey The secret access key to sign it with. @return The base64-encoded RFC 2104-compliant HMAC signature. @throws RuntimeException If the algorithm does not exist or if the key is invalid -- both should never happen.
[ "Calculate", "the", "HMAC", "/", "SHA1", "on", "a", "string", "." ]
train
https://github.com/adamfisk/littleshoot-util/blob/3c0dc4955116b3382d6b0575d2f164b7508a4f73/src/main/java/org/littleshoot/util/SecurityUtils.java#L35-L75
Stratio/stratio-cassandra
src/java/org/apache/cassandra/io/sstable/AbstractSSTableSimpleWriter.java
AbstractSSTableSimpleWriter.addCounterColumn
public void addCounterColumn(ByteBuffer name, long value) throws IOException { addColumn(new BufferCounterCell(metadata.comparator.cellFromByteBuffer(name), CounterContext.instance().createGlobal(counterid, 1L, value), System.currentTimeMillis())); }
java
public void addCounterColumn(ByteBuffer name, long value) throws IOException { addColumn(new BufferCounterCell(metadata.comparator.cellFromByteBuffer(name), CounterContext.instance().createGlobal(counterid, 1L, value), System.currentTimeMillis())); }
[ "public", "void", "addCounterColumn", "(", "ByteBuffer", "name", ",", "long", "value", ")", "throws", "IOException", "{", "addColumn", "(", "new", "BufferCounterCell", "(", "metadata", ".", "comparator", ".", "cellFromByteBuffer", "(", "name", ")", ",", "Counter...
Insert a new counter column to the current row (and super column if applicable). @param name the column name @param value the value of the counter
[ "Insert", "a", "new", "counter", "column", "to", "the", "current", "row", "(", "and", "super", "column", "if", "applicable", ")", "." ]
train
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/io/sstable/AbstractSSTableSimpleWriter.java#L166-L171
undertow-io/undertow
core/src/main/java/io/undertow/util/Headers.java
Headers.extractQuotedValueFromHeaderWithEncoding
public static String extractQuotedValueFromHeaderWithEncoding(final String header, final String key) { String value = extractQuotedValueFromHeader(header, key); if (value != null) { return value; } value = extractQuotedValueFromHeader(header , key + "*"); if(value != null) { int characterSetDelimiter = value.indexOf('\''); int languageDelimiter = value.lastIndexOf('\'', characterSetDelimiter + 1); String characterSet = value.substring(0, characterSetDelimiter); try { String fileNameURLEncoded = value.substring(languageDelimiter + 1); return URLDecoder.decode(fileNameURLEncoded, characterSet); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } return null; }
java
public static String extractQuotedValueFromHeaderWithEncoding(final String header, final String key) { String value = extractQuotedValueFromHeader(header, key); if (value != null) { return value; } value = extractQuotedValueFromHeader(header , key + "*"); if(value != null) { int characterSetDelimiter = value.indexOf('\''); int languageDelimiter = value.lastIndexOf('\'', characterSetDelimiter + 1); String characterSet = value.substring(0, characterSetDelimiter); try { String fileNameURLEncoded = value.substring(languageDelimiter + 1); return URLDecoder.decode(fileNameURLEncoded, characterSet); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } return null; }
[ "public", "static", "String", "extractQuotedValueFromHeaderWithEncoding", "(", "final", "String", "header", ",", "final", "String", "key", ")", "{", "String", "value", "=", "extractQuotedValueFromHeader", "(", "header", ",", "key", ")", ";", "if", "(", "value", ...
Extracts a quoted value from a header that has a given key. For instance if the header is <p> content-disposition=form-data; filename*="utf-8''test.txt" and the key is filename* then "test.txt" will be returned after extracting character set and language (following RFC 2231) and performing URL decoding to the value using the specified encoding @param header The header @param key The key that identifies the token to extract @return The token, or null if it was not found
[ "Extracts", "a", "quoted", "value", "from", "a", "header", "that", "has", "a", "given", "key", ".", "For", "instance", "if", "the", "header", "is", "<p", ">", "content", "-", "disposition", "=", "form", "-", "data", ";", "filename", "*", "=", "utf", ...
train
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/util/Headers.java#L407-L425
Azure/azure-sdk-for-java
keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientCustomImpl.java
KeyVaultClientCustomImpl.listCertificateVersions
public PagedList<CertificateItem> listCertificateVersions(final String vaultBaseUrl, final String certificateName) { return getCertificateVersions(vaultBaseUrl, certificateName); }
java
public PagedList<CertificateItem> listCertificateVersions(final String vaultBaseUrl, final String certificateName) { return getCertificateVersions(vaultBaseUrl, certificateName); }
[ "public", "PagedList", "<", "CertificateItem", ">", "listCertificateVersions", "(", "final", "String", "vaultBaseUrl", ",", "final", "String", "certificateName", ")", "{", "return", "getCertificateVersions", "(", "vaultBaseUrl", ",", "certificateName", ")", ";", "}" ]
List the versions of a certificate. @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net @param certificateName The name of the certificate @return the PagedList&lt;CertificateItem&gt; if successful.
[ "List", "the", "versions", "of", "a", "certificate", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientCustomImpl.java#L1545-L1547
app55/app55-java
src/support/java/com/googlecode/openbeans/beancontext/BeanContextServicesSupport.java
BeanContextServicesSupport.childJustRemovedHook
protected void childJustRemovedHook(Object child, BCSChild bcsChild) { if (bcsChild instanceof BCSSChild) { releaseServicesForChild((BCSSChild) bcsChild, false); } }
java
protected void childJustRemovedHook(Object child, BCSChild bcsChild) { if (bcsChild instanceof BCSSChild) { releaseServicesForChild((BCSSChild) bcsChild, false); } }
[ "protected", "void", "childJustRemovedHook", "(", "Object", "child", ",", "BCSChild", "bcsChild", ")", "{", "if", "(", "bcsChild", "instanceof", "BCSSChild", ")", "{", "releaseServicesForChild", "(", "(", "BCSSChild", ")", "bcsChild", ",", "false", ")", ";", "...
This method is called everytime a child is removed from this context. <p> The implementation releases all services requested by the child. </p> @see com.googlecode.openbeans.beancontext.BeanContextSupport#childJustRemovedHook(java.lang.Object, com.googlecode.openbeans.beancontext.BeanContextSupport.BCSChild)
[ "This", "method", "is", "called", "everytime", "a", "child", "is", "removed", "from", "this", "context", ".", "<p", ">", "The", "implementation", "releases", "all", "services", "requested", "by", "the", "child", ".", "<", "/", "p", ">" ]
train
https://github.com/app55/app55-java/blob/73e51d0f3141a859dfbd37ca9becef98477e553e/src/support/java/com/googlecode/openbeans/beancontext/BeanContextServicesSupport.java#L453-L459
alkacon/opencms-core
src/org/opencms/file/CmsObject.java
CmsObject.createProject
public CmsProject createProject(String name, String description, String groupname, String managergroupname) throws CmsException { return m_securityManager.createProject( m_context, name, description, groupname, managergroupname, CmsProject.PROJECT_TYPE_NORMAL); }
java
public CmsProject createProject(String name, String description, String groupname, String managergroupname) throws CmsException { return m_securityManager.createProject( m_context, name, description, groupname, managergroupname, CmsProject.PROJECT_TYPE_NORMAL); }
[ "public", "CmsProject", "createProject", "(", "String", "name", ",", "String", "description", ",", "String", "groupname", ",", "String", "managergroupname", ")", "throws", "CmsException", "{", "return", "m_securityManager", ".", "createProject", "(", "m_context", ",...
Creates a new project.<p> @param name the name of the project to create @param description the description for the new project @param groupname the name of the project user group @param managergroupname the name of the project manager group @return the created project @throws CmsException if something goes wrong
[ "Creates", "a", "new", "project", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/file/CmsObject.java#L675-L685
kkopacz/agiso-tempel
bundles/tempel-core/src/main/java/org/agiso/tempel/core/RecursiveTemplateVerifier.java
RecursiveTemplateVerifier.verifyTemplate
private void verifyTemplate(Template<?> template, LinkedHashSet<String> templates) { String id = template.getKey(); // Sprawdzanie, czy w gałęzi wywołań szablonów nie ma zapętlenia: if(templates.contains(id)) { // Wyświetlanie gałęzi z zapętleniem i wyrzucanie wyjątku: Iterator<String> t = templates.iterator(); System.out.print(t.next()); while(t.hasNext()) { System.out.print("->" + t.next()); } System.out.println("->" + id); throw new IllegalStateException("Zapętlenie wywołań szablonu '" + id + "'"); } // Szablon OK. Dodawanie do zbioru szablonów gałęzi: templates.add(id); // // Sprawdzanie każdego z podszablonów szablonu: // if(template.getReferences() != null) { // for(TemplateReference reference : template.getReferences()) { // verifyTemplate(reference, templates); // } // } }
java
private void verifyTemplate(Template<?> template, LinkedHashSet<String> templates) { String id = template.getKey(); // Sprawdzanie, czy w gałęzi wywołań szablonów nie ma zapętlenia: if(templates.contains(id)) { // Wyświetlanie gałęzi z zapętleniem i wyrzucanie wyjątku: Iterator<String> t = templates.iterator(); System.out.print(t.next()); while(t.hasNext()) { System.out.print("->" + t.next()); } System.out.println("->" + id); throw new IllegalStateException("Zapętlenie wywołań szablonu '" + id + "'"); } // Szablon OK. Dodawanie do zbioru szablonów gałęzi: templates.add(id); // // Sprawdzanie każdego z podszablonów szablonu: // if(template.getReferences() != null) { // for(TemplateReference reference : template.getReferences()) { // verifyTemplate(reference, templates); // } // } }
[ "private", "void", "verifyTemplate", "(", "Template", "<", "?", ">", "template", ",", "LinkedHashSet", "<", "String", ">", "templates", ")", "{", "String", "id", "=", "template", ".", "getKey", "(", ")", ";", "// Sprawdzanie, czy w gałęzi wywołań szablonów nie ma ...
Weryfikuje poprawność szablonu, szablonu nadrzędnego i rekurencyjne sprawdza wszystkie szablony używane. Kontroluje, czy drzewie wywołań szablonów nie występuje zapętlenie. @param template Szablon do weryfikacji. @param templates Zbiór identyfikatorów szablonów gałęzi. Wykorzystywany do wykrywania zapętleń wywołań.
[ "Weryfikuje", "poprawność", "szablonu", "szablonu", "nadrzędnego", "i", "rekurencyjne", "sprawdza", "wszystkie", "szablony", "używane", ".", "Kontroluje", "czy", "drzewie", "wywołań", "szablonów", "nie", "występuje", "zapętlenie", "." ]
train
https://github.com/kkopacz/agiso-tempel/blob/ff7a96153153b6bc07212d776816b87d9538f6fa/bundles/tempel-core/src/main/java/org/agiso/tempel/core/RecursiveTemplateVerifier.java#L51-L76
atomix/atomix
utils/src/main/java/io/atomix/utils/config/ConfigMapper.java
ConfigMapper.loadFiles
public <T> T loadFiles(Class<T> type, List<File> files, List<String> resources) { if (files == null) { return loadResources(type, resources); } Config config = ConfigFactory.systemProperties(); for (File file : files) { config = config.withFallback(ConfigFactory.parseFile(file, ConfigParseOptions.defaults().setAllowMissing(false))); } for (String resource : resources) { config = config.withFallback(ConfigFactory.load(classLoader, resource)); } return map(checkNotNull(config, "config cannot be null").resolve(), type); }
java
public <T> T loadFiles(Class<T> type, List<File> files, List<String> resources) { if (files == null) { return loadResources(type, resources); } Config config = ConfigFactory.systemProperties(); for (File file : files) { config = config.withFallback(ConfigFactory.parseFile(file, ConfigParseOptions.defaults().setAllowMissing(false))); } for (String resource : resources) { config = config.withFallback(ConfigFactory.load(classLoader, resource)); } return map(checkNotNull(config, "config cannot be null").resolve(), type); }
[ "public", "<", "T", ">", "T", "loadFiles", "(", "Class", "<", "T", ">", "type", ",", "List", "<", "File", ">", "files", ",", "List", "<", "String", ">", "resources", ")", "{", "if", "(", "files", "==", "null", ")", "{", "return", "loadResources", ...
Loads the given configuration file using the mapper, falling back to the given resources. @param type the type to load @param files the files to load @param resources the resources to which to fall back @param <T> the resulting type @return the loaded configuration
[ "Loads", "the", "given", "configuration", "file", "using", "the", "mapper", "falling", "back", "to", "the", "given", "resources", "." ]
train
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/utils/src/main/java/io/atomix/utils/config/ConfigMapper.java#L76-L90
google/error-prone-javac
src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/HtmlDocletWriter.java
HtmlDocletWriter.getTargetModulePackageLink
public Content getTargetModulePackageLink(PackageElement pkg, String target, Content label, ModuleElement mdle) { return getHyperLink(pathString(pkg, DocPaths.PACKAGE_SUMMARY), label, "", target); }
java
public Content getTargetModulePackageLink(PackageElement pkg, String target, Content label, ModuleElement mdle) { return getHyperLink(pathString(pkg, DocPaths.PACKAGE_SUMMARY), label, "", target); }
[ "public", "Content", "getTargetModulePackageLink", "(", "PackageElement", "pkg", ",", "String", "target", ",", "Content", "label", ",", "ModuleElement", "mdle", ")", "{", "return", "getHyperLink", "(", "pathString", "(", "pkg", ",", "DocPaths", ".", "PACKAGE_SUMMA...
Get Module Package link, with target frame. @param pkg the PackageElement @param target name of the target frame @param label tag for the link @param mdle the module being documented @return a content for the target module packages link
[ "Get", "Module", "Package", "link", "with", "target", "frame", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/HtmlDocletWriter.java#L372-L376
b3dgs/lionengine
lionengine-core/src/main/java/com/b3dgs/lionengine/graphic/raster/RasterImage.java
RasterImage.createRaster
private ImageBuffer createRaster(Media rasterMedia, Raster raster, int i, boolean save) { final ImageBuffer rasterBuffer; if (rasterMedia.exists()) { rasterBuffer = Graphics.getImageBuffer(rasterMedia); rasterBuffer.prepare(); } else { final double fr = getRasterFactor(i, raster.getRed()); final double fg = getRasterFactor(i, raster.getGreen()); final double fb = getRasterFactor(i, raster.getBlue()); rasterBuffer = Graphics.getRasterBuffer(surface, fr, fg, fb); if (save) { Graphics.saveImage(rasterBuffer, rasterMedia); } } return rasterBuffer; }
java
private ImageBuffer createRaster(Media rasterMedia, Raster raster, int i, boolean save) { final ImageBuffer rasterBuffer; if (rasterMedia.exists()) { rasterBuffer = Graphics.getImageBuffer(rasterMedia); rasterBuffer.prepare(); } else { final double fr = getRasterFactor(i, raster.getRed()); final double fg = getRasterFactor(i, raster.getGreen()); final double fb = getRasterFactor(i, raster.getBlue()); rasterBuffer = Graphics.getRasterBuffer(surface, fr, fg, fb); if (save) { Graphics.saveImage(rasterBuffer, rasterMedia); } } return rasterBuffer; }
[ "private", "ImageBuffer", "createRaster", "(", "Media", "rasterMedia", ",", "Raster", "raster", ",", "int", "i", ",", "boolean", "save", ")", "{", "final", "ImageBuffer", "rasterBuffer", ";", "if", "(", "rasterMedia", ".", "exists", "(", ")", ")", "{", "ra...
Create raster from data or load from cache. @param rasterMedia The raster media. @param raster The raster data. @param i The raster index. @param save <code>true</code> to save generated raster, <code>false</code> else. @return The created raster.
[ "Create", "raster", "from", "data", "or", "load", "from", "cache", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-core/src/main/java/com/b3dgs/lionengine/graphic/raster/RasterImage.java#L219-L241
Azure/azure-sdk-for-java
cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/implementation/BingWebSearchImpl.java
BingWebSearchImpl.searchWithServiceResponseAsync
public Observable<ServiceResponse<SearchResponse>> searchWithServiceResponseAsync(String query, SearchOptionalParameter searchOptionalParameter) { if (query == null) { throw new IllegalArgumentException("Parameter query is required and cannot be null."); } final String acceptLanguage = searchOptionalParameter != null ? searchOptionalParameter.acceptLanguage() : null; final String pragma = searchOptionalParameter != null ? searchOptionalParameter.pragma() : null; final String userAgent = searchOptionalParameter != null ? searchOptionalParameter.userAgent() : this.client.userAgent(); final String clientId = searchOptionalParameter != null ? searchOptionalParameter.clientId() : null; final String clientIp = searchOptionalParameter != null ? searchOptionalParameter.clientIp() : null; final String location = searchOptionalParameter != null ? searchOptionalParameter.location() : null; final Integer answerCount = searchOptionalParameter != null ? searchOptionalParameter.answerCount() : null; final String countryCode = searchOptionalParameter != null ? searchOptionalParameter.countryCode() : null; final Integer count = searchOptionalParameter != null ? searchOptionalParameter.count() : null; final Freshness freshness = searchOptionalParameter != null ? searchOptionalParameter.freshness() : null; final String market = searchOptionalParameter != null ? searchOptionalParameter.market() : null; final Integer offset = searchOptionalParameter != null ? searchOptionalParameter.offset() : null; final List<AnswerType> promote = searchOptionalParameter != null ? searchOptionalParameter.promote() : null; final List<AnswerType> responseFilter = searchOptionalParameter != null ? searchOptionalParameter.responseFilter() : null; final SafeSearch safeSearch = searchOptionalParameter != null ? searchOptionalParameter.safeSearch() : null; final String setLang = searchOptionalParameter != null ? searchOptionalParameter.setLang() : null; final Boolean textDecorations = searchOptionalParameter != null ? searchOptionalParameter.textDecorations() : null; final TextFormat textFormat = searchOptionalParameter != null ? searchOptionalParameter.textFormat() : null; return searchWithServiceResponseAsync(query, acceptLanguage, pragma, userAgent, clientId, clientIp, location, answerCount, countryCode, count, freshness, market, offset, promote, responseFilter, safeSearch, setLang, textDecorations, textFormat); }
java
public Observable<ServiceResponse<SearchResponse>> searchWithServiceResponseAsync(String query, SearchOptionalParameter searchOptionalParameter) { if (query == null) { throw new IllegalArgumentException("Parameter query is required and cannot be null."); } final String acceptLanguage = searchOptionalParameter != null ? searchOptionalParameter.acceptLanguage() : null; final String pragma = searchOptionalParameter != null ? searchOptionalParameter.pragma() : null; final String userAgent = searchOptionalParameter != null ? searchOptionalParameter.userAgent() : this.client.userAgent(); final String clientId = searchOptionalParameter != null ? searchOptionalParameter.clientId() : null; final String clientIp = searchOptionalParameter != null ? searchOptionalParameter.clientIp() : null; final String location = searchOptionalParameter != null ? searchOptionalParameter.location() : null; final Integer answerCount = searchOptionalParameter != null ? searchOptionalParameter.answerCount() : null; final String countryCode = searchOptionalParameter != null ? searchOptionalParameter.countryCode() : null; final Integer count = searchOptionalParameter != null ? searchOptionalParameter.count() : null; final Freshness freshness = searchOptionalParameter != null ? searchOptionalParameter.freshness() : null; final String market = searchOptionalParameter != null ? searchOptionalParameter.market() : null; final Integer offset = searchOptionalParameter != null ? searchOptionalParameter.offset() : null; final List<AnswerType> promote = searchOptionalParameter != null ? searchOptionalParameter.promote() : null; final List<AnswerType> responseFilter = searchOptionalParameter != null ? searchOptionalParameter.responseFilter() : null; final SafeSearch safeSearch = searchOptionalParameter != null ? searchOptionalParameter.safeSearch() : null; final String setLang = searchOptionalParameter != null ? searchOptionalParameter.setLang() : null; final Boolean textDecorations = searchOptionalParameter != null ? searchOptionalParameter.textDecorations() : null; final TextFormat textFormat = searchOptionalParameter != null ? searchOptionalParameter.textFormat() : null; return searchWithServiceResponseAsync(query, acceptLanguage, pragma, userAgent, clientId, clientIp, location, answerCount, countryCode, count, freshness, market, offset, promote, responseFilter, safeSearch, setLang, textDecorations, textFormat); }
[ "public", "Observable", "<", "ServiceResponse", "<", "SearchResponse", ">", ">", "searchWithServiceResponseAsync", "(", "String", "query", ",", "SearchOptionalParameter", "searchOptionalParameter", ")", "{", "if", "(", "query", "==", "null", ")", "{", "throw", "new"...
The Web Search API lets you send a search query to Bing and get back search results that include links to webpages, images, and more. @param query The user's search query term. The term may not be empty. The term may contain Bing Advanced Operators. For example, to limit results to a specific domain, use the site: operator. @param searchOptionalParameter 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 SearchResponse object
[ "The", "Web", "Search", "API", "lets", "you", "send", "a", "search", "query", "to", "Bing", "and", "get", "back", "search", "results", "that", "include", "links", "to", "webpages", "images", "and", "more", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/implementation/BingWebSearchImpl.java#L122-L146
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/CustomFunctions.java
CustomFunctions.word_slice
public static String word_slice(EvaluationContext ctx, Object text, Object start, @IntegerDefault(0) Object stop, @BooleanDefault(false) Object bySpaces) { String _text = Conversions.toString(text, ctx); int _start = Conversions.toInteger(start, ctx); Integer _stop = Conversions.toInteger(stop, ctx); boolean _bySpaces = Conversions.toBoolean(bySpaces, ctx); if (_start == 0) { throw new RuntimeException("Start word cannot be zero"); } else if (_start > 0) { _start -= 1; // convert to a zero-based offset } if (_stop == 0) { // zero is treated as no end _stop = null; } else if (_stop > 0) { _stop -= 1; // convert to a zero-based offset } List<String> words = getWords(_text, _bySpaces); List<String> selection = ExpressionUtils.slice(words, _start, _stop); // re-combine selected words with a single space return StringUtils.join(selection, ' '); }
java
public static String word_slice(EvaluationContext ctx, Object text, Object start, @IntegerDefault(0) Object stop, @BooleanDefault(false) Object bySpaces) { String _text = Conversions.toString(text, ctx); int _start = Conversions.toInteger(start, ctx); Integer _stop = Conversions.toInteger(stop, ctx); boolean _bySpaces = Conversions.toBoolean(bySpaces, ctx); if (_start == 0) { throw new RuntimeException("Start word cannot be zero"); } else if (_start > 0) { _start -= 1; // convert to a zero-based offset } if (_stop == 0) { // zero is treated as no end _stop = null; } else if (_stop > 0) { _stop -= 1; // convert to a zero-based offset } List<String> words = getWords(_text, _bySpaces); List<String> selection = ExpressionUtils.slice(words, _start, _stop); // re-combine selected words with a single space return StringUtils.join(selection, ' '); }
[ "public", "static", "String", "word_slice", "(", "EvaluationContext", "ctx", ",", "Object", "text", ",", "Object", "start", ",", "@", "IntegerDefault", "(", "0", ")", "Object", "stop", ",", "@", "BooleanDefault", "(", "false", ")", "Object", "bySpaces", ")",...
Extracts a substring spanning from start up to but not-including stop
[ "Extracts", "a", "substring", "spanning", "from", "start", "up", "to", "but", "not", "-", "including", "stop" ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/CustomFunctions.java#L135-L158
JOML-CI/JOML
src/org/joml/Quaternionf.java
Quaternionf.fromAxisAngleRad
public Quaternionf fromAxisAngleRad(Vector3fc axis, float angle) { return fromAxisAngleRad(axis.x(), axis.y(), axis.z(), angle); }
java
public Quaternionf fromAxisAngleRad(Vector3fc axis, float angle) { return fromAxisAngleRad(axis.x(), axis.y(), axis.z(), angle); }
[ "public", "Quaternionf", "fromAxisAngleRad", "(", "Vector3fc", "axis", ",", "float", "angle", ")", "{", "return", "fromAxisAngleRad", "(", "axis", ".", "x", "(", ")", ",", "axis", ".", "y", "(", ")", ",", "axis", ".", "z", "(", ")", ",", "angle", ")"...
Set this quaternion to be a representation of the supplied axis and angle (in radians). @param axis the rotation axis @param angle the angle in radians @return this
[ "Set", "this", "quaternion", "to", "be", "a", "representation", "of", "the", "supplied", "axis", "and", "angle", "(", "in", "radians", ")", "." ]
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Quaternionf.java#L881-L883
eurekaclinical/eurekaclinical-standard-apis
src/main/java/org/eurekaclinical/standardapis/filter/AbstractRolesFilter.java
AbstractRolesFilter.doFilter
@Override public void doFilter(ServletRequest inRequest, ServletResponse inResponse, FilterChain inChain) throws IOException, ServletException { HttpServletRequest servletRequest = (HttpServletRequest) inRequest; Principal principal = servletRequest.getUserPrincipal(); HttpSession session = servletRequest.getSession(false); if (principal != null && session != null) { String[] roleNames; synchronized (session) { roleNames = (String[]) session.getAttribute("roles"); if (roleNames == null) { roleNames = getRoles(principal, inRequest); session.setAttribute("roles", roleNames); } } HttpServletRequest wrappedRequest = new RolesRequestWrapper( servletRequest, principal, roleNames); inChain.doFilter(wrappedRequest, inResponse); } else { inChain.doFilter(inRequest, inResponse); } }
java
@Override public void doFilter(ServletRequest inRequest, ServletResponse inResponse, FilterChain inChain) throws IOException, ServletException { HttpServletRequest servletRequest = (HttpServletRequest) inRequest; Principal principal = servletRequest.getUserPrincipal(); HttpSession session = servletRequest.getSession(false); if (principal != null && session != null) { String[] roleNames; synchronized (session) { roleNames = (String[]) session.getAttribute("roles"); if (roleNames == null) { roleNames = getRoles(principal, inRequest); session.setAttribute("roles", roleNames); } } HttpServletRequest wrappedRequest = new RolesRequestWrapper( servletRequest, principal, roleNames); inChain.doFilter(wrappedRequest, inResponse); } else { inChain.doFilter(inRequest, inResponse); } }
[ "@", "Override", "public", "void", "doFilter", "(", "ServletRequest", "inRequest", ",", "ServletResponse", "inResponse", ",", "FilterChain", "inChain", ")", "throws", "IOException", ",", "ServletException", "{", "HttpServletRequest", "servletRequest", "=", "(", "HttpS...
Sets a <code>roles</code> session attribute containing an array of role names for the current user principal. It fetches the roles array from the {@link #getRoles(java.security.Principal, javax.servlet.ServletRequest) } call. If the session attribute is not null, it will not fetch the user's roles again. If there is no session or if the user principal is not set, this filter just passes the request and response onto the next filter in the chain. @param inRequest the servlet request. @param inResponse the servlet response. @param inChain the filter chain. @throws IOException if the exception is thrown from downstream in the filter chain. @throws ServletException if the {@link #getRoles(java.security.Principal, javax.servlet.ServletRequest) } call fails or if the exception is thrown from downstream in the filter chain.
[ "Sets", "a", "<code", ">", "roles<", "/", "code", ">", "session", "attribute", "containing", "an", "array", "of", "role", "names", "for", "the", "current", "user", "principal", ".", "It", "fetches", "the", "roles", "array", "from", "the", "{", "@link", "...
train
https://github.com/eurekaclinical/eurekaclinical-standard-apis/blob/690036dde82a4f2c2106d32403cdf1c713429377/src/main/java/org/eurekaclinical/standardapis/filter/AbstractRolesFilter.java#L69-L90
mikepenz/Materialize
library/src/main/java/com/mikepenz/materialize/util/UIUtils.java
UIUtils.setBackground
@Deprecated @SuppressLint("NewApi") public static void setBackground(View v, Drawable d) { ViewCompat.setBackground(v, d); }
java
@Deprecated @SuppressLint("NewApi") public static void setBackground(View v, Drawable d) { ViewCompat.setBackground(v, d); }
[ "@", "Deprecated", "@", "SuppressLint", "(", "\"NewApi\"", ")", "public", "static", "void", "setBackground", "(", "View", "v", ",", "Drawable", "d", ")", "{", "ViewCompat", ".", "setBackground", "(", "v", ",", "d", ")", ";", "}" ]
helper method to set the background depending on the android version @param v @param d
[ "helper", "method", "to", "set", "the", "background", "depending", "on", "the", "android", "version" ]
train
https://github.com/mikepenz/Materialize/blob/2612c10c7570191a78d57f23620e945d61370e3d/library/src/main/java/com/mikepenz/materialize/util/UIUtils.java#L69-L73
ist-dresden/composum
sling/core/commons/src/main/java/com/composum/sling/cpnl/CpnlElFunctions.java
CpnlElFunctions.unmappedExternalUrl
public static String unmappedExternalUrl(SlingHttpServletRequest request, String path) { return LinkUtil.getAbsoluteUrl(request, LinkUtil.getUnmappedUrl(request, path)); }
java
public static String unmappedExternalUrl(SlingHttpServletRequest request, String path) { return LinkUtil.getAbsoluteUrl(request, LinkUtil.getUnmappedUrl(request, path)); }
[ "public", "static", "String", "unmappedExternalUrl", "(", "SlingHttpServletRequest", "request", ",", "String", "path", ")", "{", "return", "LinkUtil", ".", "getAbsoluteUrl", "(", "request", ",", "LinkUtil", ".", "getUnmappedUrl", "(", "request", ",", "path", ")", ...
Builds an external (full qualified) URL for a repository path using the LinkUtil.getUnmappedURL() method. @param request the current request (domain host hint) @param path the repository path @return the URL built in the context of the requested domain host
[ "Builds", "an", "external", "(", "full", "qualified", ")", "URL", "for", "a", "repository", "path", "using", "the", "LinkUtil", ".", "getUnmappedURL", "()", "method", "." ]
train
https://github.com/ist-dresden/composum/blob/ebc79f559f6022c935240c19102539bdfb1bd1e2/sling/core/commons/src/main/java/com/composum/sling/cpnl/CpnlElFunctions.java#L231-L233
bitcoinj/bitcoinj
core/src/main/java/org/bitcoinj/core/Coin.java
Coin.valueOf
public static Coin valueOf(final int coins, final int cents) { checkArgument(cents < 100); checkArgument(cents >= 0); checkArgument(coins >= 0); final Coin coin = COIN.multiply(coins).add(CENT.multiply(cents)); return coin; }
java
public static Coin valueOf(final int coins, final int cents) { checkArgument(cents < 100); checkArgument(cents >= 0); checkArgument(coins >= 0); final Coin coin = COIN.multiply(coins).add(CENT.multiply(cents)); return coin; }
[ "public", "static", "Coin", "valueOf", "(", "final", "int", "coins", ",", "final", "int", "cents", ")", "{", "checkArgument", "(", "cents", "<", "100", ")", ";", "checkArgument", "(", "cents", ">=", "0", ")", ";", "checkArgument", "(", "coins", ">=", "...
Convert an amount expressed in the way humans are used to into satoshis.
[ "Convert", "an", "amount", "expressed", "in", "the", "way", "humans", "are", "used", "to", "into", "satoshis", "." ]
train
https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Coin.java#L109-L115
Deep-Symmetry/beat-link
src/main/java/org/deepsymmetry/beatlink/data/DeckReference.java
DeckReference.getDeckReference
public static synchronized DeckReference getDeckReference(int player, int hotCue) { Map<Integer, DeckReference> playerMap = instances.get(player); if (playerMap == null) { playerMap = new HashMap<Integer, DeckReference>(); instances.put(player, playerMap); } DeckReference result = playerMap.get(hotCue); if (result == null) { result = new DeckReference(player, hotCue); playerMap.put(hotCue, result); } return result; }
java
public static synchronized DeckReference getDeckReference(int player, int hotCue) { Map<Integer, DeckReference> playerMap = instances.get(player); if (playerMap == null) { playerMap = new HashMap<Integer, DeckReference>(); instances.put(player, playerMap); } DeckReference result = playerMap.get(hotCue); if (result == null) { result = new DeckReference(player, hotCue); playerMap.put(hotCue, result); } return result; }
[ "public", "static", "synchronized", "DeckReference", "getDeckReference", "(", "int", "player", ",", "int", "hotCue", ")", "{", "Map", "<", "Integer", ",", "DeckReference", ">", "playerMap", "=", "instances", ".", "get", "(", "player", ")", ";", "if", "(", ...
Get a unique reference to a place where a track is currently loaded in a player. @param player the player in which the track is loaded @param hotCue hot cue number in which the track is loaded, or 0 if it is actively loaded on the playback deck @return the instance that will always represent a reference to the specified player and hot cue
[ "Get", "a", "unique", "reference", "to", "a", "place", "where", "a", "track", "is", "currently", "loaded", "in", "a", "player", "." ]
train
https://github.com/Deep-Symmetry/beat-link/blob/f958a2a70e8a87a31a75326d7b4db77c2f0b4212/src/main/java/org/deepsymmetry/beatlink/data/DeckReference.java#L50-L62
VoltDB/voltdb
src/frontend/org/voltdb/exportclient/ExportEncoder.java
ExportEncoder.encodeString
static public void encodeString(final FastSerializer fs, String value) throws IOException { final byte[] strdata = value.getBytes("UTF-8"); fs.writeInt(strdata.length); fs.write(strdata); }
java
static public void encodeString(final FastSerializer fs, String value) throws IOException { final byte[] strdata = value.getBytes("UTF-8"); fs.writeInt(strdata.length); fs.write(strdata); }
[ "static", "public", "void", "encodeString", "(", "final", "FastSerializer", "fs", ",", "String", "value", ")", "throws", "IOException", "{", "final", "byte", "[", "]", "strdata", "=", "value", ".", "getBytes", "(", "\"UTF-8\"", ")", ";", "fs", ".", "writeI...
Read a string according to the Export encoding specification @param fds @throws IOException
[ "Read", "a", "string", "according", "to", "the", "Export", "encoding", "specification" ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/exportclient/ExportEncoder.java#L235-L240
netscaler/sdx_nitro
src/main/java/com/citrix/sdx/nitro/resource/config/ns/ns_device_profile.java
ns_device_profile.get_nitro_bulk_response
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { ns_device_profile_responses result = (ns_device_profile_responses) service.get_payload_formatter().string_to_resource(ns_device_profile_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == SESSION_NOT_EXISTS) service.clear_session(); throw new nitro_exception(result.message, result.errorcode, (base_response [])result.ns_device_profile_response_array); } ns_device_profile[] result_ns_device_profile = new ns_device_profile[result.ns_device_profile_response_array.length]; for(int i = 0; i < result.ns_device_profile_response_array.length; i++) { result_ns_device_profile[i] = result.ns_device_profile_response_array[i].ns_device_profile[0]; } return result_ns_device_profile; }
java
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { ns_device_profile_responses result = (ns_device_profile_responses) service.get_payload_formatter().string_to_resource(ns_device_profile_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == SESSION_NOT_EXISTS) service.clear_session(); throw new nitro_exception(result.message, result.errorcode, (base_response [])result.ns_device_profile_response_array); } ns_device_profile[] result_ns_device_profile = new ns_device_profile[result.ns_device_profile_response_array.length]; for(int i = 0; i < result.ns_device_profile_response_array.length; i++) { result_ns_device_profile[i] = result.ns_device_profile_response_array[i].ns_device_profile[0]; } return result_ns_device_profile; }
[ "protected", "base_resource", "[", "]", "get_nitro_bulk_response", "(", "nitro_service", "service", ",", "String", "response", ")", "throws", "Exception", "{", "ns_device_profile_responses", "result", "=", "(", "ns_device_profile_responses", ")", "service", ".", "get_pa...
<pre> Converts API response of bulk operation into object and returns the object array in case of get request. </pre>
[ "<pre", ">", "Converts", "API", "response", "of", "bulk", "operation", "into", "object", "and", "returns", "the", "object", "array", "in", "case", "of", "get", "request", ".", "<", "/", "pre", ">" ]
train
https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/ns/ns_device_profile.java#L238-L255
geomajas/geomajas-project-client-gwt2
impl/src/main/java/org/geomajas/gwt2/client/gfx/GeometryPath.java
GeometryPath.moveCoordinate
public void moveCoordinate(Coordinate coordinate, int index) { if (index < coordinates.length) { coordinates[index] = (Coordinate) coordinate.clone(); } setCoordinates(coordinates); }
java
public void moveCoordinate(Coordinate coordinate, int index) { if (index < coordinates.length) { coordinates[index] = (Coordinate) coordinate.clone(); } setCoordinates(coordinates); }
[ "public", "void", "moveCoordinate", "(", "Coordinate", "coordinate", ",", "int", "index", ")", "{", "if", "(", "index", "<", "coordinates", ".", "length", ")", "{", "coordinates", "[", "index", "]", "=", "(", "Coordinate", ")", "coordinate", ".", "clone", ...
Move the coordinate at the specified index. @param coordinate the new coordinate @param index
[ "Move", "the", "coordinate", "at", "the", "specified", "index", "." ]
train
https://github.com/geomajas/geomajas-project-client-gwt2/blob/bd8d7904e861fa80522eed7b83c4ea99844180c7/impl/src/main/java/org/geomajas/gwt2/client/gfx/GeometryPath.java#L154-L159
wildfly/wildfly-core
protocol/src/main/java/org/jboss/as/protocol/mgmt/AbstractMessageHandler.java
AbstractMessageHandler.executeRequest
protected <T, A> AsyncFuture<T> executeRequest(final ManagementRequest<T, A> request, final Channel channel, final ActiveOperation<T, A> support) { assert support != null; updateChannelRef(support, channel); final Integer requestId = this.requestID.incrementAndGet(); final ActiveRequest<T, A> ar = new ActiveRequest<T, A>(support, request); requests.put(requestId, ar); final ManagementRequestHeader header = new ManagementRequestHeader(ManagementProtocol.VERSION, requestId, support.getOperationId(), request.getOperationType()); final ActiveOperation.ResultHandler<T> resultHandler = support.getResultHandler(); try { request.sendRequest(resultHandler, new ManagementRequestContextImpl<T, A>(support, channel, header, getExecutor())); } catch (Exception e) { resultHandler.failed(e); requests.remove(requestId); } return support.getResult(); }
java
protected <T, A> AsyncFuture<T> executeRequest(final ManagementRequest<T, A> request, final Channel channel, final ActiveOperation<T, A> support) { assert support != null; updateChannelRef(support, channel); final Integer requestId = this.requestID.incrementAndGet(); final ActiveRequest<T, A> ar = new ActiveRequest<T, A>(support, request); requests.put(requestId, ar); final ManagementRequestHeader header = new ManagementRequestHeader(ManagementProtocol.VERSION, requestId, support.getOperationId(), request.getOperationType()); final ActiveOperation.ResultHandler<T> resultHandler = support.getResultHandler(); try { request.sendRequest(resultHandler, new ManagementRequestContextImpl<T, A>(support, channel, header, getExecutor())); } catch (Exception e) { resultHandler.failed(e); requests.remove(requestId); } return support.getResult(); }
[ "protected", "<", "T", ",", "A", ">", "AsyncFuture", "<", "T", ">", "executeRequest", "(", "final", "ManagementRequest", "<", "T", ",", "A", ">", "request", ",", "final", "Channel", "channel", ",", "final", "ActiveOperation", "<", "T", ",", "A", ">", "...
Execute a request. @param request the request @param channel the channel @param support the request support @return the future result
[ "Execute", "a", "request", "." ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/protocol/src/main/java/org/jboss/as/protocol/mgmt/AbstractMessageHandler.java#L260-L275
querydsl/querydsl
querydsl-sql/src/main/java/com/querydsl/sql/AbstractSQLQuery.java
AbstractSQLQuery.startContext
protected SQLListenerContextImpl startContext(Connection connection, QueryMetadata metadata) { SQLListenerContextImpl context = new SQLListenerContextImpl(metadata, connection); if (parentContext != null) { context.setData(PARENT_CONTEXT, parentContext); } listeners.start(context); return context; }
java
protected SQLListenerContextImpl startContext(Connection connection, QueryMetadata metadata) { SQLListenerContextImpl context = new SQLListenerContextImpl(metadata, connection); if (parentContext != null) { context.setData(PARENT_CONTEXT, parentContext); } listeners.start(context); return context; }
[ "protected", "SQLListenerContextImpl", "startContext", "(", "Connection", "connection", ",", "QueryMetadata", "metadata", ")", "{", "SQLListenerContextImpl", "context", "=", "new", "SQLListenerContextImpl", "(", "metadata", ",", "connection", ")", ";", "if", "(", "par...
Called to create and start a new SQL Listener context @param connection the database connection @param metadata the meta data for that context @return the newly started context
[ "Called", "to", "create", "and", "start", "a", "new", "SQL", "Listener", "context" ]
train
https://github.com/querydsl/querydsl/blob/2bf234caf78549813a1e0f44d9c30ecc5ef734e3/querydsl-sql/src/main/java/com/querydsl/sql/AbstractSQLQuery.java#L220-L227
HeidelTime/heideltime
src/de/unihd/dbs/uima/reader/tempeval2reader/Tempeval2Reader.java
Tempeval2Reader.addTokenAnnotation
public Integer addTokenAnnotation(String tokenString, String fileId, Integer sentId, Integer tokId, Integer positionCounter, JCas jcas){ Token token = new Token(jcas); if (!((sentId == newTokSentNumber) && (tokId == newTokSentNumber))){ if(USE_SPACES) // in chinese, there are no spaces, so the +1 correction is unnecessary positionCounter = positionCounter + 1; } token.setBegin(positionCounter); positionCounter = positionCounter + tokenString.length(); token.setEnd(positionCounter); token.setTokenId(tokId); token.setSentId(sentId); token.setFilename(fileId); token.addToIndexes(); String id = fileId+"_"+sentId+"_"+tokId; hmToken.put(id, token); return positionCounter; }
java
public Integer addTokenAnnotation(String tokenString, String fileId, Integer sentId, Integer tokId, Integer positionCounter, JCas jcas){ Token token = new Token(jcas); if (!((sentId == newTokSentNumber) && (tokId == newTokSentNumber))){ if(USE_SPACES) // in chinese, there are no spaces, so the +1 correction is unnecessary positionCounter = positionCounter + 1; } token.setBegin(positionCounter); positionCounter = positionCounter + tokenString.length(); token.setEnd(positionCounter); token.setTokenId(tokId); token.setSentId(sentId); token.setFilename(fileId); token.addToIndexes(); String id = fileId+"_"+sentId+"_"+tokId; hmToken.put(id, token); return positionCounter; }
[ "public", "Integer", "addTokenAnnotation", "(", "String", "tokenString", ",", "String", "fileId", ",", "Integer", "sentId", ",", "Integer", "tokId", ",", "Integer", "positionCounter", ",", "JCas", "jcas", ")", "{", "Token", "token", "=", "new", "Token", "(", ...
Add token annotation to jcas @param tokenString @param fileId @param tokId @param positionCounter @param jcas @return
[ "Add", "token", "annotation", "to", "jcas" ]
train
https://github.com/HeidelTime/heideltime/blob/4ef5002eb5ecfeb818086ff7e394e792ee360335/src/de/unihd/dbs/uima/reader/tempeval2reader/Tempeval2Reader.java#L391-L409
codeprimate-software/cp-elements
src/main/java/org/cp/elements/lang/factory/AbstractObjectFactory.java
AbstractObjectFactory.resolveConstructor
protected Constructor resolveConstructor(final Class<?> objectType, final Class... parameterTypes) { try { return objectType.getConstructor(parameterTypes); } catch (NoSuchMethodException e) { if (!ArrayUtils.isEmpty(parameterTypes)) { Constructor constructor = resolveCompatibleConstructor(objectType, parameterTypes); // if the "compatible" constructor is null, resolve to finding the public, default no-arg constructor return (constructor != null ? constructor : resolveConstructor(objectType)); } throw new NoSuchConstructorException(String.format( "Failed to find a constructor with signature (%1$s) in Class (%2$s)", from(parameterTypes).toString(), objectType.getName()), e); } }
java
protected Constructor resolveConstructor(final Class<?> objectType, final Class... parameterTypes) { try { return objectType.getConstructor(parameterTypes); } catch (NoSuchMethodException e) { if (!ArrayUtils.isEmpty(parameterTypes)) { Constructor constructor = resolveCompatibleConstructor(objectType, parameterTypes); // if the "compatible" constructor is null, resolve to finding the public, default no-arg constructor return (constructor != null ? constructor : resolveConstructor(objectType)); } throw new NoSuchConstructorException(String.format( "Failed to find a constructor with signature (%1$s) in Class (%2$s)", from(parameterTypes).toString(), objectType.getName()), e); } }
[ "protected", "Constructor", "resolveConstructor", "(", "final", "Class", "<", "?", ">", "objectType", ",", "final", "Class", "...", "parameterTypes", ")", "{", "try", "{", "return", "objectType", ".", "getConstructor", "(", "parameterTypes", ")", ";", "}", "ca...
Resolves the Class constructor with the given signature as determined by the parameter types. @param objectType the Class from which the constructor is resolved. @param parameterTypes the array of Class types determining the resolved constructor's signature. @return a Constructor from the specified class with a matching signature based on the parameter types. @throws NullPointerException if either the objectType or parameterTypes are null. @see #resolveCompatibleConstructor(Class, Class[]) @see java.lang.Class @see java.lang.reflect.Constructor
[ "Resolves", "the", "Class", "constructor", "with", "the", "given", "signature", "as", "determined", "by", "the", "parameter", "types", "." ]
train
https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/factory/AbstractObjectFactory.java#L136-L151
alkacon/opencms-core
src/org/opencms/xml/CmsXmlUtils.java
CmsXmlUtils.unmarshalHelper
public static Document unmarshalHelper(InputSource source, EntityResolver resolver, boolean validate) throws CmsXmlException { if (null == source) { throw new CmsXmlException(Messages.get().container(Messages.ERR_UNMARSHALLING_XML_DOC_1, "source==null!")); } try { SAXReader reader = new SAXReader(); if (resolver != null) { reader.setEntityResolver(resolver); } reader.setMergeAdjacentText(true); reader.setStripWhitespaceText(true); if (!validate) { reader.setValidation(false); reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); } else { reader.setValidation(true); } return reader.read(source); } catch (DocumentException e) { String systemId = source != null ? source.getSystemId() : "???"; throw new CmsXmlException( Messages.get().container(Messages.ERR_UNMARSHALLING_XML_DOC_1, "(systemId = " + systemId + ")"), e); } catch (SAXException e) { String systemId = source != null ? source.getSystemId() : "???"; throw new CmsXmlException( Messages.get().container(Messages.ERR_UNMARSHALLING_XML_DOC_1, "(systemId = " + systemId + ")"), e); } }
java
public static Document unmarshalHelper(InputSource source, EntityResolver resolver, boolean validate) throws CmsXmlException { if (null == source) { throw new CmsXmlException(Messages.get().container(Messages.ERR_UNMARSHALLING_XML_DOC_1, "source==null!")); } try { SAXReader reader = new SAXReader(); if (resolver != null) { reader.setEntityResolver(resolver); } reader.setMergeAdjacentText(true); reader.setStripWhitespaceText(true); if (!validate) { reader.setValidation(false); reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); } else { reader.setValidation(true); } return reader.read(source); } catch (DocumentException e) { String systemId = source != null ? source.getSystemId() : "???"; throw new CmsXmlException( Messages.get().container(Messages.ERR_UNMARSHALLING_XML_DOC_1, "(systemId = " + systemId + ")"), e); } catch (SAXException e) { String systemId = source != null ? source.getSystemId() : "???"; throw new CmsXmlException( Messages.get().container(Messages.ERR_UNMARSHALLING_XML_DOC_1, "(systemId = " + systemId + ")"), e); } }
[ "public", "static", "Document", "unmarshalHelper", "(", "InputSource", "source", ",", "EntityResolver", "resolver", ",", "boolean", "validate", ")", "throws", "CmsXmlException", "{", "if", "(", "null", "==", "source", ")", "{", "throw", "new", "CmsXmlException", ...
Helper to unmarshal (read) xml contents from an input source into a document.<p> Using this method ensures that the OpenCms XML entity resolver is used.<p> Important: The encoding provided will NOT be used during unmarshalling, the XML parser will do this on the base of the information in the source String. The encoding is used for initializing the created instance of the document, which means it will be used when marshalling the document again later.<p> @param source the XML input source to use @param resolver the XML entity resolver to use @param validate if the reader should try to validate the xml code @return the unmarshalled XML document @throws CmsXmlException if something goes wrong
[ "Helper", "to", "unmarshal", "(", "read", ")", "xml", "contents", "from", "an", "input", "source", "into", "a", "document", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/CmsXmlUtils.java#L768-L800
HtmlUnit/htmlunit-cssparser
src/main/java/com/gargoylesoftware/css/parser/ParserUtils.java
ParserUtils.trimBy
public static String trimBy(final StringBuilder s, final int left, final int right) { return s.substring(left, s.length() - right); }
java
public static String trimBy(final StringBuilder s, final int left, final int right) { return s.substring(left, s.length() - right); }
[ "public", "static", "String", "trimBy", "(", "final", "StringBuilder", "s", ",", "final", "int", "left", ",", "final", "int", "right", ")", "{", "return", "s", ".", "substring", "(", "left", ",", "s", ".", "length", "(", ")", "-", "right", ")", ";", ...
Remove the given number of chars from start and end. There is no parameter checking, the caller has to take care of this. @param s the StringBuilder @param left no of chars to be removed from start @param right no of chars to be removed from end @return the trimmed string
[ "Remove", "the", "given", "number", "of", "chars", "from", "start", "and", "end", ".", "There", "is", "no", "parameter", "checking", "the", "caller", "has", "to", "take", "care", "of", "this", "." ]
train
https://github.com/HtmlUnit/htmlunit-cssparser/blob/384e4170737169b5b4c87c5766495d9b8a6d3866/src/main/java/com/gargoylesoftware/css/parser/ParserUtils.java#L36-L38
apache/flink
flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/window/internal/InternalWindowProcessFunction.java
InternalWindowProcessFunction.open
public void open(Context<K, W> ctx) throws Exception { this.ctx = ctx; this.windowAssigner.open(ctx); }
java
public void open(Context<K, W> ctx) throws Exception { this.ctx = ctx; this.windowAssigner.open(ctx); }
[ "public", "void", "open", "(", "Context", "<", "K", ",", "W", ">", "ctx", ")", "throws", "Exception", "{", "this", ".", "ctx", "=", "ctx", ";", "this", ".", "windowAssigner", ".", "open", "(", "ctx", ")", ";", "}" ]
Initialization method for the function. It is called before the actual working methods.
[ "Initialization", "method", "for", "the", "function", ".", "It", "is", "called", "before", "the", "actual", "working", "methods", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/window/internal/InternalWindowProcessFunction.java#L58-L61
stickfigure/batchfb
src/main/java/com/googlecode/batchfb/impl/Batch.java
Batch.createFetcher
private Later<JsonNode> createFetcher() { final RequestBuilder call = new GraphRequestBuilder(getGraphEndpoint(), HttpMethod.POST, this.timeout, this.retries); // This actually creates the correct JSON structure as an array String batchValue = JSONUtils.toJSON(this.graphRequests, this.mapper); if (log.isLoggable(Level.FINEST)) log.finest("Batch request is: " + batchValue); this.addParams(call, new Param[] { new Param("batch", batchValue) }); final HttpResponse response; try { response = call.execute(); } catch (IOException ex) { throw new IOFacebookException(ex); } return new Later<JsonNode>() { @Override public JsonNode get() throws FacebookException { try { if (response.getResponseCode() == HttpURLConnection.HTTP_OK || response.getResponseCode() == HttpURLConnection.HTTP_BAD_REQUEST || response.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { // If it was an error, we will recognize it in the content later. // It's possible we should capture all 4XX codes here. JsonNode result = mapper.readTree(response.getContentStream()); if (log.isLoggable(Level.FINEST)) log.finest("Response is: " + result); return result; } else { throw new IOFacebookException( "Unrecognized error " + response.getResponseCode() + " from " + call + " :: " + StringUtils.read(response.getContentStream())); } } catch (IOException e) { throw new IOFacebookException("Error calling " + call, e); } } }; }
java
private Later<JsonNode> createFetcher() { final RequestBuilder call = new GraphRequestBuilder(getGraphEndpoint(), HttpMethod.POST, this.timeout, this.retries); // This actually creates the correct JSON structure as an array String batchValue = JSONUtils.toJSON(this.graphRequests, this.mapper); if (log.isLoggable(Level.FINEST)) log.finest("Batch request is: " + batchValue); this.addParams(call, new Param[] { new Param("batch", batchValue) }); final HttpResponse response; try { response = call.execute(); } catch (IOException ex) { throw new IOFacebookException(ex); } return new Later<JsonNode>() { @Override public JsonNode get() throws FacebookException { try { if (response.getResponseCode() == HttpURLConnection.HTTP_OK || response.getResponseCode() == HttpURLConnection.HTTP_BAD_REQUEST || response.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { // If it was an error, we will recognize it in the content later. // It's possible we should capture all 4XX codes here. JsonNode result = mapper.readTree(response.getContentStream()); if (log.isLoggable(Level.FINEST)) log.finest("Response is: " + result); return result; } else { throw new IOFacebookException( "Unrecognized error " + response.getResponseCode() + " from " + call + " :: " + StringUtils.read(response.getContentStream())); } } catch (IOException e) { throw new IOFacebookException("Error calling " + call, e); } } }; }
[ "private", "Later", "<", "JsonNode", ">", "createFetcher", "(", ")", "{", "final", "RequestBuilder", "call", "=", "new", "GraphRequestBuilder", "(", "getGraphEndpoint", "(", ")", ",", "HttpMethod", ".", "POST", ",", "this", ".", "timeout", ",", "this", ".", ...
Constructs the batch query and executes it, possibly asynchronously. @return an asynchronous handle to the raw batch result, whatever it may be.
[ "Constructs", "the", "batch", "query", "and", "executes", "it", "possibly", "asynchronously", "." ]
train
https://github.com/stickfigure/batchfb/blob/ceeda78aa6d8397eec032ab1d8997adb7378e9e2/src/main/java/com/googlecode/batchfb/impl/Batch.java#L398-L442
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/TextRowProtocol.java
TextRowProtocol.getInternalFloat
public float getInternalFloat(ColumnInformation columnInfo) throws SQLException { if (lastValueWasNull()) { return 0; } switch (columnInfo.getColumnType()) { case BIT: return parseBit(); case TINYINT: case SMALLINT: case YEAR: case INTEGER: case MEDIUMINT: case FLOAT: case DOUBLE: case DECIMAL: case VARSTRING: case VARCHAR: case STRING: case OLDDECIMAL: case BIGINT: try { return Float.valueOf(new String(buf, pos, length, StandardCharsets.UTF_8)); } catch (NumberFormatException nfe) { SQLException sqlException = new SQLException("Incorrect format \"" + new String(buf, pos, length, StandardCharsets.UTF_8) + "\" for getFloat for data field with type " + columnInfo.getColumnType() .getJavaTypeName(), "22003", 1264); //noinspection UnnecessaryInitCause sqlException.initCause(nfe); throw sqlException; } default: throw new SQLException( "getFloat not available for data field type " + columnInfo.getColumnType() .getJavaTypeName()); } }
java
public float getInternalFloat(ColumnInformation columnInfo) throws SQLException { if (lastValueWasNull()) { return 0; } switch (columnInfo.getColumnType()) { case BIT: return parseBit(); case TINYINT: case SMALLINT: case YEAR: case INTEGER: case MEDIUMINT: case FLOAT: case DOUBLE: case DECIMAL: case VARSTRING: case VARCHAR: case STRING: case OLDDECIMAL: case BIGINT: try { return Float.valueOf(new String(buf, pos, length, StandardCharsets.UTF_8)); } catch (NumberFormatException nfe) { SQLException sqlException = new SQLException("Incorrect format \"" + new String(buf, pos, length, StandardCharsets.UTF_8) + "\" for getFloat for data field with type " + columnInfo.getColumnType() .getJavaTypeName(), "22003", 1264); //noinspection UnnecessaryInitCause sqlException.initCause(nfe); throw sqlException; } default: throw new SQLException( "getFloat not available for data field type " + columnInfo.getColumnType() .getJavaTypeName()); } }
[ "public", "float", "getInternalFloat", "(", "ColumnInformation", "columnInfo", ")", "throws", "SQLException", "{", "if", "(", "lastValueWasNull", "(", ")", ")", "{", "return", "0", ";", "}", "switch", "(", "columnInfo", ".", "getColumnType", "(", ")", ")", "...
Get float from raw text format. @param columnInfo column information @return float value @throws SQLException if column type doesn't permit conversion or not in Float range
[ "Get", "float", "from", "raw", "text", "format", "." ]
train
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/TextRowProtocol.java#L350-L387
motown-io/motown
utils/rest/src/main/java/io/motown/utils/rest/response/ResponseBuilder.java
ResponseBuilder.getNextPageOffset
private static long getNextPageOffset(final int offset, final int limit, final long total) { return hasFullNextPage(offset, limit, total) ? getNextFullPageOffset(offset, limit) : getLastPageOffset(total, limit); }
java
private static long getNextPageOffset(final int offset, final int limit, final long total) { return hasFullNextPage(offset, limit, total) ? getNextFullPageOffset(offset, limit) : getLastPageOffset(total, limit); }
[ "private", "static", "long", "getNextPageOffset", "(", "final", "int", "offset", ",", "final", "int", "limit", ",", "final", "long", "total", ")", "{", "return", "hasFullNextPage", "(", "offset", ",", "limit", ",", "total", ")", "?", "getNextFullPageOffset", ...
Gets the next page offset. @param offset the current offset. @param limit the limit. @param total the total. @return the next page offset.
[ "Gets", "the", "next", "page", "offset", "." ]
train
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/utils/rest/src/main/java/io/motown/utils/rest/response/ResponseBuilder.java#L104-L106
kuali/ojb-1.0.4
src/java/org/apache/ojb/broker/accesslayer/StatementManager.java
StatementManager.bindStatement
private int bindStatement(PreparedStatement stmt, int index, ExistsCriteria crit, ClassDescriptor cld) throws SQLException { Query subQuery = (Query) crit.getValue(); // if query has criteria, bind them if (subQuery.getCriteria() != null && !subQuery.getCriteria().isEmpty()) { return bindStatement(stmt, subQuery.getCriteria(), cld.getRepository().getDescriptorFor(subQuery.getSearchClass()), index); // otherwise, just ignore it } else { return index; } }
java
private int bindStatement(PreparedStatement stmt, int index, ExistsCriteria crit, ClassDescriptor cld) throws SQLException { Query subQuery = (Query) crit.getValue(); // if query has criteria, bind them if (subQuery.getCriteria() != null && !subQuery.getCriteria().isEmpty()) { return bindStatement(stmt, subQuery.getCriteria(), cld.getRepository().getDescriptorFor(subQuery.getSearchClass()), index); // otherwise, just ignore it } else { return index; } }
[ "private", "int", "bindStatement", "(", "PreparedStatement", "stmt", ",", "int", "index", ",", "ExistsCriteria", "crit", ",", "ClassDescriptor", "cld", ")", "throws", "SQLException", "{", "Query", "subQuery", "=", "(", "Query", ")", "crit", ".", "getValue", "(...
bind ExistsCriteria @param stmt the PreparedStatement @param index the position of the parameter to bind @param crit the Criteria containing the parameter @param cld the ClassDescriptor @return next index for PreparedStatement
[ "bind", "ExistsCriteria" ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/accesslayer/StatementManager.java#L337-L352
lecousin/java-framework-core
net.lecousin.core/src/main/java/net/lecousin/framework/concurrent/synch/AsyncWork.java
AsyncWork.listenInlineGenericError
public final void listenInlineGenericError(AsyncWork<T, Exception> sp) { listenInline(new AsyncWorkListener<T,TError>() { @Override public void ready(T result) { sp.unblockSuccess(result); } @Override public void error(TError error) { sp.unblockError(error); } @Override public void cancelled(CancelException event) { sp.unblockCancel(event); } }); }
java
public final void listenInlineGenericError(AsyncWork<T, Exception> sp) { listenInline(new AsyncWorkListener<T,TError>() { @Override public void ready(T result) { sp.unblockSuccess(result); } @Override public void error(TError error) { sp.unblockError(error); } @Override public void cancelled(CancelException event) { sp.unblockCancel(event); } }); }
[ "public", "final", "void", "listenInlineGenericError", "(", "AsyncWork", "<", "T", ",", "Exception", ">", "sp", ")", "{", "listenInline", "(", "new", "AsyncWorkListener", "<", "T", ",", "TError", ">", "(", ")", "{", "@", "Override", "public", "void", "read...
Forward the result, error, or cancellation to the given AsyncWork.
[ "Forward", "the", "result", "error", "or", "cancellation", "to", "the", "given", "AsyncWork", "." ]
train
https://github.com/lecousin/java-framework-core/blob/b0c893b44bfde2c03f90ea846a49ef5749d598f3/net.lecousin.core/src/main/java/net/lecousin/framework/concurrent/synch/AsyncWork.java#L313-L330
jeremybrooks/jinx
src/main/java/net/jeremybrooks/jinx/Jinx.java
Jinx.flickrGet
public <T> T flickrGet(Map<String, String> params, Class<T> tClass) throws JinxException { return callFlickr(params, Method.GET, tClass, true); }
java
public <T> T flickrGet(Map<String, String> params, Class<T> tClass) throws JinxException { return callFlickr(params, Method.GET, tClass, true); }
[ "public", "<", "T", ">", "T", "flickrGet", "(", "Map", "<", "String", ",", "String", ">", "params", ",", "Class", "<", "T", ">", "tClass", ")", "throws", "JinxException", "{", "return", "callFlickr", "(", "params", ",", "Method", ".", "GET", ",", "tC...
Call Flickr, returning the specified class deserialized from the Flickr response. <br> This will make a signed call to Flickr using http GET. <p> Do not call this method directly. The classes in the net.jeremybrooks.jinx.api package will call this. @param params request parameters. @param tClass the class that will be returned. @param <T> type of the class returned. @return an instance of the specified class containing data from Flickr. @throws JinxException if there are any errors.
[ "Call", "Flickr", "returning", "the", "specified", "class", "deserialized", "from", "the", "Flickr", "response", ".", "<br", ">", "This", "will", "make", "a", "signed", "call", "to", "Flickr", "using", "http", "GET", ".", "<p", ">", "Do", "not", "call", ...
train
https://github.com/jeremybrooks/jinx/blob/ab7a4b7462d08bcbfd9b98bd3f5029771c20f6c6/src/main/java/net/jeremybrooks/jinx/Jinx.java#L453-L455
awin/rabbiteasy
rabbiteasy-cdi/src/main/java/com/zanox/rabbiteasy/cdi/EventPublisher.java
EventPublisher.buildMessage
static Message buildMessage(PublisherConfiguration publisherConfiguration, Object event) { Message message = new Message(publisherConfiguration.basicProperties) .exchange(publisherConfiguration.exchange) .routingKey(publisherConfiguration.routingKey); if (publisherConfiguration.persistent) { message.persistent(); } if (event instanceof ContainsData) { message.body(((ContainsData) event).getData()); } else if (event instanceof ContainsContent) { message.body(((ContainsContent) event).getContent()); } else if (event instanceof ContainsId) { message.body(((ContainsId) event).getId()); } return message; }
java
static Message buildMessage(PublisherConfiguration publisherConfiguration, Object event) { Message message = new Message(publisherConfiguration.basicProperties) .exchange(publisherConfiguration.exchange) .routingKey(publisherConfiguration.routingKey); if (publisherConfiguration.persistent) { message.persistent(); } if (event instanceof ContainsData) { message.body(((ContainsData) event).getData()); } else if (event instanceof ContainsContent) { message.body(((ContainsContent) event).getContent()); } else if (event instanceof ContainsId) { message.body(((ContainsId) event).getId()); } return message; }
[ "static", "Message", "buildMessage", "(", "PublisherConfiguration", "publisherConfiguration", ",", "Object", "event", ")", "{", "Message", "message", "=", "new", "Message", "(", "publisherConfiguration", ".", "basicProperties", ")", ".", "exchange", "(", "publisherCon...
Builds a message based on a CDI event and its publisher configuration. @param publisherConfiguration The publisher configuration @param event The CDI event @return The message
[ "Builds", "a", "message", "based", "on", "a", "CDI", "event", "and", "its", "publisher", "configuration", "." ]
train
https://github.com/awin/rabbiteasy/blob/c161efda6c0f7ef319aedf09dfe40a4a90165510/rabbiteasy-cdi/src/main/java/com/zanox/rabbiteasy/cdi/EventPublisher.java#L135-L150
gallandarakhneorg/afc
advanced/gis/gisbus/src/main/java/org/arakhne/afc/gis/bus/network/BusNetwork.java
BusNetwork.getNearestBusStop
@Pure public BusStop getNearestBusStop(double x, double y) { double distance = Double.POSITIVE_INFINITY; BusStop bestStop = null; double dist; for (final BusStop stop : this.validBusStops) { dist = stop.distance(x, y); if (dist < distance) { distance = dist; bestStop = stop; } } return bestStop; }
java
@Pure public BusStop getNearestBusStop(double x, double y) { double distance = Double.POSITIVE_INFINITY; BusStop bestStop = null; double dist; for (final BusStop stop : this.validBusStops) { dist = stop.distance(x, y); if (dist < distance) { distance = dist; bestStop = stop; } } return bestStop; }
[ "@", "Pure", "public", "BusStop", "getNearestBusStop", "(", "double", "x", ",", "double", "y", ")", "{", "double", "distance", "=", "Double", ".", "POSITIVE_INFINITY", ";", "BusStop", "bestStop", "=", "null", ";", "double", "dist", ";", "for", "(", "final"...
Replies the nearest bus stops to the given point. @param x x coordinate. @param y y coordinate. @return the nearest bus stop or <code>null</code> if none was found.
[ "Replies", "the", "nearest", "bus", "stops", "to", "the", "given", "point", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/gis/gisbus/src/main/java/org/arakhne/afc/gis/bus/network/BusNetwork.java#L1028-L1043
albfernandez/itext2
src/main/java/com/lowagie/text/pdf/parser/PdfTextExtractor.java
PdfTextExtractor.getTextFromPage
public String getTextFromPage(int page) throws IOException { int totalPages = reader.getNumberOfPages(); if (totalPages < page) { throw new IOException("indicated page does not exists, requested page " + page + " document pages " + totalPages); } if (page <= 0) { throw new IOException("page number must be postive:" + page); } PdfDictionary pageDic = reader.getPageN(page); if (pageDic == null) { return ""; } PdfDictionary resourcesDic = pageDic.getAsDict(PdfName.RESOURCES); extractionProcessor.processContent(getContentBytesForPage(page), resourcesDic); return extractionProcessor.getResultantText(); }
java
public String getTextFromPage(int page) throws IOException { int totalPages = reader.getNumberOfPages(); if (totalPages < page) { throw new IOException("indicated page does not exists, requested page " + page + " document pages " + totalPages); } if (page <= 0) { throw new IOException("page number must be postive:" + page); } PdfDictionary pageDic = reader.getPageN(page); if (pageDic == null) { return ""; } PdfDictionary resourcesDic = pageDic.getAsDict(PdfName.RESOURCES); extractionProcessor.processContent(getContentBytesForPage(page), resourcesDic); return extractionProcessor.getResultantText(); }
[ "public", "String", "getTextFromPage", "(", "int", "page", ")", "throws", "IOException", "{", "int", "totalPages", "=", "reader", ".", "getNumberOfPages", "(", ")", ";", "if", "(", "totalPages", "<", "page", ")", "{", "throw", "new", "IOException", "(", "\...
Gets the text from a page. @param page the page number of the page @return a String with the content as plain text (without PDF syntax) @throws IOException
[ "Gets", "the", "text", "from", "a", "page", "." ]
train
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/parser/PdfTextExtractor.java#L95-L110
micronaut-projects/micronaut-core
inject/src/main/java/io/micronaut/context/DefaultBeanContext.java
DefaultBeanContext.getBeanProvider
protected @Nonnull <T> Provider<T> getBeanProvider(@Nullable BeanResolutionContext resolutionContext, @Nonnull Class<T> beanType, @Nullable Qualifier<T> qualifier) { ArgumentUtils.requireNonNull("beanType", beanType); @SuppressWarnings("unchecked") BeanRegistration<T> beanRegistration = singletonObjects.get(new BeanKey(beanType, qualifier)); if (beanRegistration != null) { return new ResolvedProvider<>(beanRegistration.bean); } Optional<BeanDefinition<T>> concreteCandidate = findConcreteCandidate(beanType, qualifier, true, false); if (concreteCandidate.isPresent()) { return new UnresolvedProvider<>(beanType, qualifier, this); } else { throw new NoSuchBeanException(beanType); } }
java
protected @Nonnull <T> Provider<T> getBeanProvider(@Nullable BeanResolutionContext resolutionContext, @Nonnull Class<T> beanType, @Nullable Qualifier<T> qualifier) { ArgumentUtils.requireNonNull("beanType", beanType); @SuppressWarnings("unchecked") BeanRegistration<T> beanRegistration = singletonObjects.get(new BeanKey(beanType, qualifier)); if (beanRegistration != null) { return new ResolvedProvider<>(beanRegistration.bean); } Optional<BeanDefinition<T>> concreteCandidate = findConcreteCandidate(beanType, qualifier, true, false); if (concreteCandidate.isPresent()) { return new UnresolvedProvider<>(beanType, qualifier, this); } else { throw new NoSuchBeanException(beanType); } }
[ "protected", "@", "Nonnull", "<", "T", ">", "Provider", "<", "T", ">", "getBeanProvider", "(", "@", "Nullable", "BeanResolutionContext", "resolutionContext", ",", "@", "Nonnull", "Class", "<", "T", ">", "beanType", ",", "@", "Nullable", "Qualifier", "<", "T"...
Get a bean provider. @param resolutionContext The bean resolution context @param beanType The bean type @param qualifier The qualifier @param <T> The bean type parameter @return The bean provider
[ "Get", "a", "bean", "provider", "." ]
train
https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/inject/src/main/java/io/micronaut/context/DefaultBeanContext.java#L1107-L1120
lucee/Lucee
core/src/main/java/lucee/runtime/type/util/ListUtil.java
ListUtil.listToArray
public static Array listToArray(String list, char delimiter) { if (list.length() == 0) return new ArrayImpl(); int len = list.length(); int last = 0; Array array = new ArrayImpl(); try { for (int i = 0; i < len; i++) { if (list.charAt(i) == delimiter) { array.append(list.substring(last, i)); last = i + 1; } } if (last <= len) array.append(list.substring(last)); } catch (PageException e) {} return array; }
java
public static Array listToArray(String list, char delimiter) { if (list.length() == 0) return new ArrayImpl(); int len = list.length(); int last = 0; Array array = new ArrayImpl(); try { for (int i = 0; i < len; i++) { if (list.charAt(i) == delimiter) { array.append(list.substring(last, i)); last = i + 1; } } if (last <= len) array.append(list.substring(last)); } catch (PageException e) {} return array; }
[ "public", "static", "Array", "listToArray", "(", "String", "list", ",", "char", "delimiter", ")", "{", "if", "(", "list", ".", "length", "(", ")", "==", "0", ")", "return", "new", "ArrayImpl", "(", ")", ";", "int", "len", "=", "list", ".", "length", ...
casts a list to Array object @param list list to cast @param delimiter delimter of the list @return Array Object
[ "casts", "a", "list", "to", "Array", "object" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/type/util/ListUtil.java#L164-L181