repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
18
188
func_name
stringlengths
7
127
whole_func_string
stringlengths
77
3.91k
language
stringclasses
1 value
func_code_string
stringlengths
77
3.91k
func_code_tokens
listlengths
20
745
func_documentation_string
stringlengths
61
1.98k
func_documentation_tokens
listlengths
1
477
split_name
stringclasses
1 value
func_code_url
stringlengths
111
288
rythmengine/rythmengine
src/main/java/org/rythmengine/utils/S.java
S.isEqual
public static boolean isEqual(String s1, String s2, int modifier) { if (s1 == s2) return true; if (null == s1) { return s2 == null; } if (null == s2) { return false; } if ((modifier & IGNORESPACE) != 0) { s1 = s1.trim(); s2 = s2.trim(); } if ((modifier & IGNORECASE) != 0) { return s1.equalsIgnoreCase(s2); } else { return s1.equals(s2); } }
java
public static boolean isEqual(String s1, String s2, int modifier) { if (s1 == s2) return true; if (null == s1) { return s2 == null; } if (null == s2) { return false; } if ((modifier & IGNORESPACE) != 0) { s1 = s1.trim(); s2 = s2.trim(); } if ((modifier & IGNORECASE) != 0) { return s1.equalsIgnoreCase(s2); } else { return s1.equals(s2); } }
[ "public", "static", "boolean", "isEqual", "(", "String", "s1", ",", "String", "s2", ",", "int", "modifier", ")", "{", "if", "(", "s1", "==", "s2", ")", "return", "true", ";", "if", "(", "null", "==", "s1", ")", "{", "return", "s2", "==", "null", ...
Determine whether two string instance is equal based on the modifier passed in. <p/> <p> is 2 strings equal case insensitive? <code>S.isEqual(s1, s2, S.IGNORECASE)</code> </p> <p/> <p> is 2 strings equals case and space insensitive? <code>S.isEqual(s1, s2, S.IGNORECASE & S.IGNORESPACE)</code> </p> @param s1 @param s2 @param modifier @return true if s1 equals s2
[ "Determine", "whether", "two", "string", "instance", "is", "equal", "based", "on", "the", "modifier", "passed", "in", ".", "<p", "/", ">", "<p", ">", "is", "2", "strings", "equal", "case", "insensitive?", "<code", ">", "S", ".", "isEqual", "(", "s1", "...
train
https://github.com/rythmengine/rythmengine/blob/064b565f08d9da07378bf77a9dd856ea5831cc92/src/main/java/org/rythmengine/utils/S.java#L286-L303
jbundle/jbundle
base/base/src/main/java/org/jbundle/base/field/BaseField.java
BaseField.addQuotes
public static final String addQuotes(String szTableNames, char charStart, char charEnd) { String strFileName = szTableNames; if (charStart == -1) charStart = DBConstants.SQL_START_QUOTE; if (charEnd == -1) charEnd = DBConstants.SQL_END_QUOTE; for (int iIndex = 0; iIndex < strFileName.length(); iIndex++) { if ((strFileName.charAt(iIndex) == charStart) || (strFileName.charAt(iIndex) == charEnd)) { // If a quote is in this string, replace with a double-quote Fred's -> Fred''s strFileName = strFileName.substring(0, iIndex) + strFileName.substring(iIndex, iIndex + 1) + strFileName.substring(iIndex, iIndex + 1) + strFileName.substring(iIndex + 1, strFileName.length()); iIndex++; // Skip the second quote } } if ((charStart != ' ') && (charEnd != ' ')) strFileName = charStart + strFileName + charEnd; // Spaces in name, quotes required return strFileName; }
java
public static final String addQuotes(String szTableNames, char charStart, char charEnd) { String strFileName = szTableNames; if (charStart == -1) charStart = DBConstants.SQL_START_QUOTE; if (charEnd == -1) charEnd = DBConstants.SQL_END_QUOTE; for (int iIndex = 0; iIndex < strFileName.length(); iIndex++) { if ((strFileName.charAt(iIndex) == charStart) || (strFileName.charAt(iIndex) == charEnd)) { // If a quote is in this string, replace with a double-quote Fred's -> Fred''s strFileName = strFileName.substring(0, iIndex) + strFileName.substring(iIndex, iIndex + 1) + strFileName.substring(iIndex, iIndex + 1) + strFileName.substring(iIndex + 1, strFileName.length()); iIndex++; // Skip the second quote } } if ((charStart != ' ') && (charEnd != ' ')) strFileName = charStart + strFileName + charEnd; // Spaces in name, quotes required return strFileName; }
[ "public", "static", "final", "String", "addQuotes", "(", "String", "szTableNames", ",", "char", "charStart", ",", "char", "charEnd", ")", "{", "String", "strFileName", "=", "szTableNames", ";", "if", "(", "charStart", "==", "-", "1", ")", "charStart", "=", ...
Add these quotes to this string. @param szTableNames The source string. @param charStart The starting quote. @param charEnd The ending quote. @return The new (quoted) string.
[ "Add", "these", "quotes", "to", "this", "string", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/field/BaseField.java#L330-L353
threerings/nenya
core/src/main/java/com/threerings/miso/client/MisoScenePanel.java
MisoScenePanel.getTileCoords
public Point getTileCoords (int x, int y) { return MisoUtil.screenToTile(_metrics, x, y, new Point()); }
java
public Point getTileCoords (int x, int y) { return MisoUtil.screenToTile(_metrics, x, y, new Point()); }
[ "public", "Point", "getTileCoords", "(", "int", "x", ",", "int", "y", ")", "{", "return", "MisoUtil", ".", "screenToTile", "(", "_metrics", ",", "x", ",", "y", ",", "new", "Point", "(", ")", ")", ";", "}" ]
Converts the supplied screen coordinates to tile coordinates.
[ "Converts", "the", "supplied", "screen", "coordinates", "to", "tile", "coordinates", "." ]
train
https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/miso/client/MisoScenePanel.java#L335-L338
apache/incubator-atlas
addons/hive-bridge/src/main/java/org/apache/atlas/hive/bridge/HiveMetaStoreBridge.java
HiveMetaStoreBridge.getDatabaseReference
private Referenceable getDatabaseReference(String clusterName, String databaseName) throws Exception { LOG.debug("Getting reference for database {}", databaseName); String typeName = HiveDataTypes.HIVE_DB.getName(); return getEntityReference(typeName, getDBQualifiedName(clusterName, databaseName)); }
java
private Referenceable getDatabaseReference(String clusterName, String databaseName) throws Exception { LOG.debug("Getting reference for database {}", databaseName); String typeName = HiveDataTypes.HIVE_DB.getName(); return getEntityReference(typeName, getDBQualifiedName(clusterName, databaseName)); }
[ "private", "Referenceable", "getDatabaseReference", "(", "String", "clusterName", ",", "String", "databaseName", ")", "throws", "Exception", "{", "LOG", ".", "debug", "(", "\"Getting reference for database {}\"", ",", "databaseName", ")", ";", "String", "typeName", "=...
Gets reference to the atlas entity for the database @param databaseName database Name @param clusterName cluster name @return Reference for database if exists, else null @throws Exception
[ "Gets", "reference", "to", "the", "atlas", "entity", "for", "the", "database" ]
train
https://github.com/apache/incubator-atlas/blob/e0d2cdc27c32742ebecd24db4cca62dc04dcdf4b/addons/hive-bridge/src/main/java/org/apache/atlas/hive/bridge/HiveMetaStoreBridge.java#L226-L231
Azure/azure-sdk-for-java
edgegateway/resource-manager/v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/implementation/SharesInner.java
SharesInner.createOrUpdateAsync
public Observable<ShareInner> createOrUpdateAsync(String deviceName, String name, String resourceGroupName, ShareInner share) { return createOrUpdateWithServiceResponseAsync(deviceName, name, resourceGroupName, share).map(new Func1<ServiceResponse<ShareInner>, ShareInner>() { @Override public ShareInner call(ServiceResponse<ShareInner> response) { return response.body(); } }); }
java
public Observable<ShareInner> createOrUpdateAsync(String deviceName, String name, String resourceGroupName, ShareInner share) { return createOrUpdateWithServiceResponseAsync(deviceName, name, resourceGroupName, share).map(new Func1<ServiceResponse<ShareInner>, ShareInner>() { @Override public ShareInner call(ServiceResponse<ShareInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "ShareInner", ">", "createOrUpdateAsync", "(", "String", "deviceName", ",", "String", "name", ",", "String", "resourceGroupName", ",", "ShareInner", "share", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "deviceName", ...
Creates a new share or updates an existing share on the device. @param deviceName The device name. @param name The share name. @param resourceGroupName The resource group name. @param share The share properties. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Creates", "a", "new", "share", "or", "updates", "an", "existing", "share", "on", "the", "device", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/edgegateway/resource-manager/v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/implementation/SharesInner.java#L360-L367
js-lib-com/commons
src/main/java/js/util/Params.java
Params.notNull
public static void notNull(Object parameter, String name, Object... args) throws IllegalArgumentException { if (parameter == null) { throw new IllegalArgumentException(String.format(name, args) + " parameter is null."); } }
java
public static void notNull(Object parameter, String name, Object... args) throws IllegalArgumentException { if (parameter == null) { throw new IllegalArgumentException(String.format(name, args) + " parameter is null."); } }
[ "public", "static", "void", "notNull", "(", "Object", "parameter", ",", "String", "name", ",", "Object", "...", "args", ")", "throws", "IllegalArgumentException", "{", "if", "(", "parameter", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", ...
Throw exception if parameter is null. Name parameter can be formatted as accepted by {@link String#format(String, Object...)}. @param parameter invocation parameter to test, @param name parameter name used on exception message, @param args optional arguments if name is formatted. @throws IllegalArgumentException if <code>parameter</code> is null.
[ "Throw", "exception", "if", "parameter", "is", "null", ".", "Name", "parameter", "can", "be", "formatted", "as", "accepted", "by", "{", "@link", "String#format", "(", "String", "Object", "...", ")", "}", "." ]
train
https://github.com/js-lib-com/commons/blob/f8c64482142b163487745da74feb106f0765c16b/src/main/java/js/util/Params.java#L42-L46
netty/netty
common/src/main/java/io/netty/util/internal/StringUtil.java
StringUtil.endsWith
public static boolean endsWith(CharSequence s, char c) { int len = s.length(); return len > 0 && s.charAt(len - 1) == c; }
java
public static boolean endsWith(CharSequence s, char c) { int len = s.length(); return len > 0 && s.charAt(len - 1) == c; }
[ "public", "static", "boolean", "endsWith", "(", "CharSequence", "s", ",", "char", "c", ")", "{", "int", "len", "=", "s", ".", "length", "(", ")", ";", "return", "len", ">", "0", "&&", "s", ".", "charAt", "(", "len", "-", "1", ")", "==", "c", ";...
Determine if the string {@code s} ends with the char {@code c}. @param s the string to test @param c the tested char @return true if {@code s} ends with the char {@code c}
[ "Determine", "if", "the", "string", "{", "@code", "s", "}", "ends", "with", "the", "char", "{", "@code", "c", "}", "." ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/common/src/main/java/io/netty/util/internal/StringUtil.java#L578-L581
StripesFramework/stripes-stuff
src/main/java/org/stripesstuff/plugin/security/J2EESecurityManager.java
J2EESecurityManager.getAccessAllowed
public Boolean getAccessAllowed(ActionBean bean, Method handler) { // Determine if the event handler allows access. LOG.debug("Determining if access is allowed for " + handler.getName() + " on " + bean.toString()); Boolean allowed = determineAccessOnElement(bean, handler, handler); // If the event handler didn't decide, determine if the action bean class allows access. // Rinse and repeat for all superclasses. Class<?> beanClass = bean.getClass(); while (allowed == null && beanClass != null) { LOG.debug("Determining if access is allowed for " + beanClass.getName() + " on " + bean.toString()); allowed = determineAccessOnElement(bean, handler, beanClass); beanClass = beanClass.getSuperclass(); } // If the event handler nor the action bean class decided, allow access. // This default allows access if no security annotations are used. if (allowed == null) { allowed = true; } // Return the decision. return allowed; }
java
public Boolean getAccessAllowed(ActionBean bean, Method handler) { // Determine if the event handler allows access. LOG.debug("Determining if access is allowed for " + handler.getName() + " on " + bean.toString()); Boolean allowed = determineAccessOnElement(bean, handler, handler); // If the event handler didn't decide, determine if the action bean class allows access. // Rinse and repeat for all superclasses. Class<?> beanClass = bean.getClass(); while (allowed == null && beanClass != null) { LOG.debug("Determining if access is allowed for " + beanClass.getName() + " on " + bean.toString()); allowed = determineAccessOnElement(bean, handler, beanClass); beanClass = beanClass.getSuperclass(); } // If the event handler nor the action bean class decided, allow access. // This default allows access if no security annotations are used. if (allowed == null) { allowed = true; } // Return the decision. return allowed; }
[ "public", "Boolean", "getAccessAllowed", "(", "ActionBean", "bean", ",", "Method", "handler", ")", "{", "// Determine if the event handler allows access.", "LOG", ".", "debug", "(", "\"Determining if access is allowed for \"", "+", "handler", ".", "getName", "(", ")", "...
Determines if access for the given execution context is allowed. The security manager is used to determine if access is allowed (to handle an event) or if access is not denied (thus allowing the display of error messages for binding and/or validation errors for a secured event). If the latter would not be checked, a user can (even if only theoretically) see an error message, correct his input, and then see an &quot;access forbidden&quot; message. <p> If required contextual information (like what data is affected) is not available, no decision should be made. This is to ensure that access is not denied when required data is missing because of a binding and/or validation error. @param bean the action bean on which to perform the action @param handler the event handler to check authorization for @return {@link Boolean#TRUE} if access is allowed, {@link Boolean#FALSE} if not, and null if no decision can be made @see SecurityManager#getAccessAllowed(ActionBean,Method)
[ "Determines", "if", "access", "for", "the", "given", "execution", "context", "is", "allowed", ".", "The", "security", "manager", "is", "used", "to", "determine", "if", "access", "is", "allowed", "(", "to", "handle", "an", "event", ")", "or", "if", "access"...
train
https://github.com/StripesFramework/stripes-stuff/blob/51ad92b4bd5862ba34d7c18c5829fb00ea3a3811/src/main/java/org/stripesstuff/plugin/security/J2EESecurityManager.java#L52-L81
james-hu/jabb-core
src/main/java/net/sf/jabb/spring/rest/AbstractRestClient.java
AbstractRestClient.buildAddHeadersRequestInterceptor
protected ClientHttpRequestInterceptor buildAddHeadersRequestInterceptor(String header1, String value1, String header2, String value2, String header3, String value3, String header4, String value4){ return new AddHeadersRequestInterceptor(new String[]{header1, header2, header3, header4}, new String[]{value1, value2, value3, value4}); }
java
protected ClientHttpRequestInterceptor buildAddHeadersRequestInterceptor(String header1, String value1, String header2, String value2, String header3, String value3, String header4, String value4){ return new AddHeadersRequestInterceptor(new String[]{header1, header2, header3, header4}, new String[]{value1, value2, value3, value4}); }
[ "protected", "ClientHttpRequestInterceptor", "buildAddHeadersRequestInterceptor", "(", "String", "header1", ",", "String", "value1", ",", "String", "header2", ",", "String", "value2", ",", "String", "header3", ",", "String", "value3", ",", "String", "header4", ",", ...
Build a ClientHttpRequestInterceptor that adds three request headers @param header1 name of header 1 @param value1 value of header 1 @param header2 name of header 2 @param value2 value of header 2 @param header3 name of header 3 @param value3 value of header 3 @param header4 name of the header 4 @param value4 value of the header 4 @return the ClientHttpRequestInterceptor built
[ "Build", "a", "ClientHttpRequestInterceptor", "that", "adds", "three", "request", "headers" ]
train
https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/spring/rest/AbstractRestClient.java#L513-L515
windup/windup
config/api/src/main/java/org/jboss/windup/config/operation/Iteration.java
Iteration.as
@Override public IterationBuilderVar as(Class<? extends WindupVertexFrame> varType, String var) { setPayloadManager(new TypedNamedIterationPayloadManager(varType, var)); return this; }
java
@Override public IterationBuilderVar as(Class<? extends WindupVertexFrame> varType, String var) { setPayloadManager(new TypedNamedIterationPayloadManager(varType, var)); return this; }
[ "@", "Override", "public", "IterationBuilderVar", "as", "(", "Class", "<", "?", "extends", "WindupVertexFrame", ">", "varType", ",", "String", "var", ")", "{", "setPayloadManager", "(", "new", "TypedNamedIterationPayloadManager", "(", "varType", ",", "var", ")", ...
Change the name of the single variable of the given type. If this method is not called, the name is calculated using the {@link Iteration#singleVariableIterationName(String)} method.
[ "Change", "the", "name", "of", "the", "single", "variable", "of", "the", "given", "type", ".", "If", "this", "method", "is", "not", "called", "the", "name", "is", "calculated", "using", "the", "{" ]
train
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/config/api/src/main/java/org/jboss/windup/config/operation/Iteration.java#L185-L190
OpenLiberty/open-liberty
dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/persistent/htod/HashtableOnDisk.java
HashtableOnDisk.updateExpirationInHeader
public synchronized boolean updateExpirationInHeader(Object key, long expirationTime, long validatorExpirationTime) throws IOException, EOFException, FileManagerException, ClassNotFoundException, HashtableOnDiskException { if (filemgr == null) { throw new HashtableOnDiskException("No Filemanager"); } if (key == null) return false; // no null keys allowed HashtableEntry entry = findEntry(key, RETRIEVE_KEY, !CHECK_EXPIRED); if (entry == null) return false; // not found // // Seek to point to validator expiration time field in the header filemgr.seek(entry.location + DWORDSIZE + // room for next SWORDSIZE); // room for hash filemgr.writeLong(validatorExpirationTime); // update VET /* * comment out the code below because the expiration time does not change * filemgr.writeInt(0); * filemgr.writeInt(entry.cacheValueHashcode); // update cache value hashcode * filemgr.writeLong(entry.first_created); // update first created (not neccessary but move to pointer * filemgr.writeLong(expirationTime); // update RET */ htoddc.returnToHashtableEntryPool(entry); return true; }
java
public synchronized boolean updateExpirationInHeader(Object key, long expirationTime, long validatorExpirationTime) throws IOException, EOFException, FileManagerException, ClassNotFoundException, HashtableOnDiskException { if (filemgr == null) { throw new HashtableOnDiskException("No Filemanager"); } if (key == null) return false; // no null keys allowed HashtableEntry entry = findEntry(key, RETRIEVE_KEY, !CHECK_EXPIRED); if (entry == null) return false; // not found // // Seek to point to validator expiration time field in the header filemgr.seek(entry.location + DWORDSIZE + // room for next SWORDSIZE); // room for hash filemgr.writeLong(validatorExpirationTime); // update VET /* * comment out the code below because the expiration time does not change * filemgr.writeInt(0); * filemgr.writeInt(entry.cacheValueHashcode); // update cache value hashcode * filemgr.writeLong(entry.first_created); // update first created (not neccessary but move to pointer * filemgr.writeLong(expirationTime); // update RET */ htoddc.returnToHashtableEntryPool(entry); return true; }
[ "public", "synchronized", "boolean", "updateExpirationInHeader", "(", "Object", "key", ",", "long", "expirationTime", ",", "long", "validatorExpirationTime", ")", "throws", "IOException", ",", "EOFException", ",", "FileManagerException", ",", "ClassNotFoundException", ","...
This method is used to update expiration times in disk entry header
[ "This", "method", "is", "used", "to", "update", "expiration", "times", "in", "disk", "entry", "header" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/persistent/htod/HashtableOnDisk.java#L1201-L1233
UrielCh/ovh-java-sdk
ovh-java-sdk-cdndedicated/src/main/java/net/minidev/ovh/api/ApiOvhCdndedicated.java
ApiOvhCdndedicated.serviceName_domains_domain_cacheRules_cacheRuleId_PUT
public void serviceName_domains_domain_cacheRules_cacheRuleId_PUT(String serviceName, String domain, Long cacheRuleId, OvhCacheRule body) throws IOException { String qPath = "/cdn/dedicated/{serviceName}/domains/{domain}/cacheRules/{cacheRuleId}"; StringBuilder sb = path(qPath, serviceName, domain, cacheRuleId); exec(qPath, "PUT", sb.toString(), body); }
java
public void serviceName_domains_domain_cacheRules_cacheRuleId_PUT(String serviceName, String domain, Long cacheRuleId, OvhCacheRule body) throws IOException { String qPath = "/cdn/dedicated/{serviceName}/domains/{domain}/cacheRules/{cacheRuleId}"; StringBuilder sb = path(qPath, serviceName, domain, cacheRuleId); exec(qPath, "PUT", sb.toString(), body); }
[ "public", "void", "serviceName_domains_domain_cacheRules_cacheRuleId_PUT", "(", "String", "serviceName", ",", "String", "domain", ",", "Long", "cacheRuleId", ",", "OvhCacheRule", "body", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/cdn/dedicated/{service...
Alter this object properties REST: PUT /cdn/dedicated/{serviceName}/domains/{domain}/cacheRules/{cacheRuleId} @param body [required] New object properties @param serviceName [required] The internal name of your CDN offer @param domain [required] Domain of this object @param cacheRuleId [required] Id for this cache rule
[ "Alter", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-cdndedicated/src/main/java/net/minidev/ovh/api/ApiOvhCdndedicated.java#L305-L309
petergeneric/stdlib
guice/common/src/main/java/com/peterphi/std/guice/common/ClassScanner.java
ClassScanner.getClasses
public List<Class<?>> getClasses(final String pkg, boolean recursive, final Predicate<Class<?>> predicate) { final long started = System.currentTimeMillis(); try { return filter(finder.findClassesInPackage(pkg, recursive), predicate); } finally { final long finished = System.currentTimeMillis(); searchTime.addAndGet(finished - started); if (log.isTraceEnabled()) log.trace("getClasses " + pkg + " with predicate=" + predicate + " returned in " + (finished - started) + " ms"); } }
java
public List<Class<?>> getClasses(final String pkg, boolean recursive, final Predicate<Class<?>> predicate) { final long started = System.currentTimeMillis(); try { return filter(finder.findClassesInPackage(pkg, recursive), predicate); } finally { final long finished = System.currentTimeMillis(); searchTime.addAndGet(finished - started); if (log.isTraceEnabled()) log.trace("getClasses " + pkg + " with predicate=" + predicate + " returned in " + (finished - started) + " ms"); } }
[ "public", "List", "<", "Class", "<", "?", ">", ">", "getClasses", "(", "final", "String", "pkg", ",", "boolean", "recursive", ",", "final", "Predicate", "<", "Class", "<", "?", ">", ">", "predicate", ")", "{", "final", "long", "started", "=", "System",...
Find all the classes in a package @param pkg @param recursive @param predicate an optional additional predicate to filter the list against @return
[ "Find", "all", "the", "classes", "in", "a", "package" ]
train
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/common/src/main/java/com/peterphi/std/guice/common/ClassScanner.java#L62-L84
Appendium/objectlabkit
utils/src/main/java/net/objectlab/kit/util/StringUtil.java
StringUtil.replaceToken
public static String replaceToken(final String original, final String token, final String replacement) { final StringBuilder tok = new StringBuilder(TOKEN); tok.append(token).append(TOKEN); final String toReplace = replaceCRToken(original); return StringUtil.replace(tok.toString(), replacement, toReplace); }
java
public static String replaceToken(final String original, final String token, final String replacement) { final StringBuilder tok = new StringBuilder(TOKEN); tok.append(token).append(TOKEN); final String toReplace = replaceCRToken(original); return StringUtil.replace(tok.toString(), replacement, toReplace); }
[ "public", "static", "String", "replaceToken", "(", "final", "String", "original", ",", "final", "String", "token", ",", "final", "String", "replacement", ")", "{", "final", "StringBuilder", "tok", "=", "new", "StringBuilder", "(", "TOKEN", ")", ";", "tok", "...
Replaces the token, surrounded by % within a string with new value. Also replaces any %CR% tokens with the newline character. @return the <code>original</code> string with the <code>%token%</code> (if it exists) replaced with the <code>replacement</code> string. If <code>original</code> or <code>%token%</code> are null, then returns the <code>original</code> string.
[ "Replaces", "the", "token", "surrounded", "by", "%", "within", "a", "string", "with", "new", "value", ".", "Also", "replaces", "any", "%CR%", "tokens", "with", "the", "newline", "character", "." ]
train
https://github.com/Appendium/objectlabkit/blob/cd649bce7a32e4e926520e62cb765f3b1d451594/utils/src/main/java/net/objectlab/kit/util/StringUtil.java#L145-L152
biojava/biojava
biojava-structure/src/main/java/org/biojava/nbio/structure/geometry/SuperPositionAbstract.java
SuperPositionAbstract.checkInput
protected void checkInput(Point3d[] fixed, Point3d[] moved) { if (fixed.length != moved.length) throw new IllegalArgumentException( "Point arrays to superpose are of different lengths."); }
java
protected void checkInput(Point3d[] fixed, Point3d[] moved) { if (fixed.length != moved.length) throw new IllegalArgumentException( "Point arrays to superpose are of different lengths."); }
[ "protected", "void", "checkInput", "(", "Point3d", "[", "]", "fixed", ",", "Point3d", "[", "]", "moved", ")", "{", "if", "(", "fixed", ".", "length", "!=", "moved", ".", "length", ")", "throw", "new", "IllegalArgumentException", "(", "\"Point arrays to super...
Check that the input to the superposition algorithms is valid. @param fixed @param moved
[ "Check", "that", "the", "input", "to", "the", "superposition", "algorithms", "is", "valid", "." ]
train
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/geometry/SuperPositionAbstract.java#L55-L59
greatman/craftconomy3
src/main/java/com/greatmancode/craftconomy3/account/Account.java
Account.hasEnough
public boolean hasEnough(double amount, String worldName, String currencyName) { boolean result = false; amount = format(amount); if (!Common.getInstance().getWorldGroupManager().worldGroupExist(worldName)) { worldName = Common.getInstance().getWorldGroupManager().getWorldGroupName(worldName); } Currency currency = Common.getInstance().getCurrencyManager().getCurrency(currencyName); if (currency != null && (getBalance(worldName, currencyName) >= amount || hasInfiniteMoney())) { result = true; } return result; }
java
public boolean hasEnough(double amount, String worldName, String currencyName) { boolean result = false; amount = format(amount); if (!Common.getInstance().getWorldGroupManager().worldGroupExist(worldName)) { worldName = Common.getInstance().getWorldGroupManager().getWorldGroupName(worldName); } Currency currency = Common.getInstance().getCurrencyManager().getCurrency(currencyName); if (currency != null && (getBalance(worldName, currencyName) >= amount || hasInfiniteMoney())) { result = true; } return result; }
[ "public", "boolean", "hasEnough", "(", "double", "amount", ",", "String", "worldName", ",", "String", "currencyName", ")", "{", "boolean", "result", "=", "false", ";", "amount", "=", "format", "(", "amount", ")", ";", "if", "(", "!", "Common", ".", "getI...
Checks if we have enough money in a certain balance @param amount The amount of money to check @param worldName The World / World group we want to check @param currencyName The currency we want to check @return True if there's enough money. Else false
[ "Checks", "if", "we", "have", "enough", "money", "in", "a", "certain", "balance" ]
train
https://github.com/greatman/craftconomy3/blob/51b1b3de7d039e20c7418d1e70b8c4b02b8cf840/src/main/java/com/greatmancode/craftconomy3/account/Account.java#L275-L286
mockito/mockito
src/main/java/org/mockito/internal/junit/ExceptionFactory.java
ExceptionFactory.createArgumentsAreDifferentException
public static AssertionError createArgumentsAreDifferentException(String message, String wanted, String actual) { return factory.create(message, wanted, actual); }
java
public static AssertionError createArgumentsAreDifferentException(String message, String wanted, String actual) { return factory.create(message, wanted, actual); }
[ "public", "static", "AssertionError", "createArgumentsAreDifferentException", "(", "String", "message", ",", "String", "wanted", ",", "String", "actual", ")", "{", "return", "factory", ".", "create", "(", "message", ",", "wanted", ",", "actual", ")", ";", "}" ]
Returns an AssertionError that describes the fact that the arguments of an invocation are different. If {@link org.opentest4j.AssertionFailedError} is on the class path (used by JUnit 5 and others), it returns a class that extends it. Otherwise, if {@link junit.framework.ComparisonFailure} is on the class path (shipped with JUnit 3 and 4), it will return a class that extends that. This provides better IDE support as the comparison result can be opened in a visual diff. If neither are available, it returns an instance of {@link org.mockito.exceptions.verification.ArgumentsAreDifferent}.
[ "Returns", "an", "AssertionError", "that", "describes", "the", "fact", "that", "the", "arguments", "of", "an", "invocation", "are", "different", ".", "If", "{" ]
train
https://github.com/mockito/mockito/blob/c5e2b80af76e3192cae7c9550b70c4d1ab312034/src/main/java/org/mockito/internal/junit/ExceptionFactory.java#L58-L60
netscaler/sdx_nitro
src/main/java/com/citrix/sdx/nitro/resource/config/mps/mps_image.java
mps_image.get_nitro_bulk_response
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { mps_image_responses result = (mps_image_responses) service.get_payload_formatter().string_to_resource(mps_image_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.mps_image_response_array); } mps_image[] result_mps_image = new mps_image[result.mps_image_response_array.length]; for(int i = 0; i < result.mps_image_response_array.length; i++) { result_mps_image[i] = result.mps_image_response_array[i].mps_image[0]; } return result_mps_image; }
java
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { mps_image_responses result = (mps_image_responses) service.get_payload_formatter().string_to_resource(mps_image_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.mps_image_response_array); } mps_image[] result_mps_image = new mps_image[result.mps_image_response_array.length]; for(int i = 0; i < result.mps_image_response_array.length; i++) { result_mps_image[i] = result.mps_image_response_array[i].mps_image[0]; } return result_mps_image; }
[ "protected", "base_resource", "[", "]", "get_nitro_bulk_response", "(", "nitro_service", "service", ",", "String", "response", ")", "throws", "Exception", "{", "mps_image_responses", "result", "=", "(", "mps_image_responses", ")", "service", ".", "get_payload_formatter"...
<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/mps/mps_image.java#L265-L282
querydsl/querydsl
querydsl-core/src/main/java/com/querydsl/core/types/dsl/Expressions.java
Expressions.enumTemplate
public static <T extends Enum<T>> EnumTemplate<T> enumTemplate(Class<? extends T> cl, String template, Object... args) { return enumTemplate(cl, createTemplate(template), ImmutableList.copyOf(args)); }
java
public static <T extends Enum<T>> EnumTemplate<T> enumTemplate(Class<? extends T> cl, String template, Object... args) { return enumTemplate(cl, createTemplate(template), ImmutableList.copyOf(args)); }
[ "public", "static", "<", "T", "extends", "Enum", "<", "T", ">", ">", "EnumTemplate", "<", "T", ">", "enumTemplate", "(", "Class", "<", "?", "extends", "T", ">", "cl", ",", "String", "template", ",", "Object", "...", "args", ")", "{", "return", "enumT...
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#L725-L728
UrielCh/ovh-java-sdk
ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java
ApiOvhTelephony.billingAccount_fax_serviceName_campaigns_POST
public OvhFaxCampaign billingAccount_fax_serviceName_campaigns_POST(String billingAccount, String serviceName, String documentId, OvhFaxQualityEnum faxQuality, String name, String recipientsDocId, String[] recipientsList, OvhFaxCampaignRecipientsTypeEnum recipientsType, Date sendDate, OvhFaxCampaignSendTypeEnum sendType) throws IOException { String qPath = "/telephony/{billingAccount}/fax/{serviceName}/campaigns"; StringBuilder sb = path(qPath, billingAccount, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "documentId", documentId); addBody(o, "faxQuality", faxQuality); addBody(o, "name", name); addBody(o, "recipientsDocId", recipientsDocId); addBody(o, "recipientsList", recipientsList); addBody(o, "recipientsType", recipientsType); addBody(o, "sendDate", sendDate); addBody(o, "sendType", sendType); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhFaxCampaign.class); }
java
public OvhFaxCampaign billingAccount_fax_serviceName_campaigns_POST(String billingAccount, String serviceName, String documentId, OvhFaxQualityEnum faxQuality, String name, String recipientsDocId, String[] recipientsList, OvhFaxCampaignRecipientsTypeEnum recipientsType, Date sendDate, OvhFaxCampaignSendTypeEnum sendType) throws IOException { String qPath = "/telephony/{billingAccount}/fax/{serviceName}/campaigns"; StringBuilder sb = path(qPath, billingAccount, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "documentId", documentId); addBody(o, "faxQuality", faxQuality); addBody(o, "name", name); addBody(o, "recipientsDocId", recipientsDocId); addBody(o, "recipientsList", recipientsList); addBody(o, "recipientsType", recipientsType); addBody(o, "sendDate", sendDate); addBody(o, "sendType", sendType); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhFaxCampaign.class); }
[ "public", "OvhFaxCampaign", "billingAccount_fax_serviceName_campaigns_POST", "(", "String", "billingAccount", ",", "String", "serviceName", ",", "String", "documentId", ",", "OvhFaxQualityEnum", "faxQuality", ",", "String", "name", ",", "String", "recipientsDocId", ",", "...
Create a new fax campaign REST: POST /telephony/{billingAccount}/fax/{serviceName}/campaigns @param recipientsDocId [required] If recipientsType is set to document, the id of the document containing the recipients phone numbers @param name [required] The name of the fax campaign @param recipientsList [required] If recipientsType is set to list, the list of recipients phone numbers @param recipientsType [required] Method to set the campaign recipient @param faxQuality [required] The quality of the fax you want to send @param documentId [required] The id of the /me/document pdf you want to send @param sendDate [required] Sending date of the campaign (when sendType is scheduled) @param sendType [required] Sending type of the campaign @param billingAccount [required] The name of your billingAccount @param serviceName [required]
[ "Create", "a", "new", "fax", "campaign" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java#L4268-L4282
dottydingo/hyperion
core/src/main/java/com/dottydingo/hyperion/core/endpoint/pipeline/phase/CreatePhase.java
CreatePhase.processCollectionRequest
protected void processCollectionRequest(HyperionContext hyperionContext) { EndpointRequest request = hyperionContext.getEndpointRequest(); EndpointResponse response = hyperionContext.getEndpointResponse(); ApiVersionPlugin<ApiObject<Serializable>,PersistentObject<Serializable>,Serializable> apiVersionPlugin = hyperionContext.getVersionPlugin(); EntityPlugin plugin = hyperionContext.getEntityPlugin(); List<ApiObject<Serializable>> clientObjects = null; try { clientObjects = marshaller.unmarshallCollection(request.getInputStream(), apiVersionPlugin.getApiClass()); } catch (WriteLimitException e) { throw new BadRequestException(messageSource.getErrorMessage(ERROR_WRITE_LIMIT,hyperionContext.getLocale(),e.getWriteLimit()),e); } catch (MarshallingException e) { throw new BadRequestException(messageSource.getErrorMessage(ERROR_READING_REQUEST,hyperionContext.getLocale(),e.getMessage()),e); } PersistenceContext persistenceContext = buildPersistenceContext(hyperionContext); Set<String> fieldSet = persistenceContext.getRequestedFields(); if(fieldSet != null) fieldSet.add("id"); List<ApiObject> saved = plugin.getPersistenceOperations().createOrUpdateItems(clientObjects, persistenceContext); processChangeEvents(hyperionContext,persistenceContext); response.setResponseCode(200); EntityList<ApiObject> entityResponse = new EntityList<>(); entityResponse.setEntries(saved); hyperionContext.setResult(entityResponse); }
java
protected void processCollectionRequest(HyperionContext hyperionContext) { EndpointRequest request = hyperionContext.getEndpointRequest(); EndpointResponse response = hyperionContext.getEndpointResponse(); ApiVersionPlugin<ApiObject<Serializable>,PersistentObject<Serializable>,Serializable> apiVersionPlugin = hyperionContext.getVersionPlugin(); EntityPlugin plugin = hyperionContext.getEntityPlugin(); List<ApiObject<Serializable>> clientObjects = null; try { clientObjects = marshaller.unmarshallCollection(request.getInputStream(), apiVersionPlugin.getApiClass()); } catch (WriteLimitException e) { throw new BadRequestException(messageSource.getErrorMessage(ERROR_WRITE_LIMIT,hyperionContext.getLocale(),e.getWriteLimit()),e); } catch (MarshallingException e) { throw new BadRequestException(messageSource.getErrorMessage(ERROR_READING_REQUEST,hyperionContext.getLocale(),e.getMessage()),e); } PersistenceContext persistenceContext = buildPersistenceContext(hyperionContext); Set<String> fieldSet = persistenceContext.getRequestedFields(); if(fieldSet != null) fieldSet.add("id"); List<ApiObject> saved = plugin.getPersistenceOperations().createOrUpdateItems(clientObjects, persistenceContext); processChangeEvents(hyperionContext,persistenceContext); response.setResponseCode(200); EntityList<ApiObject> entityResponse = new EntityList<>(); entityResponse.setEntries(saved); hyperionContext.setResult(entityResponse); }
[ "protected", "void", "processCollectionRequest", "(", "HyperionContext", "hyperionContext", ")", "{", "EndpointRequest", "request", "=", "hyperionContext", ".", "getEndpointRequest", "(", ")", ";", "EndpointResponse", "response", "=", "hyperionContext", ".", "getEndpointR...
Process a multi-item request @param hyperionContext The context
[ "Process", "a", "multi", "-", "item", "request" ]
train
https://github.com/dottydingo/hyperion/blob/c4d119c90024a88c0335d7d318e9ccdb70149764/core/src/main/java/com/dottydingo/hyperion/core/endpoint/pipeline/phase/CreatePhase.java#L85-L122
xmlunit/xmlunit
xmlunit-core/src/main/java/org/xmlunit/diff/DefaultComparisonFormatter.java
DefaultComparisonFormatter.appendDocumentXmlDeclaration
protected boolean appendDocumentXmlDeclaration(StringBuilder sb, Document doc) { if ("1.0".equals(doc.getXmlVersion()) && doc.getXmlEncoding() == null && !doc.getXmlStandalone()) { // only default values => ignore return false; } sb.append("<?xml version=\""); sb.append(doc.getXmlVersion()); sb.append("\""); if (doc.getXmlEncoding() != null) { sb.append(" encoding=\""); sb.append(doc.getXmlEncoding()); sb.append("\""); } if (doc.getXmlStandalone()) { sb.append(" standalone=\"yes\""); } sb.append("?>"); return true; }
java
protected boolean appendDocumentXmlDeclaration(StringBuilder sb, Document doc) { if ("1.0".equals(doc.getXmlVersion()) && doc.getXmlEncoding() == null && !doc.getXmlStandalone()) { // only default values => ignore return false; } sb.append("<?xml version=\""); sb.append(doc.getXmlVersion()); sb.append("\""); if (doc.getXmlEncoding() != null) { sb.append(" encoding=\""); sb.append(doc.getXmlEncoding()); sb.append("\""); } if (doc.getXmlStandalone()) { sb.append(" standalone=\"yes\""); } sb.append("?>"); return true; }
[ "protected", "boolean", "appendDocumentXmlDeclaration", "(", "StringBuilder", "sb", ",", "Document", "doc", ")", "{", "if", "(", "\"1.0\"", ".", "equals", "(", "doc", ".", "getXmlVersion", "(", ")", ")", "&&", "doc", ".", "getXmlEncoding", "(", ")", "==", ...
Appends the XML declaration for {@link #getShortString} or {@link #appendFullDocumentHeader} if it contains non-default values. @param sb the builder to append to @return true if the XML declaration has been appended @since XMLUnit 2.4.0
[ "Appends", "the", "XML", "declaration", "for", "{", "@link", "#getShortString", "}", "or", "{", "@link", "#appendFullDocumentHeader", "}", "if", "it", "contains", "non", "-", "default", "values", "." ]
train
https://github.com/xmlunit/xmlunit/blob/fe3d701d43f57ee83dcba336e4c1555619d3084b/xmlunit-core/src/main/java/org/xmlunit/diff/DefaultComparisonFormatter.java#L176-L194
xiancloud/xian
xian-core/src/main/java/info/xiancloud/core/LocalUnitsManager.java
LocalUnitsManager.searchUnitMap
public static void searchUnitMap(Consumer<Map<String, Unit>> consumer) { readWriteLock.readLock().lock(); try { consumer.accept(Collections.unmodifiableMap(searchUnitMap)); } finally { readWriteLock.readLock().unlock(); } }
java
public static void searchUnitMap(Consumer<Map<String, Unit>> consumer) { readWriteLock.readLock().lock(); try { consumer.accept(Collections.unmodifiableMap(searchUnitMap)); } finally { readWriteLock.readLock().unlock(); } }
[ "public", "static", "void", "searchUnitMap", "(", "Consumer", "<", "Map", "<", "String", ",", "Unit", ">", ">", "consumer", ")", "{", "readWriteLock", ".", "readLock", "(", ")", ".", "lock", "(", ")", ";", "try", "{", "consumer", ".", "accept", "(", ...
Iterate {@link #searchUnitMap} thread-safely. @param consumer the operation for the unit map.
[ "Iterate", "{", "@link", "#searchUnitMap", "}", "thread", "-", "safely", "." ]
train
https://github.com/xiancloud/xian/blob/1948e088545553d2745b2c86d8b5a64988bb850e/xian-core/src/main/java/info/xiancloud/core/LocalUnitsManager.java#L227-L234
apache/spark
common/network-common/src/main/java/org/apache/spark/network/util/JavaUtils.java
JavaUtils.byteStringAs
public static long byteStringAs(String str, ByteUnit unit) { String lower = str.toLowerCase(Locale.ROOT).trim(); try { Matcher m = Pattern.compile("([0-9]+)([a-z]+)?").matcher(lower); Matcher fractionMatcher = Pattern.compile("([0-9]+\\.[0-9]+)([a-z]+)?").matcher(lower); if (m.matches()) { long val = Long.parseLong(m.group(1)); String suffix = m.group(2); // Check for invalid suffixes if (suffix != null && !byteSuffixes.containsKey(suffix)) { throw new NumberFormatException("Invalid suffix: \"" + suffix + "\""); } // If suffix is valid use that, otherwise none was provided and use the default passed return unit.convertFrom(val, suffix != null ? byteSuffixes.get(suffix) : unit); } else if (fractionMatcher.matches()) { throw new NumberFormatException("Fractional values are not supported. Input was: " + fractionMatcher.group(1)); } else { throw new NumberFormatException("Failed to parse byte string: " + str); } } catch (NumberFormatException e) { String byteError = "Size must be specified as bytes (b), " + "kibibytes (k), mebibytes (m), gibibytes (g), tebibytes (t), or pebibytes(p). " + "E.g. 50b, 100k, or 250m."; throw new NumberFormatException(byteError + "\n" + e.getMessage()); } }
java
public static long byteStringAs(String str, ByteUnit unit) { String lower = str.toLowerCase(Locale.ROOT).trim(); try { Matcher m = Pattern.compile("([0-9]+)([a-z]+)?").matcher(lower); Matcher fractionMatcher = Pattern.compile("([0-9]+\\.[0-9]+)([a-z]+)?").matcher(lower); if (m.matches()) { long val = Long.parseLong(m.group(1)); String suffix = m.group(2); // Check for invalid suffixes if (suffix != null && !byteSuffixes.containsKey(suffix)) { throw new NumberFormatException("Invalid suffix: \"" + suffix + "\""); } // If suffix is valid use that, otherwise none was provided and use the default passed return unit.convertFrom(val, suffix != null ? byteSuffixes.get(suffix) : unit); } else if (fractionMatcher.matches()) { throw new NumberFormatException("Fractional values are not supported. Input was: " + fractionMatcher.group(1)); } else { throw new NumberFormatException("Failed to parse byte string: " + str); } } catch (NumberFormatException e) { String byteError = "Size must be specified as bytes (b), " + "kibibytes (k), mebibytes (m), gibibytes (g), tebibytes (t), or pebibytes(p). " + "E.g. 50b, 100k, or 250m."; throw new NumberFormatException(byteError + "\n" + e.getMessage()); } }
[ "public", "static", "long", "byteStringAs", "(", "String", "str", ",", "ByteUnit", "unit", ")", "{", "String", "lower", "=", "str", ".", "toLowerCase", "(", "Locale", ".", "ROOT", ")", ".", "trim", "(", ")", ";", "try", "{", "Matcher", "m", "=", "Pat...
Convert a passed byte string (e.g. 50b, 100kb, or 250mb) to the given. If no suffix is provided, a direct conversion to the provided unit is attempted.
[ "Convert", "a", "passed", "byte", "string", "(", "e", ".", "g", ".", "50b", "100kb", "or", "250mb", ")", "to", "the", "given", ".", "If", "no", "suffix", "is", "provided", "a", "direct", "conversion", "to", "the", "provided", "unit", "is", "attempted",...
train
https://github.com/apache/spark/blob/25ee0474f47d9c30d6f553a7892d9549f91071cf/common/network-common/src/main/java/org/apache/spark/network/util/JavaUtils.java#L276-L308
recommenders/rival
rival-evaluate/src/main/java/net/recommenders/rival/evaluation/statistics/StatisticsRunner.java
StatisticsRunner.readLine
public static void readLine(final String format, final String line, final Map<String, Map<String, Double>> mapMetricUserValue, final Set<String> usersToAvoid) { String[] toks = line.split("\t"); // default (also trec_eval) format: metric \t user|all \t value if (format.equals("default")) { String metric = toks[0]; String user = toks[1]; Double score = Double.parseDouble(toks[2]); if (usersToAvoid.contains(user)) { return; } Map<String, Double> userValueMap = mapMetricUserValue.get(metric); if (userValueMap == null) { userValueMap = new HashMap<String, Double>(); mapMetricUserValue.put(metric, userValueMap); } userValueMap.put(user, score); } }
java
public static void readLine(final String format, final String line, final Map<String, Map<String, Double>> mapMetricUserValue, final Set<String> usersToAvoid) { String[] toks = line.split("\t"); // default (also trec_eval) format: metric \t user|all \t value if (format.equals("default")) { String metric = toks[0]; String user = toks[1]; Double score = Double.parseDouble(toks[2]); if (usersToAvoid.contains(user)) { return; } Map<String, Double> userValueMap = mapMetricUserValue.get(metric); if (userValueMap == null) { userValueMap = new HashMap<String, Double>(); mapMetricUserValue.put(metric, userValueMap); } userValueMap.put(user, score); } }
[ "public", "static", "void", "readLine", "(", "final", "String", "format", ",", "final", "String", "line", ",", "final", "Map", "<", "String", ",", "Map", "<", "String", ",", "Double", ">", ">", "mapMetricUserValue", ",", "final", "Set", "<", "String", ">...
Read a line from the metric file. @param format The format of the file. @param line The line. @param mapMetricUserValue Map where metric values for each user will be stored. @param usersToAvoid User ids to be avoided in the subsequent significance testing (e.g., 'all')
[ "Read", "a", "line", "from", "the", "metric", "file", "." ]
train
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-evaluate/src/main/java/net/recommenders/rival/evaluation/statistics/StatisticsRunner.java#L263-L280
Deep-Symmetry/beat-link
src/main/java/org/deepsymmetry/beatlink/data/CueList.java
CueList.sortEntries
private List<Entry> sortEntries(List<Entry> loadedEntries) { Collections.sort(loadedEntries, new Comparator<Entry>() { @Override public int compare(Entry entry1, Entry entry2) { int result = (int) (entry1.cuePosition - entry2.cuePosition); if (result == 0) { int h1 = (entry1.hotCueNumber != 0) ? 1 : 0; int h2 = (entry2.hotCueNumber != 0) ? 1 : 0; result = h1 - h2; } return result; } }); return Collections.unmodifiableList(loadedEntries); }
java
private List<Entry> sortEntries(List<Entry> loadedEntries) { Collections.sort(loadedEntries, new Comparator<Entry>() { @Override public int compare(Entry entry1, Entry entry2) { int result = (int) (entry1.cuePosition - entry2.cuePosition); if (result == 0) { int h1 = (entry1.hotCueNumber != 0) ? 1 : 0; int h2 = (entry2.hotCueNumber != 0) ? 1 : 0; result = h1 - h2; } return result; } }); return Collections.unmodifiableList(loadedEntries); }
[ "private", "List", "<", "Entry", ">", "sortEntries", "(", "List", "<", "Entry", ">", "loadedEntries", ")", "{", "Collections", ".", "sort", "(", "loadedEntries", ",", "new", "Comparator", "<", "Entry", ">", "(", ")", "{", "@", "Override", "public", "int"...
Sorts the entries into the order we want to present them in, which is by position, with hot cues coming after ordinary memory points if both exist at the same position, which often happens. @param loadedEntries the unsorted entries we have loaded from a dbserver message, metadata cache, or rekordbox database export @return an immutable list of the collections in the proper order
[ "Sorts", "the", "entries", "into", "the", "order", "we", "want", "to", "present", "them", "in", "which", "is", "by", "position", "with", "hot", "cues", "coming", "after", "ordinary", "memory", "points", "if", "both", "exist", "at", "the", "same", "position...
train
https://github.com/Deep-Symmetry/beat-link/blob/f958a2a70e8a87a31a75326d7b4db77c2f0b4212/src/main/java/org/deepsymmetry/beatlink/data/CueList.java#L204-L218
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/serializer/SerializerBase.java
SerializerBase.addXSLAttribute
public void addXSLAttribute(String name, final String value, final String uri) { if (m_elemContext.m_startTagOpen) { final String patchedName = patchName(name); final String localName = getLocalName(patchedName); addAttributeAlways(uri,localName, patchedName, "CDATA", value, true); } }
java
public void addXSLAttribute(String name, final String value, final String uri) { if (m_elemContext.m_startTagOpen) { final String patchedName = patchName(name); final String localName = getLocalName(patchedName); addAttributeAlways(uri,localName, patchedName, "CDATA", value, true); } }
[ "public", "void", "addXSLAttribute", "(", "String", "name", ",", "final", "String", "value", ",", "final", "String", "uri", ")", "{", "if", "(", "m_elemContext", ".", "m_startTagOpen", ")", "{", "final", "String", "patchedName", "=", "patchName", "(", "name"...
Adds the given xsl:attribute to the set of collected attributes, but only if there is a currently open element. @param name the attribute's qualified name (prefix:localName) @param value the value of the attribute @param uri the URI that the prefix of the name points to
[ "Adds", "the", "given", "xsl", ":", "attribute", "to", "the", "set", "of", "collected", "attributes", "but", "only", "if", "there", "is", "a", "currently", "open", "element", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/serializer/SerializerBase.java#L464-L473
netheosgithub/pcs_api
java/src/main/java/net/netheos/pcsapi/providers/dropbox/Dropbox.java
Dropbox.buildContentUrl
private String buildContentUrl( String methodPath, CPath path ) { return CONTENT_END_POINT + '/' + methodPath + '/' + scope + path.getUrlEncoded(); }
java
private String buildContentUrl( String methodPath, CPath path ) { return CONTENT_END_POINT + '/' + methodPath + '/' + scope + path.getUrlEncoded(); }
[ "private", "String", "buildContentUrl", "(", "String", "methodPath", ",", "CPath", "path", ")", "{", "return", "CONTENT_END_POINT", "+", "'", "'", "+", "methodPath", "+", "'", "'", "+", "scope", "+", "path", ".", "getUrlEncoded", "(", ")", ";", "}" ]
Url encodes blob path, and concatenate to content endpoint to get full URL @param methodPath @param path @return URL
[ "Url", "encodes", "blob", "path", "and", "concatenate", "to", "content", "endpoint", "to", "get", "full", "URL" ]
train
https://github.com/netheosgithub/pcs_api/blob/20691e52e144014f99ca75cb7dedc7ba0c18586c/java/src/main/java/net/netheos/pcsapi/providers/dropbox/Dropbox.java#L407-L410
goldmansachs/gs-collections
collections/src/main/java/com/gs/collections/impl/list/Interval.java
Interval.oddsFromTo
public static Interval oddsFromTo(int from, int to) { if (from % 2 == 0) { if (from < to) { from++; } else { from--; } } if (to % 2 == 0) { if (to > from) { to--; } else { to++; } } return Interval.fromToBy(from, to, to > from ? 2 : -2); }
java
public static Interval oddsFromTo(int from, int to) { if (from % 2 == 0) { if (from < to) { from++; } else { from--; } } if (to % 2 == 0) { if (to > from) { to--; } else { to++; } } return Interval.fromToBy(from, to, to > from ? 2 : -2); }
[ "public", "static", "Interval", "oddsFromTo", "(", "int", "from", ",", "int", "to", ")", "{", "if", "(", "from", "%", "2", "==", "0", ")", "{", "if", "(", "from", "<", "to", ")", "{", "from", "++", ";", "}", "else", "{", "from", "--", ";", "}...
Returns an Interval representing the odd values from the value from to the value to.
[ "Returns", "an", "Interval", "representing", "the", "odd", "values", "from", "the", "value", "from", "to", "the", "value", "to", "." ]
train
https://github.com/goldmansachs/gs-collections/blob/fa8bf3e103689efa18bca2ab70203e71cde34b52/collections/src/main/java/com/gs/collections/impl/list/Interval.java#L218-L243
mailin-api/sendinblue-java-mvn
src/main/java/com/sendinblue/Sendinblue.java
Sendinblue.add_users_list
public String add_users_list(Map<String, Object> data) { String id = data.get("id").toString(); Gson gson = new Gson(); String json = gson.toJson(data); return post("list/" + id + "/users", json); }
java
public String add_users_list(Map<String, Object> data) { String id = data.get("id").toString(); Gson gson = new Gson(); String json = gson.toJson(data); return post("list/" + id + "/users", json); }
[ "public", "String", "add_users_list", "(", "Map", "<", "String", ",", "Object", ">", "data", ")", "{", "String", "id", "=", "data", ".", "get", "(", "\"id\"", ")", ".", "toString", "(", ")", ";", "Gson", "gson", "=", "new", "Gson", "(", ")", ";", ...
/* Add already existing users in the SendinBlue contacts to the list. @param {Object} data contains json objects as a key value pair from HashMap. @options data {Integer} id: Id of list to link users in it [Mandatory] @options data {Array} users: Email address of the already existing user(s) in the SendinBlue contacts. Example: "test@example.net". You can use commas to separate multiple users [Mandatory]
[ "/", "*", "Add", "already", "existing", "users", "in", "the", "SendinBlue", "contacts", "to", "the", "list", "." ]
train
https://github.com/mailin-api/sendinblue-java-mvn/blob/3a186b004003450f18d619aa084adc8d75086183/src/main/java/com/sendinblue/Sendinblue.java#L653-L658
Azure/azure-sdk-for-java
logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/IntegrationAccountAssembliesInner.java
IntegrationAccountAssembliesInner.listContentCallbackUrlAsync
public Observable<WorkflowTriggerCallbackUrlInner> listContentCallbackUrlAsync(String resourceGroupName, String integrationAccountName, String assemblyArtifactName) { return listContentCallbackUrlWithServiceResponseAsync(resourceGroupName, integrationAccountName, assemblyArtifactName).map(new Func1<ServiceResponse<WorkflowTriggerCallbackUrlInner>, WorkflowTriggerCallbackUrlInner>() { @Override public WorkflowTriggerCallbackUrlInner call(ServiceResponse<WorkflowTriggerCallbackUrlInner> response) { return response.body(); } }); }
java
public Observable<WorkflowTriggerCallbackUrlInner> listContentCallbackUrlAsync(String resourceGroupName, String integrationAccountName, String assemblyArtifactName) { return listContentCallbackUrlWithServiceResponseAsync(resourceGroupName, integrationAccountName, assemblyArtifactName).map(new Func1<ServiceResponse<WorkflowTriggerCallbackUrlInner>, WorkflowTriggerCallbackUrlInner>() { @Override public WorkflowTriggerCallbackUrlInner call(ServiceResponse<WorkflowTriggerCallbackUrlInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "WorkflowTriggerCallbackUrlInner", ">", "listContentCallbackUrlAsync", "(", "String", "resourceGroupName", ",", "String", "integrationAccountName", ",", "String", "assemblyArtifactName", ")", "{", "return", "listContentCallbackUrlWithServiceResponseAs...
Get the content callback url for an integration account assembly. @param resourceGroupName The resource group name. @param integrationAccountName The integration account name. @param assemblyArtifactName The assembly artifact name. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the WorkflowTriggerCallbackUrlInner object
[ "Get", "the", "content", "callback", "url", "for", "an", "integration", "account", "assembly", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/IntegrationAccountAssembliesInner.java#L499-L506
alkacon/opencms-core
src-gwt/org/opencms/ade/sitemap/client/toolbar/CmsToolbarChooseEditorModeButton.java
CmsToolbarChooseEditorModeButton.createContextMenu
public CmsContextMenu createContextMenu() { m_entries = new ArrayList<I_CmsContextMenuEntry>(); m_entries.add( new EditorModeEntry( Messages.get().key(Messages.GUI_ONLY_NAVIGATION_BUTTON_TITLE_0), EditorMode.navigation)); m_entries.add( new EditorModeEntry(Messages.get().key(Messages.GUI_NON_NAVIGATION_BUTTON_TITLE_0), EditorMode.vfs)); m_entries.add( new EditorModeEntry(Messages.get().key(Messages.GUI_ONLY_GALLERIES_BUTTON_TITLE_0), EditorMode.galleries)); if (CmsCoreProvider.get().getUserInfo().isCategoryManager()) { m_entries.add( new EditorModeEntry( Messages.get().key(Messages.GUI_CONTEXTMENU_CATEGORY_MODE_0), EditorMode.categories)); } if (m_canEditModelPages) { m_entries.add(new EditorModeEntry(Messages.get().key(Messages.GUI_MODEL_PAGES_0), EditorMode.modelpages)); } if (CmsSitemapView.getInstance().getController().isLocaleComparisonEnabled()) { m_entries.add( new EditorModeEntry(Messages.get().key(Messages.GUI_LOCALECOMPARE_MODE_0), EditorMode.compareLocales)); } CmsContextMenu menu = new CmsContextMenu(m_entries, false, getPopup()); return menu; }
java
public CmsContextMenu createContextMenu() { m_entries = new ArrayList<I_CmsContextMenuEntry>(); m_entries.add( new EditorModeEntry( Messages.get().key(Messages.GUI_ONLY_NAVIGATION_BUTTON_TITLE_0), EditorMode.navigation)); m_entries.add( new EditorModeEntry(Messages.get().key(Messages.GUI_NON_NAVIGATION_BUTTON_TITLE_0), EditorMode.vfs)); m_entries.add( new EditorModeEntry(Messages.get().key(Messages.GUI_ONLY_GALLERIES_BUTTON_TITLE_0), EditorMode.galleries)); if (CmsCoreProvider.get().getUserInfo().isCategoryManager()) { m_entries.add( new EditorModeEntry( Messages.get().key(Messages.GUI_CONTEXTMENU_CATEGORY_MODE_0), EditorMode.categories)); } if (m_canEditModelPages) { m_entries.add(new EditorModeEntry(Messages.get().key(Messages.GUI_MODEL_PAGES_0), EditorMode.modelpages)); } if (CmsSitemapView.getInstance().getController().isLocaleComparisonEnabled()) { m_entries.add( new EditorModeEntry(Messages.get().key(Messages.GUI_LOCALECOMPARE_MODE_0), EditorMode.compareLocales)); } CmsContextMenu menu = new CmsContextMenu(m_entries, false, getPopup()); return menu; }
[ "public", "CmsContextMenu", "createContextMenu", "(", ")", "{", "m_entries", "=", "new", "ArrayList", "<", "I_CmsContextMenuEntry", ">", "(", ")", ";", "m_entries", ".", "add", "(", "new", "EditorModeEntry", "(", "Messages", ".", "get", "(", ")", ".", "key",...
Creates the menu widget for this button.<p> @return the menu widget
[ "Creates", "the", "menu", "widget", "for", "this", "button", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/sitemap/client/toolbar/CmsToolbarChooseEditorModeButton.java#L151-L178
jbossws/jbossws-common
src/main/java/org/jboss/ws/common/integration/WSHelper.java
WSHelper.getRequiredAttachment
public static <A> A getRequiredAttachment( final Deployment dep, final Class< A > key ) { final A value = dep.getAttachment( key ); if ( value == null ) { throw Messages.MESSAGES.cannotFindAttachmentInDeployment(key, dep.getSimpleName()); } return value; }
java
public static <A> A getRequiredAttachment( final Deployment dep, final Class< A > key ) { final A value = dep.getAttachment( key ); if ( value == null ) { throw Messages.MESSAGES.cannotFindAttachmentInDeployment(key, dep.getSimpleName()); } return value; }
[ "public", "static", "<", "A", ">", "A", "getRequiredAttachment", "(", "final", "Deployment", "dep", ",", "final", "Class", "<", "A", ">", "key", ")", "{", "final", "A", "value", "=", "dep", ".", "getAttachment", "(", "key", ")", ";", "if", "(", "valu...
Returns required attachment value from webservice deployment. @param <A> expected value @param dep webservice deployment @param key attachment key @return required attachment @throws IllegalStateException if attachment value is null
[ "Returns", "required", "attachment", "value", "from", "webservice", "deployment", "." ]
train
https://github.com/jbossws/jbossws-common/blob/fcff8a3ef9bfe046d6fa8c855a3fe4f62841add7/src/main/java/org/jboss/ws/common/integration/WSHelper.java#L62-L70
belaban/JGroups
src/org/jgroups/Message.java
Message.readFromSkipPayload
public int readFromSkipPayload(ByteArrayDataInputStream in) throws IOException, ClassNotFoundException { // 1. read the leading byte first byte leading=in.readByte(); // 2. the flags flags=in.readShort(); // 3. dest_addr if(Util.isFlagSet(leading, DEST_SET)) dest=Util.readAddress(in); // 4. src_addr if(Util.isFlagSet(leading, SRC_SET)) sender=Util.readAddress(in); // 5. headers int len=in.readShort(); headers=createHeaders(len); for(int i=0; i < len; i++) { short id=in.readShort(); Header hdr=readHeader(in).setProtId(id); this.headers[i]=hdr; } // 6. buf if(!Util.isFlagSet(leading, BUF_SET)) return -1; length=in.readInt(); return in.position(); }
java
public int readFromSkipPayload(ByteArrayDataInputStream in) throws IOException, ClassNotFoundException { // 1. read the leading byte first byte leading=in.readByte(); // 2. the flags flags=in.readShort(); // 3. dest_addr if(Util.isFlagSet(leading, DEST_SET)) dest=Util.readAddress(in); // 4. src_addr if(Util.isFlagSet(leading, SRC_SET)) sender=Util.readAddress(in); // 5. headers int len=in.readShort(); headers=createHeaders(len); for(int i=0; i < len; i++) { short id=in.readShort(); Header hdr=readHeader(in).setProtId(id); this.headers[i]=hdr; } // 6. buf if(!Util.isFlagSet(leading, BUF_SET)) return -1; length=in.readInt(); return in.position(); }
[ "public", "int", "readFromSkipPayload", "(", "ByteArrayDataInputStream", "in", ")", "throws", "IOException", ",", "ClassNotFoundException", "{", "// 1. read the leading byte first", "byte", "leading", "=", "in", ".", "readByte", "(", ")", ";", "// 2. the flags", "flags"...
Reads the message's contents from an input stream, but skips the buffer and instead returns the position (offset) at which the buffer starts
[ "Reads", "the", "message", "s", "contents", "from", "an", "input", "stream", "but", "skips", "the", "buffer", "and", "instead", "returns", "the", "position", "(", "offset", ")", "at", "which", "the", "buffer", "starts" ]
train
https://github.com/belaban/JGroups/blob/bd3ca786aa57fed41dfbc10a94b1281e388be03b/src/org/jgroups/Message.java#L726-L757
OpenHFT/Chronicle-Map
src/main/java/net/openhft/chronicle/hash/impl/util/math/Precision.java
Precision.isEquals
public static boolean isEquals(final double x, final double y, final int maxUlps) { final long xInt = Double.doubleToRawLongBits(x); final long yInt = Double.doubleToRawLongBits(y); final boolean isEqual; if (((xInt ^ yInt) & SGN_MASK) == 0L) { // number have same sign, there is no risk of overflow isEqual = Math.abs(xInt - yInt) <= maxUlps; } else { // number have opposite signs, take care of overflow final long deltaPlus; final long deltaMinus; if (xInt < yInt) { deltaPlus = yInt - POSITIVE_ZERO_DOUBLE_BITS; deltaMinus = xInt - NEGATIVE_ZERO_DOUBLE_BITS; } else { deltaPlus = xInt - POSITIVE_ZERO_DOUBLE_BITS; deltaMinus = yInt - NEGATIVE_ZERO_DOUBLE_BITS; } if (deltaPlus > maxUlps) { isEqual = false; } else { isEqual = deltaMinus <= (maxUlps - deltaPlus); } } return isEqual && !Double.isNaN(x) && !Double.isNaN(y); }
java
public static boolean isEquals(final double x, final double y, final int maxUlps) { final long xInt = Double.doubleToRawLongBits(x); final long yInt = Double.doubleToRawLongBits(y); final boolean isEqual; if (((xInt ^ yInt) & SGN_MASK) == 0L) { // number have same sign, there is no risk of overflow isEqual = Math.abs(xInt - yInt) <= maxUlps; } else { // number have opposite signs, take care of overflow final long deltaPlus; final long deltaMinus; if (xInt < yInt) { deltaPlus = yInt - POSITIVE_ZERO_DOUBLE_BITS; deltaMinus = xInt - NEGATIVE_ZERO_DOUBLE_BITS; } else { deltaPlus = xInt - POSITIVE_ZERO_DOUBLE_BITS; deltaMinus = yInt - NEGATIVE_ZERO_DOUBLE_BITS; } if (deltaPlus > maxUlps) { isEqual = false; } else { isEqual = deltaMinus <= (maxUlps - deltaPlus); } } return isEqual && !Double.isNaN(x) && !Double.isNaN(y); }
[ "public", "static", "boolean", "isEquals", "(", "final", "double", "x", ",", "final", "double", "y", ",", "final", "int", "maxUlps", ")", "{", "final", "long", "xInt", "=", "Double", ".", "doubleToRawLongBits", "(", "x", ")", ";", "final", "long", "yInt"...
Returns true if both arguments are equal or within the range of allowed error (inclusive). <p> Two float numbers are considered equal if there are {@code (maxUlps - 1)} (or fewer) floating point numbers between them, i.e. two adjacent floating point numbers are considered equal. </p> <p> Adapted from <a href="http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/"> Bruce Dawson</a> </p> @param x first value @param y second value @param maxUlps {@code (maxUlps - 1)} is the number of floating point values between {@code x} and {@code y}. @return {@code true} if there are fewer than {@code maxUlps} floating point values between {@code x} and {@code y}.
[ "Returns", "true", "if", "both", "arguments", "are", "equal", "or", "within", "the", "range", "of", "allowed", "error", "(", "inclusive", ")", ".", "<p", ">", "Two", "float", "numbers", "are", "considered", "equal", "if", "there", "are", "{", "@code", "(...
train
https://github.com/OpenHFT/Chronicle-Map/blob/0b09733cc96302f96be4394a261699eeb021fe37/src/main/java/net/openhft/chronicle/hash/impl/util/math/Precision.java#L72-L102
ocelotds/ocelot
ocelot-processor/src/main/java/org/ocelotds/processors/visitors/AbstractDataServiceVisitor.java
AbstractDataServiceVisitor.isConsiderateMethod
boolean isConsiderateMethod(Collection<String> methodProceeds, ExecutableElement methodElement) { // int argNum methodElement.getParameters().size(); String signature = methodElement.getSimpleName().toString(); // + "(" + argNum + ")"; // Check if method ith same signature has been already proceed. if (methodProceeds.contains(signature)) { return false; } // Herited from Object TypeElement objectElement = environment.getElementUtils().getTypeElement(Object.class.getName()); if (objectElement.getEnclosedElements().contains(methodElement)) { return false; } // Static, not public ? if (!methodElement.getModifiers().contains(Modifier.PUBLIC) || methodElement.getModifiers().contains(Modifier.STATIC)) { return false; } // TransientDataService ? List<? extends AnnotationMirror> annotationMirrors = methodElement.getAnnotationMirrors(); for (AnnotationMirror annotationMirror : annotationMirrors) { if (annotationMirror.getAnnotationType().toString().equals(TransientDataService.class.getName())) { return false; } } methodProceeds.add(signature); return true; }
java
boolean isConsiderateMethod(Collection<String> methodProceeds, ExecutableElement methodElement) { // int argNum methodElement.getParameters().size(); String signature = methodElement.getSimpleName().toString(); // + "(" + argNum + ")"; // Check if method ith same signature has been already proceed. if (methodProceeds.contains(signature)) { return false; } // Herited from Object TypeElement objectElement = environment.getElementUtils().getTypeElement(Object.class.getName()); if (objectElement.getEnclosedElements().contains(methodElement)) { return false; } // Static, not public ? if (!methodElement.getModifiers().contains(Modifier.PUBLIC) || methodElement.getModifiers().contains(Modifier.STATIC)) { return false; } // TransientDataService ? List<? extends AnnotationMirror> annotationMirrors = methodElement.getAnnotationMirrors(); for (AnnotationMirror annotationMirror : annotationMirrors) { if (annotationMirror.getAnnotationType().toString().equals(TransientDataService.class.getName())) { return false; } } methodProceeds.add(signature); return true; }
[ "boolean", "isConsiderateMethod", "(", "Collection", "<", "String", ">", "methodProceeds", ",", "ExecutableElement", "methodElement", ")", "{", "//\t\tint argNum methodElement.getParameters().size();\r", "String", "signature", "=", "methodElement", ".", "getSimpleName", "(", ...
Return if the method have to considerate<br> The method is public,<br> Not annotated by TransientDataService<br> Not static and not from Object herited. @param methodProceeds @param methodElement @return
[ "Return", "if", "the", "method", "have", "to", "considerate<br", ">", "The", "method", "is", "public", "<br", ">", "Not", "annotated", "by", "TransientDataService<br", ">", "Not", "static", "and", "not", "from", "Object", "herited", "." ]
train
https://github.com/ocelotds/ocelot/blob/5f0ac37afd8fa4dc9f7234a2aac8abbb522128e7/ocelot-processor/src/main/java/org/ocelotds/processors/visitors/AbstractDataServiceVisitor.java#L169-L194
Erudika/para
para-server/src/main/java/com/erudika/para/rest/RestUtils.java
RestUtils.getOverwriteResponse
public static Response getOverwriteResponse(App app, String id, String type, InputStream is) { try (final Metrics.Context context = Metrics.time(app == null ? null : app.getAppid(), RestUtils.class, "crud", "overwrite")) { ParaObject content; Response entityRes = getEntity(is, Map.class); if (entityRes.getStatusInfo() == Response.Status.OK) { Map<String, Object> newContent = (Map<String, Object>) entityRes.getEntity(); if (!StringUtils.isBlank(type)) { newContent.put(Config._TYPE, type); } content = ParaObjectUtils.setAnnotatedFields(newContent); if (app != null && content != null && !StringUtils.isBlank(id) && isNotAnApp(type)) { warnIfUserTypeDetected(type); content.setType(type); content.setAppid(app.getAppIdentifier()); content.setId(id); setCreatorid(app, content); int typesCount = app.getDatatypes().size(); app.addDatatypes(content); // The reason why we do two validation passes is because we want to return // the errors through the API and notify the end user. // This is the primary validation pass (validates not only core POJOS but also user defined objects). String[] errors = validateObject(app, content); if (errors.length == 0 && checkIfUserCanModifyObject(app, content)) { // Secondary validation pass called here. Object is validated again before being created // See: IndexAndCacheAspect.java CoreUtils.getInstance().overwrite(app.getAppIdentifier(), content); // new type added so update app object if (typesCount < app.getDatatypes().size()) { app.update(); } return Response.ok(content).build(); } return getStatusResponse(Response.Status.BAD_REQUEST, errors); } return getStatusResponse(Response.Status.BAD_REQUEST, "Failed to overwrite object."); } return entityRes; } }
java
public static Response getOverwriteResponse(App app, String id, String type, InputStream is) { try (final Metrics.Context context = Metrics.time(app == null ? null : app.getAppid(), RestUtils.class, "crud", "overwrite")) { ParaObject content; Response entityRes = getEntity(is, Map.class); if (entityRes.getStatusInfo() == Response.Status.OK) { Map<String, Object> newContent = (Map<String, Object>) entityRes.getEntity(); if (!StringUtils.isBlank(type)) { newContent.put(Config._TYPE, type); } content = ParaObjectUtils.setAnnotatedFields(newContent); if (app != null && content != null && !StringUtils.isBlank(id) && isNotAnApp(type)) { warnIfUserTypeDetected(type); content.setType(type); content.setAppid(app.getAppIdentifier()); content.setId(id); setCreatorid(app, content); int typesCount = app.getDatatypes().size(); app.addDatatypes(content); // The reason why we do two validation passes is because we want to return // the errors through the API and notify the end user. // This is the primary validation pass (validates not only core POJOS but also user defined objects). String[] errors = validateObject(app, content); if (errors.length == 0 && checkIfUserCanModifyObject(app, content)) { // Secondary validation pass called here. Object is validated again before being created // See: IndexAndCacheAspect.java CoreUtils.getInstance().overwrite(app.getAppIdentifier(), content); // new type added so update app object if (typesCount < app.getDatatypes().size()) { app.update(); } return Response.ok(content).build(); } return getStatusResponse(Response.Status.BAD_REQUEST, errors); } return getStatusResponse(Response.Status.BAD_REQUEST, "Failed to overwrite object."); } return entityRes; } }
[ "public", "static", "Response", "getOverwriteResponse", "(", "App", "app", ",", "String", "id", ",", "String", "type", ",", "InputStream", "is", ")", "{", "try", "(", "final", "Metrics", ".", "Context", "context", "=", "Metrics", ".", "time", "(", "app", ...
Overwrite response as JSON. @param id the object id @param type type of the object to create @param is entity input stream @param app the app object @return a status code 200 or 400
[ "Overwrite", "response", "as", "JSON", "." ]
train
https://github.com/Erudika/para/blob/5ba096c477042ea7b18e9a0e8b5b1ee0f5bd6ce9/para-server/src/main/java/com/erudika/para/rest/RestUtils.java#L366-L405
line/armeria
core/src/main/java/com/linecorp/armeria/server/docs/TypeSignature.java
TypeSignature.ofContainer
public static TypeSignature ofContainer(String containerTypeName, Iterable<TypeSignature> elementTypeSignatures) { checkBaseTypeName(containerTypeName, "containerTypeName"); requireNonNull(elementTypeSignatures, "elementTypeSignatures"); final List<TypeSignature> elementTypeSignaturesCopy = ImmutableList.copyOf(elementTypeSignatures); checkArgument(!elementTypeSignaturesCopy.isEmpty(), "elementTypeSignatures is empty."); return new TypeSignature(containerTypeName, elementTypeSignaturesCopy); }
java
public static TypeSignature ofContainer(String containerTypeName, Iterable<TypeSignature> elementTypeSignatures) { checkBaseTypeName(containerTypeName, "containerTypeName"); requireNonNull(elementTypeSignatures, "elementTypeSignatures"); final List<TypeSignature> elementTypeSignaturesCopy = ImmutableList.copyOf(elementTypeSignatures); checkArgument(!elementTypeSignaturesCopy.isEmpty(), "elementTypeSignatures is empty."); return new TypeSignature(containerTypeName, elementTypeSignaturesCopy); }
[ "public", "static", "TypeSignature", "ofContainer", "(", "String", "containerTypeName", ",", "Iterable", "<", "TypeSignature", ">", "elementTypeSignatures", ")", "{", "checkBaseTypeName", "(", "containerTypeName", ",", "\"containerTypeName\"", ")", ";", "requireNonNull", ...
Creates a new container type with the specified container type name and the type signatures of the elements it contains. @throws IllegalArgumentException if the specified type name is not valid or {@code elementTypeSignatures} is empty.
[ "Creates", "a", "new", "container", "type", "with", "the", "specified", "container", "type", "name", "and", "the", "type", "signatures", "of", "the", "elements", "it", "contains", "." ]
train
https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/core/src/main/java/com/linecorp/armeria/server/docs/TypeSignature.java#L91-L98
fozziethebeat/S-Space
src/main/java/edu/ucla/sspace/matrix/DiagonalMatrix.java
DiagonalMatrix.set
public void set(int row, int col, double val) { checkIndices(row, col); if (row != col) { throw new IllegalArgumentException( "cannot set non-diagonal elements in a DiagonalMatrix"); } values[row] = val; }
java
public void set(int row, int col, double val) { checkIndices(row, col); if (row != col) { throw new IllegalArgumentException( "cannot set non-diagonal elements in a DiagonalMatrix"); } values[row] = val; }
[ "public", "void", "set", "(", "int", "row", ",", "int", "col", ",", "double", "val", ")", "{", "checkIndices", "(", "row", ",", "col", ")", ";", "if", "(", "row", "!=", "col", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"cannot set non...
{@inheritDoc} @throws IllegalArgumentException if {@code row != col}
[ "{", "@inheritDoc", "}" ]
train
https://github.com/fozziethebeat/S-Space/blob/a608102737dfd3d59038a9ead33fe60356bc6029/src/main/java/edu/ucla/sspace/matrix/DiagonalMatrix.java#L150-L158
pip-services3-java/pip-services3-commons-java
src/org/pipservices3/commons/refer/References.java
References.getRequired
public <T> List<T> getRequired(Class<T> type, Object locator) throws ReferenceException { return find(type, locator, true); }
java
public <T> List<T> getRequired(Class<T> type, Object locator) throws ReferenceException { return find(type, locator, true); }
[ "public", "<", "T", ">", "List", "<", "T", ">", "getRequired", "(", "Class", "<", "T", ">", "type", ",", "Object", "locator", ")", "throws", "ReferenceException", "{", "return", "find", "(", "type", ",", "locator", ",", "true", ")", ";", "}" ]
Gets all component references that match specified locator. At least one component reference must be present and matching to the specified type. If it doesn't the method throws an error. @param type the Class type that defined the type of the result. @param locator the locator to find references by. @return a list with matching component references. @throws ReferenceException when no references found.
[ "Gets", "all", "component", "references", "that", "match", "specified", "locator", ".", "At", "least", "one", "component", "reference", "must", "be", "present", "and", "matching", "to", "the", "specified", "type", "." ]
train
https://github.com/pip-services3-java/pip-services3-commons-java/blob/a8a0c3e5ec58f0663c295aa855c6b3afad2af86a/src/org/pipservices3/commons/refer/References.java#L277-L279
Stratio/stratio-cassandra
src/java/org/apache/cassandra/db/filter/QueryFilter.java
QueryFilter.getIdentityFilter
public static QueryFilter getIdentityFilter(DecoratedKey key, String cfName, long timestamp) { return new QueryFilter(key, cfName, new IdentityQueryFilter(), timestamp); }
java
public static QueryFilter getIdentityFilter(DecoratedKey key, String cfName, long timestamp) { return new QueryFilter(key, cfName, new IdentityQueryFilter(), timestamp); }
[ "public", "static", "QueryFilter", "getIdentityFilter", "(", "DecoratedKey", "key", ",", "String", "cfName", ",", "long", "timestamp", ")", "{", "return", "new", "QueryFilter", "(", "key", ",", "cfName", ",", "new", "IdentityQueryFilter", "(", ")", ",", "times...
return a QueryFilter object that includes every column in the row. This is dangerous on large rows; avoid except for test code.
[ "return", "a", "QueryFilter", "object", "that", "includes", "every", "column", "in", "the", "row", ".", "This", "is", "dangerous", "on", "large", "rows", ";", "avoid", "except", "for", "test", "code", "." ]
train
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/filter/QueryFilter.java#L225-L228
vst/commons-math-extensions
src/main/java/com/vsthost/rnd/commons/math/ext/linear/EMatrixUtils.java
EMatrixUtils.getRowRange
public static RealMatrix getRowRange (RealMatrix matrix, int start, int end) { return matrix.getSubMatrix(start, end, 0, matrix.getColumnDimension() - 1); }
java
public static RealMatrix getRowRange (RealMatrix matrix, int start, int end) { return matrix.getSubMatrix(start, end, 0, matrix.getColumnDimension() - 1); }
[ "public", "static", "RealMatrix", "getRowRange", "(", "RealMatrix", "matrix", ",", "int", "start", ",", "int", "end", ")", "{", "return", "matrix", ".", "getSubMatrix", "(", "start", ",", "end", ",", "0", ",", "matrix", ".", "getColumnDimension", "(", ")",...
Returns the row range from the matrix as a new matrix. @param matrix The input matrix @param start The index of the row to start with (inclusive) @param end The index of the row to end with (inclusive) @return A new matrix with rows specified
[ "Returns", "the", "row", "range", "from", "the", "matrix", "as", "a", "new", "matrix", "." ]
train
https://github.com/vst/commons-math-extensions/blob/a11ee78ffe53ab7c016062be93c5af07aa8e1823/src/main/java/com/vsthost/rnd/commons/math/ext/linear/EMatrixUtils.java#L54-L56
looly/hutool
hutool-core/src/main/java/cn/hutool/core/text/csv/CsvReader.java
CsvReader.read
public CsvData read(Path path, Charset charset) throws IORuntimeException { Assert.notNull(path, "path must not be null"); try (Reader reader = FileUtil.getReader(path, charset)) { return read(reader); } catch (IOException e) { throw new IORuntimeException(e); } }
java
public CsvData read(Path path, Charset charset) throws IORuntimeException { Assert.notNull(path, "path must not be null"); try (Reader reader = FileUtil.getReader(path, charset)) { return read(reader); } catch (IOException e) { throw new IORuntimeException(e); } }
[ "public", "CsvData", "read", "(", "Path", "path", ",", "Charset", "charset", ")", "throws", "IORuntimeException", "{", "Assert", ".", "notNull", "(", "path", ",", "\"path must not be null\"", ")", ";", "try", "(", "Reader", "reader", "=", "FileUtil", ".", "g...
读取CSV文件 @param path CSV文件 @param charset 文件编码,默认系统编码 @return {@link CsvData},包含数据列表和行信息 @throws IORuntimeException IO异常
[ "读取CSV文件" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/text/csv/CsvReader.java#L131-L138
aNNiMON/Lightweight-Stream-API
stream/src/main/java/com/annimon/stream/IntStream.java
IntStream.findLast
@NotNull public OptionalInt findLast() { return reduce(new IntBinaryOperator() { @Override public int applyAsInt(int left, int right) { return right; } }); }
java
@NotNull public OptionalInt findLast() { return reduce(new IntBinaryOperator() { @Override public int applyAsInt(int left, int right) { return right; } }); }
[ "@", "NotNull", "public", "OptionalInt", "findLast", "(", ")", "{", "return", "reduce", "(", "new", "IntBinaryOperator", "(", ")", "{", "@", "Override", "public", "int", "applyAsInt", "(", "int", "left", ",", "int", "right", ")", "{", "return", "right", ...
Returns the last element wrapped by {@code OptionalInt} class. If stream is empty, returns {@code OptionalInt.empty()}. <p>This is a short-circuiting terminal operation. @return an {@code OptionalInt} with the last element or {@code OptionalInt.empty()} if the stream is empty @since 1.1.8
[ "Returns", "the", "last", "element", "wrapped", "by", "{", "@code", "OptionalInt", "}", "class", ".", "If", "stream", "is", "empty", "returns", "{", "@code", "OptionalInt", ".", "empty", "()", "}", "." ]
train
https://github.com/aNNiMON/Lightweight-Stream-API/blob/f29fd57208c20252a4549b084d55ed082c3e58f0/stream/src/main/java/com/annimon/stream/IntStream.java#L1209-L1217
webmetrics/browsermob-proxy
src/main/java/org/browsermob/proxy/jetty/util/UrlEncoded.java
UrlEncoded.decodeString
public static String decodeString(String encoded,String charset) { return decodeString(encoded,0,encoded.length(),charset); }
java
public static String decodeString(String encoded,String charset) { return decodeString(encoded,0,encoded.length(),charset); }
[ "public", "static", "String", "decodeString", "(", "String", "encoded", ",", "String", "charset", ")", "{", "return", "decodeString", "(", "encoded", ",", "0", ",", "encoded", ".", "length", "(", ")", ",", "charset", ")", ";", "}" ]
Decode String with % encoding. This method makes the assumption that the majority of calls will need no decoding.
[ "Decode", "String", "with", "%", "encoding", ".", "This", "method", "makes", "the", "assumption", "that", "the", "majority", "of", "calls", "will", "need", "no", "decoding", "." ]
train
https://github.com/webmetrics/browsermob-proxy/blob/a9252e62246ac33d55d51b993ba1159404e7d389/src/main/java/org/browsermob/proxy/jetty/util/UrlEncoded.java#L321-L324
eurekaclinical/javautil
src/main/java/org/arp/javautil/collections/Collections.java
Collections.containsAny
public static <K> boolean containsAny(Set<K> aSet, K[] arr) { for (K obj : arr) { if (aSet.contains(obj)) { return true; } } return false; }
java
public static <K> boolean containsAny(Set<K> aSet, K[] arr) { for (K obj : arr) { if (aSet.contains(obj)) { return true; } } return false; }
[ "public", "static", "<", "K", ">", "boolean", "containsAny", "(", "Set", "<", "K", ">", "aSet", ",", "K", "[", "]", "arr", ")", "{", "for", "(", "K", "obj", ":", "arr", ")", "{", "if", "(", "aSet", ".", "contains", "(", "obj", ")", ")", "{", ...
Checks whether any of an array's elements are also in the provided set. @param aSet a {@link Set}. @param arr an array. @return <code>true</code> or <code>false</code>.
[ "Checks", "whether", "any", "of", "an", "array", "s", "elements", "are", "also", "in", "the", "provided", "set", "." ]
train
https://github.com/eurekaclinical/javautil/blob/779bbc5bf096c75f8eed4f99ca45b99c1d44df43/src/main/java/org/arp/javautil/collections/Collections.java#L130-L137
stripe/stripe-android
stripe/src/main/java/com/stripe/android/CustomerSession.java
CustomerSession.initCustomerSession
public static void initCustomerSession(@NonNull Context context, @NonNull EphemeralKeyProvider keyProvider) { setInstance(new CustomerSession(context, keyProvider)); }
java
public static void initCustomerSession(@NonNull Context context, @NonNull EphemeralKeyProvider keyProvider) { setInstance(new CustomerSession(context, keyProvider)); }
[ "public", "static", "void", "initCustomerSession", "(", "@", "NonNull", "Context", "context", ",", "@", "NonNull", "EphemeralKeyProvider", "keyProvider", ")", "{", "setInstance", "(", "new", "CustomerSession", "(", "context", ",", "keyProvider", ")", ")", ";", "...
Create a CustomerSession with the provided {@link EphemeralKeyProvider}. @param context application context @param keyProvider an {@link EphemeralKeyProvider} used to get {@link CustomerEphemeralKey EphemeralKeys} as needed
[ "Create", "a", "CustomerSession", "with", "the", "provided", "{", "@link", "EphemeralKeyProvider", "}", "." ]
train
https://github.com/stripe/stripe-android/blob/0f199255f3769a3b84583fe3ace47bfae8c3b1c8/stripe/src/main/java/com/stripe/android/CustomerSession.java#L108-L111
belaban/JGroups
src/org/jgroups/jmx/ResourceDMBean.java
ResourceDMBean.findSetter
public static Accessor findSetter(Object target, String attr_name) { final String name=Util.attributeNameToMethodName(attr_name); final String fluent_name=toLowerCase(name); Class<?> clazz=target.getClass(); Class<?> field_type=null; Field field=Util.getField(clazz, attr_name); field_type=field != null? field.getType() : null; String setter_name="set" + name; if(field_type != null) { Method method=Util.findMethod(target, Arrays.asList(fluent_name, setter_name), field_type); if(method != null && isSetMethod(method)) return new MethodAccessor(method, target); } // Find all methods but don't include methods from Object class List<Method> methods=new ArrayList<>(Arrays.asList(clazz.getMethods())); methods.removeAll(OBJECT_METHODS); for(Method method: methods) { String method_name=method.getName(); if((method_name.equals(name) || method_name.equals(fluent_name) || method_name.equals(setter_name)) && isSetMethod(method)) return new MethodAccessor(method, target); } // Find a field last_name if(field != null) return new FieldAccessor(field, target); return null; }
java
public static Accessor findSetter(Object target, String attr_name) { final String name=Util.attributeNameToMethodName(attr_name); final String fluent_name=toLowerCase(name); Class<?> clazz=target.getClass(); Class<?> field_type=null; Field field=Util.getField(clazz, attr_name); field_type=field != null? field.getType() : null; String setter_name="set" + name; if(field_type != null) { Method method=Util.findMethod(target, Arrays.asList(fluent_name, setter_name), field_type); if(method != null && isSetMethod(method)) return new MethodAccessor(method, target); } // Find all methods but don't include methods from Object class List<Method> methods=new ArrayList<>(Arrays.asList(clazz.getMethods())); methods.removeAll(OBJECT_METHODS); for(Method method: methods) { String method_name=method.getName(); if((method_name.equals(name) || method_name.equals(fluent_name) || method_name.equals(setter_name)) && isSetMethod(method)) return new MethodAccessor(method, target); } // Find a field last_name if(field != null) return new FieldAccessor(field, target); return null; }
[ "public", "static", "Accessor", "findSetter", "(", "Object", "target", ",", "String", "attr_name", ")", "{", "final", "String", "name", "=", "Util", ".", "attributeNameToMethodName", "(", "attr_name", ")", ";", "final", "String", "fluent_name", "=", "toLowerCase...
Finds an accessor for an attribute. Tries to find setAttrName(), attrName() methods. If not found, tries to use reflection to set the value of attr_name. If still not found, creates a NullAccessor.
[ "Finds", "an", "accessor", "for", "an", "attribute", ".", "Tries", "to", "find", "setAttrName", "()", "attrName", "()", "methods", ".", "If", "not", "found", "tries", "to", "use", "reflection", "to", "set", "the", "value", "of", "attr_name", ".", "If", "...
train
https://github.com/belaban/JGroups/blob/bd3ca786aa57fed41dfbc10a94b1281e388be03b/src/org/jgroups/jmx/ResourceDMBean.java#L353-L383
mabe02/lanterna
src/main/java/com/googlecode/lanterna/terminal/swing/GraphicalTerminalImplementation.java
GraphicalTerminalImplementation.paintComponent
synchronized void paintComponent(Graphics componentGraphics) { int width = getWidth(); int height = getHeight(); this.scrollController.updateModel( virtualTerminal.getBufferLineCount() * getFontHeight(), height); boolean needToUpdateBackBuffer = // User has used the scrollbar, we need to update the back buffer to reflect this lastBufferUpdateScrollPosition != scrollController.getScrollingOffset() || // There is blinking text to update hasBlinkingText || // We simply have a hint that we should update everything needFullRedraw; // Detect resize if(width != lastComponentWidth || height != lastComponentHeight) { int columns = width / getFontWidth(); int rows = height / getFontHeight(); TerminalSize terminalSize = virtualTerminal.getTerminalSize().withColumns(columns).withRows(rows); virtualTerminal.setTerminalSize(terminalSize); // Back buffer needs to be updated since the component size has changed needToUpdateBackBuffer = true; } if(needToUpdateBackBuffer) { updateBackBuffer(scrollController.getScrollingOffset()); } ensureGraphicBufferHasRightSize(); Rectangle clipBounds = componentGraphics.getClipBounds(); if(clipBounds == null) { clipBounds = new Rectangle(0, 0, getWidth(), getHeight()); } componentGraphics.drawImage( backbuffer, // Destination coordinates clipBounds.x, clipBounds.y, clipBounds.width, clipBounds.height, // Source coordinates clipBounds.x, clipBounds.y, clipBounds.width, clipBounds.height, null); // Take care of the left-over area at the bottom and right of the component where no character can fit //int leftoverHeight = getHeight() % getFontHeight(); int leftoverWidth = getWidth() % getFontWidth(); componentGraphics.setColor(Color.BLACK); if(leftoverWidth > 0) { componentGraphics.fillRect(getWidth() - leftoverWidth, 0, leftoverWidth, getHeight()); } //0, 0, getWidth(), getHeight(), 0, 0, getWidth(), getHeight(), null); this.lastComponentWidth = width; this.lastComponentHeight = height; componentGraphics.dispose(); notifyAll(); }
java
synchronized void paintComponent(Graphics componentGraphics) { int width = getWidth(); int height = getHeight(); this.scrollController.updateModel( virtualTerminal.getBufferLineCount() * getFontHeight(), height); boolean needToUpdateBackBuffer = // User has used the scrollbar, we need to update the back buffer to reflect this lastBufferUpdateScrollPosition != scrollController.getScrollingOffset() || // There is blinking text to update hasBlinkingText || // We simply have a hint that we should update everything needFullRedraw; // Detect resize if(width != lastComponentWidth || height != lastComponentHeight) { int columns = width / getFontWidth(); int rows = height / getFontHeight(); TerminalSize terminalSize = virtualTerminal.getTerminalSize().withColumns(columns).withRows(rows); virtualTerminal.setTerminalSize(terminalSize); // Back buffer needs to be updated since the component size has changed needToUpdateBackBuffer = true; } if(needToUpdateBackBuffer) { updateBackBuffer(scrollController.getScrollingOffset()); } ensureGraphicBufferHasRightSize(); Rectangle clipBounds = componentGraphics.getClipBounds(); if(clipBounds == null) { clipBounds = new Rectangle(0, 0, getWidth(), getHeight()); } componentGraphics.drawImage( backbuffer, // Destination coordinates clipBounds.x, clipBounds.y, clipBounds.width, clipBounds.height, // Source coordinates clipBounds.x, clipBounds.y, clipBounds.width, clipBounds.height, null); // Take care of the left-over area at the bottom and right of the component where no character can fit //int leftoverHeight = getHeight() % getFontHeight(); int leftoverWidth = getWidth() % getFontWidth(); componentGraphics.setColor(Color.BLACK); if(leftoverWidth > 0) { componentGraphics.fillRect(getWidth() - leftoverWidth, 0, leftoverWidth, getHeight()); } //0, 0, getWidth(), getHeight(), 0, 0, getWidth(), getHeight(), null); this.lastComponentWidth = width; this.lastComponentHeight = height; componentGraphics.dispose(); notifyAll(); }
[ "synchronized", "void", "paintComponent", "(", "Graphics", "componentGraphics", ")", "{", "int", "width", "=", "getWidth", "(", ")", ";", "int", "height", "=", "getHeight", "(", ")", ";", "this", ".", "scrollController", ".", "updateModel", "(", "virtualTermin...
Updates the back buffer (if necessary) and draws it to the component's surface @param componentGraphics Object to use when drawing to the component's surface
[ "Updates", "the", "back", "buffer", "(", "if", "necessary", ")", "and", "draws", "it", "to", "the", "component", "s", "surface" ]
train
https://github.com/mabe02/lanterna/blob/8dfd62206ff46ab10223b2ef2dbb0a2c51850954/src/main/java/com/googlecode/lanterna/terminal/swing/GraphicalTerminalImplementation.java#L247-L310
ykrasik/jaci
jaci-utils/src/main/java/com/github/ykrasik/jaci/util/string/StringUtils.java
StringUtils.removeLeadingDelimiter
public static String removeLeadingDelimiter(String str, String delimiter) { if (!str.startsWith(delimiter)) { return str; } else { return str.substring(delimiter.length(), str.length()); } }
java
public static String removeLeadingDelimiter(String str, String delimiter) { if (!str.startsWith(delimiter)) { return str; } else { return str.substring(delimiter.length(), str.length()); } }
[ "public", "static", "String", "removeLeadingDelimiter", "(", "String", "str", ",", "String", "delimiter", ")", "{", "if", "(", "!", "str", ".", "startsWith", "(", "delimiter", ")", ")", "{", "return", "str", ";", "}", "else", "{", "return", "str", ".", ...
Removes the leading delimiter from a string. @param str String to process. @param delimiter Delimiter to remove. @return The string with the leading delimiter removed.
[ "Removes", "the", "leading", "delimiter", "from", "a", "string", "." ]
train
https://github.com/ykrasik/jaci/blob/4615edef7c76288ad5ea8d678132b161645ca1e3/jaci-utils/src/main/java/com/github/ykrasik/jaci/util/string/StringUtils.java#L75-L81
windup/windup
java-ast/addon/src/main/java/org/jboss/windup/ast/java/ASTProcessor.java
ASTProcessor.analyze
public static List<ClassReference> analyze(WildcardImportResolver importResolver, Set<String> libraryPaths, Set<String> sourcePaths, Path sourceFile) { ASTParser parser = ASTParser.newParser(AST.JLS11); parser.setEnvironment(libraryPaths.toArray(new String[libraryPaths.size()]), sourcePaths.toArray(new String[sourcePaths.size()]), null, true); parser.setBindingsRecovery(false); parser.setResolveBindings(true); Map options = JavaCore.getOptions(); JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options); parser.setCompilerOptions(options); String fileName = sourceFile.getFileName().toString(); parser.setUnitName(fileName); try { parser.setSource(FileUtils.readFileToString(sourceFile.toFile()).toCharArray()); } catch (IOException e) { throw new ASTException("Failed to get source for file: " + sourceFile.toString() + " due to: " + e.getMessage(), e); } parser.setKind(ASTParser.K_COMPILATION_UNIT); CompilationUnit cu = (CompilationUnit) parser.createAST(null); ReferenceResolvingVisitor visitor = new ReferenceResolvingVisitor(importResolver, cu, sourceFile.toString()); cu.accept(visitor); return visitor.getJavaClassReferences(); }
java
public static List<ClassReference> analyze(WildcardImportResolver importResolver, Set<String> libraryPaths, Set<String> sourcePaths, Path sourceFile) { ASTParser parser = ASTParser.newParser(AST.JLS11); parser.setEnvironment(libraryPaths.toArray(new String[libraryPaths.size()]), sourcePaths.toArray(new String[sourcePaths.size()]), null, true); parser.setBindingsRecovery(false); parser.setResolveBindings(true); Map options = JavaCore.getOptions(); JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options); parser.setCompilerOptions(options); String fileName = sourceFile.getFileName().toString(); parser.setUnitName(fileName); try { parser.setSource(FileUtils.readFileToString(sourceFile.toFile()).toCharArray()); } catch (IOException e) { throw new ASTException("Failed to get source for file: " + sourceFile.toString() + " due to: " + e.getMessage(), e); } parser.setKind(ASTParser.K_COMPILATION_UNIT); CompilationUnit cu = (CompilationUnit) parser.createAST(null); ReferenceResolvingVisitor visitor = new ReferenceResolvingVisitor(importResolver, cu, sourceFile.toString()); cu.accept(visitor); return visitor.getJavaClassReferences(); }
[ "public", "static", "List", "<", "ClassReference", ">", "analyze", "(", "WildcardImportResolver", "importResolver", ",", "Set", "<", "String", ">", "libraryPaths", ",", "Set", "<", "String", ">", "sourcePaths", ",", "Path", "sourceFile", ")", "{", "ASTParser", ...
Parses the provided file, using the given libraryPaths and sourcePaths as context. The libraries may be either jar files or references to directories containing class files. The sourcePaths must be a reference to the top level directory for sources (eg, for a file src/main/java/org/example/Foo.java, the source path would be src/main/java). The wildcard resolver provides a fallback for processing wildcard imports that the underlying parser was unable to resolve.
[ "Parses", "the", "provided", "file", "using", "the", "given", "libraryPaths", "and", "sourcePaths", "as", "context", ".", "The", "libraries", "may", "be", "either", "jar", "files", "or", "references", "to", "directories", "containing", "class", "files", "." ]
train
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/java-ast/addon/src/main/java/org/jboss/windup/ast/java/ASTProcessor.java#L41-L66
nwillc/almost-functional
src/main/java/almost/functional/utils/Iterables.java
Iterables.forEach
public static <T> void forEach(final Iterable<T> iterable, final Consumer<? super T> consumer) { checkNotNull(iterable, "forEach must have a valid iterable"); checkNotNull(consumer, "forEach must have a valid consumer"); for (T t : iterable) { consumer.accept(t); } }
java
public static <T> void forEach(final Iterable<T> iterable, final Consumer<? super T> consumer) { checkNotNull(iterable, "forEach must have a valid iterable"); checkNotNull(consumer, "forEach must have a valid consumer"); for (T t : iterable) { consumer.accept(t); } }
[ "public", "static", "<", "T", ">", "void", "forEach", "(", "final", "Iterable", "<", "T", ">", "iterable", ",", "final", "Consumer", "<", "?", "super", "T", ">", "consumer", ")", "{", "checkNotNull", "(", "iterable", ",", "\"forEach must have a valid iterabl...
Accept a consumer for each element of an iterable. @param consumer the consumer to accept for each element @param <T> the type of the iterable and consumer @param iterable the iterable
[ "Accept", "a", "consumer", "for", "each", "element", "of", "an", "iterable", "." ]
train
https://github.com/nwillc/almost-functional/blob/a6cc7c73b2be475ed1bce5128c24b2eb9c27d666/src/main/java/almost/functional/utils/Iterables.java#L43-L50
brunocvcunha/inutils4j
src/main/java/org/brunocvcunha/inutils4j/reflection/MyReflectionUtils.java
MyReflectionUtils.getClosestAnnotation
public static <T extends Annotation> T getClosestAnnotation(Method method, Class<T> typeOfT) { T annotation = method.getAnnotation(typeOfT); if (annotation == null) { Class<?> clazzToIntrospect = method.getDeclaringClass(); while (annotation == null && clazzToIntrospect != null) { annotation = clazzToIntrospect.getAnnotation(typeOfT); clazzToIntrospect = clazzToIntrospect.getSuperclass(); } } return annotation; }
java
public static <T extends Annotation> T getClosestAnnotation(Method method, Class<T> typeOfT) { T annotation = method.getAnnotation(typeOfT); if (annotation == null) { Class<?> clazzToIntrospect = method.getDeclaringClass(); while (annotation == null && clazzToIntrospect != null) { annotation = clazzToIntrospect.getAnnotation(typeOfT); clazzToIntrospect = clazzToIntrospect.getSuperclass(); } } return annotation; }
[ "public", "static", "<", "T", "extends", "Annotation", ">", "T", "getClosestAnnotation", "(", "Method", "method", ",", "Class", "<", "T", ">", "typeOfT", ")", "{", "T", "annotation", "=", "method", ".", "getAnnotation", "(", "typeOfT", ")", ";", "if", "(...
Get the closest annotation for a method (inherit from class) @param method method @param typeOfT type of annotation inspected @return annotation instance
[ "Get", "the", "closest", "annotation", "for", "a", "method", "(", "inherit", "from", "class", ")" ]
train
https://github.com/brunocvcunha/inutils4j/blob/223c4443c2cee662576ce644e552588fa114aa94/src/main/java/org/brunocvcunha/inutils4j/reflection/MyReflectionUtils.java#L116-L128
voldemort/voldemort
src/java/voldemort/utils/RebalanceUtils.java
RebalanceUtils.validateClusterStores
public static void validateClusterStores(final Cluster cluster, final List<StoreDefinition> storeDefs) { // Constructing a StoreRoutingPlan has the (desirable in this // case) side-effect of verifying that the store definition is congruent // with the cluster definition. If there are issues, exceptions are // thrown. for(StoreDefinition storeDefinition: storeDefs) { new StoreRoutingPlan(cluster, storeDefinition); } return; }
java
public static void validateClusterStores(final Cluster cluster, final List<StoreDefinition> storeDefs) { // Constructing a StoreRoutingPlan has the (desirable in this // case) side-effect of verifying that the store definition is congruent // with the cluster definition. If there are issues, exceptions are // thrown. for(StoreDefinition storeDefinition: storeDefs) { new StoreRoutingPlan(cluster, storeDefinition); } return; }
[ "public", "static", "void", "validateClusterStores", "(", "final", "Cluster", "cluster", ",", "final", "List", "<", "StoreDefinition", ">", "storeDefs", ")", "{", "// Constructing a StoreRoutingPlan has the (desirable in this", "// case) side-effect of verifying that the store de...
Verify store definitions are congruent with cluster definition. @param cluster @param storeDefs
[ "Verify", "store", "definitions", "are", "congruent", "with", "cluster", "definition", "." ]
train
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/RebalanceUtils.java#L76-L86
googleapis/google-cloud-java
google-cloud-clients/google-cloud-tasks/src/main/java/com/google/cloud/tasks/v2beta2/CloudTasksClient.java
CloudTasksClient.cancelLease
public final Task cancelLease(String name, Timestamp scheduleTime) { CancelLeaseRequest request = CancelLeaseRequest.newBuilder().setName(name).setScheduleTime(scheduleTime).build(); return cancelLease(request); }
java
public final Task cancelLease(String name, Timestamp scheduleTime) { CancelLeaseRequest request = CancelLeaseRequest.newBuilder().setName(name).setScheduleTime(scheduleTime).build(); return cancelLease(request); }
[ "public", "final", "Task", "cancelLease", "(", "String", "name", ",", "Timestamp", "scheduleTime", ")", "{", "CancelLeaseRequest", "request", "=", "CancelLeaseRequest", ".", "newBuilder", "(", ")", ".", "setName", "(", "name", ")", ".", "setScheduleTime", "(", ...
Cancel a pull task's lease. <p>The worker can use this method to cancel a task's lease by setting its [schedule_time][google.cloud.tasks.v2beta2.Task.schedule_time] to now. This will make the task available to be leased to the next caller of [LeaseTasks][google.cloud.tasks.v2beta2.CloudTasks.LeaseTasks]. <p>Sample code: <pre><code> try (CloudTasksClient cloudTasksClient = CloudTasksClient.create()) { TaskName name = TaskName.of("[PROJECT]", "[LOCATION]", "[QUEUE]", "[TASK]"); Timestamp scheduleTime = Timestamp.newBuilder().build(); Task response = cloudTasksClient.cancelLease(name.toString(), scheduleTime); } </code></pre> @param name Required. <p>The task name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID` @param scheduleTime Required. <p>The task's current schedule time, available in the [schedule_time][google.cloud.tasks.v2beta2.Task.schedule_time] returned by [LeaseTasks][google.cloud.tasks.v2beta2.CloudTasks.LeaseTasks] response or [RenewLease][google.cloud.tasks.v2beta2.CloudTasks.RenewLease] response. This restriction is to ensure that your worker currently holds the lease. @throws com.google.api.gax.rpc.ApiException if the remote call fails
[ "Cancel", "a", "pull", "task", "s", "lease", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-tasks/src/main/java/com/google/cloud/tasks/v2beta2/CloudTasksClient.java#L2544-L2549
BranchMetrics/android-branch-deep-linking
Branch-SDK/src/io/branch/referral/Branch.java
Branch.userCompletedAction
public void userCompletedAction(@NonNull final String action, JSONObject metadata, BranchViewHandler.IBranchViewEvents callback) { ServerRequest req = new ServerRequestActionCompleted(context_, action, metadata, callback); if (!req.constructError_ && !req.handleErrors(context_)) { handleNewRequest(req); } }
java
public void userCompletedAction(@NonNull final String action, JSONObject metadata, BranchViewHandler.IBranchViewEvents callback) { ServerRequest req = new ServerRequestActionCompleted(context_, action, metadata, callback); if (!req.constructError_ && !req.handleErrors(context_)) { handleNewRequest(req); } }
[ "public", "void", "userCompletedAction", "(", "@", "NonNull", "final", "String", "action", ",", "JSONObject", "metadata", ",", "BranchViewHandler", ".", "IBranchViewEvents", "callback", ")", "{", "ServerRequest", "req", "=", "new", "ServerRequestActionCompleted", "(",...
<p>A void call to indicate that the user has performed a specific action and for that to be reported to the Branch API, with additional app-defined meta data to go along with that action.</p> @param action A {@link String} value to be passed as an action that the user has carried out. For example "registered" or "logged in". @param metadata A {@link JSONObject} containing app-defined meta-data to be attached to a user action that has just been completed. @param callback instance of {@link BranchViewHandler.IBranchViewEvents} to listen Branch view events
[ "<p", ">", "A", "void", "call", "to", "indicate", "that", "the", "user", "has", "performed", "a", "specific", "action", "and", "for", "that", "to", "be", "reported", "to", "the", "Branch", "API", "with", "additional", "app", "-", "defined", "meta", "data...
train
https://github.com/BranchMetrics/android-branch-deep-linking/blob/e3bee2ccfcbf6d4bf1a5815b5b86666e4ff8f848/Branch-SDK/src/io/branch/referral/Branch.java#L2049-L2055
graknlabs/grakn
server/src/server/kb/ValidateGlobalRules.java
ValidateGlobalRules.validatePlaysAndRelatesStructure
static Set<String> validatePlaysAndRelatesStructure(Casting casting) { Set<String> errors = new HashSet<>(); //Gets here to make sure we traverse/read only once Thing thing = casting.getRolePlayer(); Role role = casting.getRole(); Relation relation = casting.getRelation(); //Actual checks roleNotAllowedToBePlayed(role, thing).ifPresent(errors::add); roleNotLinkedToRelation(role, relation.type(), relation).ifPresent(errors::add); return errors; }
java
static Set<String> validatePlaysAndRelatesStructure(Casting casting) { Set<String> errors = new HashSet<>(); //Gets here to make sure we traverse/read only once Thing thing = casting.getRolePlayer(); Role role = casting.getRole(); Relation relation = casting.getRelation(); //Actual checks roleNotAllowedToBePlayed(role, thing).ifPresent(errors::add); roleNotLinkedToRelation(role, relation.type(), relation).ifPresent(errors::add); return errors; }
[ "static", "Set", "<", "String", ">", "validatePlaysAndRelatesStructure", "(", "Casting", "casting", ")", "{", "Set", "<", "String", ">", "errors", "=", "new", "HashSet", "<>", "(", ")", ";", "//Gets here to make sure we traverse/read only once", "Thing", "thing", ...
This method checks if the plays edge has been added between the roleplayer's Type and the Role being played. It also checks if the Role of the Casting has been linked to the RelationType of the Relation which the Casting connects to. @return Specific errors if any are found
[ "This", "method", "checks", "if", "the", "plays", "edge", "has", "been", "added", "between", "the", "roleplayer", "s", "Type", "and", "the", "Role", "being", "played", ".", "It", "also", "checks", "if", "the", "Role", "of", "the", "Casting", "has", "been...
train
https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/server/kb/ValidateGlobalRules.java#L99-L112
sargue/mailgun
src/main/java/net/sargue/mailgun/content/Builder.java
Builder.rowh
public <T> Builder rowh(String label, T data) { return tag("tr").cellHeader(label, false).cell(data).end(); }
java
public <T> Builder rowh(String label, T data) { return tag("tr").cellHeader(label, false).cell(data).end(); }
[ "public", "<", "T", ">", "Builder", "rowh", "(", "String", "label", ",", "T", "data", ")", "{", "return", "tag", "(", "\"tr\"", ")", ".", "cellHeader", "(", "label", ",", "false", ")", ".", "cell", "(", "data", ")", ".", "end", "(", ")", ";", "...
Adds a new row with two columns, the first one being a header cell. @param <T> the type parameter @param label the header cell content @param data the second cell content @return this builder
[ "Adds", "a", "new", "row", "with", "two", "columns", "the", "first", "one", "being", "a", "header", "cell", "." ]
train
https://github.com/sargue/mailgun/blob/2ffb0a156f3f3666eb1bb2db661451b9377c3d11/src/main/java/net/sargue/mailgun/content/Builder.java#L452-L454
ansell/csvstream
src/main/java/com/github/ansell/csv/stream/CSVStream.java
CSVStream.buildSchema
public static CsvSchema buildSchema(List<String> headers, boolean useHeader) { return CsvSchema.builder().addColumns(headers, ColumnType.STRING).setUseHeader(useHeader).build(); }
java
public static CsvSchema buildSchema(List<String> headers, boolean useHeader) { return CsvSchema.builder().addColumns(headers, ColumnType.STRING).setUseHeader(useHeader).build(); }
[ "public", "static", "CsvSchema", "buildSchema", "(", "List", "<", "String", ">", "headers", ",", "boolean", "useHeader", ")", "{", "return", "CsvSchema", ".", "builder", "(", ")", ".", "addColumns", "(", "headers", ",", "ColumnType", ".", "STRING", ")", "....
Build a {@link CsvSchema} object using the given headers. @param headers The list of strings in the header. @param useHeader Set to false to avoid writing the header line, which is necessary if appending to an existing file. @return A {@link CsvSchema} object including the given header items.
[ "Build", "a", "{", "@link", "CsvSchema", "}", "object", "using", "the", "given", "headers", "." ]
train
https://github.com/ansell/csvstream/blob/9468bfbd6997fbc4237eafc990ba811cd5905dc1/src/main/java/com/github/ansell/csv/stream/CSVStream.java#L563-L565
GenesysPureEngage/provisioning-client-java
src/main/java/com/genesys/internal/provisioning/api/OperationsApi.java
OperationsApi.postCheckImportStatusWithHttpInfo
public ApiResponse<ApiAsyncSuccessResponse> postCheckImportStatusWithHttpInfo() throws ApiException { com.squareup.okhttp.Call call = postCheckImportStatusValidateBeforeCall(null, null); Type localVarReturnType = new TypeToken<ApiAsyncSuccessResponse>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
java
public ApiResponse<ApiAsyncSuccessResponse> postCheckImportStatusWithHttpInfo() throws ApiException { com.squareup.okhttp.Call call = postCheckImportStatusValidateBeforeCall(null, null); Type localVarReturnType = new TypeToken<ApiAsyncSuccessResponse>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
[ "public", "ApiResponse", "<", "ApiAsyncSuccessResponse", ">", "postCheckImportStatusWithHttpInfo", "(", ")", "throws", "ApiException", "{", "com", ".", "squareup", ".", "okhttp", ".", "Call", "call", "=", "postCheckImportStatusValidateBeforeCall", "(", "null", ",", "n...
Check import status Get [CfgPerson](https://docs.genesys.com/Documentation/PSDK/latest/ConfigLayerRef/CfgPerson) objects based on the specified filters. @return ApiResponse&lt;ApiAsyncSuccessResponse&gt; @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
[ "Check", "import", "status", "Get", "[", "CfgPerson", "]", "(", "https", ":", "//", "docs", ".", "genesys", ".", "com", "/", "Documentation", "/", "PSDK", "/", "latest", "/", "ConfigLayerRef", "/", "CfgPerson", ")", "objects", "based", "on", "the", "spec...
train
https://github.com/GenesysPureEngage/provisioning-client-java/blob/1ad594c3767cec83052168e350994f922a26f75e/src/main/java/com/genesys/internal/provisioning/api/OperationsApi.java#L797-L801
PawelAdamski/HttpClientMock
src/main/java/com/github/paweladamski/httpclientmock/HttpClientVerifyBuilder.java
HttpClientVerifyBuilder.withHeader
public HttpClientVerifyBuilder withHeader(String header, String value) { return withHeader(header, equalTo(value)); }
java
public HttpClientVerifyBuilder withHeader(String header, String value) { return withHeader(header, equalTo(value)); }
[ "public", "HttpClientVerifyBuilder", "withHeader", "(", "String", "header", ",", "String", "value", ")", "{", "return", "withHeader", "(", "header", ",", "equalTo", "(", "value", ")", ")", ";", "}" ]
Adds header condition. Header must be equal to provided value. @param header header name @param value expected value @return verification builder
[ "Adds", "header", "condition", ".", "Header", "must", "be", "equal", "to", "provided", "value", "." ]
train
https://github.com/PawelAdamski/HttpClientMock/blob/0205498434bbc0c78c187a51181cac9b266a28fb/src/main/java/com/github/paweladamski/httpclientmock/HttpClientVerifyBuilder.java#L29-L31
jbundle/jbundle
thin/base/remote/src/main/java/org/jbundle/thin/base/message/session/ClientSessionMessageFilter.java
ClientSessionMessageFilter.init
public void init(String strQueueName, String strQueueType, Object source, RemoteSession session, Map propertiesForFilter, boolean bPrivate) { super.init(strQueueName, strQueueType, source, null); m_session = session; m_propertiesForFilter = propertiesForFilter; m_bPrivate = bPrivate; this.setThinTarget(true); // Yes, this is always a thin target }
java
public void init(String strQueueName, String strQueueType, Object source, RemoteSession session, Map propertiesForFilter, boolean bPrivate) { super.init(strQueueName, strQueueType, source, null); m_session = session; m_propertiesForFilter = propertiesForFilter; m_bPrivate = bPrivate; this.setThinTarget(true); // Yes, this is always a thin target }
[ "public", "void", "init", "(", "String", "strQueueName", ",", "String", "strQueueType", ",", "Object", "source", ",", "RemoteSession", "session", ",", "Map", "propertiesForFilter", ",", "boolean", "bPrivate", ")", "{", "super", ".", "init", "(", "strQueueName", ...
Constructor. @param strQueueName The queue name. @param strQueueType The queue type. @param source The source (sender). @param session The remote session. @param propertiesForFilter The properties for the filter.
[ "Constructor", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/remote/src/main/java/org/jbundle/thin/base/message/session/ClientSessionMessageFilter.java#L115-L122
phax/ph-schedule
ph-mini-quartz/src/main/java/com/helger/quartz/CronScheduleBuilder.java
CronScheduleBuilder.cronSchedule
@Nonnull public static CronScheduleBuilder cronSchedule (final String cronExpression) { try { return cronSchedule (new CronExpression (cronExpression)); } catch (final ParseException e) { // all methods of construction ensure the expression is valid by // this point... throw new RuntimeException ("CronExpression '" + cronExpression + "' is invalid.", e); } }
java
@Nonnull public static CronScheduleBuilder cronSchedule (final String cronExpression) { try { return cronSchedule (new CronExpression (cronExpression)); } catch (final ParseException e) { // all methods of construction ensure the expression is valid by // this point... throw new RuntimeException ("CronExpression '" + cronExpression + "' is invalid.", e); } }
[ "@", "Nonnull", "public", "static", "CronScheduleBuilder", "cronSchedule", "(", "final", "String", "cronExpression", ")", "{", "try", "{", "return", "cronSchedule", "(", "new", "CronExpression", "(", "cronExpression", ")", ")", ";", "}", "catch", "(", "final", ...
Create a CronScheduleBuilder with the given cron-expression string - which is presumed to b e valid cron expression (and hence only a RuntimeException will be thrown if it is not). @param cronExpression the cron expression string to base the schedule on. @return the new CronScheduleBuilder @throws RuntimeException wrapping a ParseException if the expression is invalid @see CronExpression
[ "Create", "a", "CronScheduleBuilder", "with", "the", "given", "cron", "-", "expression", "string", "-", "which", "is", "presumed", "to", "b", "e", "valid", "cron", "expression", "(", "and", "hence", "only", "a", "RuntimeException", "will", "be", "thrown", "i...
train
https://github.com/phax/ph-schedule/blob/b000790b46a9f8d23ad44cc20591f753d07c0229/ph-mini-quartz/src/main/java/com/helger/quartz/CronScheduleBuilder.java#L102-L115
adessoAG/wicked-charts
showcase/wicked-charts-showcase-wicket6/src/main/java/de/adesso/wickedcharts/showcase/HomepageHighcharts.java
HomepageHighcharts.addThemeLinks
private void addThemeLinks(PageParameters parameters){ if (parameters.getAllNamed().size() < 2) { add(new UpdateThemeLink("defaultTheme", "chart")); add(new UpdateThemeLink("grid", "chart")); add(new UpdateThemeLink("skies", "chart")); add(new UpdateThemeLink("gray", "chart")); add(new UpdateThemeLink("darkblue", "chart")); } else { String chartString = parameters.getAllNamed().get(1).getValue(); add(new UpdateThemeLink("defaultTheme", chartString)); add(new UpdateThemeLink("grid", chartString)); add(new UpdateThemeLink("skies", chartString)); add(new UpdateThemeLink("gray", chartString)); add(new UpdateThemeLink("darkblue", chartString)); } }
java
private void addThemeLinks(PageParameters parameters){ if (parameters.getAllNamed().size() < 2) { add(new UpdateThemeLink("defaultTheme", "chart")); add(new UpdateThemeLink("grid", "chart")); add(new UpdateThemeLink("skies", "chart")); add(new UpdateThemeLink("gray", "chart")); add(new UpdateThemeLink("darkblue", "chart")); } else { String chartString = parameters.getAllNamed().get(1).getValue(); add(new UpdateThemeLink("defaultTheme", chartString)); add(new UpdateThemeLink("grid", chartString)); add(new UpdateThemeLink("skies", chartString)); add(new UpdateThemeLink("gray", chartString)); add(new UpdateThemeLink("darkblue", chartString)); } }
[ "private", "void", "addThemeLinks", "(", "PageParameters", "parameters", ")", "{", "if", "(", "parameters", ".", "getAllNamed", "(", ")", ".", "size", "(", ")", "<", "2", ")", "{", "add", "(", "new", "UpdateThemeLink", "(", "\"defaultTheme\"", ",", "\"char...
Adds links to the different themes @param parameters the page parameters from the page URI
[ "Adds", "links", "to", "the", "different", "themes" ]
train
https://github.com/adessoAG/wicked-charts/blob/498aceff025f612e22ba5135b26531afeabac03c/showcase/wicked-charts-showcase-wicket6/src/main/java/de/adesso/wickedcharts/showcase/HomepageHighcharts.java#L63-L78
alkacon/opencms-core
src/org/opencms/util/CmsParameterEscaper.java
CmsParameterEscaper.createAntiSamy
public AntiSamy createAntiSamy(CmsObject cms, String policyPath) { String rootPath = cms.addSiteRoot(policyPath); Policy policy = null; if (policyPath != null) { Object cacheValue = CmsVfsMemoryObjectCache.getVfsMemoryObjectCache().getCachedObject(cms, rootPath); if (cacheValue == null) { policy = readPolicy(cms, policyPath); if (policy != null) { CmsVfsMemoryObjectCache.getVfsMemoryObjectCache().putCachedObject(cms, rootPath, policy); } } else { policy = (Policy)cacheValue; } } if (policy == null) { policy = defaultPolicy; } if (policy != null) { return new AntiSamy(policy); } return null; }
java
public AntiSamy createAntiSamy(CmsObject cms, String policyPath) { String rootPath = cms.addSiteRoot(policyPath); Policy policy = null; if (policyPath != null) { Object cacheValue = CmsVfsMemoryObjectCache.getVfsMemoryObjectCache().getCachedObject(cms, rootPath); if (cacheValue == null) { policy = readPolicy(cms, policyPath); if (policy != null) { CmsVfsMemoryObjectCache.getVfsMemoryObjectCache().putCachedObject(cms, rootPath, policy); } } else { policy = (Policy)cacheValue; } } if (policy == null) { policy = defaultPolicy; } if (policy != null) { return new AntiSamy(policy); } return null; }
[ "public", "AntiSamy", "createAntiSamy", "(", "CmsObject", "cms", ",", "String", "policyPath", ")", "{", "String", "rootPath", "=", "cms", ".", "addSiteRoot", "(", "policyPath", ")", ";", "Policy", "policy", "=", "null", ";", "if", "(", "policyPath", "!=", ...
Creates a new AntiSamy instance for a given policy path.<p> @param cms the current CMS context @param policyPath the policy site path @return the new AntiSamy instance
[ "Creates", "a", "new", "AntiSamy", "instance", "for", "a", "given", "policy", "path", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/util/CmsParameterEscaper.java#L125-L147
taskadapter/redmine-java-api
src/main/java/com/taskadapter/redmineapi/RedmineManagerFactory.java
RedmineManagerFactory.createWithApiKey
public static RedmineManager createWithApiKey(String uri, String apiAccessKey) { return createWithApiKey(uri, apiAccessKey, createDefaultHttpClient(uri)); }
java
public static RedmineManager createWithApiKey(String uri, String apiAccessKey) { return createWithApiKey(uri, apiAccessKey, createDefaultHttpClient(uri)); }
[ "public", "static", "RedmineManager", "createWithApiKey", "(", "String", "uri", ",", "String", "apiAccessKey", ")", "{", "return", "createWithApiKey", "(", "uri", ",", "apiAccessKey", ",", "createDefaultHttpClient", "(", "uri", ")", ")", ";", "}" ]
Creates an instance of RedmineManager class. Host and apiAccessKey are not checked at this moment. @param uri complete Redmine server web URI, including protocol and port number. Example: http://demo.redmine.org:8080 @param apiAccessKey Redmine API access key. It is shown on "My Account" / "API access key" webpage (check <i>http://redmine_server_url/my/account</i> URL). This parameter is <strong>optional</strong> (can be set to NULL) for Redmine projects, which are "public".
[ "Creates", "an", "instance", "of", "RedmineManager", "class", ".", "Host", "and", "apiAccessKey", "are", "not", "checked", "at", "this", "moment", "." ]
train
https://github.com/taskadapter/redmine-java-api/blob/0bb65f27ee806ec3bd4007e1641f3e996261a04e/src/main/java/com/taskadapter/redmineapi/RedmineManagerFactory.java#L92-L96
taimos/dvalin
jaxrs-jwtauth/src/main/java/de/taimos/dvalin/jaxrs/security/jwt/JWTAuth.java
JWTAuth.signToken
public SignedJWT signToken(JWTClaimsSet claims) { try { SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), claims); signedJWT.sign(new MACSigner(this.jwtSharedSecret)); return signedJWT; } catch (JOSEException e) { throw new RuntimeException("Error signing JSON Web Token", e); } }
java
public SignedJWT signToken(JWTClaimsSet claims) { try { SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), claims); signedJWT.sign(new MACSigner(this.jwtSharedSecret)); return signedJWT; } catch (JOSEException e) { throw new RuntimeException("Error signing JSON Web Token", e); } }
[ "public", "SignedJWT", "signToken", "(", "JWTClaimsSet", "claims", ")", "{", "try", "{", "SignedJWT", "signedJWT", "=", "new", "SignedJWT", "(", "new", "JWSHeader", "(", "JWSAlgorithm", ".", "HS256", ")", ",", "claims", ")", ";", "signedJWT", ".", "sign", ...
Sign the given claims @param claims the claims to sign @return the created and signed JSON Web Token
[ "Sign", "the", "given", "claims" ]
train
https://github.com/taimos/dvalin/blob/ff8f1bf594e43d7e8ca8de0b4da9f923b66a1a47/jaxrs-jwtauth/src/main/java/de/taimos/dvalin/jaxrs/security/jwt/JWTAuth.java#L67-L75
kuali/ojb-1.0.4
src/java/org/apache/ojb/broker/accesslayer/StatementManager.java
StatementManager.bindStatement
private int bindStatement(PreparedStatement stmt, int index, InCriteria crit, ClassDescriptor cld) throws SQLException { if (crit.getValue() instanceof Collection) { Collection values = (Collection) crit.getValue(); Iterator iter = values.iterator(); while (iter.hasNext()) { index = bindStatementValue(stmt, index, crit.getAttribute(), iter.next(), cld); } } else { index = bindStatementValue(stmt, index, crit.getAttribute(), crit.getValue(), cld); } return index; }
java
private int bindStatement(PreparedStatement stmt, int index, InCriteria crit, ClassDescriptor cld) throws SQLException { if (crit.getValue() instanceof Collection) { Collection values = (Collection) crit.getValue(); Iterator iter = values.iterator(); while (iter.hasNext()) { index = bindStatementValue(stmt, index, crit.getAttribute(), iter.next(), cld); } } else { index = bindStatementValue(stmt, index, crit.getAttribute(), crit.getValue(), cld); } return index; }
[ "private", "int", "bindStatement", "(", "PreparedStatement", "stmt", ",", "int", "index", ",", "InCriteria", "crit", ",", "ClassDescriptor", "cld", ")", "throws", "SQLException", "{", "if", "(", "crit", ".", "getValue", "(", ")", "instanceof", "Collection", ")...
bind InCriteria @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", "InCriteria" ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/accesslayer/StatementManager.java#L310-L327
xvik/dropwizard-guicey
src/main/java/ru/vyarus/dropwizard/guice/module/context/debug/util/RenderUtils.java
RenderUtils.renderClassLine
public static String renderClassLine(final Class<?> type, final List<String> markers) { return String.format("%-28s %-26s %s", getClassName(type), brackets(renderPackage(type)), markers(markers)); }
java
public static String renderClassLine(final Class<?> type, final List<String> markers) { return String.format("%-28s %-26s %s", getClassName(type), brackets(renderPackage(type)), markers(markers)); }
[ "public", "static", "String", "renderClassLine", "(", "final", "Class", "<", "?", ">", "type", ",", "final", "List", "<", "String", ">", "markers", ")", "{", "return", "String", ".", "format", "(", "\"%-28s %-26s %s\"", ",", "getClassName", "(", "type", ")...
Renders class as: class-simple-name (class-package) *markers. For anonymous class simple name will be Class$1. @param type class @param markers markers @return rendered class line
[ "Renders", "class", "as", ":", "class", "-", "simple", "-", "name", "(", "class", "-", "package", ")", "*", "markers", ".", "For", "anonymous", "class", "simple", "name", "will", "be", "Class$1", "." ]
train
https://github.com/xvik/dropwizard-guicey/blob/dd39ad77283555be21f606d5ebf0f11207a733d4/src/main/java/ru/vyarus/dropwizard/guice/module/context/debug/util/RenderUtils.java#L62-L64
opencypher/openCypher
tools/grammar/src/main/java/org/opencypher/tools/Functions.java
Functions.requireNonNull
public static <T> T requireNonNull( Class<T> type, T value ) { return Objects.requireNonNull( value, type::getSimpleName ); }
java
public static <T> T requireNonNull( Class<T> type, T value ) { return Objects.requireNonNull( value, type::getSimpleName ); }
[ "public", "static", "<", "T", ">", "T", "requireNonNull", "(", "Class", "<", "T", ">", "type", ",", "T", "value", ")", "{", "return", "Objects", ".", "requireNonNull", "(", "value", ",", "type", "::", "getSimpleName", ")", ";", "}" ]
Require an instance not to be null, using the (simple) name of the required type as an error message if it is. @param type the required type. @param value the value that must not be null. @param <T> the type. @return the value, that is guaranteed not to be null. @see Objects#requireNonNull(Object, Supplier)
[ "Require", "an", "instance", "not", "to", "be", "null", "using", "the", "(", "simple", ")", "name", "of", "the", "required", "type", "as", "an", "error", "message", "if", "it", "is", "." ]
train
https://github.com/opencypher/openCypher/blob/eb780caea625900ddbedd28a1eac9a5dbe09c5f0/tools/grammar/src/main/java/org/opencypher/tools/Functions.java#L58-L61
JM-Lab/utils-java8
src/main/java/kr/jm/utils/helper/JMLambda.java
JMLambda.functionIfTrue
public static <T, R> Optional<R> functionIfTrue(boolean bool, T target, Function<T, R> function) { return supplierIfTrue(bool, () -> function.apply(target)); }
java
public static <T, R> Optional<R> functionIfTrue(boolean bool, T target, Function<T, R> function) { return supplierIfTrue(bool, () -> function.apply(target)); }
[ "public", "static", "<", "T", ",", "R", ">", "Optional", "<", "R", ">", "functionIfTrue", "(", "boolean", "bool", ",", "T", "target", ",", "Function", "<", "T", ",", "R", ">", "function", ")", "{", "return", "supplierIfTrue", "(", "bool", ",", "(", ...
Function if true optional. @param <T> the type parameter @param <R> the type parameter @param bool the bool @param target the target @param function the function @return the optional
[ "Function", "if", "true", "optional", "." ]
train
https://github.com/JM-Lab/utils-java8/blob/9e407b3f28a7990418a1e877229fa8344f4d78a5/src/main/java/kr/jm/utils/helper/JMLambda.java#L269-L272
Azure/azure-sdk-for-java
edgegateway/resource-manager/v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/implementation/DevicesInner.java
DevicesInner.beginScanForUpdatesAsync
public Observable<Void> beginScanForUpdatesAsync(String deviceName, String resourceGroupName) { return beginScanForUpdatesWithServiceResponseAsync(deviceName, resourceGroupName).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
java
public Observable<Void> beginScanForUpdatesAsync(String deviceName, String resourceGroupName) { return beginScanForUpdatesWithServiceResponseAsync(deviceName, resourceGroupName).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Void", ">", "beginScanForUpdatesAsync", "(", "String", "deviceName", ",", "String", "resourceGroupName", ")", "{", "return", "beginScanForUpdatesWithServiceResponseAsync", "(", "deviceName", ",", "resourceGroupName", ")", ".", "map", "(", ...
Scans for updates on a data box edge/gateway device. @param deviceName The device name. @param resourceGroupName The resource group name. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceResponse} object if successful.
[ "Scans", "for", "updates", "on", "a", "data", "box", "edge", "/", "gateway", "device", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/edgegateway/resource-manager/v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/implementation/DevicesInner.java#L1775-L1782
tweea/matrixjavalib-main-common
src/main/java/net/matrix/lang/Reflections.java
Reflections.getAccessibleMethod
public static Method getAccessibleMethod(final Object target, final String name, final Class<?>... parameterTypes) { for (Class<?> searchType = target.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) { try { Method method = searchType.getDeclaredMethod(name, parameterTypes); makeAccessible(method); return method; } catch (NoSuchMethodException e) { // Method不在当前类定义,继续向上转型 LOG.trace("", e); } } return null; }
java
public static Method getAccessibleMethod(final Object target, final String name, final Class<?>... parameterTypes) { for (Class<?> searchType = target.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) { try { Method method = searchType.getDeclaredMethod(name, parameterTypes); makeAccessible(method); return method; } catch (NoSuchMethodException e) { // Method不在当前类定义,继续向上转型 LOG.trace("", e); } } return null; }
[ "public", "static", "Method", "getAccessibleMethod", "(", "final", "Object", "target", ",", "final", "String", "name", ",", "final", "Class", "<", "?", ">", "...", "parameterTypes", ")", "{", "for", "(", "Class", "<", "?", ">", "searchType", "=", "target",...
循环向上转型,获取对象的 DeclaredMethod,并强制设置为可访问。 如向上转型到 Object 仍无法找到,返回 null。 匹配函数名 + 参数类型。 用于方法需要被多次调用的情况。先使用本函数先取得 Method,然后调用 Method.invoke(Object obj, Object... args) @param target 目标对象 @param name 方法名 @param parameterTypes 参数类型 @return 方法
[ "循环向上转型,获取对象的", "DeclaredMethod,并强制设置为可访问。", "如向上转型到", "Object", "仍无法找到,返回", "null。", "匹配函数名", "+", "参数类型。", "用于方法需要被多次调用的情况。先使用本函数先取得", "Method,然后调用", "Method", ".", "invoke", "(", "Object", "obj", "Object", "...", "args", ")" ]
train
https://github.com/tweea/matrixjavalib-main-common/blob/ac8f98322a422e3ef76c3e12d47b98268cec7006/src/main/java/net/matrix/lang/Reflections.java#L224-L236
SimiaCryptus/utilities
java-util/src/main/java/com/simiacryptus/text/TextGenerator.java
TextGenerator.generateDictionary
public String generateDictionary(int length, int context, final String seed, int lookahead, boolean destructive) { return generateDictionary(length, context, seed, lookahead, destructive, false); }
java
public String generateDictionary(int length, int context, final String seed, int lookahead, boolean destructive) { return generateDictionary(length, context, seed, lookahead, destructive, false); }
[ "public", "String", "generateDictionary", "(", "int", "length", ",", "int", "context", ",", "final", "String", "seed", ",", "int", "lookahead", ",", "boolean", "destructive", ")", "{", "return", "generateDictionary", "(", "length", ",", "context", ",", "seed",...
Generate dictionary string. @param length the length @param context the context @param seed the seed @param lookahead the lookahead @param destructive the destructive @return the string
[ "Generate", "dictionary", "string", "." ]
train
https://github.com/SimiaCryptus/utilities/blob/b5a5e73449aae57de7dbfca2ed7a074432c5b17e/java-util/src/main/java/com/simiacryptus/text/TextGenerator.java#L92-L94
haifengl/smile
math/src/main/java/smile/stat/distribution/DiscreteDistribution.java
DiscreteDistribution.quantile
protected double quantile(double p, int xmin, int xmax) { while (xmax - xmin > 1) { int xmed = (xmax + xmin) / 2; if (cdf(xmed) > p) { xmax = xmed; } else { xmin = xmed; } } if (cdf(xmin) >= p) return xmin; else return xmax; }
java
protected double quantile(double p, int xmin, int xmax) { while (xmax - xmin > 1) { int xmed = (xmax + xmin) / 2; if (cdf(xmed) > p) { xmax = xmed; } else { xmin = xmed; } } if (cdf(xmin) >= p) return xmin; else return xmax; }
[ "protected", "double", "quantile", "(", "double", "p", ",", "int", "xmin", ",", "int", "xmax", ")", "{", "while", "(", "xmax", "-", "xmin", ">", "1", ")", "{", "int", "xmed", "=", "(", "xmax", "+", "xmin", ")", "/", "2", ";", "if", "(", "cdf", ...
Invertion of cdf by bisection numeric root finding of "cdf(x) = p" for discrete distribution.* Returns integer n such that P(<n) &le; p &le; P(<n+1).
[ "Invertion", "of", "cdf", "by", "bisection", "numeric", "root", "finding", "of", "cdf", "(", "x", ")", "=", "p", "for", "discrete", "distribution", ".", "*", "Returns", "integer", "n", "such", "that", "P", "(", "<n", ")", "&le", ";", "p", "&le", ";",...
train
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/math/src/main/java/smile/stat/distribution/DiscreteDistribution.java#L79-L93
bazaarvoice/emodb
event/src/main/java/com/bazaarvoice/emodb/event/db/astyanax/AstyanaxEventReaderDAO.java
AstyanaxEventReaderDAO.markUnread
@Override public void markUnread(String channel, Collection<EventId> events) { // For each slab keep track of the earliest index for each unread event. ConcurrentMap<ChannelSlab, Integer> channelSlabs = Maps.newConcurrentMap(); for (EventId event : events) { AstyanaxEventId astyanaxEvent = (AstyanaxEventId) event; checkArgument(channel.equals(astyanaxEvent.getChannel())); channelSlabs.merge(new ChannelSlab(channel, astyanaxEvent.getSlabId()), astyanaxEvent.getEventIdx(), Ints::min); } for (Map.Entry<ChannelSlab, Integer> entry : channelSlabs.entrySet()) { ChannelSlab channelSlab = entry.getKey(); int eventIdx = entry.getValue(); // Get the closed slab cursor, if any SlabCursor cursor = _closedSlabCursors.getIfPresent(channelSlab); // If the cursor exists and is beyond the lowest unread index, rewind it if (cursor != null && (cursor.get() == SlabCursor.END || cursor.get() > eventIdx)) { // Synchronize on the cursor before updating it to avoid concurrent updates with a read //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (cursor) { if (cursor.get() == SlabCursor.END || cursor.get() > eventIdx) { cursor.set(eventIdx); } } } } }
java
@Override public void markUnread(String channel, Collection<EventId> events) { // For each slab keep track of the earliest index for each unread event. ConcurrentMap<ChannelSlab, Integer> channelSlabs = Maps.newConcurrentMap(); for (EventId event : events) { AstyanaxEventId astyanaxEvent = (AstyanaxEventId) event; checkArgument(channel.equals(astyanaxEvent.getChannel())); channelSlabs.merge(new ChannelSlab(channel, astyanaxEvent.getSlabId()), astyanaxEvent.getEventIdx(), Ints::min); } for (Map.Entry<ChannelSlab, Integer> entry : channelSlabs.entrySet()) { ChannelSlab channelSlab = entry.getKey(); int eventIdx = entry.getValue(); // Get the closed slab cursor, if any SlabCursor cursor = _closedSlabCursors.getIfPresent(channelSlab); // If the cursor exists and is beyond the lowest unread index, rewind it if (cursor != null && (cursor.get() == SlabCursor.END || cursor.get() > eventIdx)) { // Synchronize on the cursor before updating it to avoid concurrent updates with a read //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (cursor) { if (cursor.get() == SlabCursor.END || cursor.get() > eventIdx) { cursor.set(eventIdx); } } } } }
[ "@", "Override", "public", "void", "markUnread", "(", "String", "channel", ",", "Collection", "<", "EventId", ">", "events", ")", "{", "// For each slab keep track of the earliest index for each unread event.", "ConcurrentMap", "<", "ChannelSlab", ",", "Integer", ">", "...
When all events from a slab have been read via {@link #readNewer(String, EventSink)} _closedSlabCursors caches that the slab is empty for 10 seconds. When a slab is marked as unread update the cursor, if present, such that it is rewound far enough to read the unread event again.
[ "When", "all", "events", "from", "a", "slab", "have", "been", "read", "via", "{" ]
train
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/event/src/main/java/com/bazaarvoice/emodb/event/db/astyanax/AstyanaxEventReaderDAO.java#L523-L549
EdwardRaff/JSAT
JSAT/src/jsat/linear/Matrix.java
Matrix.eye
public static DenseMatrix eye(int k) { DenseMatrix eye = new DenseMatrix(k, k); for(int i = 0; i < k; i++ ) eye.set(i, i, 1); return eye; }
java
public static DenseMatrix eye(int k) { DenseMatrix eye = new DenseMatrix(k, k); for(int i = 0; i < k; i++ ) eye.set(i, i, 1); return eye; }
[ "public", "static", "DenseMatrix", "eye", "(", "int", "k", ")", "{", "DenseMatrix", "eye", "=", "new", "DenseMatrix", "(", "k", ",", "k", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "k", ";", "i", "++", ")", "eye", ".", "set", ...
Creates a new dense identity matrix with <i>k</i> rows and columns. @param k the number of rows / columns @return a new dense identity matrix <i>I<sub>k</sub></i>
[ "Creates", "a", "new", "dense", "identity", "matrix", "with", "<i", ">", "k<", "/", "i", ">", "rows", "and", "columns", "." ]
train
https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/linear/Matrix.java#L981-L987
gallandarakhneorg/afc
advanced/mathfx/src/main/java/org/arakhne/afc/math/geometry/d3/ifx/Segment3ifx.java
Segment3ifx.y1Property
@Pure public IntegerProperty y1Property() { if (this.p1.y == null) { this.p1.y = new SimpleIntegerProperty(this, MathFXAttributeNames.Y1); } return this.p1.y; }
java
@Pure public IntegerProperty y1Property() { if (this.p1.y == null) { this.p1.y = new SimpleIntegerProperty(this, MathFXAttributeNames.Y1); } return this.p1.y; }
[ "@", "Pure", "public", "IntegerProperty", "y1Property", "(", ")", "{", "if", "(", "this", ".", "p1", ".", "y", "==", "null", ")", "{", "this", ".", "p1", ".", "y", "=", "new", "SimpleIntegerProperty", "(", "this", ",", "MathFXAttributeNames", ".", "Y1"...
Replies the property that is the y coordinate of the first segment point. @return the y1 property.
[ "Replies", "the", "property", "that", "is", "the", "y", "coordinate", "of", "the", "first", "segment", "point", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/mathfx/src/main/java/org/arakhne/afc/math/geometry/d3/ifx/Segment3ifx.java#L222-L228
tvesalainen/util
util/src/main/java/org/vesalainen/math/matrix/Matrix.java
Matrix.set
public void set(int i, int j, Matrix<T> B) { int m = B.rows(); int n = B.columns(); for (int ii = 0; ii < m; ii++) { for (int jj = 0; jj < n; jj++) { set(i+ii, j+jj, B.get(ii, jj)); } } }
java
public void set(int i, int j, Matrix<T> B) { int m = B.rows(); int n = B.columns(); for (int ii = 0; ii < m; ii++) { for (int jj = 0; jj < n; jj++) { set(i+ii, j+jj, B.get(ii, jj)); } } }
[ "public", "void", "set", "(", "int", "i", ",", "int", "j", ",", "Matrix", "<", "T", ">", "B", ")", "{", "int", "m", "=", "B", ".", "rows", "(", ")", ";", "int", "n", "=", "B", ".", "columns", "(", ")", ";", "for", "(", "int", "ii", "=", ...
Assign matrix A items starting at i,j @param i @param j @param B
[ "Assign", "matrix", "A", "items", "starting", "at", "i", "j" ]
train
https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/math/matrix/Matrix.java#L74-L85
alkacon/opencms-core
src/org/opencms/file/CmsObject.java
CmsObject.writePropertyObjects
public void writePropertyObjects(String resourcename, List<CmsProperty> properties) throws CmsException { CmsResource resource = readResource(resourcename, CmsResourceFilter.IGNORE_EXPIRATION); getResourceType(resource).writePropertyObjects(this, m_securityManager, resource, properties); }
java
public void writePropertyObjects(String resourcename, List<CmsProperty> properties) throws CmsException { CmsResource resource = readResource(resourcename, CmsResourceFilter.IGNORE_EXPIRATION); getResourceType(resource).writePropertyObjects(this, m_securityManager, resource, properties); }
[ "public", "void", "writePropertyObjects", "(", "String", "resourcename", ",", "List", "<", "CmsProperty", ">", "properties", ")", "throws", "CmsException", "{", "CmsResource", "resource", "=", "readResource", "(", "resourcename", ",", "CmsResourceFilter", ".", "IGNO...
Writes a list of properties for a specified resource.<p> Code calling this method has to ensure that the no properties <code>a, b</code> are contained in the specified list so that <code>a.equals(b)</code>, otherwise an exception is thrown.<p> @param resourcename the name of resource with complete path @param properties the list of properties to write @throws CmsException if something goes wrong
[ "Writes", "a", "list", "of", "properties", "for", "a", "specified", "resource", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/file/CmsObject.java#L4103-L4107
elki-project/elki
elki-index-mtree/src/main/java/de/lmu/ifi/dbs/elki/index/tree/metrical/mtreevariants/mktrees/mkcop/MkCoPTree.java
MkCoPTree.createNewDirectoryEntry
@Override protected MkCoPEntry createNewDirectoryEntry(MkCoPTreeNode<O> node, DBID routingObjectID, double parentDistance) { return new MkCoPDirectoryEntry(routingObjectID, parentDistance, node.getPageID(), node.coveringRadiusFromEntries(routingObjectID, this), null); // node.conservativeKnnDistanceApproximation(k_max)); }
java
@Override protected MkCoPEntry createNewDirectoryEntry(MkCoPTreeNode<O> node, DBID routingObjectID, double parentDistance) { return new MkCoPDirectoryEntry(routingObjectID, parentDistance, node.getPageID(), node.coveringRadiusFromEntries(routingObjectID, this), null); // node.conservativeKnnDistanceApproximation(k_max)); }
[ "@", "Override", "protected", "MkCoPEntry", "createNewDirectoryEntry", "(", "MkCoPTreeNode", "<", "O", ">", "node", ",", "DBID", "routingObjectID", ",", "double", "parentDistance", ")", "{", "return", "new", "MkCoPDirectoryEntry", "(", "routingObjectID", ",", "paren...
Creates a new directory entry representing the specified node. @param node the node to be represented by the new entry @param routingObjectID the id of the routing object of the node @param parentDistance the distance from the routing object of the node to the routing object of the parent node
[ "Creates", "a", "new", "directory", "entry", "representing", "the", "specified", "node", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-index-mtree/src/main/java/de/lmu/ifi/dbs/elki/index/tree/metrical/mtreevariants/mktrees/mkcop/MkCoPTree.java#L720-L724
alibaba/jstorm
jstorm-hdfs/src/main/java/com/alibaba/jstorm/hdfs/trident/HdfsState.java
HdfsState.getTxnRecord
private TxnRecord getTxnRecord(Path indexFilePath) throws IOException { Path tmpPath = tmpFilePath(indexFilePath.toString()); if (this.options.fs.exists(indexFilePath)) { return readTxnRecord(indexFilePath); } else if (this.options.fs.exists(tmpPath)) { return readTxnRecord(tmpPath); } return new TxnRecord(0, options.currentFile.toString(), 0); }
java
private TxnRecord getTxnRecord(Path indexFilePath) throws IOException { Path tmpPath = tmpFilePath(indexFilePath.toString()); if (this.options.fs.exists(indexFilePath)) { return readTxnRecord(indexFilePath); } else if (this.options.fs.exists(tmpPath)) { return readTxnRecord(tmpPath); } return new TxnRecord(0, options.currentFile.toString(), 0); }
[ "private", "TxnRecord", "getTxnRecord", "(", "Path", "indexFilePath", ")", "throws", "IOException", "{", "Path", "tmpPath", "=", "tmpFilePath", "(", "indexFilePath", ".", "toString", "(", ")", ")", ";", "if", "(", "this", ".", "options", ".", "fs", ".", "e...
Reads the last txn record from index file if it exists, if not from .tmp file if exists. @param indexFilePath the index file path @return the txn record from the index file or a default initial record. @throws IOException
[ "Reads", "the", "last", "txn", "record", "from", "index", "file", "if", "it", "exists", "if", "not", "from", ".", "tmp", "file", "if", "exists", "." ]
train
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-hdfs/src/main/java/com/alibaba/jstorm/hdfs/trident/HdfsState.java#L470-L478
netscaler/nitro
src/main/java/com/citrix/netscaler/nitro/resource/config/tm/tmtrafficaction.java
tmtrafficaction.get
public static tmtrafficaction get(nitro_service service, String name) throws Exception{ tmtrafficaction obj = new tmtrafficaction(); obj.set_name(name); tmtrafficaction response = (tmtrafficaction) obj.get_resource(service); return response; }
java
public static tmtrafficaction get(nitro_service service, String name) throws Exception{ tmtrafficaction obj = new tmtrafficaction(); obj.set_name(name); tmtrafficaction response = (tmtrafficaction) obj.get_resource(service); return response; }
[ "public", "static", "tmtrafficaction", "get", "(", "nitro_service", "service", ",", "String", "name", ")", "throws", "Exception", "{", "tmtrafficaction", "obj", "=", "new", "tmtrafficaction", "(", ")", ";", "obj", ".", "set_name", "(", "name", ")", ";", "tmt...
Use this API to fetch tmtrafficaction resource of given name .
[ "Use", "this", "API", "to", "fetch", "tmtrafficaction", "resource", "of", "given", "name", "." ]
train
https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/tm/tmtrafficaction.java#L429-L434
UrielCh/ovh-java-sdk
ovh-java-sdk-dedicatedserver/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedserver.java
ApiOvhDedicatedserver.serviceName_features_ipmi_access_POST
public OvhTask serviceName_features_ipmi_access_POST(String serviceName, String ipToAllow, String sshKey, OvhCacheTTLEnum ttl, OvhIpmiAccessTypeEnum type) throws IOException { String qPath = "/dedicated/server/{serviceName}/features/ipmi/access"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "ipToAllow", ipToAllow); addBody(o, "sshKey", sshKey); addBody(o, "ttl", ttl); addBody(o, "type", type); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhTask.class); }
java
public OvhTask serviceName_features_ipmi_access_POST(String serviceName, String ipToAllow, String sshKey, OvhCacheTTLEnum ttl, OvhIpmiAccessTypeEnum type) throws IOException { String qPath = "/dedicated/server/{serviceName}/features/ipmi/access"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "ipToAllow", ipToAllow); addBody(o, "sshKey", sshKey); addBody(o, "ttl", ttl); addBody(o, "type", type); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhTask.class); }
[ "public", "OvhTask", "serviceName_features_ipmi_access_POST", "(", "String", "serviceName", ",", "String", "ipToAllow", ",", "String", "sshKey", ",", "OvhCacheTTLEnum", "ttl", ",", "OvhIpmiAccessTypeEnum", "type", ")", "throws", "IOException", "{", "String", "qPath", ...
Request an acces on KVM IPMI interface REST: POST /dedicated/server/{serviceName}/features/ipmi/access @param ttl [required] Session access time to live in minutes @param type [required] IPMI console access @param ipToAllow [required] IP to allow connection from for this IPMI session @param sshKey [required] SSH key name to allow access on KVM/IP interface with (name from /me/sshKey) @param serviceName [required] The internal name of your dedicated server
[ "Request", "an", "acces", "on", "KVM", "IPMI", "interface" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dedicatedserver/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedserver.java#L1080-L1090
googleads/googleads-java-lib
examples/adwords_axis/src/main/java/adwords/axis/v201809/migration/MigrateToExtensionSettings.java
MigrateToExtensionSettings.getFeedItemIdsForCampaign
private static Set<Long> getFeedItemIdsForCampaign(CampaignFeed campaignFeed) throws RemoteException { Set<Long> feedItemIds = Sets.newHashSet(); FunctionOperator functionOperator = campaignFeed.getMatchingFunction().getOperator(); if (FunctionOperator.IN.equals(functionOperator)) { // Check if matchingFunction is of the form IN(FEED_ITEM_ID,{xxx,xxx}). // Extract feed items if applicable. feedItemIds.addAll(getFeedItemIdsFromArgument(campaignFeed.getMatchingFunction())); } else if (FunctionOperator.AND.equals(functionOperator)) { // Check if matchingFunction is of the form IN(FEED_ITEM_ID,{xxx,xxx}). // Extract feed items if applicable. Arrays.stream(campaignFeed.getMatchingFunction().getLhsOperand()) .filter(FunctionOperand.class::isInstance) .map(argument -> (FunctionOperand) argument) .filter(operand -> FunctionOperator.IN.equals(operand.getValue().getOperator())) .forEach(operand -> feedItemIds.addAll(getFeedItemIdsFromArgument(operand.getValue()))); } else { // There are no other matching functions involving feed item IDs. } return feedItemIds; }
java
private static Set<Long> getFeedItemIdsForCampaign(CampaignFeed campaignFeed) throws RemoteException { Set<Long> feedItemIds = Sets.newHashSet(); FunctionOperator functionOperator = campaignFeed.getMatchingFunction().getOperator(); if (FunctionOperator.IN.equals(functionOperator)) { // Check if matchingFunction is of the form IN(FEED_ITEM_ID,{xxx,xxx}). // Extract feed items if applicable. feedItemIds.addAll(getFeedItemIdsFromArgument(campaignFeed.getMatchingFunction())); } else if (FunctionOperator.AND.equals(functionOperator)) { // Check if matchingFunction is of the form IN(FEED_ITEM_ID,{xxx,xxx}). // Extract feed items if applicable. Arrays.stream(campaignFeed.getMatchingFunction().getLhsOperand()) .filter(FunctionOperand.class::isInstance) .map(argument -> (FunctionOperand) argument) .filter(operand -> FunctionOperator.IN.equals(operand.getValue().getOperator())) .forEach(operand -> feedItemIds.addAll(getFeedItemIdsFromArgument(operand.getValue()))); } else { // There are no other matching functions involving feed item IDs. } return feedItemIds; }
[ "private", "static", "Set", "<", "Long", ">", "getFeedItemIdsForCampaign", "(", "CampaignFeed", "campaignFeed", ")", "throws", "RemoteException", "{", "Set", "<", "Long", ">", "feedItemIds", "=", "Sets", ".", "newHashSet", "(", ")", ";", "FunctionOperator", "fun...
Returns the list of feed item IDs that are used by a campaign through a given campaign feed.
[ "Returns", "the", "list", "of", "feed", "item", "IDs", "that", "are", "used", "by", "a", "campaign", "through", "a", "given", "campaign", "feed", "." ]
train
https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/examples/adwords_axis/src/main/java/adwords/axis/v201809/migration/MigrateToExtensionSettings.java#L506-L529
vvakame/JsonPullParser
jsonpullparser-core/src/main/java/net/vvakame/util/jsonpullparser/util/JsonUtil.java
JsonUtil.putLongList
public static void putLongList(Writer writer, List<Long> values) throws IOException { if (values == null) { writer.write("null"); } else { startArray(writer); for (int i = 0; i < values.size(); i++) { put(writer, values.get(i)); if (i != values.size() - 1) { addSeparator(writer); } } endArray(writer); } }
java
public static void putLongList(Writer writer, List<Long> values) throws IOException { if (values == null) { writer.write("null"); } else { startArray(writer); for (int i = 0; i < values.size(); i++) { put(writer, values.get(i)); if (i != values.size() - 1) { addSeparator(writer); } } endArray(writer); } }
[ "public", "static", "void", "putLongList", "(", "Writer", "writer", ",", "List", "<", "Long", ">", "values", ")", "throws", "IOException", "{", "if", "(", "values", "==", "null", ")", "{", "writer", ".", "write", "(", "\"null\"", ")", ";", "}", "else",...
Writes the given value with the given writer. @param writer @param values @throws IOException @author vvakame
[ "Writes", "the", "given", "value", "with", "the", "given", "writer", "." ]
train
https://github.com/vvakame/JsonPullParser/blob/fce183ca66354723323a77f2ae8cb5222b5836bc/jsonpullparser-core/src/main/java/net/vvakame/util/jsonpullparser/util/JsonUtil.java#L404-L417
alkacon/opencms-core
src/org/opencms/xml/content/CmsXmlContent.java
CmsXmlContent.synchronizeLocaleIndependentValues
public void synchronizeLocaleIndependentValues(CmsObject cms, Collection<String> skipPaths, Locale sourceLocale) { if (getContentDefinition().getContentHandler().hasSynchronizedElements() && (getLocales().size() > 1)) { for (String elementPath : getContentDefinition().getContentHandler().getSynchronizations()) { synchronizeElement(cms, elementPath, skipPaths, sourceLocale); } } }
java
public void synchronizeLocaleIndependentValues(CmsObject cms, Collection<String> skipPaths, Locale sourceLocale) { if (getContentDefinition().getContentHandler().hasSynchronizedElements() && (getLocales().size() > 1)) { for (String elementPath : getContentDefinition().getContentHandler().getSynchronizations()) { synchronizeElement(cms, elementPath, skipPaths, sourceLocale); } } }
[ "public", "void", "synchronizeLocaleIndependentValues", "(", "CmsObject", "cms", ",", "Collection", "<", "String", ">", "skipPaths", ",", "Locale", "sourceLocale", ")", "{", "if", "(", "getContentDefinition", "(", ")", ".", "getContentHandler", "(", ")", ".", "h...
Synchronizes the locale independent fields for the given locale.<p> @param cms the cms context @param skipPaths the paths to skip @param sourceLocale the source locale
[ "Synchronizes", "the", "locale", "independent", "fields", "for", "the", "given", "locale", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/content/CmsXmlContent.java#L771-L778
gsi-upm/Shanks
shanks-core/src/main/java/es/upm/dit/gsi/shanks/agent/capability/movement/Location.java
Location.isNearTo
public boolean isNearTo(Location location, double distance) { if (this.is2DLocation() && location.is2DLocation()) { return this.isNearTo(location.getLocation2D(), distance); } else if (this.is3DLocation() && location.is3DLocation()) { return this.isNearTo(location.getLocation3D(), distance); } else { return false; } }
java
public boolean isNearTo(Location location, double distance) { if (this.is2DLocation() && location.is2DLocation()) { return this.isNearTo(location.getLocation2D(), distance); } else if (this.is3DLocation() && location.is3DLocation()) { return this.isNearTo(location.getLocation3D(), distance); } else { return false; } }
[ "public", "boolean", "isNearTo", "(", "Location", "location", ",", "double", "distance", ")", "{", "if", "(", "this", ".", "is2DLocation", "(", ")", "&&", "location", ".", "is2DLocation", "(", ")", ")", "{", "return", "this", ".", "isNearTo", "(", "locat...
Compare two locations and return if the locations are near or not @param location Location to compare with @param distance The distance between two locations @return true is the real distance is lower or equals than the distance parameter
[ "Compare", "two", "locations", "and", "return", "if", "the", "locations", "are", "near", "or", "not" ]
train
https://github.com/gsi-upm/Shanks/blob/35d87a81c22731f4f83bbd0571c9c6d466bd16be/shanks-core/src/main/java/es/upm/dit/gsi/shanks/agent/capability/movement/Location.java#L136-L144
jaxio/celerio
celerio-engine/src/main/java/com/jaxio/celerio/template/PreviousEngine.java
PreviousEngine.setCurrentFilename
private String setCurrentFilename(String relativePathOrPackage, String filename, String domain) throws Exception { currentFullFilename = convertToFullFilename(relativePathOrPackage, filename, domain); return ""; }
java
private String setCurrentFilename(String relativePathOrPackage, String filename, String domain) throws Exception { currentFullFilename = convertToFullFilename(relativePathOrPackage, filename, domain); return ""; }
[ "private", "String", "setCurrentFilename", "(", "String", "relativePathOrPackage", ",", "String", "filename", ",", "String", "domain", ")", "throws", "Exception", "{", "currentFullFilename", "=", "convertToFullFilename", "(", "relativePathOrPackage", ",", "filename", ",...
called within the velocity script.<br> see $velocity.setJavaFilename(...)<br> this allows us to generate dynamically the filename. @param relativePathOrPackage @param filename @param domain @throws Exception
[ "called", "within", "the", "velocity", "script", ".", "<br", ">", "see", "$velocity", ".", "setJavaFilename", "(", "...", ")", "<br", ">", "this", "allows", "us", "to", "generate", "dynamically", "the", "filename", "." ]
train
https://github.com/jaxio/celerio/blob/fbfacb639e286f9f3f3a18986f74ea275bebd887/celerio-engine/src/main/java/com/jaxio/celerio/template/PreviousEngine.java#L118-L121
DDTH/ddth-dao
ddth-dao-core/src/main/java/com/github/ddth/dao/BaseDao.java
BaseDao.addProfiling
public static ProfilingRecord addProfiling(long execTimeMs, String command, long durationMs) { ProfilingRecord record = new ProfilingRecord(execTimeMs, command, durationMs); List<ProfilingRecord> records = profilingRecords.get(); records.add(record); while (records.size() > 100) { records.remove(0); } return record; }
java
public static ProfilingRecord addProfiling(long execTimeMs, String command, long durationMs) { ProfilingRecord record = new ProfilingRecord(execTimeMs, command, durationMs); List<ProfilingRecord> records = profilingRecords.get(); records.add(record); while (records.size() > 100) { records.remove(0); } return record; }
[ "public", "static", "ProfilingRecord", "addProfiling", "(", "long", "execTimeMs", ",", "String", "command", ",", "long", "durationMs", ")", "{", "ProfilingRecord", "record", "=", "new", "ProfilingRecord", "(", "execTimeMs", ",", "command", ",", "durationMs", ")", ...
Adds a new profiling record. @param execTimeMs @param command @return
[ "Adds", "a", "new", "profiling", "record", "." ]
train
https://github.com/DDTH/ddth-dao/blob/8d059ddf641a1629aa53851f9d1b41abf175a180/ddth-dao-core/src/main/java/com/github/ddth/dao/BaseDao.java#L63-L71
eBay/parallec
src/main/java/io/parallec/core/taskbuilder/targethosts/TargetHostsBuilderHelperCms.java
TargetHostsBuilderHelperCms.readJsonFromUrlWithCmsHeader
static JSONObject readJsonFromUrlWithCmsHeader(String url, String token) throws MalformedURLException, IOException, JSONException { InputStream is = null; JSONObject jObj = new JSONObject(); try { HttpURLConnection.setFollowRedirects(false); HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection(); con.setRequestMethod("GET"); if(token!=null){ con.setRequestProperty("Authorization", token); } con.setConnectTimeout(ParallecGlobalConfig.urlConnectionConnectTimeoutMillis); con.setReadTimeout(ParallecGlobalConfig.urlConnectionReadTimeoutMillis); is = con.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); String jsonText = PcFileNetworkIoUtils.readAll(rd); jObj = new JSONObject(jsonText); rd.close(); } catch (Exception t) { logger.error("readJsonFromUrl() exception: " + t.getLocalizedMessage() + PcDateUtils.getNowDateTimeStrStandard()); } finally { if (is != null) { is.close(); } } return jObj; }
java
static JSONObject readJsonFromUrlWithCmsHeader(String url, String token) throws MalformedURLException, IOException, JSONException { InputStream is = null; JSONObject jObj = new JSONObject(); try { HttpURLConnection.setFollowRedirects(false); HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection(); con.setRequestMethod("GET"); if(token!=null){ con.setRequestProperty("Authorization", token); } con.setConnectTimeout(ParallecGlobalConfig.urlConnectionConnectTimeoutMillis); con.setReadTimeout(ParallecGlobalConfig.urlConnectionReadTimeoutMillis); is = con.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); String jsonText = PcFileNetworkIoUtils.readAll(rd); jObj = new JSONObject(jsonText); rd.close(); } catch (Exception t) { logger.error("readJsonFromUrl() exception: " + t.getLocalizedMessage() + PcDateUtils.getNowDateTimeStrStandard()); } finally { if (is != null) { is.close(); } } return jObj; }
[ "static", "JSONObject", "readJsonFromUrlWithCmsHeader", "(", "String", "url", ",", "String", "token", ")", "throws", "MalformedURLException", ",", "IOException", ",", "JSONException", "{", "InputStream", "is", "=", "null", ";", "JSONObject", "jObj", "=", "new", "J...
removed header (only used for authorization for PP) 2015.08 @param url the url @return the JSON object @throws MalformedURLException the malformed url exception @throws IOException Signals that an I/O exception has occurred. @throws JSONException the JSON exception
[ "removed", "header", "(", "only", "used", "for", "authorization", "for", "PP", ")", "2015", ".", "08" ]
train
https://github.com/eBay/parallec/blob/1b4f1628f34fedfb06b24c33a5372d64d3df0952/src/main/java/io/parallec/core/taskbuilder/targethosts/TargetHostsBuilderHelperCms.java#L109-L143
pressgang-ccms/PressGangCCMSCommonUtilities
src/main/java/org/jboss/pressgang/ccms/utils/common/StringUtilities.java
StringUtilities.lastIndexOf
public static int lastIndexOf(final String input, final char delim, final int fromIndex) { if (input == null) return -1; int index = input.lastIndexOf(delim, fromIndex); while (index != -1 && index != 0) { if (input.charAt(index - 1) != '\\') break; index = input.lastIndexOf(delim, index - 1); } return index; }
java
public static int lastIndexOf(final String input, final char delim, final int fromIndex) { if (input == null) return -1; int index = input.lastIndexOf(delim, fromIndex); while (index != -1 && index != 0) { if (input.charAt(index - 1) != '\\') break; index = input.lastIndexOf(delim, index - 1); } return index; }
[ "public", "static", "int", "lastIndexOf", "(", "final", "String", "input", ",", "final", "char", "delim", ",", "final", "int", "fromIndex", ")", "{", "if", "(", "input", "==", "null", ")", "return", "-", "1", ";", "int", "index", "=", "input", ".", "...
Gets the last index of a character starting at fromIndex. Ignoring characters that have been escaped @param input The string to be searched @param delim The character to be found @param fromIndex Start searching from this index @return The index of the found character or -1 if the character wasn't found
[ "Gets", "the", "last", "index", "of", "a", "character", "starting", "at", "fromIndex", ".", "Ignoring", "characters", "that", "have", "been", "escaped" ]
train
https://github.com/pressgang-ccms/PressGangCCMSCommonUtilities/blob/5ebf5ed30a94c34c33f4708caa04a8da99cbb15c/src/main/java/org/jboss/pressgang/ccms/utils/common/StringUtilities.java#L260-L268
SeleniumHQ/selenium
java/client/src/org/openqa/selenium/interactions/Actions.java
Actions.moveToElement
public Actions moveToElement(WebElement target, int xOffset, int yOffset) { if (isBuildingActions()) { action.addAction(new MoveToOffsetAction(jsonMouse, (Locatable) target, xOffset, yOffset)); } // Of course, this is the offset from the centre of the element. We have no idea what the width // and height are once we execute this method. LOG.info("When using the W3C Action commands, offsets are from the center of element"); return moveInTicks(target, xOffset, yOffset); }
java
public Actions moveToElement(WebElement target, int xOffset, int yOffset) { if (isBuildingActions()) { action.addAction(new MoveToOffsetAction(jsonMouse, (Locatable) target, xOffset, yOffset)); } // Of course, this is the offset from the centre of the element. We have no idea what the width // and height are once we execute this method. LOG.info("When using the W3C Action commands, offsets are from the center of element"); return moveInTicks(target, xOffset, yOffset); }
[ "public", "Actions", "moveToElement", "(", "WebElement", "target", ",", "int", "xOffset", ",", "int", "yOffset", ")", "{", "if", "(", "isBuildingActions", "(", ")", ")", "{", "action", ".", "addAction", "(", "new", "MoveToOffsetAction", "(", "jsonMouse", ","...
Moves the mouse to an offset from the top-left corner of the element. The element is scrolled into view and its location is calculated using getBoundingClientRect. @param target element to move to. @param xOffset Offset from the top-left corner. A negative value means coordinates left from the element. @param yOffset Offset from the top-left corner. A negative value means coordinates above the element. @return A self reference.
[ "Moves", "the", "mouse", "to", "an", "offset", "from", "the", "top", "-", "left", "corner", "of", "the", "element", ".", "The", "element", "is", "scrolled", "into", "view", "and", "its", "location", "is", "calculated", "using", "getBoundingClientRect", "." ]
train
https://github.com/SeleniumHQ/selenium/blob/7af172729f17b20269c8ca4ea6f788db48616535/java/client/src/org/openqa/selenium/interactions/Actions.java#L376-L385
eFaps/eFaps-Kernel
src/main/java/org/efaps/admin/common/SystemConfiguration.java
SystemConfiguration.getAttributeValueAsEncryptedProperties
public Properties getAttributeValueAsEncryptedProperties(final String _key) throws EFapsException { final Properties properties = getAttributeValueAsProperties(_key, false); final Properties props = new EncryptableProperties(properties, SystemConfiguration.ENCRYPTOR); return props; }
java
public Properties getAttributeValueAsEncryptedProperties(final String _key) throws EFapsException { final Properties properties = getAttributeValueAsProperties(_key, false); final Properties props = new EncryptableProperties(properties, SystemConfiguration.ENCRYPTOR); return props; }
[ "public", "Properties", "getAttributeValueAsEncryptedProperties", "(", "final", "String", "_key", ")", "throws", "EFapsException", "{", "final", "Properties", "properties", "=", "getAttributeValueAsProperties", "(", "_key", ",", "false", ")", ";", "final", "Properties",...
Returns for given <code>_key</code> the related value as Properties. If no attribute is found an empty Properties is returned. @param _key key of searched attribute @return Properties @throws EFapsException on error @see #attributes
[ "Returns", "for", "given", "<code", ">", "_key<", "/", "code", ">", "the", "related", "value", "as", "Properties", ".", "If", "no", "attribute", "is", "found", "an", "empty", "Properties", "is", "returned", "." ]
train
https://github.com/eFaps/eFaps-Kernel/blob/04b96548f518c2386a93f5ec2b9349f9b9063859/src/main/java/org/efaps/admin/common/SystemConfiguration.java#L435-L441
apache/groovy
src/main/groovy/groovy/lang/ExpandoMetaClass.java
ExpandoMetaClass.isGetter
private boolean isGetter(String name, CachedClass[] args) { if (name == null || name.length() == 0 || args == null) return false; if (args.length != 0) return false; if (name.startsWith("get")) { name = name.substring(3); return isPropertyName(name); } else if (name.startsWith("is")) { name = name.substring(2); return isPropertyName(name); } return false; }
java
private boolean isGetter(String name, CachedClass[] args) { if (name == null || name.length() == 0 || args == null) return false; if (args.length != 0) return false; if (name.startsWith("get")) { name = name.substring(3); return isPropertyName(name); } else if (name.startsWith("is")) { name = name.substring(2); return isPropertyName(name); } return false; }
[ "private", "boolean", "isGetter", "(", "String", "name", ",", "CachedClass", "[", "]", "args", ")", "{", "if", "(", "name", "==", "null", "||", "name", ".", "length", "(", ")", "==", "0", "||", "args", "==", "null", ")", "return", "false", ";", "if...
Returns true if the name of the method specified and the number of arguments make it a javabean property @param name True if its a Javabean property @param args The arguments @return True if it is a javabean property method
[ "Returns", "true", "if", "the", "name", "of", "the", "method", "specified", "and", "the", "number", "of", "arguments", "make", "it", "a", "javabean", "property" ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/groovy/groovy/lang/ExpandoMetaClass.java#L1236-L1248
cdk/cdk
legacy/src/main/java/org/openscience/cdk/ringsearch/FiguerasSSSRFinder.java
FiguerasSSSRFinder.checkEdges
private IBond checkEdges(IRing ring, IAtomContainer molecule) { IRing r1, r2; IRingSet ringSet = ring.getBuilder().newInstance(IRingSet.class); IBond bond; int minMaxSize = Integer.MAX_VALUE; int minMax = 0; logger.debug("Molecule: " + molecule); Iterator<IBond> bonds = ring.bonds().iterator(); while (bonds.hasNext()) { bond = (IBond) bonds.next(); molecule.removeElectronContainer(bond); r1 = getRing(bond.getBegin(), molecule); r2 = getRing(bond.getEnd(), molecule); logger.debug("checkEdges: " + bond); if (r1.getAtomCount() > r2.getAtomCount()) { ringSet.addAtomContainer(r1); } else { ringSet.addAtomContainer(r2); } molecule.addBond(bond); } for (int i = 0; i < ringSet.getAtomContainerCount(); i++) { if (((IRing) ringSet.getAtomContainer(i)).getBondCount() < minMaxSize) { minMaxSize = ((IRing) ringSet.getAtomContainer(i)).getBondCount(); minMax = i; } } return (IBond) ring.getElectronContainer(minMax); }
java
private IBond checkEdges(IRing ring, IAtomContainer molecule) { IRing r1, r2; IRingSet ringSet = ring.getBuilder().newInstance(IRingSet.class); IBond bond; int minMaxSize = Integer.MAX_VALUE; int minMax = 0; logger.debug("Molecule: " + molecule); Iterator<IBond> bonds = ring.bonds().iterator(); while (bonds.hasNext()) { bond = (IBond) bonds.next(); molecule.removeElectronContainer(bond); r1 = getRing(bond.getBegin(), molecule); r2 = getRing(bond.getEnd(), molecule); logger.debug("checkEdges: " + bond); if (r1.getAtomCount() > r2.getAtomCount()) { ringSet.addAtomContainer(r1); } else { ringSet.addAtomContainer(r2); } molecule.addBond(bond); } for (int i = 0; i < ringSet.getAtomContainerCount(); i++) { if (((IRing) ringSet.getAtomContainer(i)).getBondCount() < minMaxSize) { minMaxSize = ((IRing) ringSet.getAtomContainer(i)).getBondCount(); minMax = i; } } return (IBond) ring.getElectronContainer(minMax); }
[ "private", "IBond", "checkEdges", "(", "IRing", "ring", ",", "IAtomContainer", "molecule", ")", "{", "IRing", "r1", ",", "r2", ";", "IRingSet", "ringSet", "=", "ring", ".", "getBuilder", "(", ")", ".", "newInstance", "(", "IRingSet", ".", "class", ")", "...
Selects an optimum edge for elimination in structures without N2 nodes. <p>This might be severely broken! Would have helped if there was an explanation of how this algorithm worked. @param ring @param molecule
[ "Selects", "an", "optimum", "edge", "for", "elimination", "in", "structures", "without", "N2", "nodes", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/legacy/src/main/java/org/openscience/cdk/ringsearch/FiguerasSSSRFinder.java#L374-L402
google/closure-compiler
src/com/google/javascript/jscomp/NodeUtil.java
NodeUtil.mayEffectMutableState
static boolean mayEffectMutableState(Node n, AbstractCompiler compiler) { checkNotNull(compiler); return checkForStateChangeHelper(n, true, compiler); }
java
static boolean mayEffectMutableState(Node n, AbstractCompiler compiler) { checkNotNull(compiler); return checkForStateChangeHelper(n, true, compiler); }
[ "static", "boolean", "mayEffectMutableState", "(", "Node", "n", ",", "AbstractCompiler", "compiler", ")", "{", "checkNotNull", "(", "compiler", ")", ";", "return", "checkForStateChangeHelper", "(", "n", ",", "true", ",", "compiler", ")", ";", "}" ]
Returns true if the node may create new mutable state, or change existing state. @see <a href="http://www.xkcd.org/326/">XKCD Cartoon</a>
[ "Returns", "true", "if", "the", "node", "may", "create", "new", "mutable", "state", "or", "change", "existing", "state", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/NodeUtil.java#L1066-L1069
NextFaze/power-adapters
power-adapters/src/main/java/com/nextfaze/poweradapters/DividerAdapterBuilder.java
DividerAdapterBuilder.leadingView
@NonNull public DividerAdapterBuilder leadingView(@NonNull ViewFactory viewFactory) { mLeadingItem = new Item(checkNotNull(viewFactory, "viewFactory"), false); return this; }
java
@NonNull public DividerAdapterBuilder leadingView(@NonNull ViewFactory viewFactory) { mLeadingItem = new Item(checkNotNull(viewFactory, "viewFactory"), false); return this; }
[ "@", "NonNull", "public", "DividerAdapterBuilder", "leadingView", "(", "@", "NonNull", "ViewFactory", "viewFactory", ")", "{", "mLeadingItem", "=", "new", "Item", "(", "checkNotNull", "(", "viewFactory", ",", "\"viewFactory\"", ")", ",", "false", ")", ";", "retu...
Sets the divider that appears before the wrapped adapters items.
[ "Sets", "the", "divider", "that", "appears", "before", "the", "wrapped", "adapters", "items", "." ]
train
https://github.com/NextFaze/power-adapters/blob/cdf00b1b723ed9d6bcd549ae9741a19dd59651e1/power-adapters/src/main/java/com/nextfaze/poweradapters/DividerAdapterBuilder.java#L38-L42
DataSketches/sketches-core
src/main/java/com/yahoo/sketches/Util.java
Util.floorPowerOfBdouble
public static double floorPowerOfBdouble(final double b, final double n) { final double x = (n < 1.0) ? 1.0 : n; return pow(b, floor(logB(b, x))); }
java
public static double floorPowerOfBdouble(final double b, final double n) { final double x = (n < 1.0) ? 1.0 : n; return pow(b, floor(logB(b, x))); }
[ "public", "static", "double", "floorPowerOfBdouble", "(", "final", "double", "b", ",", "final", "double", "n", ")", "{", "final", "double", "x", "=", "(", "n", "<", "1.0", ")", "?", "1.0", ":", "n", ";", "return", "pow", "(", "b", ",", "floor", "("...
Computes the floor power of B as a double. This is the largest positive power of B that equal to or less than the given n and equal to a mathematical integer. The result of this function is consistent with {@link #floorPowerOf2(int)} for values less than one. I.e., if <i>n &lt; 1,</i> the result is 1. @param b The base in the expression &#8970;b<sup>n</sup>&#8971;. @param n The input argument. @return the floor power of 2 and equal to a mathematical integer.
[ "Computes", "the", "floor", "power", "of", "B", "as", "a", "double", ".", "This", "is", "the", "largest", "positive", "power", "of", "B", "that", "equal", "to", "or", "less", "than", "the", "given", "n", "and", "equal", "to", "a", "mathematical", "inte...
train
https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/Util.java#L594-L597
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/beans/PropertyChangeSupport.java
PropertyChangeSupport.fireIndexedPropertyChange
public void fireIndexedPropertyChange(String propertyName, int index, Object oldValue, Object newValue) { if (oldValue == null || newValue == null || !oldValue.equals(newValue)) { firePropertyChange(new IndexedPropertyChangeEvent(source, propertyName, oldValue, newValue, index)); } }
java
public void fireIndexedPropertyChange(String propertyName, int index, Object oldValue, Object newValue) { if (oldValue == null || newValue == null || !oldValue.equals(newValue)) { firePropertyChange(new IndexedPropertyChangeEvent(source, propertyName, oldValue, newValue, index)); } }
[ "public", "void", "fireIndexedPropertyChange", "(", "String", "propertyName", ",", "int", "index", ",", "Object", "oldValue", ",", "Object", "newValue", ")", "{", "if", "(", "oldValue", "==", "null", "||", "newValue", "==", "null", "||", "!", "oldValue", "."...
Reports a bound indexed property update to listeners that have been registered to track updates of all properties or a property with the specified name. <p> No event is fired if old and new values are equal and non-null. <p> This is merely a convenience wrapper around the more general {@link #firePropertyChange(PropertyChangeEvent)} method. @param propertyName the programmatic name of the property that was changed @param index the index of the property element that was changed @param oldValue the old value of the property @param newValue the new value of the property @since 1.5
[ "Reports", "a", "bound", "indexed", "property", "update", "to", "listeners", "that", "have", "been", "registered", "to", "track", "updates", "of", "all", "properties", "or", "a", "property", "with", "the", "specified", "name", ".", "<p", ">", "No", "event", ...
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/beans/PropertyChangeSupport.java#L356-L360