repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
218
func_name
stringlengths
4
140
whole_func_string
stringlengths
153
5.32k
language
stringclasses
1 value
func_code_string
stringlengths
72
4k
func_code_tokens
sequencelengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
sequencelengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
apereo/cas
support/cas-server-support-trusted-mfa/src/main/java/org/apereo/cas/trusted/authentication/api/MultifactorAuthenticationTrustRecord.java
MultifactorAuthenticationTrustRecord.newInstance
public static MultifactorAuthenticationTrustRecord newInstance(final String principal, final String geography, final String fingerprint) { """ New instance of authentication trust record. @param principal the principal @param geography the geography @param fingerprint the device fingerprint @return the authentication trust record """ val r = new MultifactorAuthenticationTrustRecord(); r.setRecordDate(LocalDateTime.now().truncatedTo(ChronoUnit.SECONDS)); r.setPrincipal(principal); r.setDeviceFingerprint(fingerprint); r.setName(principal.concat("-").concat(LocalDate.now().toString()).concat("-").concat(geography)); return r; }
java
public static MultifactorAuthenticationTrustRecord newInstance(final String principal, final String geography, final String fingerprint) { val r = new MultifactorAuthenticationTrustRecord(); r.setRecordDate(LocalDateTime.now().truncatedTo(ChronoUnit.SECONDS)); r.setPrincipal(principal); r.setDeviceFingerprint(fingerprint); r.setName(principal.concat("-").concat(LocalDate.now().toString()).concat("-").concat(geography)); return r; }
[ "public", "static", "MultifactorAuthenticationTrustRecord", "newInstance", "(", "final", "String", "principal", ",", "final", "String", "geography", ",", "final", "String", "fingerprint", ")", "{", "val", "r", "=", "new", "MultifactorAuthenticationTrustRecord", "(", ")", ";", "r", ".", "setRecordDate", "(", "LocalDateTime", ".", "now", "(", ")", ".", "truncatedTo", "(", "ChronoUnit", ".", "SECONDS", ")", ")", ";", "r", ".", "setPrincipal", "(", "principal", ")", ";", "r", ".", "setDeviceFingerprint", "(", "fingerprint", ")", ";", "r", ".", "setName", "(", "principal", ".", "concat", "(", "\"-\"", ")", ".", "concat", "(", "LocalDate", ".", "now", "(", ")", ".", "toString", "(", ")", ")", ".", "concat", "(", "\"-\"", ")", ".", "concat", "(", "geography", ")", ")", ";", "return", "r", ";", "}" ]
New instance of authentication trust record. @param principal the principal @param geography the geography @param fingerprint the device fingerprint @return the authentication trust record
[ "New", "instance", "of", "authentication", "trust", "record", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-trusted-mfa/src/main/java/org/apereo/cas/trusted/authentication/api/MultifactorAuthenticationTrustRecord.java#L83-L90
gallandarakhneorg/afc
advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/mapelement/MapPolygon.java
MapPolygon.intersects
@Override @Pure public boolean intersects(Shape2D<?, ?, ?, ?, ?, ? extends Rectangle2afp<?, ?, ?, ?, ?, ?>> rectangle) { """ Replies if this element has an intersection with the specified rectangle. @return <code>true</code> if this MapElement is intersecting the specified area, otherwise <code>false</code> """ if (boundsIntersects(rectangle)) { final Path2d p = toPath2D(); return p.intersects(rectangle); } return false; }
java
@Override @Pure public boolean intersects(Shape2D<?, ?, ?, ?, ?, ? extends Rectangle2afp<?, ?, ?, ?, ?, ?>> rectangle) { if (boundsIntersects(rectangle)) { final Path2d p = toPath2D(); return p.intersects(rectangle); } return false; }
[ "@", "Override", "@", "Pure", "public", "boolean", "intersects", "(", "Shape2D", "<", "?", ",", "?", ",", "?", ",", "?", ",", "?", ",", "?", "extends", "Rectangle2afp", "<", "?", ",", "?", ",", "?", ",", "?", ",", "?", ",", "?", ">", ">", "rectangle", ")", "{", "if", "(", "boundsIntersects", "(", "rectangle", ")", ")", "{", "final", "Path2d", "p", "=", "toPath2D", "(", ")", ";", "return", "p", ".", "intersects", "(", "rectangle", ")", ";", "}", "return", "false", ";", "}" ]
Replies if this element has an intersection with the specified rectangle. @return <code>true</code> if this MapElement is intersecting the specified area, otherwise <code>false</code>
[ "Replies", "if", "this", "element", "has", "an", "intersection", "with", "the", "specified", "rectangle", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/mapelement/MapPolygon.java#L138-L146
OpenLiberty/open-liberty
dev/com.ibm.ws.jaxws.common/src/com/ibm/ws/jaxws/client/LibertyServiceImpl.java
LibertyServiceImpl.prepareProperties
private void prepareProperties(QName portQName, Map<String, String> serviceRefProps, Map<String, String> portProps) throws IOException { """ merge the serviceRef properties and port properties, and update the merged properties in the configAdmin service. @param configAdmin @param serviceRefProps @param portProps @return @throws IOException """ // Merge the properties form port and service. Map<String, String> allProperties = new HashMap<String, String>(); if (null != serviceRefProps) { allProperties.putAll(serviceRefProps); } if (null != portProps) { allProperties.putAll(portProps); } for (Map.Entry<String, String> entry : servicePidToPropertyPrefixMap.entrySet()) { String serviceFactoryPid = entry.getKey(); String prefix = entry.getValue(); // Extract the properties according to different property prefix, // update the extracted properties by corresponding factory service. Map<String, String> extractProps = extract(prefix, allProperties); // Put the port QName and the properties into the servicePropertiesMap ConfigProperties configProps = new ConfigProperties(serviceFactoryPid, extractProps); Set<ConfigProperties> configSet = servicePropertiesMap.get(portQName); if (null == configSet) { configSet = new HashSet<ConfigProperties>(); servicePropertiesMap.put(portQName, configSet); } if (configSet.contains(configProps)) { // re-add the config props configSet.remove(configProps); configSet.add(configProps); } else { configSet.add(configProps); } } }
java
private void prepareProperties(QName portQName, Map<String, String> serviceRefProps, Map<String, String> portProps) throws IOException { // Merge the properties form port and service. Map<String, String> allProperties = new HashMap<String, String>(); if (null != serviceRefProps) { allProperties.putAll(serviceRefProps); } if (null != portProps) { allProperties.putAll(portProps); } for (Map.Entry<String, String> entry : servicePidToPropertyPrefixMap.entrySet()) { String serviceFactoryPid = entry.getKey(); String prefix = entry.getValue(); // Extract the properties according to different property prefix, // update the extracted properties by corresponding factory service. Map<String, String> extractProps = extract(prefix, allProperties); // Put the port QName and the properties into the servicePropertiesMap ConfigProperties configProps = new ConfigProperties(serviceFactoryPid, extractProps); Set<ConfigProperties> configSet = servicePropertiesMap.get(portQName); if (null == configSet) { configSet = new HashSet<ConfigProperties>(); servicePropertiesMap.put(portQName, configSet); } if (configSet.contains(configProps)) { // re-add the config props configSet.remove(configProps); configSet.add(configProps); } else { configSet.add(configProps); } } }
[ "private", "void", "prepareProperties", "(", "QName", "portQName", ",", "Map", "<", "String", ",", "String", ">", "serviceRefProps", ",", "Map", "<", "String", ",", "String", ">", "portProps", ")", "throws", "IOException", "{", "// Merge the properties form port and service.", "Map", "<", "String", ",", "String", ">", "allProperties", "=", "new", "HashMap", "<", "String", ",", "String", ">", "(", ")", ";", "if", "(", "null", "!=", "serviceRefProps", ")", "{", "allProperties", ".", "putAll", "(", "serviceRefProps", ")", ";", "}", "if", "(", "null", "!=", "portProps", ")", "{", "allProperties", ".", "putAll", "(", "portProps", ")", ";", "}", "for", "(", "Map", ".", "Entry", "<", "String", ",", "String", ">", "entry", ":", "servicePidToPropertyPrefixMap", ".", "entrySet", "(", ")", ")", "{", "String", "serviceFactoryPid", "=", "entry", ".", "getKey", "(", ")", ";", "String", "prefix", "=", "entry", ".", "getValue", "(", ")", ";", "// Extract the properties according to different property prefix,", "// update the extracted properties by corresponding factory service.", "Map", "<", "String", ",", "String", ">", "extractProps", "=", "extract", "(", "prefix", ",", "allProperties", ")", ";", "// Put the port QName and the properties into the servicePropertiesMap", "ConfigProperties", "configProps", "=", "new", "ConfigProperties", "(", "serviceFactoryPid", ",", "extractProps", ")", ";", "Set", "<", "ConfigProperties", ">", "configSet", "=", "servicePropertiesMap", ".", "get", "(", "portQName", ")", ";", "if", "(", "null", "==", "configSet", ")", "{", "configSet", "=", "new", "HashSet", "<", "ConfigProperties", ">", "(", ")", ";", "servicePropertiesMap", ".", "put", "(", "portQName", ",", "configSet", ")", ";", "}", "if", "(", "configSet", ".", "contains", "(", "configProps", ")", ")", "{", "// re-add the config props", "configSet", ".", "remove", "(", "configProps", ")", ";", "configSet", ".", "add", "(", "configProps", ")", ";", "}", "else", "{", "configSet", ".", "add", "(", "configProps", ")", ";", "}", "}", "}" ]
merge the serviceRef properties and port properties, and update the merged properties in the configAdmin service. @param configAdmin @param serviceRefProps @param portProps @return @throws IOException
[ "merge", "the", "serviceRef", "properties", "and", "port", "properties", "and", "update", "the", "merged", "properties", "in", "the", "configAdmin", "service", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jaxws.common/src/com/ibm/ws/jaxws/client/LibertyServiceImpl.java#L233-L269
kuali/ojb-1.0.4
src/java/org/apache/ojb/broker/core/PersistenceBrokerFactoryBaseImpl.java
PersistenceBrokerFactoryBaseImpl.createPersistenceBroker
public PersistenceBrokerInternal createPersistenceBroker(PBKey pbKey) throws PBFactoryException { """ Always return a new created {@link PersistenceBroker} instance @param pbKey @return @throws PBFactoryException """ if (log.isDebugEnabled()) log.debug("Obtain broker from pool, used PBKey is " + pbKey); /* try to find a valid PBKey, if given key does not full match */ pbKey = BrokerHelper.crossCheckPBKey(pbKey); try { return createNewBrokerInstance(pbKey); } catch (Exception e) { throw new PBFactoryException("Borrow broker from pool failed, using PBKey " + pbKey, e); } }
java
public PersistenceBrokerInternal createPersistenceBroker(PBKey pbKey) throws PBFactoryException { if (log.isDebugEnabled()) log.debug("Obtain broker from pool, used PBKey is " + pbKey); /* try to find a valid PBKey, if given key does not full match */ pbKey = BrokerHelper.crossCheckPBKey(pbKey); try { return createNewBrokerInstance(pbKey); } catch (Exception e) { throw new PBFactoryException("Borrow broker from pool failed, using PBKey " + pbKey, e); } }
[ "public", "PersistenceBrokerInternal", "createPersistenceBroker", "(", "PBKey", "pbKey", ")", "throws", "PBFactoryException", "{", "if", "(", "log", ".", "isDebugEnabled", "(", ")", ")", "log", ".", "debug", "(", "\"Obtain broker from pool, used PBKey is \"", "+", "pbKey", ")", ";", "/*\r\n try to find a valid PBKey, if given key does not full match\r\n */", "pbKey", "=", "BrokerHelper", ".", "crossCheckPBKey", "(", "pbKey", ")", ";", "try", "{", "return", "createNewBrokerInstance", "(", "pbKey", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "PBFactoryException", "(", "\"Borrow broker from pool failed, using PBKey \"", "+", "pbKey", ",", "e", ")", ";", "}", "}" ]
Always return a new created {@link PersistenceBroker} instance @param pbKey @return @throws PBFactoryException
[ "Always", "return", "a", "new", "created", "{", "@link", "PersistenceBroker", "}", "instance" ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/core/PersistenceBrokerFactoryBaseImpl.java#L124-L142
graphhopper/graphhopper
core/src/main/java/com/graphhopper/util/EngineWarmUp.java
EngineWarmUp.warmUp
public static void warmUp(GraphHopper graphHopper, int iterations) { """ Do the 'warm up' for the specified GraphHopper instance. @param iterations the 'intensity' of the warm up procedure """ GraphHopperStorage ghStorage = graphHopper.getGraphHopperStorage(); if (ghStorage == null) throw new IllegalArgumentException("The storage of GraphHopper must not be empty"); try { if (ghStorage.isCHPossible()) warmUpCHSubNetwork(graphHopper, iterations); else warmUpNonCHSubNetwork(graphHopper, iterations); } catch (Exception ex) { LOGGER.warn("Problem while sending warm up queries", ex); } }
java
public static void warmUp(GraphHopper graphHopper, int iterations) { GraphHopperStorage ghStorage = graphHopper.getGraphHopperStorage(); if (ghStorage == null) throw new IllegalArgumentException("The storage of GraphHopper must not be empty"); try { if (ghStorage.isCHPossible()) warmUpCHSubNetwork(graphHopper, iterations); else warmUpNonCHSubNetwork(graphHopper, iterations); } catch (Exception ex) { LOGGER.warn("Problem while sending warm up queries", ex); } }
[ "public", "static", "void", "warmUp", "(", "GraphHopper", "graphHopper", ",", "int", "iterations", ")", "{", "GraphHopperStorage", "ghStorage", "=", "graphHopper", ".", "getGraphHopperStorage", "(", ")", ";", "if", "(", "ghStorage", "==", "null", ")", "throw", "new", "IllegalArgumentException", "(", "\"The storage of GraphHopper must not be empty\"", ")", ";", "try", "{", "if", "(", "ghStorage", ".", "isCHPossible", "(", ")", ")", "warmUpCHSubNetwork", "(", "graphHopper", ",", "iterations", ")", ";", "else", "warmUpNonCHSubNetwork", "(", "graphHopper", ",", "iterations", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "LOGGER", ".", "warn", "(", "\"Problem while sending warm up queries\"", ",", "ex", ")", ";", "}", "}" ]
Do the 'warm up' for the specified GraphHopper instance. @param iterations the 'intensity' of the warm up procedure
[ "Do", "the", "warm", "up", "for", "the", "specified", "GraphHopper", "instance", "." ]
train
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/util/EngineWarmUp.java#L40-L53
micronaut-projects/micronaut-core
cli/src/main/groovy/io/micronaut/cli/util/NameUtils.java
NameUtils.getLogicalName
public static String getLogicalName(Class<?> clazz, String trailingName) { """ Retrieves the logical class name of a Micronaut artifact given the Micronaut class and a specified trailing name. @param clazz The class @param trailingName The trailing name such as "Controller" or "Service" @return The logical class name """ return getLogicalName(clazz.getName(), trailingName); }
java
public static String getLogicalName(Class<?> clazz, String trailingName) { return getLogicalName(clazz.getName(), trailingName); }
[ "public", "static", "String", "getLogicalName", "(", "Class", "<", "?", ">", "clazz", ",", "String", "trailingName", ")", "{", "return", "getLogicalName", "(", "clazz", ".", "getName", "(", ")", ",", "trailingName", ")", ";", "}" ]
Retrieves the logical class name of a Micronaut artifact given the Micronaut class and a specified trailing name. @param clazz The class @param trailingName The trailing name such as "Controller" or "Service" @return The logical class name
[ "Retrieves", "the", "logical", "class", "name", "of", "a", "Micronaut", "artifact", "given", "the", "Micronaut", "class", "and", "a", "specified", "trailing", "name", "." ]
train
https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/cli/src/main/groovy/io/micronaut/cli/util/NameUtils.java#L203-L205
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.jms.2.0/src/com/ibm/ws/sib/ra/inbound/impl/SibRaCommonEndpointActivation.java
SibRaCommonEndpointActivation.sessionError
@Override void sessionError(SibRaMessagingEngineConnection connection, ConsumerSession session, Throwable throwable) { """ A session error has occured on the connection, drop the connection and, if necessary, try to create a new connection """ final String methodName = "sessionError"; if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.entry(this, TRACE, methodName, new Object[] { connection, session }); } final SIDestinationAddress destination = session.getDestinationAddress(); SibTr.warning(TRACE, "CONSUMER_FAILED_CWSIV0770", new Object[] { destination.getDestinationName(), _endpointConfiguration.getBusName(), this, throwable }); dropConnection(connection, true, true, false); if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.exit(this, TRACE, methodName); } }
java
@Override void sessionError(SibRaMessagingEngineConnection connection, ConsumerSession session, Throwable throwable) { final String methodName = "sessionError"; if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.entry(this, TRACE, methodName, new Object[] { connection, session }); } final SIDestinationAddress destination = session.getDestinationAddress(); SibTr.warning(TRACE, "CONSUMER_FAILED_CWSIV0770", new Object[] { destination.getDestinationName(), _endpointConfiguration.getBusName(), this, throwable }); dropConnection(connection, true, true, false); if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.exit(this, TRACE, methodName); } }
[ "@", "Override", "void", "sessionError", "(", "SibRaMessagingEngineConnection", "connection", ",", "ConsumerSession", "session", ",", "Throwable", "throwable", ")", "{", "final", "String", "methodName", "=", "\"sessionError\"", ";", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "TRACE", ".", "isEntryEnabled", "(", ")", ")", "{", "SibTr", ".", "entry", "(", "this", ",", "TRACE", ",", "methodName", ",", "new", "Object", "[", "]", "{", "connection", ",", "session", "}", ")", ";", "}", "final", "SIDestinationAddress", "destination", "=", "session", ".", "getDestinationAddress", "(", ")", ";", "SibTr", ".", "warning", "(", "TRACE", ",", "\"CONSUMER_FAILED_CWSIV0770\"", ",", "new", "Object", "[", "]", "{", "destination", ".", "getDestinationName", "(", ")", ",", "_endpointConfiguration", ".", "getBusName", "(", ")", ",", "this", ",", "throwable", "}", ")", ";", "dropConnection", "(", "connection", ",", "true", ",", "true", ",", "false", ")", ";", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "TRACE", ".", "isEntryEnabled", "(", ")", ")", "{", "SibTr", ".", "exit", "(", "this", ",", "TRACE", ",", "methodName", ")", ";", "}", "}" ]
A session error has occured on the connection, drop the connection and, if necessary, try to create a new connection
[ "A", "session", "error", "has", "occured", "on", "the", "connection", "drop", "the", "connection", "and", "if", "necessary", "try", "to", "create", "a", "new", "connection" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.jms.2.0/src/com/ibm/ws/sib/ra/inbound/impl/SibRaCommonEndpointActivation.java#L1190-L1210
policeman-tools/forbidden-apis
src/main/java/de/thetaphi/forbiddenapis/AsmUtils.java
AsmUtils.binaryToInternal
public static String binaryToInternal(String clazz) { """ Converts a binary class name (dotted) to the JVM internal one (slashed). Only accepts valid class names, no arrays. """ if (clazz.indexOf('/') >= 0 || clazz.indexOf('[') >= 0) { throw new IllegalArgumentException(String.format(Locale.ENGLISH, "'%s' is not a valid binary class name.", clazz)); } return clazz.replace('.', '/'); }
java
public static String binaryToInternal(String clazz) { if (clazz.indexOf('/') >= 0 || clazz.indexOf('[') >= 0) { throw new IllegalArgumentException(String.format(Locale.ENGLISH, "'%s' is not a valid binary class name.", clazz)); } return clazz.replace('.', '/'); }
[ "public", "static", "String", "binaryToInternal", "(", "String", "clazz", ")", "{", "if", "(", "clazz", ".", "indexOf", "(", "'", "'", ")", ">=", "0", "||", "clazz", ".", "indexOf", "(", "'", "'", ")", ">=", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "String", ".", "format", "(", "Locale", ".", "ENGLISH", ",", "\"'%s' is not a valid binary class name.\"", ",", "clazz", ")", ")", ";", "}", "return", "clazz", ".", "replace", "(", "'", "'", ",", "'", "'", ")", ";", "}" ]
Converts a binary class name (dotted) to the JVM internal one (slashed). Only accepts valid class names, no arrays.
[ "Converts", "a", "binary", "class", "name", "(", "dotted", ")", "to", "the", "JVM", "internal", "one", "(", "slashed", ")", ".", "Only", "accepts", "valid", "class", "names", "no", "arrays", "." ]
train
https://github.com/policeman-tools/forbidden-apis/blob/df5f00c6bb779875ec6bae967f7cec96670b27d9/src/main/java/de/thetaphi/forbiddenapis/AsmUtils.java#L79-L84
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/BreakIterator.java
BreakIterator.registerInstance
public static Object registerInstance(BreakIterator iter, ULocale locale, int kind) { """ <strong>[icu]</strong> Registers a new break iterator of the indicated kind, to use in the given locale. Clones of the iterator will be returned if a request for a break iterator of the given kind matches or falls back to this locale. <p>Because ICU may choose to cache BreakIterator objects internally, this must be called at application startup, prior to any calls to BreakIterator.getInstance to avoid undefined behavior. @param iter the BreakIterator instance to adopt. @param locale the Locale for which this instance is to be registered @param kind the type of iterator for which this instance is to be registered @return a registry key that can be used to unregister this instance @hide unsupported on Android """ // If the registered object matches the one in the cache, then // flush the cached object. if (iterCache[kind] != null) { BreakIteratorCache cache = (BreakIteratorCache) iterCache[kind].get(); if (cache != null) { if (cache.getLocale().equals(locale)) { iterCache[kind] = null; } } } return getShim().registerInstance(iter, locale, kind); }
java
public static Object registerInstance(BreakIterator iter, ULocale locale, int kind) { // If the registered object matches the one in the cache, then // flush the cached object. if (iterCache[kind] != null) { BreakIteratorCache cache = (BreakIteratorCache) iterCache[kind].get(); if (cache != null) { if (cache.getLocale().equals(locale)) { iterCache[kind] = null; } } } return getShim().registerInstance(iter, locale, kind); }
[ "public", "static", "Object", "registerInstance", "(", "BreakIterator", "iter", ",", "ULocale", "locale", ",", "int", "kind", ")", "{", "// If the registered object matches the one in the cache, then", "// flush the cached object.", "if", "(", "iterCache", "[", "kind", "]", "!=", "null", ")", "{", "BreakIteratorCache", "cache", "=", "(", "BreakIteratorCache", ")", "iterCache", "[", "kind", "]", ".", "get", "(", ")", ";", "if", "(", "cache", "!=", "null", ")", "{", "if", "(", "cache", ".", "getLocale", "(", ")", ".", "equals", "(", "locale", ")", ")", "{", "iterCache", "[", "kind", "]", "=", "null", ";", "}", "}", "}", "return", "getShim", "(", ")", ".", "registerInstance", "(", "iter", ",", "locale", ",", "kind", ")", ";", "}" ]
<strong>[icu]</strong> Registers a new break iterator of the indicated kind, to use in the given locale. Clones of the iterator will be returned if a request for a break iterator of the given kind matches or falls back to this locale. <p>Because ICU may choose to cache BreakIterator objects internally, this must be called at application startup, prior to any calls to BreakIterator.getInstance to avoid undefined behavior. @param iter the BreakIterator instance to adopt. @param locale the Locale for which this instance is to be registered @param kind the type of iterator for which this instance is to be registered @return a registry key that can be used to unregister this instance @hide unsupported on Android
[ "<strong", ">", "[", "icu", "]", "<", "/", "strong", ">", "Registers", "a", "new", "break", "iterator", "of", "the", "indicated", "kind", "to", "use", "in", "the", "given", "locale", ".", "Clones", "of", "the", "iterator", "will", "be", "returned", "if", "a", "request", "for", "a", "break", "iterator", "of", "the", "given", "kind", "matches", "or", "falls", "back", "to", "this", "locale", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/BreakIterator.java#L748-L760
jpelzer/pelzer-util
src/main/java/com/pelzer/util/Timecode.java
Timecode.getToken
private int getToken(String inString, int index) throws Timecode.TimecodeException { """ Breaks a string on any non-numeric character and returns the index token, zero indexed """ inString = inString.trim(); String valid = "0123456789"; String token = ""; int count = 0; for (int i = 0; i < inString.length(); i++) { char current = inString.charAt(i); if (valid.indexOf(current) > -1) { token += current; } else { count++; if (count > index) break; // Found the token. token = ""; // Start reading the next token } } if (count < index || token.equals("")) throw new Timecode.TimecodeException("Malformed timecode '" + inString + "', can't get index=" + index); try { return Integer.parseInt(token); } catch (NumberFormatException ex) { throw new Timecode.TimecodeException("Malformed timecode '" + inString + "', '" + token + "' is not an integer"); } }
java
private int getToken(String inString, int index) throws Timecode.TimecodeException { inString = inString.trim(); String valid = "0123456789"; String token = ""; int count = 0; for (int i = 0; i < inString.length(); i++) { char current = inString.charAt(i); if (valid.indexOf(current) > -1) { token += current; } else { count++; if (count > index) break; // Found the token. token = ""; // Start reading the next token } } if (count < index || token.equals("")) throw new Timecode.TimecodeException("Malformed timecode '" + inString + "', can't get index=" + index); try { return Integer.parseInt(token); } catch (NumberFormatException ex) { throw new Timecode.TimecodeException("Malformed timecode '" + inString + "', '" + token + "' is not an integer"); } }
[ "private", "int", "getToken", "(", "String", "inString", ",", "int", "index", ")", "throws", "Timecode", ".", "TimecodeException", "{", "inString", "=", "inString", ".", "trim", "(", ")", ";", "String", "valid", "=", "\"0123456789\"", ";", "String", "token", "=", "\"\"", ";", "int", "count", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "inString", ".", "length", "(", ")", ";", "i", "++", ")", "{", "char", "current", "=", "inString", ".", "charAt", "(", "i", ")", ";", "if", "(", "valid", ".", "indexOf", "(", "current", ")", ">", "-", "1", ")", "{", "token", "+=", "current", ";", "}", "else", "{", "count", "++", ";", "if", "(", "count", ">", "index", ")", "break", ";", "// Found the token.\r", "token", "=", "\"\"", ";", "// Start reading the next token\r", "}", "}", "if", "(", "count", "<", "index", "||", "token", ".", "equals", "(", "\"\"", ")", ")", "throw", "new", "Timecode", ".", "TimecodeException", "(", "\"Malformed timecode '\"", "+", "inString", "+", "\"', can't get index=\"", "+", "index", ")", ";", "try", "{", "return", "Integer", ".", "parseInt", "(", "token", ")", ";", "}", "catch", "(", "NumberFormatException", "ex", ")", "{", "throw", "new", "Timecode", ".", "TimecodeException", "(", "\"Malformed timecode '\"", "+", "inString", "+", "\"', '\"", "+", "token", "+", "\"' is not an integer\"", ")", ";", "}", "}" ]
Breaks a string on any non-numeric character and returns the index token, zero indexed
[ "Breaks", "a", "string", "on", "any", "non", "-", "numeric", "character", "and", "returns", "the", "index", "token", "zero", "indexed" ]
train
https://github.com/jpelzer/pelzer-util/blob/ec14f2573fd977d1442dba5d1507a264f5ea9aa6/src/main/java/com/pelzer/util/Timecode.java#L376-L399
Omertron/api-rottentomatoes
src/main/java/com/omertron/rottentomatoesapi/RottenTomatoesApi.java
RottenTomatoesApi.getMoviesSearch
public List<RTMovie> getMoviesSearch(String query, int pageLimit, int page) throws RottenTomatoesException { """ The movies search endpoint for plain text queries. Let's you search for movies! @param query @param pageLimit @param page @return @throws RottenTomatoesException """ properties.clear(); properties.put(ApiBuilder.PROPERTY_URL, URL_MOVIES_SEARCH); properties.put(ApiBuilder.PROPERTY_PAGE_LIMIT, ApiBuilder.validatePageLimit(pageLimit)); properties.put(ApiBuilder.PROPERTY_PAGE, ApiBuilder.validatePage(page)); try { properties.put(ApiBuilder.PROPERTY_QUERY, URLEncoder.encode(query, ENCODING_UTF8)); } catch (UnsupportedEncodingException ex) { throw new RottenTomatoesException(ApiExceptionType.MAPPING_FAILED, "Failed to encode URL", query, ex); } WrapperLists wrapper = response.getResponse(WrapperLists.class, properties); if (wrapper != null && wrapper.getMovies() != null) { return wrapper.getMovies(); } else { return Collections.emptyList(); } }
java
public List<RTMovie> getMoviesSearch(String query, int pageLimit, int page) throws RottenTomatoesException { properties.clear(); properties.put(ApiBuilder.PROPERTY_URL, URL_MOVIES_SEARCH); properties.put(ApiBuilder.PROPERTY_PAGE_LIMIT, ApiBuilder.validatePageLimit(pageLimit)); properties.put(ApiBuilder.PROPERTY_PAGE, ApiBuilder.validatePage(page)); try { properties.put(ApiBuilder.PROPERTY_QUERY, URLEncoder.encode(query, ENCODING_UTF8)); } catch (UnsupportedEncodingException ex) { throw new RottenTomatoesException(ApiExceptionType.MAPPING_FAILED, "Failed to encode URL", query, ex); } WrapperLists wrapper = response.getResponse(WrapperLists.class, properties); if (wrapper != null && wrapper.getMovies() != null) { return wrapper.getMovies(); } else { return Collections.emptyList(); } }
[ "public", "List", "<", "RTMovie", ">", "getMoviesSearch", "(", "String", "query", ",", "int", "pageLimit", ",", "int", "page", ")", "throws", "RottenTomatoesException", "{", "properties", ".", "clear", "(", ")", ";", "properties", ".", "put", "(", "ApiBuilder", ".", "PROPERTY_URL", ",", "URL_MOVIES_SEARCH", ")", ";", "properties", ".", "put", "(", "ApiBuilder", ".", "PROPERTY_PAGE_LIMIT", ",", "ApiBuilder", ".", "validatePageLimit", "(", "pageLimit", ")", ")", ";", "properties", ".", "put", "(", "ApiBuilder", ".", "PROPERTY_PAGE", ",", "ApiBuilder", ".", "validatePage", "(", "page", ")", ")", ";", "try", "{", "properties", ".", "put", "(", "ApiBuilder", ".", "PROPERTY_QUERY", ",", "URLEncoder", ".", "encode", "(", "query", ",", "ENCODING_UTF8", ")", ")", ";", "}", "catch", "(", "UnsupportedEncodingException", "ex", ")", "{", "throw", "new", "RottenTomatoesException", "(", "ApiExceptionType", ".", "MAPPING_FAILED", ",", "\"Failed to encode URL\"", ",", "query", ",", "ex", ")", ";", "}", "WrapperLists", "wrapper", "=", "response", ".", "getResponse", "(", "WrapperLists", ".", "class", ",", "properties", ")", ";", "if", "(", "wrapper", "!=", "null", "&&", "wrapper", ".", "getMovies", "(", ")", "!=", "null", ")", "{", "return", "wrapper", ".", "getMovies", "(", ")", ";", "}", "else", "{", "return", "Collections", ".", "emptyList", "(", ")", ";", "}", "}" ]
The movies search endpoint for plain text queries. Let's you search for movies! @param query @param pageLimit @param page @return @throws RottenTomatoesException
[ "The", "movies", "search", "endpoint", "for", "plain", "text", "queries", ".", "Let", "s", "you", "search", "for", "movies!" ]
train
https://github.com/Omertron/api-rottentomatoes/blob/abaf1833acafc6ada593d52b14ff1bacb4e441ee/src/main/java/com/omertron/rottentomatoesapi/RottenTomatoesApi.java#L682-L700
box/box-java-sdk
src/main/java/com/box/sdk/BoxGroup.java
BoxGroup.addMembership
public BoxGroupMembership.Info addMembership(BoxUser user, Role role) { """ Adds a member to this group with the specified role. @param user the member to be added to this group. @param role the role of the user in this group. Can be null to assign the default role. @return info about the new group membership. """ BoxAPIConnection api = this.getAPI(); JsonObject requestJSON = new JsonObject(); requestJSON.add("user", new JsonObject().add("id", user.getID())); requestJSON.add("group", new JsonObject().add("id", this.getID())); if (role != null) { requestJSON.add("role", role.toJSONString()); } URL url = ADD_MEMBERSHIP_URL_TEMPLATE.build(api.getBaseURL()); BoxJSONRequest request = new BoxJSONRequest(api, url, "POST"); request.setBody(requestJSON.toString()); BoxJSONResponse response = (BoxJSONResponse) request.send(); JsonObject responseJSON = JsonObject.readFrom(response.getJSON()); BoxGroupMembership membership = new BoxGroupMembership(api, responseJSON.get("id").asString()); return membership.new Info(responseJSON); }
java
public BoxGroupMembership.Info addMembership(BoxUser user, Role role) { BoxAPIConnection api = this.getAPI(); JsonObject requestJSON = new JsonObject(); requestJSON.add("user", new JsonObject().add("id", user.getID())); requestJSON.add("group", new JsonObject().add("id", this.getID())); if (role != null) { requestJSON.add("role", role.toJSONString()); } URL url = ADD_MEMBERSHIP_URL_TEMPLATE.build(api.getBaseURL()); BoxJSONRequest request = new BoxJSONRequest(api, url, "POST"); request.setBody(requestJSON.toString()); BoxJSONResponse response = (BoxJSONResponse) request.send(); JsonObject responseJSON = JsonObject.readFrom(response.getJSON()); BoxGroupMembership membership = new BoxGroupMembership(api, responseJSON.get("id").asString()); return membership.new Info(responseJSON); }
[ "public", "BoxGroupMembership", ".", "Info", "addMembership", "(", "BoxUser", "user", ",", "Role", "role", ")", "{", "BoxAPIConnection", "api", "=", "this", ".", "getAPI", "(", ")", ";", "JsonObject", "requestJSON", "=", "new", "JsonObject", "(", ")", ";", "requestJSON", ".", "add", "(", "\"user\"", ",", "new", "JsonObject", "(", ")", ".", "add", "(", "\"id\"", ",", "user", ".", "getID", "(", ")", ")", ")", ";", "requestJSON", ".", "add", "(", "\"group\"", ",", "new", "JsonObject", "(", ")", ".", "add", "(", "\"id\"", ",", "this", ".", "getID", "(", ")", ")", ")", ";", "if", "(", "role", "!=", "null", ")", "{", "requestJSON", ".", "add", "(", "\"role\"", ",", "role", ".", "toJSONString", "(", ")", ")", ";", "}", "URL", "url", "=", "ADD_MEMBERSHIP_URL_TEMPLATE", ".", "build", "(", "api", ".", "getBaseURL", "(", ")", ")", ";", "BoxJSONRequest", "request", "=", "new", "BoxJSONRequest", "(", "api", ",", "url", ",", "\"POST\"", ")", ";", "request", ".", "setBody", "(", "requestJSON", ".", "toString", "(", ")", ")", ";", "BoxJSONResponse", "response", "=", "(", "BoxJSONResponse", ")", "request", ".", "send", "(", ")", ";", "JsonObject", "responseJSON", "=", "JsonObject", ".", "readFrom", "(", "response", ".", "getJSON", "(", ")", ")", ";", "BoxGroupMembership", "membership", "=", "new", "BoxGroupMembership", "(", "api", ",", "responseJSON", ".", "get", "(", "\"id\"", ")", ".", "asString", "(", ")", ")", ";", "return", "membership", ".", "new", "Info", "(", "responseJSON", ")", ";", "}" ]
Adds a member to this group with the specified role. @param user the member to be added to this group. @param role the role of the user in this group. Can be null to assign the default role. @return info about the new group membership.
[ "Adds", "a", "member", "to", "this", "group", "with", "the", "specified", "role", "." ]
train
https://github.com/box/box-java-sdk/blob/35b4ba69417f9d6a002c19dfaab57527750ef349/src/main/java/com/box/sdk/BoxGroup.java#L254-L272
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/jdbc/cloud/storage/SnowflakeAzureClient.java
SnowflakeAzureClient.setupAzureClient
private void setupAzureClient(StageInfo stage, RemoteStoreFileEncryptionMaterial encMat) throws IllegalArgumentException, SnowflakeSQLException { """ /* Initializes the Azure client This method is used during the object contruction, but also to reset/recreate the encapsulated CloudBlobClient object with new credentials (after SAS token expiration) @param stage The stage information that the client will operate on @param encMat The encryption material required to decrypt/encrypt content in stage @throws IllegalArgumentException when invalid credentials are used """ // Save the client creation parameters so that we can reuse them, // to reset the Azure client. this.stageInfo = stage; this.encMat = encMat; logger.debug("Setting up the Azure client "); try { URI storageEndpoint = buildAzureStorageEndpointURI(stage.getEndPoint(), stage.getStorageAccount()); StorageCredentials azCreds; String sasToken = (String) stage.getCredentials().get("AZURE_SAS_TOKEN"); if (sasToken != null) { // We are authenticated with a shared access token. azCreds = new StorageCredentialsSharedAccessSignature(sasToken); } else { // Use anonymous authentication. azCreds = StorageCredentialsAnonymous.ANONYMOUS; } if (encMat != null) { byte[] decodedKey = Base64.decode(encMat.getQueryStageMasterKey()); encryptionKeySize = decodedKey.length * 8; if (encryptionKeySize != 128 && encryptionKeySize != 192 && encryptionKeySize != 256) { throw new SnowflakeSQLException(SqlState.INTERNAL_ERROR, ErrorCode.INTERNAL_ERROR.getMessageCode(), "unsupported key size", encryptionKeySize); } } this.azStorageClient = new CloudBlobClient(storageEndpoint, azCreds); } catch (URISyntaxException ex) { throw new IllegalArgumentException("invalid_azure_credentials"); } }
java
private void setupAzureClient(StageInfo stage, RemoteStoreFileEncryptionMaterial encMat) throws IllegalArgumentException, SnowflakeSQLException { // Save the client creation parameters so that we can reuse them, // to reset the Azure client. this.stageInfo = stage; this.encMat = encMat; logger.debug("Setting up the Azure client "); try { URI storageEndpoint = buildAzureStorageEndpointURI(stage.getEndPoint(), stage.getStorageAccount()); StorageCredentials azCreds; String sasToken = (String) stage.getCredentials().get("AZURE_SAS_TOKEN"); if (sasToken != null) { // We are authenticated with a shared access token. azCreds = new StorageCredentialsSharedAccessSignature(sasToken); } else { // Use anonymous authentication. azCreds = StorageCredentialsAnonymous.ANONYMOUS; } if (encMat != null) { byte[] decodedKey = Base64.decode(encMat.getQueryStageMasterKey()); encryptionKeySize = decodedKey.length * 8; if (encryptionKeySize != 128 && encryptionKeySize != 192 && encryptionKeySize != 256) { throw new SnowflakeSQLException(SqlState.INTERNAL_ERROR, ErrorCode.INTERNAL_ERROR.getMessageCode(), "unsupported key size", encryptionKeySize); } } this.azStorageClient = new CloudBlobClient(storageEndpoint, azCreds); } catch (URISyntaxException ex) { throw new IllegalArgumentException("invalid_azure_credentials"); } }
[ "private", "void", "setupAzureClient", "(", "StageInfo", "stage", ",", "RemoteStoreFileEncryptionMaterial", "encMat", ")", "throws", "IllegalArgumentException", ",", "SnowflakeSQLException", "{", "// Save the client creation parameters so that we can reuse them,", "// to reset the Azure client.", "this", ".", "stageInfo", "=", "stage", ";", "this", ".", "encMat", "=", "encMat", ";", "logger", ".", "debug", "(", "\"Setting up the Azure client \"", ")", ";", "try", "{", "URI", "storageEndpoint", "=", "buildAzureStorageEndpointURI", "(", "stage", ".", "getEndPoint", "(", ")", ",", "stage", ".", "getStorageAccount", "(", ")", ")", ";", "StorageCredentials", "azCreds", ";", "String", "sasToken", "=", "(", "String", ")", "stage", ".", "getCredentials", "(", ")", ".", "get", "(", "\"AZURE_SAS_TOKEN\"", ")", ";", "if", "(", "sasToken", "!=", "null", ")", "{", "// We are authenticated with a shared access token.", "azCreds", "=", "new", "StorageCredentialsSharedAccessSignature", "(", "sasToken", ")", ";", "}", "else", "{", "// Use anonymous authentication.", "azCreds", "=", "StorageCredentialsAnonymous", ".", "ANONYMOUS", ";", "}", "if", "(", "encMat", "!=", "null", ")", "{", "byte", "[", "]", "decodedKey", "=", "Base64", ".", "decode", "(", "encMat", ".", "getQueryStageMasterKey", "(", ")", ")", ";", "encryptionKeySize", "=", "decodedKey", ".", "length", "*", "8", ";", "if", "(", "encryptionKeySize", "!=", "128", "&&", "encryptionKeySize", "!=", "192", "&&", "encryptionKeySize", "!=", "256", ")", "{", "throw", "new", "SnowflakeSQLException", "(", "SqlState", ".", "INTERNAL_ERROR", ",", "ErrorCode", ".", "INTERNAL_ERROR", ".", "getMessageCode", "(", ")", ",", "\"unsupported key size\"", ",", "encryptionKeySize", ")", ";", "}", "}", "this", ".", "azStorageClient", "=", "new", "CloudBlobClient", "(", "storageEndpoint", ",", "azCreds", ")", ";", "}", "catch", "(", "URISyntaxException", "ex", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"invalid_azure_credentials\"", ")", ";", "}", "}" ]
/* Initializes the Azure client This method is used during the object contruction, but also to reset/recreate the encapsulated CloudBlobClient object with new credentials (after SAS token expiration) @param stage The stage information that the client will operate on @param encMat The encryption material required to decrypt/encrypt content in stage @throws IllegalArgumentException when invalid credentials are used
[ "/", "*", "Initializes", "the", "Azure", "client", "This", "method", "is", "used", "during", "the", "object", "contruction", "but", "also", "to", "reset", "/", "recreate", "the", "encapsulated", "CloudBlobClient", "object", "with", "new", "credentials", "(", "after", "SAS", "token", "expiration", ")" ]
train
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/jdbc/cloud/storage/SnowflakeAzureClient.java#L111-L158
eclipse/hawkbit
hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/TargetAssignmentOperations.java
TargetAssignmentOperations.createAssignmentTab
public static ConfirmationTab createAssignmentTab( final ActionTypeOptionGroupAssignmentLayout actionTypeOptionGroupLayout, final MaintenanceWindowLayout maintenanceWindowLayout, final Consumer<Boolean> saveButtonToggle, final VaadinMessageSource i18n, final UiProperties uiProperties) { """ Create the Assignment Confirmation Tab @param actionTypeOptionGroupLayout the action Type Option Group Layout @param maintenanceWindowLayout the Maintenance Window Layout @param saveButtonToggle The event listener to derimne if save button should be enabled or not @param i18n the Vaadin Message Source for multi language @param uiProperties the UI Properties @return the Assignment Confirmation tab """ final CheckBox maintenanceWindowControl = maintenanceWindowControl(i18n, maintenanceWindowLayout, saveButtonToggle); final Link maintenanceWindowHelpLink = maintenanceWindowHelpLinkControl(uiProperties, i18n); final HorizontalLayout layout = createHorizontalLayout(maintenanceWindowControl, maintenanceWindowHelpLink); actionTypeOptionGroupLayout.selectDefaultOption(); initMaintenanceWindow(maintenanceWindowLayout, saveButtonToggle); addValueChangeListener(actionTypeOptionGroupLayout, maintenanceWindowControl, maintenanceWindowHelpLink); return createAssignmentTab(actionTypeOptionGroupLayout, layout, maintenanceWindowLayout); }
java
public static ConfirmationTab createAssignmentTab( final ActionTypeOptionGroupAssignmentLayout actionTypeOptionGroupLayout, final MaintenanceWindowLayout maintenanceWindowLayout, final Consumer<Boolean> saveButtonToggle, final VaadinMessageSource i18n, final UiProperties uiProperties) { final CheckBox maintenanceWindowControl = maintenanceWindowControl(i18n, maintenanceWindowLayout, saveButtonToggle); final Link maintenanceWindowHelpLink = maintenanceWindowHelpLinkControl(uiProperties, i18n); final HorizontalLayout layout = createHorizontalLayout(maintenanceWindowControl, maintenanceWindowHelpLink); actionTypeOptionGroupLayout.selectDefaultOption(); initMaintenanceWindow(maintenanceWindowLayout, saveButtonToggle); addValueChangeListener(actionTypeOptionGroupLayout, maintenanceWindowControl, maintenanceWindowHelpLink); return createAssignmentTab(actionTypeOptionGroupLayout, layout, maintenanceWindowLayout); }
[ "public", "static", "ConfirmationTab", "createAssignmentTab", "(", "final", "ActionTypeOptionGroupAssignmentLayout", "actionTypeOptionGroupLayout", ",", "final", "MaintenanceWindowLayout", "maintenanceWindowLayout", ",", "final", "Consumer", "<", "Boolean", ">", "saveButtonToggle", ",", "final", "VaadinMessageSource", "i18n", ",", "final", "UiProperties", "uiProperties", ")", "{", "final", "CheckBox", "maintenanceWindowControl", "=", "maintenanceWindowControl", "(", "i18n", ",", "maintenanceWindowLayout", ",", "saveButtonToggle", ")", ";", "final", "Link", "maintenanceWindowHelpLink", "=", "maintenanceWindowHelpLinkControl", "(", "uiProperties", ",", "i18n", ")", ";", "final", "HorizontalLayout", "layout", "=", "createHorizontalLayout", "(", "maintenanceWindowControl", ",", "maintenanceWindowHelpLink", ")", ";", "actionTypeOptionGroupLayout", ".", "selectDefaultOption", "(", ")", ";", "initMaintenanceWindow", "(", "maintenanceWindowLayout", ",", "saveButtonToggle", ")", ";", "addValueChangeListener", "(", "actionTypeOptionGroupLayout", ",", "maintenanceWindowControl", ",", "maintenanceWindowHelpLink", ")", ";", "return", "createAssignmentTab", "(", "actionTypeOptionGroupLayout", ",", "layout", ",", "maintenanceWindowLayout", ")", ";", "}" ]
Create the Assignment Confirmation Tab @param actionTypeOptionGroupLayout the action Type Option Group Layout @param maintenanceWindowLayout the Maintenance Window Layout @param saveButtonToggle The event listener to derimne if save button should be enabled or not @param i18n the Vaadin Message Source for multi language @param uiProperties the UI Properties @return the Assignment Confirmation tab
[ "Create", "the", "Assignment", "Confirmation", "Tab" ]
train
https://github.com/eclipse/hawkbit/blob/9884452ad42f3b4827461606d8a9215c8625a7fe/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/TargetAssignmentOperations.java#L197-L211
openbase/jul
exception/src/main/java/org/openbase/jul/exception/StackTracePrinter.java
StackTracePrinter.printAllStackTraces
public static void printAllStackTraces(final String filter, final Logger logger, final LogLevel logLevel) { """ Method prints the stack traces of all running java threads via the given logger. @param filter only thread where the name of the thread contains this given {@code filter} key are printed. If the filter is null, no filtering will be performed. @param logger the logger used for printing. @param logLevel the level to print. """ for (Map.Entry<Thread, StackTraceElement[]> entry : Thread.getAllStackTraces().entrySet()) { if (filter == null || entry.getKey().getName().contains(filter)) { StackTracePrinter.printStackTrace("Thread[" + entry.getKey().getName() + "] state[" + entry.getKey().getState().name() + "]", entry.getValue(), logger, logLevel); } } }
java
public static void printAllStackTraces(final String filter, final Logger logger, final LogLevel logLevel) { for (Map.Entry<Thread, StackTraceElement[]> entry : Thread.getAllStackTraces().entrySet()) { if (filter == null || entry.getKey().getName().contains(filter)) { StackTracePrinter.printStackTrace("Thread[" + entry.getKey().getName() + "] state[" + entry.getKey().getState().name() + "]", entry.getValue(), logger, logLevel); } } }
[ "public", "static", "void", "printAllStackTraces", "(", "final", "String", "filter", ",", "final", "Logger", "logger", ",", "final", "LogLevel", "logLevel", ")", "{", "for", "(", "Map", ".", "Entry", "<", "Thread", ",", "StackTraceElement", "[", "]", ">", "entry", ":", "Thread", ".", "getAllStackTraces", "(", ")", ".", "entrySet", "(", ")", ")", "{", "if", "(", "filter", "==", "null", "||", "entry", ".", "getKey", "(", ")", ".", "getName", "(", ")", ".", "contains", "(", "filter", ")", ")", "{", "StackTracePrinter", ".", "printStackTrace", "(", "\"Thread[\"", "+", "entry", ".", "getKey", "(", ")", ".", "getName", "(", ")", "+", "\"] state[\"", "+", "entry", ".", "getKey", "(", ")", ".", "getState", "(", ")", ".", "name", "(", ")", "+", "\"]\"", ",", "entry", ".", "getValue", "(", ")", ",", "logger", ",", "logLevel", ")", ";", "}", "}", "}" ]
Method prints the stack traces of all running java threads via the given logger. @param filter only thread where the name of the thread contains this given {@code filter} key are printed. If the filter is null, no filtering will be performed. @param logger the logger used for printing. @param logLevel the level to print.
[ "Method", "prints", "the", "stack", "traces", "of", "all", "running", "java", "threads", "via", "the", "given", "logger", "." ]
train
https://github.com/openbase/jul/blob/662e98c3a853085e475be54c3be3deb72193c72d/exception/src/main/java/org/openbase/jul/exception/StackTracePrinter.java#L150-L156
undertow-io/undertow
core/src/main/java/io/undertow/protocols/ssl/SNISSLExplorer.java
SNISSLExplorer.exploreExtensions
private static ExtensionInfo exploreExtensions(ByteBuffer input) throws SSLException { """ /* struct { ExtensionType extension_type; opaque extension_data<0..2^16-1>; } Extension; enum { server_name(0), max_fragment_length(1), client_certificate_url(2), trusted_ca_keys(3), truncated_hmac(4), status_request(5), (65535) } ExtensionType; """ List<SNIServerName> sni = Collections.emptyList(); List<String> alpn = Collections.emptyList(); int length = getInt16(input); // length of extensions while (length > 0) { int extType = getInt16(input); // extension type int extLen = getInt16(input); // length of extension data if (extType == 0x00) { // 0x00: type of server name indication sni = exploreSNIExt(input, extLen); } else if (extType == 0x10) { // 0x10: type of alpn alpn = exploreALPN(input, extLen); } else { // ignore other extensions ignoreByteVector(input, extLen); } length -= extLen + 4; } return new ExtensionInfo(sni, alpn); }
java
private static ExtensionInfo exploreExtensions(ByteBuffer input) throws SSLException { List<SNIServerName> sni = Collections.emptyList(); List<String> alpn = Collections.emptyList(); int length = getInt16(input); // length of extensions while (length > 0) { int extType = getInt16(input); // extension type int extLen = getInt16(input); // length of extension data if (extType == 0x00) { // 0x00: type of server name indication sni = exploreSNIExt(input, extLen); } else if (extType == 0x10) { // 0x10: type of alpn alpn = exploreALPN(input, extLen); } else { // ignore other extensions ignoreByteVector(input, extLen); } length -= extLen + 4; } return new ExtensionInfo(sni, alpn); }
[ "private", "static", "ExtensionInfo", "exploreExtensions", "(", "ByteBuffer", "input", ")", "throws", "SSLException", "{", "List", "<", "SNIServerName", ">", "sni", "=", "Collections", ".", "emptyList", "(", ")", ";", "List", "<", "String", ">", "alpn", "=", "Collections", ".", "emptyList", "(", ")", ";", "int", "length", "=", "getInt16", "(", "input", ")", ";", "// length of extensions", "while", "(", "length", ">", "0", ")", "{", "int", "extType", "=", "getInt16", "(", "input", ")", ";", "// extension type", "int", "extLen", "=", "getInt16", "(", "input", ")", ";", "// length of extension data", "if", "(", "extType", "==", "0x00", ")", "{", "// 0x00: type of server name indication", "sni", "=", "exploreSNIExt", "(", "input", ",", "extLen", ")", ";", "}", "else", "if", "(", "extType", "==", "0x10", ")", "{", "// 0x10: type of alpn", "alpn", "=", "exploreALPN", "(", "input", ",", "extLen", ")", ";", "}", "else", "{", "// ignore other extensions", "ignoreByteVector", "(", "input", ",", "extLen", ")", ";", "}", "length", "-=", "extLen", "+", "4", ";", "}", "return", "new", "ExtensionInfo", "(", "sni", ",", "alpn", ")", ";", "}" ]
/* struct { ExtensionType extension_type; opaque extension_data<0..2^16-1>; } Extension; enum { server_name(0), max_fragment_length(1), client_certificate_url(2), trusted_ca_keys(3), truncated_hmac(4), status_request(5), (65535) } ExtensionType;
[ "/", "*", "struct", "{", "ExtensionType", "extension_type", ";", "opaque", "extension_data<0", "..", "2^16", "-", "1", ">", ";", "}", "Extension", ";" ]
train
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/protocols/ssl/SNISSLExplorer.java#L377-L400
UrielCh/ovh-java-sdk
ovh-java-sdk-dedicatedserver/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedserver.java
ApiOvhDedicatedserver.serviceName_statistics_raid_unit_volume_volume_port_port_GET
public OvhRtmRaidVolumePort serviceName_statistics_raid_unit_volume_volume_port_port_GET(String serviceName, String unit, String volume, String port) throws IOException { """ Get this object properties REST: GET /dedicated/server/{serviceName}/statistics/raid/{unit}/volume/{volume}/port/{port} @param serviceName [required] The internal name of your dedicated server @param unit [required] Raid unit @param volume [required] Raid volume name @param port [required] Raid volume port """ String qPath = "/dedicated/server/{serviceName}/statistics/raid/{unit}/volume/{volume}/port/{port}"; StringBuilder sb = path(qPath, serviceName, unit, volume, port); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhRtmRaidVolumePort.class); }
java
public OvhRtmRaidVolumePort serviceName_statistics_raid_unit_volume_volume_port_port_GET(String serviceName, String unit, String volume, String port) throws IOException { String qPath = "/dedicated/server/{serviceName}/statistics/raid/{unit}/volume/{volume}/port/{port}"; StringBuilder sb = path(qPath, serviceName, unit, volume, port); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhRtmRaidVolumePort.class); }
[ "public", "OvhRtmRaidVolumePort", "serviceName_statistics_raid_unit_volume_volume_port_port_GET", "(", "String", "serviceName", ",", "String", "unit", ",", "String", "volume", ",", "String", "port", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/dedicated/server/{serviceName}/statistics/raid/{unit}/volume/{volume}/port/{port}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ",", "unit", ",", "volume", ",", "port", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhRtmRaidVolumePort", ".", "class", ")", ";", "}" ]
Get this object properties REST: GET /dedicated/server/{serviceName}/statistics/raid/{unit}/volume/{volume}/port/{port} @param serviceName [required] The internal name of your dedicated server @param unit [required] Raid unit @param volume [required] Raid volume name @param port [required] Raid volume port
[ "Get", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dedicatedserver/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedserver.java#L1417-L1422
alkacon/opencms-core
src/org/opencms/util/CmsFileUtil.java
CmsFileUtil.walkFileSystem
public static void walkFileSystem(File base, Closure action) { """ Traverses the file system starting from a base folder and executes a callback for every directory found.<p> @param base the base folder @param action a callback which will be passed a FileWalkState object for every directory encountered """ List<FileWalkState> m_states = new ArrayList<FileWalkState>(); m_states.add(createFileWalkState(base)); while (!m_states.isEmpty()) { // pop the top off the state stack, process it, then push states for all subdirectories onto it FileWalkState last = m_states.remove(m_states.size() - 1); action.execute(last); for (File dir : last.getDirectories()) { m_states.add(createFileWalkState(dir)); } } }
java
public static void walkFileSystem(File base, Closure action) { List<FileWalkState> m_states = new ArrayList<FileWalkState>(); m_states.add(createFileWalkState(base)); while (!m_states.isEmpty()) { // pop the top off the state stack, process it, then push states for all subdirectories onto it FileWalkState last = m_states.remove(m_states.size() - 1); action.execute(last); for (File dir : last.getDirectories()) { m_states.add(createFileWalkState(dir)); } } }
[ "public", "static", "void", "walkFileSystem", "(", "File", "base", ",", "Closure", "action", ")", "{", "List", "<", "FileWalkState", ">", "m_states", "=", "new", "ArrayList", "<", "FileWalkState", ">", "(", ")", ";", "m_states", ".", "add", "(", "createFileWalkState", "(", "base", ")", ")", ";", "while", "(", "!", "m_states", ".", "isEmpty", "(", ")", ")", "{", "// pop the top off the state stack, process it, then push states for all subdirectories onto it", "FileWalkState", "last", "=", "m_states", ".", "remove", "(", "m_states", ".", "size", "(", ")", "-", "1", ")", ";", "action", ".", "execute", "(", "last", ")", ";", "for", "(", "File", "dir", ":", "last", ".", "getDirectories", "(", ")", ")", "{", "m_states", ".", "add", "(", "createFileWalkState", "(", "dir", ")", ")", ";", "}", "}", "}" ]
Traverses the file system starting from a base folder and executes a callback for every directory found.<p> @param base the base folder @param action a callback which will be passed a FileWalkState object for every directory encountered
[ "Traverses", "the", "file", "system", "starting", "from", "a", "base", "folder", "and", "executes", "a", "callback", "for", "every", "directory", "found", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/util/CmsFileUtil.java#L943-L955
aws/aws-sdk-java
aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/StartSessionRequest.java
StartSessionRequest.setParameters
public void setParameters(java.util.Map<String, java.util.List<String>> parameters) { """ <p> Reserved for future use. </p> @param parameters Reserved for future use. """ this.parameters = parameters; }
java
public void setParameters(java.util.Map<String, java.util.List<String>> parameters) { this.parameters = parameters; }
[ "public", "void", "setParameters", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "java", ".", "util", ".", "List", "<", "String", ">", ">", "parameters", ")", "{", "this", ".", "parameters", "=", "parameters", ";", "}" ]
<p> Reserved for future use. </p> @param parameters Reserved for future use.
[ "<p", ">", "Reserved", "for", "future", "use", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/StartSessionRequest.java#L162-L164
Azure/azure-sdk-for-java
compute/resource-manager/v2017_03_30/src/main/java/com/microsoft/azure/management/compute/v2017_03_30/implementation/VirtualMachineScaleSetRollingUpgradesInner.java
VirtualMachineScaleSetRollingUpgradesInner.beginStartOSUpgrade
public OperationStatusResponseInner beginStartOSUpgrade(String resourceGroupName, String vmScaleSetName) { """ Starts a rolling upgrade to move all virtual machine scale set instances to the latest available Platform Image OS version. Instances which are already running the latest available OS version are not affected. @param resourceGroupName The name of the resource group. @param vmScaleSetName The name of the VM scale set. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the OperationStatusResponseInner object if successful. """ return beginStartOSUpgradeWithServiceResponseAsync(resourceGroupName, vmScaleSetName).toBlocking().single().body(); }
java
public OperationStatusResponseInner beginStartOSUpgrade(String resourceGroupName, String vmScaleSetName) { return beginStartOSUpgradeWithServiceResponseAsync(resourceGroupName, vmScaleSetName).toBlocking().single().body(); }
[ "public", "OperationStatusResponseInner", "beginStartOSUpgrade", "(", "String", "resourceGroupName", ",", "String", "vmScaleSetName", ")", "{", "return", "beginStartOSUpgradeWithServiceResponseAsync", "(", "resourceGroupName", ",", "vmScaleSetName", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Starts a rolling upgrade to move all virtual machine scale set instances to the latest available Platform Image OS version. Instances which are already running the latest available OS version are not affected. @param resourceGroupName The name of the resource group. @param vmScaleSetName The name of the VM scale set. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the OperationStatusResponseInner object if successful.
[ "Starts", "a", "rolling", "upgrade", "to", "move", "all", "virtual", "machine", "scale", "set", "instances", "to", "the", "latest", "available", "Platform", "Image", "OS", "version", ".", "Instances", "which", "are", "already", "running", "the", "latest", "available", "OS", "version", "are", "not", "affected", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/compute/resource-manager/v2017_03_30/src/main/java/com/microsoft/azure/management/compute/v2017_03_30/implementation/VirtualMachineScaleSetRollingUpgradesInner.java#L312-L314
zeroturnaround/zt-zip
src/main/java/org/zeroturnaround/zip/ZipUtil.java
ZipUtil.handle
public static boolean handle(InputStream is, String name, ZipEntryCallback action) { """ Reads the given ZIP stream and executes the given action for a single entry. @param is input ZIP stream (it will not be closed automatically). @param name entry name. @param action action to be called for this entry. @return <code>true</code> if the entry was found, <code>false</code> if the entry was not found. @see ZipEntryCallback """ SingleZipEntryCallback helper = new SingleZipEntryCallback(name, action); iterate(is, helper); return helper.found(); }
java
public static boolean handle(InputStream is, String name, ZipEntryCallback action) { SingleZipEntryCallback helper = new SingleZipEntryCallback(name, action); iterate(is, helper); return helper.found(); }
[ "public", "static", "boolean", "handle", "(", "InputStream", "is", ",", "String", "name", ",", "ZipEntryCallback", "action", ")", "{", "SingleZipEntryCallback", "helper", "=", "new", "SingleZipEntryCallback", "(", "name", ",", "action", ")", ";", "iterate", "(", "is", ",", "helper", ")", ";", "return", "helper", ".", "found", "(", ")", ";", "}" ]
Reads the given ZIP stream and executes the given action for a single entry. @param is input ZIP stream (it will not be closed automatically). @param name entry name. @param action action to be called for this entry. @return <code>true</code> if the entry was found, <code>false</code> if the entry was not found. @see ZipEntryCallback
[ "Reads", "the", "given", "ZIP", "stream", "and", "executes", "the", "given", "action", "for", "a", "single", "entry", "." ]
train
https://github.com/zeroturnaround/zt-zip/blob/abb4dc43583e4d19339c0c021035019798970a13/src/main/java/org/zeroturnaround/zip/ZipUtil.java#L889-L893
algermissen/hawkj
src/main/java/net/jalg/hawkj/HawkWwwAuthenticateContext.java
HawkWwwAuthenticateContext.generateHmac
private String generateHmac() throws HawkException { """ Generate an HMAC from the context ts parameter. @return @throws HawkException """ String baseString = getBaseString(); Mac mac; try { mac = Mac.getInstance(getAlgorithm().getMacName()); } catch (NoSuchAlgorithmException e) { throw new HawkException("Unknown algorithm " + getAlgorithm().getMacName(), e); } SecretKeySpec secret_key = new SecretKeySpec(getKey().getBytes( Charsets.UTF_8), getAlgorithm().getMacName()); try { mac.init(secret_key); } catch (InvalidKeyException e) { throw new HawkException("Key is invalid ", e); } return new String(Base64.encodeBase64(mac.doFinal(baseString .getBytes(Charsets.UTF_8))), Charsets.UTF_8); }
java
private String generateHmac() throws HawkException { String baseString = getBaseString(); Mac mac; try { mac = Mac.getInstance(getAlgorithm().getMacName()); } catch (NoSuchAlgorithmException e) { throw new HawkException("Unknown algorithm " + getAlgorithm().getMacName(), e); } SecretKeySpec secret_key = new SecretKeySpec(getKey().getBytes( Charsets.UTF_8), getAlgorithm().getMacName()); try { mac.init(secret_key); } catch (InvalidKeyException e) { throw new HawkException("Key is invalid ", e); } return new String(Base64.encodeBase64(mac.doFinal(baseString .getBytes(Charsets.UTF_8))), Charsets.UTF_8); }
[ "private", "String", "generateHmac", "(", ")", "throws", "HawkException", "{", "String", "baseString", "=", "getBaseString", "(", ")", ";", "Mac", "mac", ";", "try", "{", "mac", "=", "Mac", ".", "getInstance", "(", "getAlgorithm", "(", ")", ".", "getMacName", "(", ")", ")", ";", "}", "catch", "(", "NoSuchAlgorithmException", "e", ")", "{", "throw", "new", "HawkException", "(", "\"Unknown algorithm \"", "+", "getAlgorithm", "(", ")", ".", "getMacName", "(", ")", ",", "e", ")", ";", "}", "SecretKeySpec", "secret_key", "=", "new", "SecretKeySpec", "(", "getKey", "(", ")", ".", "getBytes", "(", "Charsets", ".", "UTF_8", ")", ",", "getAlgorithm", "(", ")", ".", "getMacName", "(", ")", ")", ";", "try", "{", "mac", ".", "init", "(", "secret_key", ")", ";", "}", "catch", "(", "InvalidKeyException", "e", ")", "{", "throw", "new", "HawkException", "(", "\"Key is invalid \"", ",", "e", ")", ";", "}", "return", "new", "String", "(", "Base64", ".", "encodeBase64", "(", "mac", ".", "doFinal", "(", "baseString", ".", "getBytes", "(", "Charsets", ".", "UTF_8", ")", ")", ")", ",", "Charsets", ".", "UTF_8", ")", ";", "}" ]
Generate an HMAC from the context ts parameter. @return @throws HawkException
[ "Generate", "an", "HMAC", "from", "the", "context", "ts", "parameter", "." ]
train
https://github.com/algermissen/hawkj/blob/f798a20f058474bcfe761f7c5c02afee17326c71/src/main/java/net/jalg/hawkj/HawkWwwAuthenticateContext.java#L205-L227
hibernate/hibernate-ogm
neo4j/src/main/java/org/hibernate/ogm/datastore/neo4j/dialect/impl/BaseNeo4jEntityQueries.java
BaseNeo4jEntityQueries.initFindEntityQuery
private static String initFindEntityQuery(EntityKeyMetadata entityKeyMetadata, boolean includeEmbedded) { """ /* Example: MATCH (owner:ENTITY:table {id: {0}}) RETURN owner """ StringBuilder queryBuilder = new StringBuilder(); appendMatchOwnerEntityNode( queryBuilder, entityKeyMetadata ); appendGetEmbeddedNodesIfNeeded( includeEmbedded, queryBuilder ); return queryBuilder.toString(); }
java
private static String initFindEntityQuery(EntityKeyMetadata entityKeyMetadata, boolean includeEmbedded) { StringBuilder queryBuilder = new StringBuilder(); appendMatchOwnerEntityNode( queryBuilder, entityKeyMetadata ); appendGetEmbeddedNodesIfNeeded( includeEmbedded, queryBuilder ); return queryBuilder.toString(); }
[ "private", "static", "String", "initFindEntityQuery", "(", "EntityKeyMetadata", "entityKeyMetadata", ",", "boolean", "includeEmbedded", ")", "{", "StringBuilder", "queryBuilder", "=", "new", "StringBuilder", "(", ")", ";", "appendMatchOwnerEntityNode", "(", "queryBuilder", ",", "entityKeyMetadata", ")", ";", "appendGetEmbeddedNodesIfNeeded", "(", "includeEmbedded", ",", "queryBuilder", ")", ";", "return", "queryBuilder", ".", "toString", "(", ")", ";", "}" ]
/* Example: MATCH (owner:ENTITY:table {id: {0}}) RETURN owner
[ "/", "*", "Example", ":", "MATCH", "(", "owner", ":", "ENTITY", ":", "table", "{", "id", ":", "{", "0", "}}", ")", "RETURN", "owner" ]
train
https://github.com/hibernate/hibernate-ogm/blob/9ea971df7c27277029006a6f748d8272fb1d69d2/neo4j/src/main/java/org/hibernate/ogm/datastore/neo4j/dialect/impl/BaseNeo4jEntityQueries.java#L433-L438
buschmais/jqa-java-plugin
src/main/java/com/buschmais/jqassistant/plugin/java/impl/scanner/visitor/VisitorHelper.java
VisitorHelper.getVariableDescriptor
VariableDescriptor getVariableDescriptor(String name, String signature) { """ Return the field descriptor for the given type and field signature. @param name The variable name. @param signature The variable signature. @return The field descriptor. """ VariableDescriptor variableDescriptor = scannerContext.getStore().create(VariableDescriptor.class); variableDescriptor.setName(name); variableDescriptor.setSignature(signature); return variableDescriptor; }
java
VariableDescriptor getVariableDescriptor(String name, String signature) { VariableDescriptor variableDescriptor = scannerContext.getStore().create(VariableDescriptor.class); variableDescriptor.setName(name); variableDescriptor.setSignature(signature); return variableDescriptor; }
[ "VariableDescriptor", "getVariableDescriptor", "(", "String", "name", ",", "String", "signature", ")", "{", "VariableDescriptor", "variableDescriptor", "=", "scannerContext", ".", "getStore", "(", ")", ".", "create", "(", "VariableDescriptor", ".", "class", ")", ";", "variableDescriptor", ".", "setName", "(", "name", ")", ";", "variableDescriptor", ".", "setSignature", "(", "signature", ")", ";", "return", "variableDescriptor", ";", "}" ]
Return the field descriptor for the given type and field signature. @param name The variable name. @param signature The variable signature. @return The field descriptor.
[ "Return", "the", "field", "descriptor", "for", "the", "given", "type", "and", "field", "signature", "." ]
train
https://github.com/buschmais/jqa-java-plugin/blob/4c050943e9c28cf1c4a08aa962d5b5bf03c4fe54/src/main/java/com/buschmais/jqassistant/plugin/java/impl/scanner/visitor/VisitorHelper.java#L199-L204
terrestris/shogun-core
src/shogun-core-main/src/main/java/de/terrestris/shoguncore/service/Csv2ExtJsLocaleService.java
Csv2ExtJsLocaleService.detectColumnIndexOfLocale
private int detectColumnIndexOfLocale(String locale, CSVReader csvReader) throws Exception { """ Extracts the column index of the given locale in the CSV file. @param locale @param csvReader @return @throws IOException @throws Exception """ int indexOfLocale = -1; List<String> headerLine = Arrays.asList(ArrayUtils.nullToEmpty(csvReader.readNext())); if (headerLine == null || headerLine.isEmpty()) { throw new Exception("CSV locale file seems to be empty."); } if (headerLine.size() < 3) { // we expect at least three columns: component;field;locale1 throw new Exception("CSV locale file is invalid: Not enough columns."); } // start with the third column as the first two columns must not be a // locale column for (int i = 2; i < headerLine.size(); i++) { String columnName = headerLine.get(i); if (locale.equalsIgnoreCase(columnName)) { indexOfLocale = headerLine.indexOf(columnName); break; } } if (indexOfLocale < 0) { throw new Exception("Could not find locale " + locale + " in CSV file"); } return indexOfLocale; }
java
private int detectColumnIndexOfLocale(String locale, CSVReader csvReader) throws Exception { int indexOfLocale = -1; List<String> headerLine = Arrays.asList(ArrayUtils.nullToEmpty(csvReader.readNext())); if (headerLine == null || headerLine.isEmpty()) { throw new Exception("CSV locale file seems to be empty."); } if (headerLine.size() < 3) { // we expect at least three columns: component;field;locale1 throw new Exception("CSV locale file is invalid: Not enough columns."); } // start with the third column as the first two columns must not be a // locale column for (int i = 2; i < headerLine.size(); i++) { String columnName = headerLine.get(i); if (locale.equalsIgnoreCase(columnName)) { indexOfLocale = headerLine.indexOf(columnName); break; } } if (indexOfLocale < 0) { throw new Exception("Could not find locale " + locale + " in CSV file"); } return indexOfLocale; }
[ "private", "int", "detectColumnIndexOfLocale", "(", "String", "locale", ",", "CSVReader", "csvReader", ")", "throws", "Exception", "{", "int", "indexOfLocale", "=", "-", "1", ";", "List", "<", "String", ">", "headerLine", "=", "Arrays", ".", "asList", "(", "ArrayUtils", ".", "nullToEmpty", "(", "csvReader", ".", "readNext", "(", ")", ")", ")", ";", "if", "(", "headerLine", "==", "null", "||", "headerLine", ".", "isEmpty", "(", ")", ")", "{", "throw", "new", "Exception", "(", "\"CSV locale file seems to be empty.\"", ")", ";", "}", "if", "(", "headerLine", ".", "size", "(", ")", "<", "3", ")", "{", "// we expect at least three columns: component;field;locale1", "throw", "new", "Exception", "(", "\"CSV locale file is invalid: Not enough columns.\"", ")", ";", "}", "// start with the third column as the first two columns must not be a", "// locale column", "for", "(", "int", "i", "=", "2", ";", "i", "<", "headerLine", ".", "size", "(", ")", ";", "i", "++", ")", "{", "String", "columnName", "=", "headerLine", ".", "get", "(", "i", ")", ";", "if", "(", "locale", ".", "equalsIgnoreCase", "(", "columnName", ")", ")", "{", "indexOfLocale", "=", "headerLine", ".", "indexOf", "(", "columnName", ")", ";", "break", ";", "}", "}", "if", "(", "indexOfLocale", "<", "0", ")", "{", "throw", "new", "Exception", "(", "\"Could not find locale \"", "+", "locale", "+", "\" in CSV file\"", ")", ";", "}", "return", "indexOfLocale", ";", "}" ]
Extracts the column index of the given locale in the CSV file. @param locale @param csvReader @return @throws IOException @throws Exception
[ "Extracts", "the", "column", "index", "of", "the", "given", "locale", "in", "the", "CSV", "file", "." ]
train
https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/service/Csv2ExtJsLocaleService.java#L140-L166
maven-nar/nar-maven-plugin
src/main/java/com/github/maven_nar/cpptasks/borland/CBuilderXProjectWriter.java
CBuilderXProjectWriter.writeLinkOptions
private void writeLinkOptions(final String baseDir, final PropertyWriter writer, final TargetInfo linkTarget) throws SAXException { """ Writes elements corresponding to link options. @param baseDir String base directory @param writer PropertyWriter property writer @param linkTarget TargetInfo link target @throws SAXException if I/O error or illegal content """ if (linkTarget != null) { final ProcessorConfiguration config = linkTarget.getConfiguration(); if (config instanceof CommandLineLinkerConfiguration) { final CommandLineLinkerConfiguration linkConfig = (CommandLineLinkerConfiguration) config; if (linkConfig.getLinker() instanceof BorlandLinker) { final String linkID = "win32.Debug_Build.win32b.ilink32"; writeIlinkArgs(writer, linkID, linkConfig.getPreArguments()); writeIlinkArgs(writer, linkID, linkConfig.getEndArguments()); writer.write(linkID, "param.libfiles.1", "cw32mt.lib"); writer.write(linkID, "param.libfiles.2", "import32.lib"); int libIndex = 3; final String[] libNames = linkConfig.getLibraryNames(); for (final String libName : libNames) { writer.write(linkID, "param.libfiles." + libIndex++, libName); } final String startup = linkConfig.getStartupObject(); if (startup != null) { writer.write(linkID, "param.objfiles.1", startup); } } else { final String linkID = "linux.Debug_Build.gnuc++.g++link"; writeLdArgs(writer, linkID, linkConfig.getPreArguments()); writeLdArgs(writer, linkID, linkConfig.getEndArguments()); } } } }
java
private void writeLinkOptions(final String baseDir, final PropertyWriter writer, final TargetInfo linkTarget) throws SAXException { if (linkTarget != null) { final ProcessorConfiguration config = linkTarget.getConfiguration(); if (config instanceof CommandLineLinkerConfiguration) { final CommandLineLinkerConfiguration linkConfig = (CommandLineLinkerConfiguration) config; if (linkConfig.getLinker() instanceof BorlandLinker) { final String linkID = "win32.Debug_Build.win32b.ilink32"; writeIlinkArgs(writer, linkID, linkConfig.getPreArguments()); writeIlinkArgs(writer, linkID, linkConfig.getEndArguments()); writer.write(linkID, "param.libfiles.1", "cw32mt.lib"); writer.write(linkID, "param.libfiles.2", "import32.lib"); int libIndex = 3; final String[] libNames = linkConfig.getLibraryNames(); for (final String libName : libNames) { writer.write(linkID, "param.libfiles." + libIndex++, libName); } final String startup = linkConfig.getStartupObject(); if (startup != null) { writer.write(linkID, "param.objfiles.1", startup); } } else { final String linkID = "linux.Debug_Build.gnuc++.g++link"; writeLdArgs(writer, linkID, linkConfig.getPreArguments()); writeLdArgs(writer, linkID, linkConfig.getEndArguments()); } } } }
[ "private", "void", "writeLinkOptions", "(", "final", "String", "baseDir", ",", "final", "PropertyWriter", "writer", ",", "final", "TargetInfo", "linkTarget", ")", "throws", "SAXException", "{", "if", "(", "linkTarget", "!=", "null", ")", "{", "final", "ProcessorConfiguration", "config", "=", "linkTarget", ".", "getConfiguration", "(", ")", ";", "if", "(", "config", "instanceof", "CommandLineLinkerConfiguration", ")", "{", "final", "CommandLineLinkerConfiguration", "linkConfig", "=", "(", "CommandLineLinkerConfiguration", ")", "config", ";", "if", "(", "linkConfig", ".", "getLinker", "(", ")", "instanceof", "BorlandLinker", ")", "{", "final", "String", "linkID", "=", "\"win32.Debug_Build.win32b.ilink32\"", ";", "writeIlinkArgs", "(", "writer", ",", "linkID", ",", "linkConfig", ".", "getPreArguments", "(", ")", ")", ";", "writeIlinkArgs", "(", "writer", ",", "linkID", ",", "linkConfig", ".", "getEndArguments", "(", ")", ")", ";", "writer", ".", "write", "(", "linkID", ",", "\"param.libfiles.1\"", ",", "\"cw32mt.lib\"", ")", ";", "writer", ".", "write", "(", "linkID", ",", "\"param.libfiles.2\"", ",", "\"import32.lib\"", ")", ";", "int", "libIndex", "=", "3", ";", "final", "String", "[", "]", "libNames", "=", "linkConfig", ".", "getLibraryNames", "(", ")", ";", "for", "(", "final", "String", "libName", ":", "libNames", ")", "{", "writer", ".", "write", "(", "linkID", ",", "\"param.libfiles.\"", "+", "libIndex", "++", ",", "libName", ")", ";", "}", "final", "String", "startup", "=", "linkConfig", ".", "getStartupObject", "(", ")", ";", "if", "(", "startup", "!=", "null", ")", "{", "writer", ".", "write", "(", "linkID", ",", "\"param.objfiles.1\"", ",", "startup", ")", ";", "}", "}", "else", "{", "final", "String", "linkID", "=", "\"linux.Debug_Build.gnuc++.g++link\"", ";", "writeLdArgs", "(", "writer", ",", "linkID", ",", "linkConfig", ".", "getPreArguments", "(", ")", ")", ";", "writeLdArgs", "(", "writer", ",", "linkID", ",", "linkConfig", ".", "getEndArguments", "(", ")", ")", ";", "}", "}", "}", "}" ]
Writes elements corresponding to link options. @param baseDir String base directory @param writer PropertyWriter property writer @param linkTarget TargetInfo link target @throws SAXException if I/O error or illegal content
[ "Writes", "elements", "corresponding", "to", "link", "options", "." ]
train
https://github.com/maven-nar/nar-maven-plugin/blob/3c622e2024296b4203431bbae3bde290a01dac00/src/main/java/com/github/maven_nar/cpptasks/borland/CBuilderXProjectWriter.java#L329-L358
threerings/narya
core/src/main/java/com/threerings/presents/server/RebootManager.java
RebootManager.getRebootMessage
protected String getRebootMessage (String key, int minutes) { """ Composes the given reboot message with the minutes and either the custom or standard details about the pending reboot. """ String msg = getCustomRebootMessage(); if (StringUtil.isBlank(msg)) { msg = "m.reboot_msg_standard"; } return MessageBundle.compose(key, MessageBundle.taint("" + minutes), msg); }
java
protected String getRebootMessage (String key, int minutes) { String msg = getCustomRebootMessage(); if (StringUtil.isBlank(msg)) { msg = "m.reboot_msg_standard"; } return MessageBundle.compose(key, MessageBundle.taint("" + minutes), msg); }
[ "protected", "String", "getRebootMessage", "(", "String", "key", ",", "int", "minutes", ")", "{", "String", "msg", "=", "getCustomRebootMessage", "(", ")", ";", "if", "(", "StringUtil", ".", "isBlank", "(", "msg", ")", ")", "{", "msg", "=", "\"m.reboot_msg_standard\"", ";", "}", "return", "MessageBundle", ".", "compose", "(", "key", ",", "MessageBundle", ".", "taint", "(", "\"\"", "+", "minutes", ")", ",", "msg", ")", ";", "}" ]
Composes the given reboot message with the minutes and either the custom or standard details about the pending reboot.
[ "Composes", "the", "given", "reboot", "message", "with", "the", "minutes", "and", "either", "the", "custom", "or", "standard", "details", "about", "the", "pending", "reboot", "." ]
train
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/server/RebootManager.java#L256-L264
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/compiler/XPathParser.java
XPathParser.insertOp
void insertOp(int pos, int length, int op) { """ Insert room for operation. This will NOT set the length value of the operation, but will update the length value for the total expression. @param pos The position where the op is to be inserted. @param length The length of the operation space in the op map. @param op The op code to the inserted. """ int totalLen = m_ops.getOp(OpMap.MAPINDEX_LENGTH); for (int i = totalLen - 1; i >= pos; i--) { m_ops.setOp(i + length, m_ops.getOp(i)); } m_ops.setOp(pos,op); m_ops.setOp(OpMap.MAPINDEX_LENGTH,totalLen + length); }
java
void insertOp(int pos, int length, int op) { int totalLen = m_ops.getOp(OpMap.MAPINDEX_LENGTH); for (int i = totalLen - 1; i >= pos; i--) { m_ops.setOp(i + length, m_ops.getOp(i)); } m_ops.setOp(pos,op); m_ops.setOp(OpMap.MAPINDEX_LENGTH,totalLen + length); }
[ "void", "insertOp", "(", "int", "pos", ",", "int", "length", ",", "int", "op", ")", "{", "int", "totalLen", "=", "m_ops", ".", "getOp", "(", "OpMap", ".", "MAPINDEX_LENGTH", ")", ";", "for", "(", "int", "i", "=", "totalLen", "-", "1", ";", "i", ">=", "pos", ";", "i", "--", ")", "{", "m_ops", ".", "setOp", "(", "i", "+", "length", ",", "m_ops", ".", "getOp", "(", "i", ")", ")", ";", "}", "m_ops", ".", "setOp", "(", "pos", ",", "op", ")", ";", "m_ops", ".", "setOp", "(", "OpMap", ".", "MAPINDEX_LENGTH", ",", "totalLen", "+", "length", ")", ";", "}" ]
Insert room for operation. This will NOT set the length value of the operation, but will update the length value for the total expression. @param pos The position where the op is to be inserted. @param length The length of the operation space in the op map. @param op The op code to the inserted.
[ "Insert", "room", "for", "operation", ".", "This", "will", "NOT", "set", "the", "length", "value", "of", "the", "operation", "but", "will", "update", "the", "length", "value", "for", "the", "total", "expression", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/compiler/XPathParser.java#L746-L758
gallandarakhneorg/afc
advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/coordinate/GISCoordinates.java
GISCoordinates.NTFLambdaPhi_WSG84
@SuppressWarnings( { """ This function convert extended France NTF Lambert coordinate to geographic WSG84 Data. @param lambda_ntf is the lambda coordinate in NTF @param lambda_ntf is the phi coordinate in NTF @return lambda and phi in geographic WSG84 in degrees. """"checkstyle:magicnumber", "checkstyle:localfinalvariablename", "checkstyle:localvariablename"}) private static GeodesicPosition NTFLambdaPhi_WSG84(double lambda_ntf, double phi_ntf) { // Geographical coordinate NTF (lamda_ntf,phi_ntf) // -> Cartesian coordinate NTF (x_ntf,y_ntf,z_ntf) // ALG0009 double a = 6378249.2; // 100 meters final double h = 100; final double N = a / Math.pow(1. - (NTF_E * NTF_E) * (Math.sin(phi_ntf) * Math.sin(phi_ntf)), .5); final double x_ntf = (N + h) * Math.cos(phi_ntf) * Math.cos(lambda_ntf); final double y_ntf = (N + h) * Math.cos(phi_ntf) * Math.sin(lambda_ntf); final double z_ntf = ((N * (1. - (NTF_E * NTF_E))) + h) * Math.sin(phi_ntf); // Cartesian coordinate NTF (x_ntf,y_ntf,z_ntf) // -> Cartesian coordinate WGS84 (x_w,y_w,z_w) // ALG0013 // This is a simple translation. final double x_w = x_ntf - 168.; final double y_w = y_ntf - 60.; final double z_w = z_ntf + 320; // Cartesian coordinate WGS84 (x_w,y_w,z_w) // -> Geographic coordinate WGS84 (lamda_w,phi_w) // ALG0012 // 0.04079234433 to use the Greenwich meridian, 0 else final double l840 = 0.04079234433; a = 6378137.0; final double P = Math.hypot(x_w, y_w); double lambda_w = l840 + Math.atan(y_w / x_w); double phi0_w = Math.atan(z_w / (P * (1 - ((a * WSG84_E * WSG84_E)) / Math.sqrt((x_w * x_w) + (y_w * y_w) + (z_w * z_w))))); double phi_w = Math.atan((z_w / P) / (1 - ((a * WSG84_E * WSG84_E * Math.cos(phi0_w)) / (P * Math.sqrt(1 - NTF_E * NTF_E * (Math.sin(phi0_w) * Math.sin(phi0_w))))))); while (Math.abs(phi_w - phi0_w) >= EPSILON) { phi0_w = phi_w; phi_w = Math.atan((z_w / P) / (1 - ((a * WSG84_E * WSG84_E * Math.cos(phi0_w)) / (P * Math.sqrt(1 - ((WSG84_E * WSG84_E) * (Math.sin(phi0_w) * Math.sin(phi0_w)))))))); } // Convert radians to degrees. lambda_w = Math.toDegrees(lambda_w); phi_w = Math.toDegrees(phi_w); return new GeodesicPosition(lambda_w, phi_w); }
java
@SuppressWarnings({"checkstyle:magicnumber", "checkstyle:localfinalvariablename", "checkstyle:localvariablename"}) private static GeodesicPosition NTFLambdaPhi_WSG84(double lambda_ntf, double phi_ntf) { // Geographical coordinate NTF (lamda_ntf,phi_ntf) // -> Cartesian coordinate NTF (x_ntf,y_ntf,z_ntf) // ALG0009 double a = 6378249.2; // 100 meters final double h = 100; final double N = a / Math.pow(1. - (NTF_E * NTF_E) * (Math.sin(phi_ntf) * Math.sin(phi_ntf)), .5); final double x_ntf = (N + h) * Math.cos(phi_ntf) * Math.cos(lambda_ntf); final double y_ntf = (N + h) * Math.cos(phi_ntf) * Math.sin(lambda_ntf); final double z_ntf = ((N * (1. - (NTF_E * NTF_E))) + h) * Math.sin(phi_ntf); // Cartesian coordinate NTF (x_ntf,y_ntf,z_ntf) // -> Cartesian coordinate WGS84 (x_w,y_w,z_w) // ALG0013 // This is a simple translation. final double x_w = x_ntf - 168.; final double y_w = y_ntf - 60.; final double z_w = z_ntf + 320; // Cartesian coordinate WGS84 (x_w,y_w,z_w) // -> Geographic coordinate WGS84 (lamda_w,phi_w) // ALG0012 // 0.04079234433 to use the Greenwich meridian, 0 else final double l840 = 0.04079234433; a = 6378137.0; final double P = Math.hypot(x_w, y_w); double lambda_w = l840 + Math.atan(y_w / x_w); double phi0_w = Math.atan(z_w / (P * (1 - ((a * WSG84_E * WSG84_E)) / Math.sqrt((x_w * x_w) + (y_w * y_w) + (z_w * z_w))))); double phi_w = Math.atan((z_w / P) / (1 - ((a * WSG84_E * WSG84_E * Math.cos(phi0_w)) / (P * Math.sqrt(1 - NTF_E * NTF_E * (Math.sin(phi0_w) * Math.sin(phi0_w))))))); while (Math.abs(phi_w - phi0_w) >= EPSILON) { phi0_w = phi_w; phi_w = Math.atan((z_w / P) / (1 - ((a * WSG84_E * WSG84_E * Math.cos(phi0_w)) / (P * Math.sqrt(1 - ((WSG84_E * WSG84_E) * (Math.sin(phi0_w) * Math.sin(phi0_w)))))))); } // Convert radians to degrees. lambda_w = Math.toDegrees(lambda_w); phi_w = Math.toDegrees(phi_w); return new GeodesicPosition(lambda_w, phi_w); }
[ "@", "SuppressWarnings", "(", "{", "\"checkstyle:magicnumber\"", ",", "\"checkstyle:localfinalvariablename\"", ",", "\"checkstyle:localvariablename\"", "}", ")", "private", "static", "GeodesicPosition", "NTFLambdaPhi_WSG84", "(", "double", "lambda_ntf", ",", "double", "phi_ntf", ")", "{", "// Geographical coordinate NTF (lamda_ntf,phi_ntf)", "// -> Cartesian coordinate NTF (x_ntf,y_ntf,z_ntf)", "// ALG0009", "double", "a", "=", "6378249.2", ";", "// 100 meters", "final", "double", "h", "=", "100", ";", "final", "double", "N", "=", "a", "/", "Math", ".", "pow", "(", "1.", "-", "(", "NTF_E", "*", "NTF_E", ")", "*", "(", "Math", ".", "sin", "(", "phi_ntf", ")", "*", "Math", ".", "sin", "(", "phi_ntf", ")", ")", ",", ".5", ")", ";", "final", "double", "x_ntf", "=", "(", "N", "+", "h", ")", "*", "Math", ".", "cos", "(", "phi_ntf", ")", "*", "Math", ".", "cos", "(", "lambda_ntf", ")", ";", "final", "double", "y_ntf", "=", "(", "N", "+", "h", ")", "*", "Math", ".", "cos", "(", "phi_ntf", ")", "*", "Math", ".", "sin", "(", "lambda_ntf", ")", ";", "final", "double", "z_ntf", "=", "(", "(", "N", "*", "(", "1.", "-", "(", "NTF_E", "*", "NTF_E", ")", ")", ")", "+", "h", ")", "*", "Math", ".", "sin", "(", "phi_ntf", ")", ";", "// Cartesian coordinate NTF (x_ntf,y_ntf,z_ntf)", "// -> Cartesian coordinate WGS84 (x_w,y_w,z_w)", "// ALG0013", "// This is a simple translation.", "final", "double", "x_w", "=", "x_ntf", "-", "168.", ";", "final", "double", "y_w", "=", "y_ntf", "-", "60.", ";", "final", "double", "z_w", "=", "z_ntf", "+", "320", ";", "// Cartesian coordinate WGS84 (x_w,y_w,z_w)", "// -> Geographic coordinate WGS84 (lamda_w,phi_w)", "// ALG0012", "// 0.04079234433 to use the Greenwich meridian, 0 else", "final", "double", "l840", "=", "0.04079234433", ";", "a", "=", "6378137.0", ";", "final", "double", "P", "=", "Math", ".", "hypot", "(", "x_w", ",", "y_w", ")", ";", "double", "lambda_w", "=", "l840", "+", "Math", ".", "atan", "(", "y_w", "/", "x_w", ")", ";", "double", "phi0_w", "=", "Math", ".", "atan", "(", "z_w", "/", "(", "P", "*", "(", "1", "-", "(", "(", "a", "*", "WSG84_E", "*", "WSG84_E", ")", ")", "/", "Math", ".", "sqrt", "(", "(", "x_w", "*", "x_w", ")", "+", "(", "y_w", "*", "y_w", ")", "+", "(", "z_w", "*", "z_w", ")", ")", ")", ")", ")", ";", "double", "phi_w", "=", "Math", ".", "atan", "(", "(", "z_w", "/", "P", ")", "/", "(", "1", "-", "(", "(", "a", "*", "WSG84_E", "*", "WSG84_E", "*", "Math", ".", "cos", "(", "phi0_w", ")", ")", "/", "(", "P", "*", "Math", ".", "sqrt", "(", "1", "-", "NTF_E", "*", "NTF_E", "*", "(", "Math", ".", "sin", "(", "phi0_w", ")", "*", "Math", ".", "sin", "(", "phi0_w", ")", ")", ")", ")", ")", ")", ")", ";", "while", "(", "Math", ".", "abs", "(", "phi_w", "-", "phi0_w", ")", ">=", "EPSILON", ")", "{", "phi0_w", "=", "phi_w", ";", "phi_w", "=", "Math", ".", "atan", "(", "(", "z_w", "/", "P", ")", "/", "(", "1", "-", "(", "(", "a", "*", "WSG84_E", "*", "WSG84_E", "*", "Math", ".", "cos", "(", "phi0_w", ")", ")", "/", "(", "P", "*", "Math", ".", "sqrt", "(", "1", "-", "(", "(", "WSG84_E", "*", "WSG84_E", ")", "*", "(", "Math", ".", "sin", "(", "phi0_w", ")", "*", "Math", ".", "sin", "(", "phi0_w", ")", ")", ")", ")", ")", ")", ")", ")", ";", "}", "// Convert radians to degrees.", "lambda_w", "=", "Math", ".", "toDegrees", "(", "lambda_w", ")", ";", "phi_w", "=", "Math", ".", "toDegrees", "(", "phi_w", ")", ";", "return", "new", "GeodesicPosition", "(", "lambda_w", ",", "phi_w", ")", ";", "}" ]
This function convert extended France NTF Lambert coordinate to geographic WSG84 Data. @param lambda_ntf is the lambda coordinate in NTF @param lambda_ntf is the phi coordinate in NTF @return lambda and phi in geographic WSG84 in degrees.
[ "This", "function", "convert", "extended", "France", "NTF", "Lambert", "coordinate", "to", "geographic", "WSG84", "Data", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/coordinate/GISCoordinates.java#L982-L1034
UrielCh/ovh-java-sdk
ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java
ApiOvhCloud.project_serviceName_user_userId_rclone_GET
public OvhRclone project_serviceName_user_userId_rclone_GET(String serviceName, Long userId, String region) throws IOException { """ Get rclone configuration file REST: GET /cloud/project/{serviceName}/user/{userId}/rclone @param region [required] Region @param serviceName [required] Service name @param userId [required] User id """ String qPath = "/cloud/project/{serviceName}/user/{userId}/rclone"; StringBuilder sb = path(qPath, serviceName, userId); query(sb, "region", region); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhRclone.class); }
java
public OvhRclone project_serviceName_user_userId_rclone_GET(String serviceName, Long userId, String region) throws IOException { String qPath = "/cloud/project/{serviceName}/user/{userId}/rclone"; StringBuilder sb = path(qPath, serviceName, userId); query(sb, "region", region); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhRclone.class); }
[ "public", "OvhRclone", "project_serviceName_user_userId_rclone_GET", "(", "String", "serviceName", ",", "Long", "userId", ",", "String", "region", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/cloud/project/{serviceName}/user/{userId}/rclone\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ",", "userId", ")", ";", "query", "(", "sb", ",", "\"region\"", ",", "region", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhRclone", ".", "class", ")", ";", "}" ]
Get rclone configuration file REST: GET /cloud/project/{serviceName}/user/{userId}/rclone @param region [required] Region @param serviceName [required] Service name @param userId [required] User id
[ "Get", "rclone", "configuration", "file" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java#L403-L409
looly/hutool
hutool-http/src/main/java/cn/hutool/http/HttpRequest.java
HttpRequest.form
public HttpRequest form(String name, Object value, Object... parameters) { """ 设置表单数据 @param name 名 @param value 值 @param parameters 参数对,奇数为名,偶数为值 @return this """ form(name, value); for (int i = 0; i < parameters.length; i += 2) { name = parameters[i].toString(); form(name, parameters[i + 1]); } return this; }
java
public HttpRequest form(String name, Object value, Object... parameters) { form(name, value); for (int i = 0; i < parameters.length; i += 2) { name = parameters[i].toString(); form(name, parameters[i + 1]); } return this; }
[ "public", "HttpRequest", "form", "(", "String", "name", ",", "Object", "value", ",", "Object", "...", "parameters", ")", "{", "form", "(", "name", ",", "value", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "parameters", ".", "length", ";", "i", "+=", "2", ")", "{", "name", "=", "parameters", "[", "i", "]", ".", "toString", "(", ")", ";", "form", "(", "name", ",", "parameters", "[", "i", "+", "1", "]", ")", ";", "}", "return", "this", ";", "}" ]
设置表单数据 @param name 名 @param value 值 @param parameters 参数对,奇数为名,偶数为值 @return this
[ "设置表单数据" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-http/src/main/java/cn/hutool/http/HttpRequest.java#L465-L473
infinispan/infinispan
commons/src/main/java/org/infinispan/commons/util/ReflectionUtil.java
ReflectionUtil.invokeAccessibly
public static Object invokeAccessibly(Object instance, Method method, Object[] parameters) { """ Invokes a method using reflection, in an accessible manner (by using {@link Method#setAccessible(boolean)} @param instance instance on which to execute the method @param method method to execute @param parameters parameters """ return SecurityActions.invokeAccessibly(instance, method, parameters); }
java
public static Object invokeAccessibly(Object instance, Method method, Object[] parameters) { return SecurityActions.invokeAccessibly(instance, method, parameters); }
[ "public", "static", "Object", "invokeAccessibly", "(", "Object", "instance", ",", "Method", "method", ",", "Object", "[", "]", "parameters", ")", "{", "return", "SecurityActions", ".", "invokeAccessibly", "(", "instance", ",", "method", ",", "parameters", ")", ";", "}" ]
Invokes a method using reflection, in an accessible manner (by using {@link Method#setAccessible(boolean)} @param instance instance on which to execute the method @param method method to execute @param parameters parameters
[ "Invokes", "a", "method", "using", "reflection", "in", "an", "accessible", "manner", "(", "by", "using", "{", "@link", "Method#setAccessible", "(", "boolean", ")", "}" ]
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/commons/src/main/java/org/infinispan/commons/util/ReflectionUtil.java#L180-L182
aws/aws-sdk-java
aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/document/utils/ValueMap.java
ValueMap.withBoolean
public ValueMap withBoolean(String key, boolean val) { """ Sets the value of the specified key in the current ValueMap to the boolean value. """ super.put(key, Boolean.valueOf(val)); return this; }
java
public ValueMap withBoolean(String key, boolean val) { super.put(key, Boolean.valueOf(val)); return this; }
[ "public", "ValueMap", "withBoolean", "(", "String", "key", ",", "boolean", "val", ")", "{", "super", ".", "put", "(", "key", ",", "Boolean", ".", "valueOf", "(", "val", ")", ")", ";", "return", "this", ";", "}" ]
Sets the value of the specified key in the current ValueMap to the boolean value.
[ "Sets", "the", "value", "of", "the", "specified", "key", "in", "the", "current", "ValueMap", "to", "the", "boolean", "value", "." ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/document/utils/ValueMap.java#L186-L189
timewalker74/ffmq
core/src/main/java/net/timewalker/ffmq4/common/destination/DestinationTools.java
DestinationTools.asRef
public static DestinationRef asRef( Destination destination ) throws JMSException { """ Make sure the given destination is a light-weight serializable destination reference """ if (destination == null) return null; if (destination instanceof DestinationRef) return (DestinationRef)destination; if (destination instanceof Queue) return new QueueRef(((Queue)destination).getQueueName()); if (destination instanceof Topic) return new TopicRef(((Topic)destination).getTopicName()); throw new InvalidDestinationException("Unsupported destination type : "+destination,"INVALID_DESTINATION"); }
java
public static DestinationRef asRef( Destination destination ) throws JMSException { if (destination == null) return null; if (destination instanceof DestinationRef) return (DestinationRef)destination; if (destination instanceof Queue) return new QueueRef(((Queue)destination).getQueueName()); if (destination instanceof Topic) return new TopicRef(((Topic)destination).getTopicName()); throw new InvalidDestinationException("Unsupported destination type : "+destination,"INVALID_DESTINATION"); }
[ "public", "static", "DestinationRef", "asRef", "(", "Destination", "destination", ")", "throws", "JMSException", "{", "if", "(", "destination", "==", "null", ")", "return", "null", ";", "if", "(", "destination", "instanceof", "DestinationRef", ")", "return", "(", "DestinationRef", ")", "destination", ";", "if", "(", "destination", "instanceof", "Queue", ")", "return", "new", "QueueRef", "(", "(", "(", "Queue", ")", "destination", ")", ".", "getQueueName", "(", ")", ")", ";", "if", "(", "destination", "instanceof", "Topic", ")", "return", "new", "TopicRef", "(", "(", "(", "Topic", ")", "destination", ")", ".", "getTopicName", "(", ")", ")", ";", "throw", "new", "InvalidDestinationException", "(", "\"Unsupported destination type : \"", "+", "destination", ",", "\"INVALID_DESTINATION\"", ")", ";", "}" ]
Make sure the given destination is a light-weight serializable destination reference
[ "Make", "sure", "the", "given", "destination", "is", "a", "light", "-", "weight", "serializable", "destination", "reference" ]
train
https://github.com/timewalker74/ffmq/blob/638773ee29a4a5f9c6119ed74ad14ac9c46382b3/core/src/main/java/net/timewalker/ffmq4/common/destination/DestinationTools.java#L38-L53
craterdog/java-security-framework
java-certificate-management-providers/src/main/java/craterdog/security/RsaCertificateManager.java
RsaCertificateManager.signCertificateRequest
public X509Certificate signCertificateRequest(PrivateKey caPrivateKey, X509Certificate caCertificate, PKCS10CertificationRequest request, BigInteger serialNumber, long lifetime) { """ This method signs a certificate signing request (CSR) using the specified certificate authority (CA). This is a convenience method that really should be part of the <code>CertificateManagement</code> interface except that it depends on a Bouncy Castle class in the signature. The java security framework does not have a similar class so it has been left out of the interface. @param caPrivateKey The private key for the certificate authority. @param caCertificate The certificate containing the public key for the certificate authority. @param request The certificate signing request (CSR) to be signed. @param serialNumber The serial number for the new certificate. @param lifetime How long the certificate should be valid. @return The newly signed certificate. """ try { logger.entry(); logger.debug("Extract public key and subject from the CSR..."); PublicKey publicKey = new JcaPEMKeyConverter().getPublicKey(request.getSubjectPublicKeyInfo()); String subject = request.getSubject().toString(); logger.debug("Generate and sign the certificate..."); X509Certificate result = createCertificate(caPrivateKey, caCertificate, publicKey, subject, serialNumber, lifetime); logger.exit(); return result; } catch (PEMException e) { RuntimeException exception = new RuntimeException("An unexpected exception occurred while attempting to sign a certificate.", e); logger.error(exception.toString()); throw exception; } }
java
public X509Certificate signCertificateRequest(PrivateKey caPrivateKey, X509Certificate caCertificate, PKCS10CertificationRequest request, BigInteger serialNumber, long lifetime) { try { logger.entry(); logger.debug("Extract public key and subject from the CSR..."); PublicKey publicKey = new JcaPEMKeyConverter().getPublicKey(request.getSubjectPublicKeyInfo()); String subject = request.getSubject().toString(); logger.debug("Generate and sign the certificate..."); X509Certificate result = createCertificate(caPrivateKey, caCertificate, publicKey, subject, serialNumber, lifetime); logger.exit(); return result; } catch (PEMException e) { RuntimeException exception = new RuntimeException("An unexpected exception occurred while attempting to sign a certificate.", e); logger.error(exception.toString()); throw exception; } }
[ "public", "X509Certificate", "signCertificateRequest", "(", "PrivateKey", "caPrivateKey", ",", "X509Certificate", "caCertificate", ",", "PKCS10CertificationRequest", "request", ",", "BigInteger", "serialNumber", ",", "long", "lifetime", ")", "{", "try", "{", "logger", ".", "entry", "(", ")", ";", "logger", ".", "debug", "(", "\"Extract public key and subject from the CSR...\"", ")", ";", "PublicKey", "publicKey", "=", "new", "JcaPEMKeyConverter", "(", ")", ".", "getPublicKey", "(", "request", ".", "getSubjectPublicKeyInfo", "(", ")", ")", ";", "String", "subject", "=", "request", ".", "getSubject", "(", ")", ".", "toString", "(", ")", ";", "logger", ".", "debug", "(", "\"Generate and sign the certificate...\"", ")", ";", "X509Certificate", "result", "=", "createCertificate", "(", "caPrivateKey", ",", "caCertificate", ",", "publicKey", ",", "subject", ",", "serialNumber", ",", "lifetime", ")", ";", "logger", ".", "exit", "(", ")", ";", "return", "result", ";", "}", "catch", "(", "PEMException", "e", ")", "{", "RuntimeException", "exception", "=", "new", "RuntimeException", "(", "\"An unexpected exception occurred while attempting to sign a certificate.\"", ",", "e", ")", ";", "logger", ".", "error", "(", "exception", ".", "toString", "(", ")", ")", ";", "throw", "exception", ";", "}", "}" ]
This method signs a certificate signing request (CSR) using the specified certificate authority (CA). This is a convenience method that really should be part of the <code>CertificateManagement</code> interface except that it depends on a Bouncy Castle class in the signature. The java security framework does not have a similar class so it has been left out of the interface. @param caPrivateKey The private key for the certificate authority. @param caCertificate The certificate containing the public key for the certificate authority. @param request The certificate signing request (CSR) to be signed. @param serialNumber The serial number for the new certificate. @param lifetime How long the certificate should be valid. @return The newly signed certificate.
[ "This", "method", "signs", "a", "certificate", "signing", "request", "(", "CSR", ")", "using", "the", "specified", "certificate", "authority", "(", "CA", ")", ".", "This", "is", "a", "convenience", "method", "that", "really", "should", "be", "part", "of", "the", "<code", ">", "CertificateManagement<", "/", "code", ">", "interface", "except", "that", "it", "depends", "on", "a", "Bouncy", "Castle", "class", "in", "the", "signature", ".", "The", "java", "security", "framework", "does", "not", "have", "a", "similar", "class", "so", "it", "has", "been", "left", "out", "of", "the", "interface", "." ]
train
https://github.com/craterdog/java-security-framework/blob/a5634c19812d473b608bc11060f5cbb4b4b0b5da/java-certificate-management-providers/src/main/java/craterdog/security/RsaCertificateManager.java#L150-L170
wstrange/GoogleAuth
src/main/java/com/warrenstrange/googleauth/GoogleAuthenticator.java
GoogleAuthenticator.calculateCode
int calculateCode(byte[] key, long tm) { """ Calculates the verification code of the provided key at the specified instant of time using the algorithm specified in RFC 6238. @param key the secret key in binary format. @param tm the instant of time. @return the validation code for the provided key at the specified instant of time. """ // Allocating an array of bytes to represent the specified instant // of time. byte[] data = new byte[8]; long value = tm; // Converting the instant of time from the long representation to a // big-endian array of bytes (RFC4226, 5.2. Description). for (int i = 8; i-- > 0; value >>>= 8) { data[i] = (byte) value; } // Building the secret key specification for the HmacSHA1 algorithm. SecretKeySpec signKey = new SecretKeySpec(key, config.getHmacHashFunction().toString()); try { // Getting an HmacSHA1/HmacSHA256 algorithm implementation from the JCE. Mac mac = Mac.getInstance(config.getHmacHashFunction().toString()); // Initializing the MAC algorithm. mac.init(signKey); // Processing the instant of time and getting the encrypted data. byte[] hash = mac.doFinal(data); // Building the validation code performing dynamic truncation // (RFC4226, 5.3. Generating an HOTP value) int offset = hash[hash.length - 1] & 0xF; // We are using a long because Java hasn't got an unsigned integer type // and we need 32 unsigned bits). long truncatedHash = 0; for (int i = 0; i < 4; ++i) { truncatedHash <<= 8; // Java bytes are signed but we need an unsigned integer: // cleaning off all but the LSB. truncatedHash |= (hash[offset + i] & 0xFF); } // Clean bits higher than the 32nd (inclusive) and calculate the // module with the maximum validation code value. truncatedHash &= 0x7FFFFFFF; truncatedHash %= config.getKeyModulus(); // Returning the validation code to the caller. return (int) truncatedHash; } catch (NoSuchAlgorithmException | InvalidKeyException ex) { // Logging the exception. LOGGER.log(Level.SEVERE, ex.getMessage(), ex); // We're not disclosing internal error details to our clients. throw new GoogleAuthenticatorException("The operation cannot be performed now."); } }
java
int calculateCode(byte[] key, long tm) { // Allocating an array of bytes to represent the specified instant // of time. byte[] data = new byte[8]; long value = tm; // Converting the instant of time from the long representation to a // big-endian array of bytes (RFC4226, 5.2. Description). for (int i = 8; i-- > 0; value >>>= 8) { data[i] = (byte) value; } // Building the secret key specification for the HmacSHA1 algorithm. SecretKeySpec signKey = new SecretKeySpec(key, config.getHmacHashFunction().toString()); try { // Getting an HmacSHA1/HmacSHA256 algorithm implementation from the JCE. Mac mac = Mac.getInstance(config.getHmacHashFunction().toString()); // Initializing the MAC algorithm. mac.init(signKey); // Processing the instant of time and getting the encrypted data. byte[] hash = mac.doFinal(data); // Building the validation code performing dynamic truncation // (RFC4226, 5.3. Generating an HOTP value) int offset = hash[hash.length - 1] & 0xF; // We are using a long because Java hasn't got an unsigned integer type // and we need 32 unsigned bits). long truncatedHash = 0; for (int i = 0; i < 4; ++i) { truncatedHash <<= 8; // Java bytes are signed but we need an unsigned integer: // cleaning off all but the LSB. truncatedHash |= (hash[offset + i] & 0xFF); } // Clean bits higher than the 32nd (inclusive) and calculate the // module with the maximum validation code value. truncatedHash &= 0x7FFFFFFF; truncatedHash %= config.getKeyModulus(); // Returning the validation code to the caller. return (int) truncatedHash; } catch (NoSuchAlgorithmException | InvalidKeyException ex) { // Logging the exception. LOGGER.log(Level.SEVERE, ex.getMessage(), ex); // We're not disclosing internal error details to our clients. throw new GoogleAuthenticatorException("The operation cannot be performed now."); } }
[ "int", "calculateCode", "(", "byte", "[", "]", "key", ",", "long", "tm", ")", "{", "// Allocating an array of bytes to represent the specified instant", "// of time.", "byte", "[", "]", "data", "=", "new", "byte", "[", "8", "]", ";", "long", "value", "=", "tm", ";", "// Converting the instant of time from the long representation to a", "// big-endian array of bytes (RFC4226, 5.2. Description).", "for", "(", "int", "i", "=", "8", ";", "i", "--", ">", "0", ";", "value", ">>>=", "8", ")", "{", "data", "[", "i", "]", "=", "(", "byte", ")", "value", ";", "}", "// Building the secret key specification for the HmacSHA1 algorithm.", "SecretKeySpec", "signKey", "=", "new", "SecretKeySpec", "(", "key", ",", "config", ".", "getHmacHashFunction", "(", ")", ".", "toString", "(", ")", ")", ";", "try", "{", "// Getting an HmacSHA1/HmacSHA256 algorithm implementation from the JCE.", "Mac", "mac", "=", "Mac", ".", "getInstance", "(", "config", ".", "getHmacHashFunction", "(", ")", ".", "toString", "(", ")", ")", ";", "// Initializing the MAC algorithm.", "mac", ".", "init", "(", "signKey", ")", ";", "// Processing the instant of time and getting the encrypted data.", "byte", "[", "]", "hash", "=", "mac", ".", "doFinal", "(", "data", ")", ";", "// Building the validation code performing dynamic truncation", "// (RFC4226, 5.3. Generating an HOTP value)", "int", "offset", "=", "hash", "[", "hash", ".", "length", "-", "1", "]", "&", "0xF", ";", "// We are using a long because Java hasn't got an unsigned integer type", "// and we need 32 unsigned bits).", "long", "truncatedHash", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "4", ";", "++", "i", ")", "{", "truncatedHash", "<<=", "8", ";", "// Java bytes are signed but we need an unsigned integer:", "// cleaning off all but the LSB.", "truncatedHash", "|=", "(", "hash", "[", "offset", "+", "i", "]", "&", "0xFF", ")", ";", "}", "// Clean bits higher than the 32nd (inclusive) and calculate the", "// module with the maximum validation code value.", "truncatedHash", "&=", "0x7FFFFFFF", ";", "truncatedHash", "%=", "config", ".", "getKeyModulus", "(", ")", ";", "// Returning the validation code to the caller.", "return", "(", "int", ")", "truncatedHash", ";", "}", "catch", "(", "NoSuchAlgorithmException", "|", "InvalidKeyException", "ex", ")", "{", "// Logging the exception.", "LOGGER", ".", "log", "(", "Level", ".", "SEVERE", ",", "ex", ".", "getMessage", "(", ")", ",", "ex", ")", ";", "// We're not disclosing internal error details to our clients.", "throw", "new", "GoogleAuthenticatorException", "(", "\"The operation cannot be performed now.\"", ")", ";", "}", "}" ]
Calculates the verification code of the provided key at the specified instant of time using the algorithm specified in RFC 6238. @param key the secret key in binary format. @param tm the instant of time. @return the validation code for the provided key at the specified instant of time.
[ "Calculates", "the", "verification", "code", "of", "the", "provided", "key", "at", "the", "specified", "instant", "of", "time", "using", "the", "algorithm", "specified", "in", "RFC", "6238", "." ]
train
https://github.com/wstrange/GoogleAuth/blob/03f37333f8b3e411e10e63a7c85c4d2155929321/src/main/java/com/warrenstrange/googleauth/GoogleAuthenticator.java#L209-L270
BorderTech/wcomponents
wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/SimpleTabs.java
SimpleTabs.addTab
public void addTab(final WComponent card, final String name) { """ Adds a tab. @param card the tab content. @param name the tab name. """ WContainer titledCard = new WContainer(); WText title = new WText("<b>[" + name + "]:</b><br/>"); title.setEncodeText(false); titledCard.add(title); titledCard.add(card); deck.add(titledCard); final TabButton button = new TabButton(name, titledCard); button.setAction(new Action() { @Override public void execute(final ActionEvent event) { deck.makeVisible(button.getAssociatedCard()); } }); btnPanel.add(button); }
java
public void addTab(final WComponent card, final String name) { WContainer titledCard = new WContainer(); WText title = new WText("<b>[" + name + "]:</b><br/>"); title.setEncodeText(false); titledCard.add(title); titledCard.add(card); deck.add(titledCard); final TabButton button = new TabButton(name, titledCard); button.setAction(new Action() { @Override public void execute(final ActionEvent event) { deck.makeVisible(button.getAssociatedCard()); } }); btnPanel.add(button); }
[ "public", "void", "addTab", "(", "final", "WComponent", "card", ",", "final", "String", "name", ")", "{", "WContainer", "titledCard", "=", "new", "WContainer", "(", ")", ";", "WText", "title", "=", "new", "WText", "(", "\"<b>[\"", "+", "name", "+", "\"]:</b><br/>\"", ")", ";", "title", ".", "setEncodeText", "(", "false", ")", ";", "titledCard", ".", "add", "(", "title", ")", ";", "titledCard", ".", "add", "(", "card", ")", ";", "deck", ".", "add", "(", "titledCard", ")", ";", "final", "TabButton", "button", "=", "new", "TabButton", "(", "name", ",", "titledCard", ")", ";", "button", ".", "setAction", "(", "new", "Action", "(", ")", "{", "@", "Override", "public", "void", "execute", "(", "final", "ActionEvent", "event", ")", "{", "deck", ".", "makeVisible", "(", "button", ".", "getAssociatedCard", "(", ")", ")", ";", "}", "}", ")", ";", "btnPanel", ".", "add", "(", "button", ")", ";", "}" ]
Adds a tab. @param card the tab content. @param name the tab name.
[ "Adds", "a", "tab", "." ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/SimpleTabs.java#L46-L65
Azure/azure-sdk-for-java
batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/JobSchedulesImpl.java
JobSchedulesImpl.enableAsync
public Observable<Void> enableAsync(String jobScheduleId) { """ Enables a job schedule. @param jobScheduleId The ID of the job schedule to enable. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceResponseWithHeaders} object if successful. """ return enableWithServiceResponseAsync(jobScheduleId).map(new Func1<ServiceResponseWithHeaders<Void, JobScheduleEnableHeaders>, Void>() { @Override public Void call(ServiceResponseWithHeaders<Void, JobScheduleEnableHeaders> response) { return response.body(); } }); }
java
public Observable<Void> enableAsync(String jobScheduleId) { return enableWithServiceResponseAsync(jobScheduleId).map(new Func1<ServiceResponseWithHeaders<Void, JobScheduleEnableHeaders>, Void>() { @Override public Void call(ServiceResponseWithHeaders<Void, JobScheduleEnableHeaders> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Void", ">", "enableAsync", "(", "String", "jobScheduleId", ")", "{", "return", "enableWithServiceResponseAsync", "(", "jobScheduleId", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponseWithHeaders", "<", "Void", ",", "JobScheduleEnableHeaders", ">", ",", "Void", ">", "(", ")", "{", "@", "Override", "public", "Void", "call", "(", "ServiceResponseWithHeaders", "<", "Void", ",", "JobScheduleEnableHeaders", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Enables a job schedule. @param jobScheduleId The ID of the job schedule to enable. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceResponseWithHeaders} object if successful.
[ "Enables", "a", "job", "schedule", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/JobSchedulesImpl.java#L1576-L1583
apache/flink
flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/util/SegmentsUtil.java
SegmentsUtil.bitUnSet
public static void bitUnSet(MemorySegment segment, int baseOffset, int index) { """ unset bit. @param segment target segment. @param baseOffset bits base offset. @param index bit index from base offset. """ int offset = baseOffset + ((index & BIT_BYTE_POSITION_MASK) >>> 3); byte current = segment.get(offset); current &= ~(1 << (index & BIT_BYTE_INDEX_MASK)); segment.put(offset, current); }
java
public static void bitUnSet(MemorySegment segment, int baseOffset, int index) { int offset = baseOffset + ((index & BIT_BYTE_POSITION_MASK) >>> 3); byte current = segment.get(offset); current &= ~(1 << (index & BIT_BYTE_INDEX_MASK)); segment.put(offset, current); }
[ "public", "static", "void", "bitUnSet", "(", "MemorySegment", "segment", ",", "int", "baseOffset", ",", "int", "index", ")", "{", "int", "offset", "=", "baseOffset", "+", "(", "(", "index", "&", "BIT_BYTE_POSITION_MASK", ")", ">>>", "3", ")", ";", "byte", "current", "=", "segment", ".", "get", "(", "offset", ")", ";", "current", "&=", "~", "(", "1", "<<", "(", "index", "&", "BIT_BYTE_INDEX_MASK", ")", ")", ";", "segment", ".", "put", "(", "offset", ",", "current", ")", ";", "}" ]
unset bit. @param segment target segment. @param baseOffset bits base offset. @param index bit index from base offset.
[ "unset", "bit", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/util/SegmentsUtil.java#L419-L424
sarl/sarl
contribs/io.sarl.pythongenerator/io.sarl.pythongenerator.generator/src/io/sarl/pythongenerator/generator/generator/PyExpressionGenerator.java
PyExpressionGenerator._generate
@SuppressWarnings("static-method") protected XExpression _generate(XNumberLiteral literal, IAppendable it, IExtraLanguageGeneratorContext context) { """ Generate the given object. @param literal the literal. @param it the target for the generated content. @param context the context. @return the literal. """ appendReturnIfExpectedReturnedExpression(it, context); it.append(literal.getValue()); return literal; }
java
@SuppressWarnings("static-method") protected XExpression _generate(XNumberLiteral literal, IAppendable it, IExtraLanguageGeneratorContext context) { appendReturnIfExpectedReturnedExpression(it, context); it.append(literal.getValue()); return literal; }
[ "@", "SuppressWarnings", "(", "\"static-method\"", ")", "protected", "XExpression", "_generate", "(", "XNumberLiteral", "literal", ",", "IAppendable", "it", ",", "IExtraLanguageGeneratorContext", "context", ")", "{", "appendReturnIfExpectedReturnedExpression", "(", "it", ",", "context", ")", ";", "it", ".", "append", "(", "literal", ".", "getValue", "(", ")", ")", ";", "return", "literal", ";", "}" ]
Generate the given object. @param literal the literal. @param it the target for the generated content. @param context the context. @return the literal.
[ "Generate", "the", "given", "object", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/contribs/io.sarl.pythongenerator/io.sarl.pythongenerator.generator/src/io/sarl/pythongenerator/generator/generator/PyExpressionGenerator.java#L337-L342
timewalker74/ffmq
core/src/main/java/net/timewalker/ffmq4/local/connection/LocalConnection.java
LocalConnection.checkPermission
public final void checkPermission( Destination destination , String action ) throws JMSException { """ Check if the connection has the required credentials to use the given destination """ if (securityContext == null) return; // Security is disabled DestinationRef destinationRef = DestinationTools.asRef(destination); securityContext.checkPermission(destinationRef.getResourceName(), action); }
java
public final void checkPermission( Destination destination , String action ) throws JMSException { if (securityContext == null) return; // Security is disabled DestinationRef destinationRef = DestinationTools.asRef(destination); securityContext.checkPermission(destinationRef.getResourceName(), action); }
[ "public", "final", "void", "checkPermission", "(", "Destination", "destination", ",", "String", "action", ")", "throws", "JMSException", "{", "if", "(", "securityContext", "==", "null", ")", "return", ";", "// Security is disabled", "DestinationRef", "destinationRef", "=", "DestinationTools", ".", "asRef", "(", "destination", ")", ";", "securityContext", ".", "checkPermission", "(", "destinationRef", ".", "getResourceName", "(", ")", ",", "action", ")", ";", "}" ]
Check if the connection has the required credentials to use the given destination
[ "Check", "if", "the", "connection", "has", "the", "required", "credentials", "to", "use", "the", "given", "destination" ]
train
https://github.com/timewalker74/ffmq/blob/638773ee29a4a5f9c6119ed74ad14ac9c46382b3/core/src/main/java/net/timewalker/ffmq4/local/connection/LocalConnection.java#L182-L189
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/stats/Counters.java
Counters.dotProduct
public static <E> double dotProduct(Counter<E> c, double[] a, Index<E> idx) { """ Returns the product of Counter c and double[] a, using Index idx to map entries in C onto a. @return The product of c and a. """ double dotProd = 0; for (Map.Entry<E, Double> entry : c.entrySet()) { int keyIdx = idx.indexOf(entry.getKey()); if (keyIdx == -1) { continue; } dotProd += entry.getValue() * a[keyIdx]; } return dotProd; }
java
public static <E> double dotProduct(Counter<E> c, double[] a, Index<E> idx) { double dotProd = 0; for (Map.Entry<E, Double> entry : c.entrySet()) { int keyIdx = idx.indexOf(entry.getKey()); if (keyIdx == -1) { continue; } dotProd += entry.getValue() * a[keyIdx]; } return dotProd; }
[ "public", "static", "<", "E", ">", "double", "dotProduct", "(", "Counter", "<", "E", ">", "c", ",", "double", "[", "]", "a", ",", "Index", "<", "E", ">", "idx", ")", "{", "double", "dotProd", "=", "0", ";", "for", "(", "Map", ".", "Entry", "<", "E", ",", "Double", ">", "entry", ":", "c", ".", "entrySet", "(", ")", ")", "{", "int", "keyIdx", "=", "idx", ".", "indexOf", "(", "entry", ".", "getKey", "(", ")", ")", ";", "if", "(", "keyIdx", "==", "-", "1", ")", "{", "continue", ";", "}", "dotProd", "+=", "entry", ".", "getValue", "(", ")", "*", "a", "[", "keyIdx", "]", ";", "}", "return", "dotProd", ";", "}" ]
Returns the product of Counter c and double[] a, using Index idx to map entries in C onto a. @return The product of c and a.
[ "Returns", "the", "product", "of", "Counter", "c", "and", "double", "[]", "a", "using", "Index", "idx", "to", "map", "entries", "in", "C", "onto", "a", "." ]
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/stats/Counters.java#L1051-L1061
gallandarakhneorg/afc
core/vmutils/src/main/java/org/arakhne/afc/vmutil/FileSystem.java
FileSystem.makeAbsolute
@Pure public static File makeAbsolute(File filename, File current) { """ Make the given filename absolute from the given root if it is not already absolute. <table border="1" width="100%" summary="Cases"> <thead> <tr> <td>{@code filename}</td><td>{@code current}</td><td>Result</td> </tr> </thead> <tr> <td><code>null</code></td> <td><code>null</code></td> <td><code>null</code></td> </tr> <tr> <td><code>null</code></td> <td><code>/myroot</code></td> <td><code>null</code></td> </tr> <tr> <td><code>/path/to/file</code></td> <td><code>null</code></td> <td><code>/path/to/file</code></td> </tr> <tr> <td><code>path/to/file</code></td> <td><code>null</code></td> <td><code>path/to/file</code></td> </tr> <tr> <td><code>/path/to/file</code></td> <td><code>/myroot</code></td> <td><code>/path/to/file</code></td> </tr> <tr> <td><code>path/to/file</code></td> <td><code>/myroot</code></td> <td><code>/myroot/path/to/file</code></td> </tr> </table> @param filename is the name to make absolute. @param current is the current directory which permits to make absolute. @return an absolute filename. """ if (filename == null) { return null; } if (current != null && !filename.isAbsolute()) { try { return new File(current.getCanonicalFile(), filename.getPath()); } catch (IOException exception) { return new File(current.getAbsoluteFile(), filename.getPath()); } } return filename; }
java
@Pure public static File makeAbsolute(File filename, File current) { if (filename == null) { return null; } if (current != null && !filename.isAbsolute()) { try { return new File(current.getCanonicalFile(), filename.getPath()); } catch (IOException exception) { return new File(current.getAbsoluteFile(), filename.getPath()); } } return filename; }
[ "@", "Pure", "public", "static", "File", "makeAbsolute", "(", "File", "filename", ",", "File", "current", ")", "{", "if", "(", "filename", "==", "null", ")", "{", "return", "null", ";", "}", "if", "(", "current", "!=", "null", "&&", "!", "filename", ".", "isAbsolute", "(", ")", ")", "{", "try", "{", "return", "new", "File", "(", "current", ".", "getCanonicalFile", "(", ")", ",", "filename", ".", "getPath", "(", ")", ")", ";", "}", "catch", "(", "IOException", "exception", ")", "{", "return", "new", "File", "(", "current", ".", "getAbsoluteFile", "(", ")", ",", "filename", ".", "getPath", "(", ")", ")", ";", "}", "}", "return", "filename", ";", "}" ]
Make the given filename absolute from the given root if it is not already absolute. <table border="1" width="100%" summary="Cases"> <thead> <tr> <td>{@code filename}</td><td>{@code current}</td><td>Result</td> </tr> </thead> <tr> <td><code>null</code></td> <td><code>null</code></td> <td><code>null</code></td> </tr> <tr> <td><code>null</code></td> <td><code>/myroot</code></td> <td><code>null</code></td> </tr> <tr> <td><code>/path/to/file</code></td> <td><code>null</code></td> <td><code>/path/to/file</code></td> </tr> <tr> <td><code>path/to/file</code></td> <td><code>null</code></td> <td><code>path/to/file</code></td> </tr> <tr> <td><code>/path/to/file</code></td> <td><code>/myroot</code></td> <td><code>/path/to/file</code></td> </tr> <tr> <td><code>path/to/file</code></td> <td><code>/myroot</code></td> <td><code>/myroot/path/to/file</code></td> </tr> </table> @param filename is the name to make absolute. @param current is the current directory which permits to make absolute. @return an absolute filename.
[ "Make", "the", "given", "filename", "absolute", "from", "the", "given", "root", "if", "it", "is", "not", "already", "absolute", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/vmutils/src/main/java/org/arakhne/afc/vmutil/FileSystem.java#L2165-L2178
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/tiles/overlay/BoundedOverlay.java
BoundedOverlay.isWithinBoundingBox
public boolean isWithinBoundingBox(int x, int y, int zoom) { """ Check if the tile request is within the desired tile bounds @param x x coordinate @param y y coordinate @param zoom zoom value @return true if within bounds """ boolean withinBounds = true; // If a bounding box is set, check if it overlaps with the request if (webMercatorBoundingBox != null) { // Get the bounding box of the requested tile BoundingBox tileWebMercatorBoundingBox = TileBoundingBoxUtils .getWebMercatorBoundingBox(x, y, zoom); // Adjust the bounding box if needed BoundingBox adjustedWebMercatorBoundingBox = getWebMercatorBoundingBox(tileWebMercatorBoundingBox); // Check if the request overlaps withinBounds = adjustedWebMercatorBoundingBox.intersects( tileWebMercatorBoundingBox, true); } return withinBounds; }
java
public boolean isWithinBoundingBox(int x, int y, int zoom) { boolean withinBounds = true; // If a bounding box is set, check if it overlaps with the request if (webMercatorBoundingBox != null) { // Get the bounding box of the requested tile BoundingBox tileWebMercatorBoundingBox = TileBoundingBoxUtils .getWebMercatorBoundingBox(x, y, zoom); // Adjust the bounding box if needed BoundingBox adjustedWebMercatorBoundingBox = getWebMercatorBoundingBox(tileWebMercatorBoundingBox); // Check if the request overlaps withinBounds = adjustedWebMercatorBoundingBox.intersects( tileWebMercatorBoundingBox, true); } return withinBounds; }
[ "public", "boolean", "isWithinBoundingBox", "(", "int", "x", ",", "int", "y", ",", "int", "zoom", ")", "{", "boolean", "withinBounds", "=", "true", ";", "// If a bounding box is set, check if it overlaps with the request", "if", "(", "webMercatorBoundingBox", "!=", "null", ")", "{", "// Get the bounding box of the requested tile", "BoundingBox", "tileWebMercatorBoundingBox", "=", "TileBoundingBoxUtils", ".", "getWebMercatorBoundingBox", "(", "x", ",", "y", ",", "zoom", ")", ";", "// Adjust the bounding box if needed", "BoundingBox", "adjustedWebMercatorBoundingBox", "=", "getWebMercatorBoundingBox", "(", "tileWebMercatorBoundingBox", ")", ";", "// Check if the request overlaps", "withinBounds", "=", "adjustedWebMercatorBoundingBox", ".", "intersects", "(", "tileWebMercatorBoundingBox", ",", "true", ")", ";", "}", "return", "withinBounds", ";", "}" ]
Check if the tile request is within the desired tile bounds @param x x coordinate @param y y coordinate @param zoom zoom value @return true if within bounds
[ "Check", "if", "the", "tile", "request", "is", "within", "the", "desired", "tile", "bounds" ]
train
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/tiles/overlay/BoundedOverlay.java#L213-L232
stickfigure/batchfb
src/main/java/com/googlecode/batchfb/impl/Batch.java
Batch.addParams
private void addParams(RequestBuilder call, Param[] params) { """ Adds the appropriate parameters to the call, including boilerplate ones (access token, format). @param params can be null or empty """ // Once upon a time this was necessary, now it isn't //call.addParam("format", "json"); if (this.accessToken != null) call.addParam("access_token", this.accessToken); if (this.appSecretProof != null) call.addParam("appsecret_proof", this.appSecretProof); if (params != null) { for (Param param: params) { if (param instanceof BinaryParam) { call.addParam(param.name, (InputStream)param.value, ((BinaryParam)param).contentType, "irrelevant"); } else { String paramValue = StringUtils.stringifyValue(param, this.mapper); call.addParam(param.name, paramValue); } } } }
java
private void addParams(RequestBuilder call, Param[] params) { // Once upon a time this was necessary, now it isn't //call.addParam("format", "json"); if (this.accessToken != null) call.addParam("access_token", this.accessToken); if (this.appSecretProof != null) call.addParam("appsecret_proof", this.appSecretProof); if (params != null) { for (Param param: params) { if (param instanceof BinaryParam) { call.addParam(param.name, (InputStream)param.value, ((BinaryParam)param).contentType, "irrelevant"); } else { String paramValue = StringUtils.stringifyValue(param, this.mapper); call.addParam(param.name, paramValue); } } } }
[ "private", "void", "addParams", "(", "RequestBuilder", "call", ",", "Param", "[", "]", "params", ")", "{", "// Once upon a time this was necessary, now it isn't\r", "//call.addParam(\"format\", \"json\");\r", "if", "(", "this", ".", "accessToken", "!=", "null", ")", "call", ".", "addParam", "(", "\"access_token\"", ",", "this", ".", "accessToken", ")", ";", "if", "(", "this", ".", "appSecretProof", "!=", "null", ")", "call", ".", "addParam", "(", "\"appsecret_proof\"", ",", "this", ".", "appSecretProof", ")", ";", "if", "(", "params", "!=", "null", ")", "{", "for", "(", "Param", "param", ":", "params", ")", "{", "if", "(", "param", "instanceof", "BinaryParam", ")", "{", "call", ".", "addParam", "(", "param", ".", "name", ",", "(", "InputStream", ")", "param", ".", "value", ",", "(", "(", "BinaryParam", ")", "param", ")", ".", "contentType", ",", "\"irrelevant\"", ")", ";", "}", "else", "{", "String", "paramValue", "=", "StringUtils", ".", "stringifyValue", "(", "param", ",", "this", ".", "mapper", ")", ";", "call", ".", "addParam", "(", "param", ".", "name", ",", "paramValue", ")", ";", "}", "}", "}", "}" ]
Adds the appropriate parameters to the call, including boilerplate ones (access token, format). @param params can be null or empty
[ "Adds", "the", "appropriate", "parameters", "to", "the", "call", "including", "boilerplate", "ones", "(", "access", "token", "format", ")", "." ]
train
https://github.com/stickfigure/batchfb/blob/ceeda78aa6d8397eec032ab1d8997adb7378e9e2/src/main/java/com/googlecode/batchfb/impl/Batch.java#L449-L470
morimekta/utils
console-util/src/main/java/net/morimekta/console/args/ArgumentParser.java
ArgumentParser.printUsage
public void printUsage(PrintWriter writer, boolean showHidden) { """ Print the option usage list. Essentially printed as a list of options with the description indented where it overflows the available line width. @param writer The output printer. @param showHidden Whether to show hidden options. """ if (writer instanceof IndentedPrintWriter) { printUsageInternal((IndentedPrintWriter) writer, showHidden); } else { printUsageInternal(new IndentedPrintWriter(writer), showHidden); } }
java
public void printUsage(PrintWriter writer, boolean showHidden) { if (writer instanceof IndentedPrintWriter) { printUsageInternal((IndentedPrintWriter) writer, showHidden); } else { printUsageInternal(new IndentedPrintWriter(writer), showHidden); } }
[ "public", "void", "printUsage", "(", "PrintWriter", "writer", ",", "boolean", "showHidden", ")", "{", "if", "(", "writer", "instanceof", "IndentedPrintWriter", ")", "{", "printUsageInternal", "(", "(", "IndentedPrintWriter", ")", "writer", ",", "showHidden", ")", ";", "}", "else", "{", "printUsageInternal", "(", "new", "IndentedPrintWriter", "(", "writer", ")", ",", "showHidden", ")", ";", "}", "}" ]
Print the option usage list. Essentially printed as a list of options with the description indented where it overflows the available line width. @param writer The output printer. @param showHidden Whether to show hidden options.
[ "Print", "the", "option", "usage", "list", ".", "Essentially", "printed", "as", "a", "list", "of", "options", "with", "the", "description", "indented", "where", "it", "overflows", "the", "available", "line", "width", "." ]
train
https://github.com/morimekta/utils/blob/dc987485902f1a7d58169c89c61db97425a6226d/console-util/src/main/java/net/morimekta/console/args/ArgumentParser.java#L412-L418
mygreen/xlsmapper
src/main/java/com/gh/mygreen/xlsmapper/XlsLoader.java
XlsLoader.loadMultiple
@SuppressWarnings("unchecked") public <P> P[] loadMultiple(final InputStream xlsIn, final Class<P> clazz) throws XlsMapperException, IOException { """ Excelファイルの複数シートを読み込み、任意のクラスにマップする。 <p>{@link XlsSheet#regex()}により、複数のシートが同じ形式で、同じクラスにマッピングすする際に使用します。</p> @param <P> シートをマッピングするクラスタイプ @param xlsIn 読み込み元のExcelファイルのストリーム。 @param clazz マッピング先のクラスタイプ。 @return マッピングした複数のシート。 {@link Configuration#isIgnoreSheetNotFound()}の値がtrueで、シートが見つからない場合、マッピング結果には含まれません。 @throws IllegalArgumentException {@literal xlsIn == null or clazz == null} @throws XlsMapperException マッピングに失敗した場合 @throws IOException ファイルの読み込みに失敗した場合 """ return loadMultipleDetail(xlsIn, clazz).getAll().stream() .map(s -> s.getTarget()) .toArray(n -> (P[])Array.newInstance(clazz, n)); }
java
@SuppressWarnings("unchecked") public <P> P[] loadMultiple(final InputStream xlsIn, final Class<P> clazz) throws XlsMapperException, IOException { return loadMultipleDetail(xlsIn, clazz).getAll().stream() .map(s -> s.getTarget()) .toArray(n -> (P[])Array.newInstance(clazz, n)); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "<", "P", ">", "P", "[", "]", "loadMultiple", "(", "final", "InputStream", "xlsIn", ",", "final", "Class", "<", "P", ">", "clazz", ")", "throws", "XlsMapperException", ",", "IOException", "{", "return", "loadMultipleDetail", "(", "xlsIn", ",", "clazz", ")", ".", "getAll", "(", ")", ".", "stream", "(", ")", ".", "map", "(", "s", "->", "s", ".", "getTarget", "(", ")", ")", ".", "toArray", "(", "n", "->", "(", "P", "[", "]", ")", "Array", ".", "newInstance", "(", "clazz", ",", "n", ")", ")", ";", "}" ]
Excelファイルの複数シートを読み込み、任意のクラスにマップする。 <p>{@link XlsSheet#regex()}により、複数のシートが同じ形式で、同じクラスにマッピングすする際に使用します。</p> @param <P> シートをマッピングするクラスタイプ @param xlsIn 読み込み元のExcelファイルのストリーム。 @param clazz マッピング先のクラスタイプ。 @return マッピングした複数のシート。 {@link Configuration#isIgnoreSheetNotFound()}の値がtrueで、シートが見つからない場合、マッピング結果には含まれません。 @throws IllegalArgumentException {@literal xlsIn == null or clazz == null} @throws XlsMapperException マッピングに失敗した場合 @throws IOException ファイルの読み込みに失敗した場合
[ "Excelファイルの複数シートを読み込み、任意のクラスにマップする。", "<p", ">", "{", "@link", "XlsSheet#regex", "()", "}", "により、複数のシートが同じ形式で、同じクラスにマッピングすする際に使用します。<", "/", "p", ">" ]
train
https://github.com/mygreen/xlsmapper/blob/a0c6b25c622e5f3a50b199ef685d2ee46ad5483c/src/main/java/com/gh/mygreen/xlsmapper/XlsLoader.java#L154-L160
scalanlp/nak
src/main/java/nak/liblinear/Tron.java
Tron.daxpy
private static void daxpy(double constant, double vector1[], double vector2[]) { """ constant times a vector plus a vector <pre> vector2 += constant * vector1 </pre> @since 1.8 """ if (constant == 0) return; assert vector1.length == vector2.length; for (int i = 0; i < vector1.length; i++) { vector2[i] += constant * vector1[i]; } }
java
private static void daxpy(double constant, double vector1[], double vector2[]) { if (constant == 0) return; assert vector1.length == vector2.length; for (int i = 0; i < vector1.length; i++) { vector2[i] += constant * vector1[i]; } }
[ "private", "static", "void", "daxpy", "(", "double", "constant", ",", "double", "vector1", "[", "]", ",", "double", "vector2", "[", "]", ")", "{", "if", "(", "constant", "==", "0", ")", "return", ";", "assert", "vector1", ".", "length", "==", "vector2", ".", "length", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "vector1", ".", "length", ";", "i", "++", ")", "{", "vector2", "[", "i", "]", "+=", "constant", "*", "vector1", "[", "i", "]", ";", "}", "}" ]
constant times a vector plus a vector <pre> vector2 += constant * vector1 </pre> @since 1.8
[ "constant", "times", "a", "vector", "plus", "a", "vector" ]
train
https://github.com/scalanlp/nak/blob/46462728f0fa85a884387e33f9beeec57f9cd109/src/main/java/nak/liblinear/Tron.java#L184-L191
Ordinastie/MalisisCore
src/main/java/net/malisis/core/util/EntityUtils.java
EntityUtils.addDestroyEffects
@SideOnly(Side.CLIENT) public static void addDestroyEffects(World world, BlockPos pos, ParticleManager particleManager, IBlockState... states) { """ Adds the destroy effects into the world for the specified {@link IBlockState}. @param world the world @param pos the pos @param particleManager the effect renderer @param states the states """ if (ArrayUtils.isEmpty(states)) states = new IBlockState[] { world.getBlockState(pos) }; byte nb = 4; ParticleDigging.Factory factory = new ParticleDigging.Factory(); for (int i = 0; i < nb; ++i) { for (int j = 0; j < nb; ++j) { for (int k = 0; k < nb; ++k) { double fxX = pos.getX() + (i + 0.5D) / nb; double fxY = pos.getY() + (j + 0.5D) / nb; double fxZ = pos.getZ() + (k + 0.5D) / nb; int id = Block.getStateId(states[world.rand.nextInt(states.length)]); ParticleDigging fx = (ParticleDigging) factory.createParticle( 0, world, fxX, fxY, fxZ, fxX - pos.getX() - 0.5D, fxY - pos.getY() - 0.5D, fxZ - pos.getZ() - 0.5D, id); particleManager.addEffect(fx); } } } }
java
@SideOnly(Side.CLIENT) public static void addDestroyEffects(World world, BlockPos pos, ParticleManager particleManager, IBlockState... states) { if (ArrayUtils.isEmpty(states)) states = new IBlockState[] { world.getBlockState(pos) }; byte nb = 4; ParticleDigging.Factory factory = new ParticleDigging.Factory(); for (int i = 0; i < nb; ++i) { for (int j = 0; j < nb; ++j) { for (int k = 0; k < nb; ++k) { double fxX = pos.getX() + (i + 0.5D) / nb; double fxY = pos.getY() + (j + 0.5D) / nb; double fxZ = pos.getZ() + (k + 0.5D) / nb; int id = Block.getStateId(states[world.rand.nextInt(states.length)]); ParticleDigging fx = (ParticleDigging) factory.createParticle( 0, world, fxX, fxY, fxZ, fxX - pos.getX() - 0.5D, fxY - pos.getY() - 0.5D, fxZ - pos.getZ() - 0.5D, id); particleManager.addEffect(fx); } } } }
[ "@", "SideOnly", "(", "Side", ".", "CLIENT", ")", "public", "static", "void", "addDestroyEffects", "(", "World", "world", ",", "BlockPos", "pos", ",", "ParticleManager", "particleManager", ",", "IBlockState", "...", "states", ")", "{", "if", "(", "ArrayUtils", ".", "isEmpty", "(", "states", ")", ")", "states", "=", "new", "IBlockState", "[", "]", "{", "world", ".", "getBlockState", "(", "pos", ")", "}", ";", "byte", "nb", "=", "4", ";", "ParticleDigging", ".", "Factory", "factory", "=", "new", "ParticleDigging", ".", "Factory", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "nb", ";", "++", "i", ")", "{", "for", "(", "int", "j", "=", "0", ";", "j", "<", "nb", ";", "++", "j", ")", "{", "for", "(", "int", "k", "=", "0", ";", "k", "<", "nb", ";", "++", "k", ")", "{", "double", "fxX", "=", "pos", ".", "getX", "(", ")", "+", "(", "i", "+", "0.5D", ")", "/", "nb", ";", "double", "fxY", "=", "pos", ".", "getY", "(", ")", "+", "(", "j", "+", "0.5D", ")", "/", "nb", ";", "double", "fxZ", "=", "pos", ".", "getZ", "(", ")", "+", "(", "k", "+", "0.5D", ")", "/", "nb", ";", "int", "id", "=", "Block", ".", "getStateId", "(", "states", "[", "world", ".", "rand", ".", "nextInt", "(", "states", ".", "length", ")", "]", ")", ";", "ParticleDigging", "fx", "=", "(", "ParticleDigging", ")", "factory", ".", "createParticle", "(", "0", ",", "world", ",", "fxX", ",", "fxY", ",", "fxZ", ",", "fxX", "-", "pos", ".", "getX", "(", ")", "-", "0.5D", ",", "fxY", "-", "pos", ".", "getY", "(", ")", "-", "0.5D", ",", "fxZ", "-", "pos", ".", "getZ", "(", ")", "-", "0.5D", ",", "id", ")", ";", "particleManager", ".", "addEffect", "(", "fx", ")", ";", "}", "}", "}", "}" ]
Adds the destroy effects into the world for the specified {@link IBlockState}. @param world the world @param pos the pos @param particleManager the effect renderer @param states the states
[ "Adds", "the", "destroy", "effects", "into", "the", "world", "for", "the", "specified", "{", "@link", "IBlockState", "}", "." ]
train
https://github.com/Ordinastie/MalisisCore/blob/4f8e1fa462d5c372fc23414482ba9f429881cc54/src/main/java/net/malisis/core/util/EntityUtils.java#L283-L317
comapi/comapi-chat-sdk-android
COMAPI/chat/src/main/java/com/comapi/chat/ChatController.java
ChatController.handleConversationDeleted
Observable<ChatResult> handleConversationDeleted(String conversationId, ComapiResult<Void> result) { """ Handles conversation delete service response. @param conversationId Unique identifier of an conversation. @param result Service call response. @return Observable emitting result of operations. """ if (result.getCode() != ETAG_NOT_VALID) { return persistenceController.deleteConversation(conversationId).map(success -> adapter.adaptResult(result, success)); } else { return checkState().flatMap(client -> client.service().messaging().getConversation(conversationId) .flatMap(newResult -> { if (newResult.isSuccessful()) { return persistenceController.upsertConversation(ChatConversation.builder().populate(newResult.getResult(), newResult.getETag()).build()) .flatMap(success -> Observable.fromCallable(() -> new ChatResult(false, success ? new ChatResult.Error(ETAG_NOT_VALID, "Conversation updated, try delete again.", "Conversation "+conversationId+" updated in response to wrong eTag error when deleting.") : new ChatResult.Error(0, "Error updating custom store.", null)))); } else { return Observable.fromCallable(() -> adapter.adaptResult(newResult)); } })); } }
java
Observable<ChatResult> handleConversationDeleted(String conversationId, ComapiResult<Void> result) { if (result.getCode() != ETAG_NOT_VALID) { return persistenceController.deleteConversation(conversationId).map(success -> adapter.adaptResult(result, success)); } else { return checkState().flatMap(client -> client.service().messaging().getConversation(conversationId) .flatMap(newResult -> { if (newResult.isSuccessful()) { return persistenceController.upsertConversation(ChatConversation.builder().populate(newResult.getResult(), newResult.getETag()).build()) .flatMap(success -> Observable.fromCallable(() -> new ChatResult(false, success ? new ChatResult.Error(ETAG_NOT_VALID, "Conversation updated, try delete again.", "Conversation "+conversationId+" updated in response to wrong eTag error when deleting.") : new ChatResult.Error(0, "Error updating custom store.", null)))); } else { return Observable.fromCallable(() -> adapter.adaptResult(newResult)); } })); } }
[ "Observable", "<", "ChatResult", ">", "handleConversationDeleted", "(", "String", "conversationId", ",", "ComapiResult", "<", "Void", ">", "result", ")", "{", "if", "(", "result", ".", "getCode", "(", ")", "!=", "ETAG_NOT_VALID", ")", "{", "return", "persistenceController", ".", "deleteConversation", "(", "conversationId", ")", ".", "map", "(", "success", "->", "adapter", ".", "adaptResult", "(", "result", ",", "success", ")", ")", ";", "}", "else", "{", "return", "checkState", "(", ")", ".", "flatMap", "(", "client", "->", "client", ".", "service", "(", ")", ".", "messaging", "(", ")", ".", "getConversation", "(", "conversationId", ")", ".", "flatMap", "(", "newResult", "->", "{", "if", "(", "newResult", ".", "isSuccessful", "(", ")", ")", "{", "return", "persistenceController", ".", "upsertConversation", "(", "ChatConversation", ".", "builder", "(", ")", ".", "populate", "(", "newResult", ".", "getResult", "(", ")", ",", "newResult", ".", "getETag", "(", ")", ")", ".", "build", "(", ")", ")", ".", "flatMap", "(", "success", "->", "Observable", ".", "fromCallable", "(", "(", ")", "->", "new", "ChatResult", "(", "false", ",", "success", "?", "new", "ChatResult", ".", "Error", "(", "ETAG_NOT_VALID", ",", "\"Conversation updated, try delete again.\"", ",", "\"Conversation \"", "+", "conversationId", "+", "\" updated in response to wrong eTag error when deleting.\"", ")", ":", "new", "ChatResult", ".", "Error", "(", "0", ",", "\"Error updating custom store.\"", ",", "null", ")", ")", ")", ")", ";", "}", "else", "{", "return", "Observable", ".", "fromCallable", "(", "(", ")", "->", "adapter", ".", "adaptResult", "(", "newResult", ")", ")", ";", "}", "}", ")", ")", ";", "}", "}" ]
Handles conversation delete service response. @param conversationId Unique identifier of an conversation. @param result Service call response. @return Observable emitting result of operations.
[ "Handles", "conversation", "delete", "service", "response", "." ]
train
https://github.com/comapi/comapi-chat-sdk-android/blob/388f37bfacb7793ce30c92ab70e5f32848bbe460/COMAPI/chat/src/main/java/com/comapi/chat/ChatController.java#L371-L385
killbill/killbill
invoice/src/main/java/org/killbill/billing/invoice/tree/NodeInterval.java
NodeInterval.findNode
public NodeInterval findNode(final LocalDate targetDate, final SearchCallback callback) { """ Return the first node satisfying the date and match callback. @param targetDate target date for possible match nodes whose interval comprises that date @param callback custom logic to decide if a given node is a match @return the found node or null if there is nothing. """ Preconditions.checkNotNull(callback); Preconditions.checkNotNull(targetDate); if (targetDate.compareTo(getStart()) < 0 || targetDate.compareTo(getEnd()) > 0) { return null; } NodeInterval curChild = leftChild; while (curChild != null) { if (curChild.getStart().compareTo(targetDate) <= 0 && curChild.getEnd().compareTo(targetDate) >= 0) { if (callback.isMatch(curChild)) { return curChild; } NodeInterval result = curChild.findNode(targetDate, callback); if (result != null) { return result; } } curChild = curChild.getRightSibling(); } return null; }
java
public NodeInterval findNode(final LocalDate targetDate, final SearchCallback callback) { Preconditions.checkNotNull(callback); Preconditions.checkNotNull(targetDate); if (targetDate.compareTo(getStart()) < 0 || targetDate.compareTo(getEnd()) > 0) { return null; } NodeInterval curChild = leftChild; while (curChild != null) { if (curChild.getStart().compareTo(targetDate) <= 0 && curChild.getEnd().compareTo(targetDate) >= 0) { if (callback.isMatch(curChild)) { return curChild; } NodeInterval result = curChild.findNode(targetDate, callback); if (result != null) { return result; } } curChild = curChild.getRightSibling(); } return null; }
[ "public", "NodeInterval", "findNode", "(", "final", "LocalDate", "targetDate", ",", "final", "SearchCallback", "callback", ")", "{", "Preconditions", ".", "checkNotNull", "(", "callback", ")", ";", "Preconditions", ".", "checkNotNull", "(", "targetDate", ")", ";", "if", "(", "targetDate", ".", "compareTo", "(", "getStart", "(", ")", ")", "<", "0", "||", "targetDate", ".", "compareTo", "(", "getEnd", "(", ")", ")", ">", "0", ")", "{", "return", "null", ";", "}", "NodeInterval", "curChild", "=", "leftChild", ";", "while", "(", "curChild", "!=", "null", ")", "{", "if", "(", "curChild", ".", "getStart", "(", ")", ".", "compareTo", "(", "targetDate", ")", "<=", "0", "&&", "curChild", ".", "getEnd", "(", ")", ".", "compareTo", "(", "targetDate", ")", ">=", "0", ")", "{", "if", "(", "callback", ".", "isMatch", "(", "curChild", ")", ")", "{", "return", "curChild", ";", "}", "NodeInterval", "result", "=", "curChild", ".", "findNode", "(", "targetDate", ",", "callback", ")", ";", "if", "(", "result", "!=", "null", ")", "{", "return", "result", ";", "}", "}", "curChild", "=", "curChild", ".", "getRightSibling", "(", ")", ";", "}", "return", "null", ";", "}" ]
Return the first node satisfying the date and match callback. @param targetDate target date for possible match nodes whose interval comprises that date @param callback custom logic to decide if a given node is a match @return the found node or null if there is nothing.
[ "Return", "the", "first", "node", "satisfying", "the", "date", "and", "match", "callback", "." ]
train
https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/invoice/src/main/java/org/killbill/billing/invoice/tree/NodeInterval.java#L215-L238
square/spoon
spoon-runner/src/main/java/com/squareup/spoon/html/HtmlUtils.java
HtmlUtils.getScreenshot
static Screenshot getScreenshot(File screenshot, File output) { """ Get a HTML representation of a screenshot with respect to {@code output} directory. """ String relativePath = createRelativeUri(screenshot, output); String caption = screenshot.getName(); return new Screenshot(relativePath, caption); }
java
static Screenshot getScreenshot(File screenshot, File output) { String relativePath = createRelativeUri(screenshot, output); String caption = screenshot.getName(); return new Screenshot(relativePath, caption); }
[ "static", "Screenshot", "getScreenshot", "(", "File", "screenshot", ",", "File", "output", ")", "{", "String", "relativePath", "=", "createRelativeUri", "(", "screenshot", ",", "output", ")", ";", "String", "caption", "=", "screenshot", ".", "getName", "(", ")", ";", "return", "new", "Screenshot", "(", "relativePath", ",", "caption", ")", ";", "}" ]
Get a HTML representation of a screenshot with respect to {@code output} directory.
[ "Get", "a", "HTML", "representation", "of", "a", "screenshot", "with", "respect", "to", "{" ]
train
https://github.com/square/spoon/blob/ebd51fbc1498f6bdcb61aa1281bbac2af99117b3/spoon-runner/src/main/java/com/squareup/spoon/html/HtmlUtils.java#L124-L128
google/error-prone
check_api/src/main/java/com/google/errorprone/scanner/ErrorProneScanner.java
ErrorProneScanner.handleError
@Override protected void handleError(Suppressible s, Throwable t) { """ Handles an exception thrown by an individual BugPattern. By default, wraps the exception in an {@link ErrorProneError} and rethrows. May be overridden by subclasses, for example to log the error and continue. """ if (t instanceof ErrorProneError) { throw (ErrorProneError) t; } if (t instanceof CompletionFailure) { throw (CompletionFailure) t; } TreePath path = getCurrentPath(); throw new ErrorProneError( s.canonicalName(), t, (DiagnosticPosition) path.getLeaf(), path.getCompilationUnit().getSourceFile()); }
java
@Override protected void handleError(Suppressible s, Throwable t) { if (t instanceof ErrorProneError) { throw (ErrorProneError) t; } if (t instanceof CompletionFailure) { throw (CompletionFailure) t; } TreePath path = getCurrentPath(); throw new ErrorProneError( s.canonicalName(), t, (DiagnosticPosition) path.getLeaf(), path.getCompilationUnit().getSourceFile()); }
[ "@", "Override", "protected", "void", "handleError", "(", "Suppressible", "s", ",", "Throwable", "t", ")", "{", "if", "(", "t", "instanceof", "ErrorProneError", ")", "{", "throw", "(", "ErrorProneError", ")", "t", ";", "}", "if", "(", "t", "instanceof", "CompletionFailure", ")", "{", "throw", "(", "CompletionFailure", ")", "t", ";", "}", "TreePath", "path", "=", "getCurrentPath", "(", ")", ";", "throw", "new", "ErrorProneError", "(", "s", ".", "canonicalName", "(", ")", ",", "t", ",", "(", "DiagnosticPosition", ")", "path", ".", "getLeaf", "(", ")", ",", "path", ".", "getCompilationUnit", "(", ")", ".", "getSourceFile", "(", ")", ")", ";", "}" ]
Handles an exception thrown by an individual BugPattern. By default, wraps the exception in an {@link ErrorProneError} and rethrows. May be overridden by subclasses, for example to log the error and continue.
[ "Handles", "an", "exception", "thrown", "by", "an", "individual", "BugPattern", ".", "By", "default", "wraps", "the", "exception", "in", "an", "{" ]
train
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/scanner/ErrorProneScanner.java#L894-L908
haifengl/smile
core/src/main/java/smile/association/FPGrowth.java
FPGrowth.getLocalItemSupport
private boolean getLocalItemSupport(FPTree.Node node, int[] localItemSupport) { """ Counts the supports of single items in ancestor item sets linked list. @return true if there are condition patterns given this node """ boolean end = true; Arrays.fill(localItemSupport, 0); while (node != null) { int support = node.count; Node parent = node.parent; while (parent != null) { localItemSupport[parent.id] += support; parent = parent.parent; end = false; } node = node.next; } return !end; }
java
private boolean getLocalItemSupport(FPTree.Node node, int[] localItemSupport) { boolean end = true; Arrays.fill(localItemSupport, 0); while (node != null) { int support = node.count; Node parent = node.parent; while (parent != null) { localItemSupport[parent.id] += support; parent = parent.parent; end = false; } node = node.next; } return !end; }
[ "private", "boolean", "getLocalItemSupport", "(", "FPTree", ".", "Node", "node", ",", "int", "[", "]", "localItemSupport", ")", "{", "boolean", "end", "=", "true", ";", "Arrays", ".", "fill", "(", "localItemSupport", ",", "0", ")", ";", "while", "(", "node", "!=", "null", ")", "{", "int", "support", "=", "node", ".", "count", ";", "Node", "parent", "=", "node", ".", "parent", ";", "while", "(", "parent", "!=", "null", ")", "{", "localItemSupport", "[", "parent", ".", "id", "]", "+=", "support", ";", "parent", "=", "parent", ".", "parent", ";", "end", "=", "false", ";", "}", "node", "=", "node", ".", "next", ";", "}", "return", "!", "end", ";", "}" ]
Counts the supports of single items in ancestor item sets linked list. @return true if there are condition patterns given this node
[ "Counts", "the", "supports", "of", "single", "items", "in", "ancestor", "item", "sets", "linked", "list", "." ]
train
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/core/src/main/java/smile/association/FPGrowth.java#L421-L437
codeprimate-software/cp-elements
src/main/java/org/cp/elements/lang/ObjectUtils.java
ObjectUtils.doOperationSafely
public static <T> T doOperationSafely(ExceptionThrowingOperation<T> operation, T defaultValue) { """ Safely executes the given {@link ExceptionThrowingOperation} handling any checked {@link Exception} thrown during the normal execution of the operation by returning the given {@link Object default value} or rethrowing an {@link IllegalStateException} if the {@link Object default value} is {@literal null}. @param <T> {@link Class type} of the return value. @param operation {@link ExceptionThrowingOperation} to execute. @param defaultValue {@link Object} to return if the {@link ExceptionThrowingOperation} throws a checked {@link Exception}. @return the {@link Object result} of the {@link ExceptionThrowingOperation} or {@link Object default value} if the {@link ExceptionThrowingOperation} throws a checked {@link Exception}. @see org.cp.elements.lang.ObjectUtils.ExceptionThrowingOperation @see #returnValueOrThrowIfNull(Object, RuntimeException) """ try { return operation.doExceptionThrowingOperation(); } catch (Exception cause) { return returnValueOrThrowIfNull(defaultValue, newIllegalStateException(cause, "Failed to execute operation [%s]", operation)); } }
java
public static <T> T doOperationSafely(ExceptionThrowingOperation<T> operation, T defaultValue) { try { return operation.doExceptionThrowingOperation(); } catch (Exception cause) { return returnValueOrThrowIfNull(defaultValue, newIllegalStateException(cause, "Failed to execute operation [%s]", operation)); } }
[ "public", "static", "<", "T", ">", "T", "doOperationSafely", "(", "ExceptionThrowingOperation", "<", "T", ">", "operation", ",", "T", "defaultValue", ")", "{", "try", "{", "return", "operation", ".", "doExceptionThrowingOperation", "(", ")", ";", "}", "catch", "(", "Exception", "cause", ")", "{", "return", "returnValueOrThrowIfNull", "(", "defaultValue", ",", "newIllegalStateException", "(", "cause", ",", "\"Failed to execute operation [%s]\"", ",", "operation", ")", ")", ";", "}", "}" ]
Safely executes the given {@link ExceptionThrowingOperation} handling any checked {@link Exception} thrown during the normal execution of the operation by returning the given {@link Object default value} or rethrowing an {@link IllegalStateException} if the {@link Object default value} is {@literal null}. @param <T> {@link Class type} of the return value. @param operation {@link ExceptionThrowingOperation} to execute. @param defaultValue {@link Object} to return if the {@link ExceptionThrowingOperation} throws a checked {@link Exception}. @return the {@link Object result} of the {@link ExceptionThrowingOperation} or {@link Object default value} if the {@link ExceptionThrowingOperation} throws a checked {@link Exception}. @see org.cp.elements.lang.ObjectUtils.ExceptionThrowingOperation @see #returnValueOrThrowIfNull(Object, RuntimeException)
[ "Safely", "executes", "the", "given", "{", "@link", "ExceptionThrowingOperation", "}", "handling", "any", "checked", "{", "@link", "Exception", "}", "thrown", "during", "the", "normal", "execution", "of", "the", "operation", "by", "returning", "the", "given", "{", "@link", "Object", "default", "value", "}", "or", "rethrowing", "an", "{", "@link", "IllegalStateException", "}", "if", "the", "{", "@link", "Object", "default", "value", "}", "is", "{", "@literal", "null", "}", "." ]
train
https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/ObjectUtils.java#L170-L179
javamelody/javamelody
javamelody-spring-boot-starter/src/main/java/net/bull/javamelody/JavaMelodyAutoConfiguration.java
JavaMelodyAutoConfiguration.monitoringFeignClientAdvisor
@SuppressWarnings("unchecked") @Bean @ConditionalOnClass(name = "org.springframework.cloud.openfeign.FeignClient") @ConditionalOnProperty(prefix = JavaMelodyConfigurationProperties.PREFIX, name = "spring-monitoring-enabled", matchIfMissing = true) // we check that the DefaultAdvisorAutoProxyCreator above is not enabled, because if it's enabled then feign calls are counted twice @ConditionalOnMissingBean(DefaultAdvisorAutoProxyCreator.class) public MonitoringSpringAdvisor monitoringFeignClientAdvisor() throws ClassNotFoundException { """ Monitoring of Feign clients. @return MonitoringSpringAdvisor @throws ClassNotFoundException should not happen """ final Class<? extends Annotation> feignClientClass = (Class<? extends Annotation>) Class .forName("org.springframework.cloud.openfeign.FeignClient"); final MonitoringSpringAdvisor advisor = new MonitoringSpringAdvisor( new AnnotationMatchingPointcut(feignClientClass, true)); advisor.setAdvice(new MonitoringSpringInterceptor() { private static final long serialVersionUID = 1L; @Override protected String getRequestName(MethodInvocation invocation) { final StringBuilder sb = new StringBuilder(); final Method method = invocation.getMethod(); final RequestMapping requestMapping = method.getAnnotation(RequestMapping.class); if (requestMapping != null) { String[] path = requestMapping.value(); if (path.length == 0) { path = requestMapping.path(); } if (path.length > 0) { sb.append(path[0]); sb.append(' '); if (requestMapping.method().length > 0) { sb.append(requestMapping.method()[0].name()); } else { sb.append("GET"); } sb.append('\n'); } } final Class<?> declaringClass = method.getDeclaringClass(); final String classPart = declaringClass.getSimpleName(); final String methodPart = method.getName(); sb.append(classPart).append('.').append(methodPart); return sb.toString(); } }); return advisor; }
java
@SuppressWarnings("unchecked") @Bean @ConditionalOnClass(name = "org.springframework.cloud.openfeign.FeignClient") @ConditionalOnProperty(prefix = JavaMelodyConfigurationProperties.PREFIX, name = "spring-monitoring-enabled", matchIfMissing = true) // we check that the DefaultAdvisorAutoProxyCreator above is not enabled, because if it's enabled then feign calls are counted twice @ConditionalOnMissingBean(DefaultAdvisorAutoProxyCreator.class) public MonitoringSpringAdvisor monitoringFeignClientAdvisor() throws ClassNotFoundException { final Class<? extends Annotation> feignClientClass = (Class<? extends Annotation>) Class .forName("org.springframework.cloud.openfeign.FeignClient"); final MonitoringSpringAdvisor advisor = new MonitoringSpringAdvisor( new AnnotationMatchingPointcut(feignClientClass, true)); advisor.setAdvice(new MonitoringSpringInterceptor() { private static final long serialVersionUID = 1L; @Override protected String getRequestName(MethodInvocation invocation) { final StringBuilder sb = new StringBuilder(); final Method method = invocation.getMethod(); final RequestMapping requestMapping = method.getAnnotation(RequestMapping.class); if (requestMapping != null) { String[] path = requestMapping.value(); if (path.length == 0) { path = requestMapping.path(); } if (path.length > 0) { sb.append(path[0]); sb.append(' '); if (requestMapping.method().length > 0) { sb.append(requestMapping.method()[0].name()); } else { sb.append("GET"); } sb.append('\n'); } } final Class<?> declaringClass = method.getDeclaringClass(); final String classPart = declaringClass.getSimpleName(); final String methodPart = method.getName(); sb.append(classPart).append('.').append(methodPart); return sb.toString(); } }); return advisor; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "@", "Bean", "@", "ConditionalOnClass", "(", "name", "=", "\"org.springframework.cloud.openfeign.FeignClient\"", ")", "@", "ConditionalOnProperty", "(", "prefix", "=", "JavaMelodyConfigurationProperties", ".", "PREFIX", ",", "name", "=", "\"spring-monitoring-enabled\"", ",", "matchIfMissing", "=", "true", ")", "// we check that the DefaultAdvisorAutoProxyCreator above is not enabled, because if it's enabled then feign calls are counted twice", "@", "ConditionalOnMissingBean", "(", "DefaultAdvisorAutoProxyCreator", ".", "class", ")", "public", "MonitoringSpringAdvisor", "monitoringFeignClientAdvisor", "(", ")", "throws", "ClassNotFoundException", "{", "final", "Class", "<", "?", "extends", "Annotation", ">", "feignClientClass", "=", "(", "Class", "<", "?", "extends", "Annotation", ">", ")", "Class", ".", "forName", "(", "\"org.springframework.cloud.openfeign.FeignClient\"", ")", ";", "final", "MonitoringSpringAdvisor", "advisor", "=", "new", "MonitoringSpringAdvisor", "(", "new", "AnnotationMatchingPointcut", "(", "feignClientClass", ",", "true", ")", ")", ";", "advisor", ".", "setAdvice", "(", "new", "MonitoringSpringInterceptor", "(", ")", "{", "private", "static", "final", "long", "serialVersionUID", "=", "1L", ";", "@", "Override", "protected", "String", "getRequestName", "(", "MethodInvocation", "invocation", ")", "{", "final", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "final", "Method", "method", "=", "invocation", ".", "getMethod", "(", ")", ";", "final", "RequestMapping", "requestMapping", "=", "method", ".", "getAnnotation", "(", "RequestMapping", ".", "class", ")", ";", "if", "(", "requestMapping", "!=", "null", ")", "{", "String", "[", "]", "path", "=", "requestMapping", ".", "value", "(", ")", ";", "if", "(", "path", ".", "length", "==", "0", ")", "{", "path", "=", "requestMapping", ".", "path", "(", ")", ";", "}", "if", "(", "path", ".", "length", ">", "0", ")", "{", "sb", ".", "append", "(", "path", "[", "0", "]", ")", ";", "sb", ".", "append", "(", "'", "'", ")", ";", "if", "(", "requestMapping", ".", "method", "(", ")", ".", "length", ">", "0", ")", "{", "sb", ".", "append", "(", "requestMapping", ".", "method", "(", ")", "[", "0", "]", ".", "name", "(", ")", ")", ";", "}", "else", "{", "sb", ".", "append", "(", "\"GET\"", ")", ";", "}", "sb", ".", "append", "(", "'", "'", ")", ";", "}", "}", "final", "Class", "<", "?", ">", "declaringClass", "=", "method", ".", "getDeclaringClass", "(", ")", ";", "final", "String", "classPart", "=", "declaringClass", ".", "getSimpleName", "(", ")", ";", "final", "String", "methodPart", "=", "method", ".", "getName", "(", ")", ";", "sb", ".", "append", "(", "classPart", ")", ".", "append", "(", "'", "'", ")", ".", "append", "(", "methodPart", ")", ";", "return", "sb", ".", "toString", "(", ")", ";", "}", "}", ")", ";", "return", "advisor", ";", "}" ]
Monitoring of Feign clients. @return MonitoringSpringAdvisor @throws ClassNotFoundException should not happen
[ "Monitoring", "of", "Feign", "clients", "." ]
train
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-spring-boot-starter/src/main/java/net/bull/javamelody/JavaMelodyAutoConfiguration.java#L279-L322
protostuff/protostuff
protostuff-xml/src/main/java/io/protostuff/XmlIOUtil.java
XmlIOUtil.writeTo
public static <T> void writeTo(Writer w, T message, Schema<T> schema) throws IOException { """ Serializes the {@code message} into a {@link Writer} using the given {@code schema}. """ writeTo(w, message, schema, DEFAULT_OUTPUT_FACTORY); }
java
public static <T> void writeTo(Writer w, T message, Schema<T> schema) throws IOException { writeTo(w, message, schema, DEFAULT_OUTPUT_FACTORY); }
[ "public", "static", "<", "T", ">", "void", "writeTo", "(", "Writer", "w", ",", "T", "message", ",", "Schema", "<", "T", ">", "schema", ")", "throws", "IOException", "{", "writeTo", "(", "w", ",", "message", ",", "schema", ",", "DEFAULT_OUTPUT_FACTORY", ")", ";", "}" ]
Serializes the {@code message} into a {@link Writer} using the given {@code schema}.
[ "Serializes", "the", "{" ]
train
https://github.com/protostuff/protostuff/blob/af669cf089057d0ec83220266131ce411854af7b/protostuff-xml/src/main/java/io/protostuff/XmlIOUtil.java#L399-L403
d-michail/jheaps
src/main/java/org/jheaps/tree/SkewHeap.java
SkewHeap.unlinkAndUnionChildren
protected Node<K, V> unlinkAndUnionChildren(Node<K, V> n) { """ Unlink the two children of a node and union them forming a new tree. @param n the node @return the tree which is formed by the two children subtrees of the node """ // disconnect children Node<K, V> child1 = n.o_c; if (child1 == null) { return null; } n.o_c = null; Node<K, V> child2 = child1.y_s; if (child2 == n) { child2 = null; } else { child2.y_s = null; } child1.y_s = null; if (comparator == null) { return union(child1, child2); } else { return unionWithComparator(child1, child2); } }
java
protected Node<K, V> unlinkAndUnionChildren(Node<K, V> n) { // disconnect children Node<K, V> child1 = n.o_c; if (child1 == null) { return null; } n.o_c = null; Node<K, V> child2 = child1.y_s; if (child2 == n) { child2 = null; } else { child2.y_s = null; } child1.y_s = null; if (comparator == null) { return union(child1, child2); } else { return unionWithComparator(child1, child2); } }
[ "protected", "Node", "<", "K", ",", "V", ">", "unlinkAndUnionChildren", "(", "Node", "<", "K", ",", "V", ">", "n", ")", "{", "// disconnect children", "Node", "<", "K", ",", "V", ">", "child1", "=", "n", ".", "o_c", ";", "if", "(", "child1", "==", "null", ")", "{", "return", "null", ";", "}", "n", ".", "o_c", "=", "null", ";", "Node", "<", "K", ",", "V", ">", "child2", "=", "child1", ".", "y_s", ";", "if", "(", "child2", "==", "n", ")", "{", "child2", "=", "null", ";", "}", "else", "{", "child2", ".", "y_s", "=", "null", ";", "}", "child1", ".", "y_s", "=", "null", ";", "if", "(", "comparator", "==", "null", ")", "{", "return", "union", "(", "child1", ",", "child2", ")", ";", "}", "else", "{", "return", "unionWithComparator", "(", "child1", ",", "child2", ")", ";", "}", "}" ]
Unlink the two children of a node and union them forming a new tree. @param n the node @return the tree which is formed by the two children subtrees of the node
[ "Unlink", "the", "two", "children", "of", "a", "node", "and", "union", "them", "forming", "a", "new", "tree", "." ]
train
https://github.com/d-michail/jheaps/blob/7146451dd6591c2a8559dc564c9c40428c4a2c10/src/main/java/org/jheaps/tree/SkewHeap.java#L486-L507
google/j2objc
translator/src/main/java/com/google/devtools/j2objc/gen/TypeDeclarationGenerator.java
TypeDeclarationGenerator.printMethodDeclaration
private void printMethodDeclaration(MethodDeclaration m, boolean isCompanionClass) { """ Emit method declaration. @param m The method. @param isCompanionClass If true, emit only if m is a static interface method. """ ExecutableElement methodElement = m.getExecutableElement(); TypeElement typeElement = ElementUtil.getDeclaringClass(methodElement); if (typeElement.getKind().isInterface()) { // isCompanion and isStatic must be both false (i.e. this prints a non-static method decl // in @protocol) or must both be true (i.e. this prints a static method decl in the // companion class' @interface). if (isCompanionClass != ElementUtil.isStatic(methodElement)) { return; } } newline(); JavadocGenerator.printDocComment(getBuilder(), m.getJavadoc()); String methodSignature = getMethodSignature(m); // In order to properly map the method name from the entire signature, we must isolate it from // associated type and parameter declarations. The method name is guaranteed to be between the // first closing parenthesis and first colon (for methods with arguments), or the entirety of // the declaration after the first closing parenthesis (for methods with no arguments). int identifierStartIndex = methodSignature.indexOf(')') + 1; int identifierEndIndex = methodSignature.contains(":") ? methodSignature.indexOf(':') : methodSignature.length(); generatedSourceMappings.addMethodMapping( m /* methodDeclaration */, getBuilder().length() + identifierStartIndex /* targetBegin */, identifierEndIndex - identifierStartIndex /* length */); print(methodSignature); String methodName = nameTable.getMethodSelector(methodElement); if (!m.isConstructor() && NameTable.needsObjcMethodFamilyNoneAttribute(methodName)) { // Getting around a clang warning. // clang assumes that methods with names starting with new, alloc or copy // return objects of the same type as the receiving class, regardless of // the actual declared return type. This attribute tells clang to not do // that, please. // See http://clang.llvm.org/docs/AutomaticReferenceCounting.html // Sections 5.1 (Explicit method family control) // and 5.2.2 (Related result types) print(" OBJC_METHOD_FAMILY_NONE"); } if (needsDeprecatedAttribute(m.getAnnotations())) { print(" " + DEPRECATED_ATTRIBUTE); } if (m.isUnavailable()) { print(" NS_UNAVAILABLE"); } println(";"); }
java
private void printMethodDeclaration(MethodDeclaration m, boolean isCompanionClass) { ExecutableElement methodElement = m.getExecutableElement(); TypeElement typeElement = ElementUtil.getDeclaringClass(methodElement); if (typeElement.getKind().isInterface()) { // isCompanion and isStatic must be both false (i.e. this prints a non-static method decl // in @protocol) or must both be true (i.e. this prints a static method decl in the // companion class' @interface). if (isCompanionClass != ElementUtil.isStatic(methodElement)) { return; } } newline(); JavadocGenerator.printDocComment(getBuilder(), m.getJavadoc()); String methodSignature = getMethodSignature(m); // In order to properly map the method name from the entire signature, we must isolate it from // associated type and parameter declarations. The method name is guaranteed to be between the // first closing parenthesis and first colon (for methods with arguments), or the entirety of // the declaration after the first closing parenthesis (for methods with no arguments). int identifierStartIndex = methodSignature.indexOf(')') + 1; int identifierEndIndex = methodSignature.contains(":") ? methodSignature.indexOf(':') : methodSignature.length(); generatedSourceMappings.addMethodMapping( m /* methodDeclaration */, getBuilder().length() + identifierStartIndex /* targetBegin */, identifierEndIndex - identifierStartIndex /* length */); print(methodSignature); String methodName = nameTable.getMethodSelector(methodElement); if (!m.isConstructor() && NameTable.needsObjcMethodFamilyNoneAttribute(methodName)) { // Getting around a clang warning. // clang assumes that methods with names starting with new, alloc or copy // return objects of the same type as the receiving class, regardless of // the actual declared return type. This attribute tells clang to not do // that, please. // See http://clang.llvm.org/docs/AutomaticReferenceCounting.html // Sections 5.1 (Explicit method family control) // and 5.2.2 (Related result types) print(" OBJC_METHOD_FAMILY_NONE"); } if (needsDeprecatedAttribute(m.getAnnotations())) { print(" " + DEPRECATED_ATTRIBUTE); } if (m.isUnavailable()) { print(" NS_UNAVAILABLE"); } println(";"); }
[ "private", "void", "printMethodDeclaration", "(", "MethodDeclaration", "m", ",", "boolean", "isCompanionClass", ")", "{", "ExecutableElement", "methodElement", "=", "m", ".", "getExecutableElement", "(", ")", ";", "TypeElement", "typeElement", "=", "ElementUtil", ".", "getDeclaringClass", "(", "methodElement", ")", ";", "if", "(", "typeElement", ".", "getKind", "(", ")", ".", "isInterface", "(", ")", ")", "{", "// isCompanion and isStatic must be both false (i.e. this prints a non-static method decl", "// in @protocol) or must both be true (i.e. this prints a static method decl in the", "// companion class' @interface).", "if", "(", "isCompanionClass", "!=", "ElementUtil", ".", "isStatic", "(", "methodElement", ")", ")", "{", "return", ";", "}", "}", "newline", "(", ")", ";", "JavadocGenerator", ".", "printDocComment", "(", "getBuilder", "(", ")", ",", "m", ".", "getJavadoc", "(", ")", ")", ";", "String", "methodSignature", "=", "getMethodSignature", "(", "m", ")", ";", "// In order to properly map the method name from the entire signature, we must isolate it from", "// associated type and parameter declarations. The method name is guaranteed to be between the", "// first closing parenthesis and first colon (for methods with arguments), or the entirety of", "// the declaration after the first closing parenthesis (for methods with no arguments).", "int", "identifierStartIndex", "=", "methodSignature", ".", "indexOf", "(", "'", "'", ")", "+", "1", ";", "int", "identifierEndIndex", "=", "methodSignature", ".", "contains", "(", "\":\"", ")", "?", "methodSignature", ".", "indexOf", "(", "'", "'", ")", ":", "methodSignature", ".", "length", "(", ")", ";", "generatedSourceMappings", ".", "addMethodMapping", "(", "m", "/* methodDeclaration */", ",", "getBuilder", "(", ")", ".", "length", "(", ")", "+", "identifierStartIndex", "/* targetBegin */", ",", "identifierEndIndex", "-", "identifierStartIndex", "/* length */", ")", ";", "print", "(", "methodSignature", ")", ";", "String", "methodName", "=", "nameTable", ".", "getMethodSelector", "(", "methodElement", ")", ";", "if", "(", "!", "m", ".", "isConstructor", "(", ")", "&&", "NameTable", ".", "needsObjcMethodFamilyNoneAttribute", "(", "methodName", ")", ")", "{", "// Getting around a clang warning.", "// clang assumes that methods with names starting with new, alloc or copy", "// return objects of the same type as the receiving class, regardless of", "// the actual declared return type. This attribute tells clang to not do", "// that, please.", "// See http://clang.llvm.org/docs/AutomaticReferenceCounting.html", "// Sections 5.1 (Explicit method family control)", "// and 5.2.2 (Related result types)", "print", "(", "\" OBJC_METHOD_FAMILY_NONE\"", ")", ";", "}", "if", "(", "needsDeprecatedAttribute", "(", "m", ".", "getAnnotations", "(", ")", ")", ")", "{", "print", "(", "\" \"", "+", "DEPRECATED_ATTRIBUTE", ")", ";", "}", "if", "(", "m", ".", "isUnavailable", "(", ")", ")", "{", "print", "(", "\" NS_UNAVAILABLE\"", ")", ";", "}", "println", "(", "\";\"", ")", ";", "}" ]
Emit method declaration. @param m The method. @param isCompanionClass If true, emit only if m is a static interface method.
[ "Emit", "method", "declaration", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/translator/src/main/java/com/google/devtools/j2objc/gen/TypeDeclarationGenerator.java#L556-L608
docker-java/docker-java
src/main/java/com/github/dockerjava/core/DefaultDockerClientConfig.java
DefaultDockerClientConfig.createDefaultConfigBuilder
static Builder createDefaultConfigBuilder(Map<String, String> env, Properties systemProperties) { """ Allows you to build the config without system environment interfering for more robust testing """ Properties properties = loadIncludedDockerProperties(systemProperties); properties = overrideDockerPropertiesWithSettingsFromUserHome(properties, systemProperties); properties = overrideDockerPropertiesWithEnv(properties, env); properties = overrideDockerPropertiesWithSystemProperties(properties, systemProperties); return new Builder().withProperties(properties); }
java
static Builder createDefaultConfigBuilder(Map<String, String> env, Properties systemProperties) { Properties properties = loadIncludedDockerProperties(systemProperties); properties = overrideDockerPropertiesWithSettingsFromUserHome(properties, systemProperties); properties = overrideDockerPropertiesWithEnv(properties, env); properties = overrideDockerPropertiesWithSystemProperties(properties, systemProperties); return new Builder().withProperties(properties); }
[ "static", "Builder", "createDefaultConfigBuilder", "(", "Map", "<", "String", ",", "String", ">", "env", ",", "Properties", "systemProperties", ")", "{", "Properties", "properties", "=", "loadIncludedDockerProperties", "(", "systemProperties", ")", ";", "properties", "=", "overrideDockerPropertiesWithSettingsFromUserHome", "(", "properties", ",", "systemProperties", ")", ";", "properties", "=", "overrideDockerPropertiesWithEnv", "(", "properties", ",", "env", ")", ";", "properties", "=", "overrideDockerPropertiesWithSystemProperties", "(", "properties", ",", "systemProperties", ")", ";", "return", "new", "Builder", "(", ")", ".", "withProperties", "(", "properties", ")", ";", "}" ]
Allows you to build the config without system environment interfering for more robust testing
[ "Allows", "you", "to", "build", "the", "config", "without", "system", "environment", "interfering", "for", "more", "robust", "testing" ]
train
https://github.com/docker-java/docker-java/blob/c5c89327108abdc50aa41d7711d4743b8bac75fe/src/main/java/com/github/dockerjava/core/DefaultDockerClientConfig.java#L198-L204
wcm-io/wcm-io-tooling
commons/content-package-builder/src/main/java/io/wcm/tooling/commons/contentpackagebuilder/ContentPackage.java
ContentPackage.addFile
public void addFile(String path, File file, String contentType) throws IOException { """ Adds a binary file with explicit mime type. @param path Full content path and file name of file @param file File with binary data @param contentType Mime type, optionally with ";charset=XYZ" extension @throws IOException I/O exception """ try (InputStream is = new FileInputStream(file)) { addFile(path, is, contentType); } }
java
public void addFile(String path, File file, String contentType) throws IOException { try (InputStream is = new FileInputStream(file)) { addFile(path, is, contentType); } }
[ "public", "void", "addFile", "(", "String", "path", ",", "File", "file", ",", "String", "contentType", ")", "throws", "IOException", "{", "try", "(", "InputStream", "is", "=", "new", "FileInputStream", "(", "file", ")", ")", "{", "addFile", "(", "path", ",", "is", ",", "contentType", ")", ";", "}", "}" ]
Adds a binary file with explicit mime type. @param path Full content path and file name of file @param file File with binary data @param contentType Mime type, optionally with ";charset=XYZ" extension @throws IOException I/O exception
[ "Adds", "a", "binary", "file", "with", "explicit", "mime", "type", "." ]
train
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/commons/content-package-builder/src/main/java/io/wcm/tooling/commons/contentpackagebuilder/ContentPackage.java#L234-L238
icode/ameba
src/main/java/ameba/feature/AmebaFeature.java
AmebaFeature.subscribeSystemEvent
protected <E extends Event> Listener subscribeSystemEvent(Class<E> eventClass, final Class<? extends Listener<E>> listenerClass) { """ <p>subscribeSystemEvent.</p> @param eventClass a {@link java.lang.Class} object. @param listenerClass a {@link java.lang.Class} object. @return a {@link ameba.event.Listener} object. @since 0.1.6e @param <E> a E object. """ Listener<E> listener = locator.createAndInitialize(listenerClass); SystemEventBus.subscribe(eventClass, listener); return listener; }
java
protected <E extends Event> Listener subscribeSystemEvent(Class<E> eventClass, final Class<? extends Listener<E>> listenerClass) { Listener<E> listener = locator.createAndInitialize(listenerClass); SystemEventBus.subscribe(eventClass, listener); return listener; }
[ "protected", "<", "E", "extends", "Event", ">", "Listener", "subscribeSystemEvent", "(", "Class", "<", "E", ">", "eventClass", ",", "final", "Class", "<", "?", "extends", "Listener", "<", "E", ">", ">", "listenerClass", ")", "{", "Listener", "<", "E", ">", "listener", "=", "locator", ".", "createAndInitialize", "(", "listenerClass", ")", ";", "SystemEventBus", ".", "subscribe", "(", "eventClass", ",", "listener", ")", ";", "return", "listener", ";", "}" ]
<p>subscribeSystemEvent.</p> @param eventClass a {@link java.lang.Class} object. @param listenerClass a {@link java.lang.Class} object. @return a {@link ameba.event.Listener} object. @since 0.1.6e @param <E> a E object.
[ "<p", ">", "subscribeSystemEvent", ".", "<", "/", "p", ">" ]
train
https://github.com/icode/ameba/blob/9d4956e935898e41331b2745e400ef869cd265e0/src/main/java/ameba/feature/AmebaFeature.java#L156-L160
ehcache/ehcache3
impl/src/main/java/org/ehcache/config/builders/CacheConfigurationBuilder.java
CacheConfigurationBuilder.withExpiry
@Deprecated public CacheConfigurationBuilder<K, V> withExpiry(org.ehcache.expiry.Expiry<? super K, ? super V> expiry) { """ Adds {@link org.ehcache.expiry.Expiry} configuration to the returned builder. <p> {@code Expiry} is what controls data freshness in a cache. @param expiry the expiry to use @return a new builder with the added expiry @deprecated Use {@link #withExpiry(ExpiryPolicy)} instead """ return withExpiry(convertToExpiryPolicy(requireNonNull(expiry, "Null expiry"))); }
java
@Deprecated public CacheConfigurationBuilder<K, V> withExpiry(org.ehcache.expiry.Expiry<? super K, ? super V> expiry) { return withExpiry(convertToExpiryPolicy(requireNonNull(expiry, "Null expiry"))); }
[ "@", "Deprecated", "public", "CacheConfigurationBuilder", "<", "K", ",", "V", ">", "withExpiry", "(", "org", ".", "ehcache", ".", "expiry", ".", "Expiry", "<", "?", "super", "K", ",", "?", "super", "V", ">", "expiry", ")", "{", "return", "withExpiry", "(", "convertToExpiryPolicy", "(", "requireNonNull", "(", "expiry", ",", "\"Null expiry\"", ")", ")", ")", ";", "}" ]
Adds {@link org.ehcache.expiry.Expiry} configuration to the returned builder. <p> {@code Expiry} is what controls data freshness in a cache. @param expiry the expiry to use @return a new builder with the added expiry @deprecated Use {@link #withExpiry(ExpiryPolicy)} instead
[ "Adds", "{", "@link", "org", ".", "ehcache", ".", "expiry", ".", "Expiry", "}", "configuration", "to", "the", "returned", "builder", ".", "<p", ">", "{", "@code", "Expiry", "}", "is", "what", "controls", "data", "freshness", "in", "a", "cache", "." ]
train
https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/config/builders/CacheConfigurationBuilder.java#L298-L301
sagiegurari/fax4j
src/main/java/org/fax4j/util/IOHelper.java
IOHelper.readAndWriteStreams
public static void readAndWriteStreams(InputStream inputStream,OutputStream outputStream) throws IOException { """ Reads the data from the input stream and writes to the output stream. @param inputStream The inputStream to read from @param outputStream The output stream to write to @throws IOException Any IO exception """ byte[] buffer=new byte[5000]; int read=-1; try { do { //read next buffer read=inputStream.read(buffer); if(read!=-1) { //write to in memory stream outputStream.write(buffer,0,read); } }while(read!=-1); } finally { //close streams IOHelper.closeResource(inputStream); IOHelper.closeResource(outputStream); } }
java
public static void readAndWriteStreams(InputStream inputStream,OutputStream outputStream) throws IOException { byte[] buffer=new byte[5000]; int read=-1; try { do { //read next buffer read=inputStream.read(buffer); if(read!=-1) { //write to in memory stream outputStream.write(buffer,0,read); } }while(read!=-1); } finally { //close streams IOHelper.closeResource(inputStream); IOHelper.closeResource(outputStream); } }
[ "public", "static", "void", "readAndWriteStreams", "(", "InputStream", "inputStream", ",", "OutputStream", "outputStream", ")", "throws", "IOException", "{", "byte", "[", "]", "buffer", "=", "new", "byte", "[", "5000", "]", ";", "int", "read", "=", "-", "1", ";", "try", "{", "do", "{", "//read next buffer", "read", "=", "inputStream", ".", "read", "(", "buffer", ")", ";", "if", "(", "read", "!=", "-", "1", ")", "{", "//write to in memory stream", "outputStream", ".", "write", "(", "buffer", ",", "0", ",", "read", ")", ";", "}", "}", "while", "(", "read", "!=", "-", "1", ")", ";", "}", "finally", "{", "//close streams", "IOHelper", ".", "closeResource", "(", "inputStream", ")", ";", "IOHelper", ".", "closeResource", "(", "outputStream", ")", ";", "}", "}" ]
Reads the data from the input stream and writes to the output stream. @param inputStream The inputStream to read from @param outputStream The output stream to write to @throws IOException Any IO exception
[ "Reads", "the", "data", "from", "the", "input", "stream", "and", "writes", "to", "the", "output", "stream", "." ]
train
https://github.com/sagiegurari/fax4j/blob/42fa51acabe7bf279e27ab3dd1cf76146b27955f/src/main/java/org/fax4j/util/IOHelper.java#L384-L408
googleapis/google-cloud-java
google-cloud-clients/google-cloud-vision/src/main/java/com/google/cloud/vision/v1/ProductSearchClient.java
ProductSearchClient.formatProductName
@Deprecated public static final String formatProductName(String project, String location, String product) { """ Formats a string containing the fully-qualified path to represent a product resource. @deprecated Use the {@link ProductName} class instead. """ return PRODUCT_PATH_TEMPLATE.instantiate( "project", project, "location", location, "product", product); }
java
@Deprecated public static final String formatProductName(String project, String location, String product) { return PRODUCT_PATH_TEMPLATE.instantiate( "project", project, "location", location, "product", product); }
[ "@", "Deprecated", "public", "static", "final", "String", "formatProductName", "(", "String", "project", ",", "String", "location", ",", "String", "product", ")", "{", "return", "PRODUCT_PATH_TEMPLATE", ".", "instantiate", "(", "\"project\"", ",", "project", ",", "\"location\"", ",", "location", ",", "\"product\"", ",", "product", ")", ";", "}" ]
Formats a string containing the fully-qualified path to represent a product resource. @deprecated Use the {@link ProductName} class instead.
[ "Formats", "a", "string", "containing", "the", "fully", "-", "qualified", "path", "to", "represent", "a", "product", "resource", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-vision/src/main/java/com/google/cloud/vision/v1/ProductSearchClient.java#L163-L169
linkedin/dexmaker
dexmaker/src/main/java/com/android/dx/Code.java
Code.aput
public void aput(Local<?> array, Local<Integer> index, Local<?> source) { """ Assigns {@code source} to the element at {@code index} in {@code array}. """ addInstruction(new ThrowingInsn(Rops.opAput(source.type.ropType), sourcePosition, RegisterSpecList.make(source.spec(), array.spec(), index.spec()), catches)); }
java
public void aput(Local<?> array, Local<Integer> index, Local<?> source) { addInstruction(new ThrowingInsn(Rops.opAput(source.type.ropType), sourcePosition, RegisterSpecList.make(source.spec(), array.spec(), index.spec()), catches)); }
[ "public", "void", "aput", "(", "Local", "<", "?", ">", "array", ",", "Local", "<", "Integer", ">", "index", ",", "Local", "<", "?", ">", "source", ")", "{", "addInstruction", "(", "new", "ThrowingInsn", "(", "Rops", ".", "opAput", "(", "source", ".", "type", ".", "ropType", ")", ",", "sourcePosition", ",", "RegisterSpecList", ".", "make", "(", "source", ".", "spec", "(", ")", ",", "array", ".", "spec", "(", ")", ",", "index", ".", "spec", "(", ")", ")", ",", "catches", ")", ")", ";", "}" ]
Assigns {@code source} to the element at {@code index} in {@code array}.
[ "Assigns", "{" ]
train
https://github.com/linkedin/dexmaker/blob/c58ffebcbb2564c7d1fa6fb58b48f351c330296d/dexmaker/src/main/java/com/android/dx/Code.java#L812-L815
looly/hutool
hutool-db/src/main/java/cn/hutool/db/AbstractDb.java
AbstractDb.update
public int update(Entity record, Entity where) throws SQLException { """ 更新数据<br> 更新条件为多个key value对表示,默认key = value,如果使用其它条件可以使用:where.put("key", " &gt; 1"),value也可以传Condition对象,key被忽略 @param record 记录 @param where 条件 @return 影响行数 @throws SQLException SQL执行异常 """ Connection conn = null; try { conn = this.getConnection(); return runner.update(conn, record, where); } catch (SQLException e) { throw e; } finally { this.closeConnection(conn); } }
java
public int update(Entity record, Entity where) throws SQLException { Connection conn = null; try { conn = this.getConnection(); return runner.update(conn, record, where); } catch (SQLException e) { throw e; } finally { this.closeConnection(conn); } }
[ "public", "int", "update", "(", "Entity", "record", ",", "Entity", "where", ")", "throws", "SQLException", "{", "Connection", "conn", "=", "null", ";", "try", "{", "conn", "=", "this", ".", "getConnection", "(", ")", ";", "return", "runner", ".", "update", "(", "conn", ",", "record", ",", "where", ")", ";", "}", "catch", "(", "SQLException", "e", ")", "{", "throw", "e", ";", "}", "finally", "{", "this", ".", "closeConnection", "(", "conn", ")", ";", "}", "}" ]
更新数据<br> 更新条件为多个key value对表示,默认key = value,如果使用其它条件可以使用:where.put("key", " &gt; 1"),value也可以传Condition对象,key被忽略 @param record 记录 @param where 条件 @return 影响行数 @throws SQLException SQL执行异常
[ "更新数据<br", ">", "更新条件为多个key", "value对表示,默认key", "=", "value,如果使用其它条件可以使用:where", ".", "put", "(", "key", "&gt", ";", "1", ")", ",value也可以传Condition对象,key被忽略" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-db/src/main/java/cn/hutool/db/AbstractDb.java#L380-L390
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/operators/hash/InMemoryPartition.java
InMemoryPartition.overwriteRecordAt
@Deprecated public void overwriteRecordAt(long pointer, T record) throws IOException { """ UNSAFE!! overwrites record causes inconsistency or data loss for overwriting everything but records of the exact same size @param pointer pointer to start of record @param record record to overwrite old one with @throws IOException @deprecated Don't use this, overwrites record and causes inconsistency or data loss for overwriting everything but records of the exact same size """ long tmpPointer = this.writeView.getCurrentPointer(); this.writeView.resetTo(pointer); this.serializer.serialize(record, this.writeView); this.writeView.resetTo(tmpPointer); }
java
@Deprecated public void overwriteRecordAt(long pointer, T record) throws IOException { long tmpPointer = this.writeView.getCurrentPointer(); this.writeView.resetTo(pointer); this.serializer.serialize(record, this.writeView); this.writeView.resetTo(tmpPointer); }
[ "@", "Deprecated", "public", "void", "overwriteRecordAt", "(", "long", "pointer", ",", "T", "record", ")", "throws", "IOException", "{", "long", "tmpPointer", "=", "this", ".", "writeView", ".", "getCurrentPointer", "(", ")", ";", "this", ".", "writeView", ".", "resetTo", "(", "pointer", ")", ";", "this", ".", "serializer", ".", "serialize", "(", "record", ",", "this", ".", "writeView", ")", ";", "this", ".", "writeView", ".", "resetTo", "(", "tmpPointer", ")", ";", "}" ]
UNSAFE!! overwrites record causes inconsistency or data loss for overwriting everything but records of the exact same size @param pointer pointer to start of record @param record record to overwrite old one with @throws IOException @deprecated Don't use this, overwrites record and causes inconsistency or data loss for overwriting everything but records of the exact same size
[ "UNSAFE!!", "overwrites", "record", "causes", "inconsistency", "or", "data", "loss", "for", "overwriting", "everything", "but", "records", "of", "the", "exact", "same", "size" ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/operators/hash/InMemoryPartition.java#L254-L260
eFaps/eFaps-Kernel
src/main/java/org/efaps/admin/user/Person.java
Person.getLocale
public Locale getLocale() { """ Method to get the Locale of this Person. Default is the "English" Locale. @return Locale of this Person """ final Locale ret; if (this.attrValues.get(Person.AttrName.LOCALE) != null) { final String localeStr = this.attrValues.get(Person.AttrName.LOCALE); final String[] countries = localeStr.split("_"); if (countries.length == 2) { ret = new Locale(countries[0], countries[1]); } else if (countries.length == 3) { ret = new Locale(countries[0], countries[1], countries[2]); } else { ret = new Locale(localeStr); } } else { ret = Locale.ENGLISH; } return ret; }
java
public Locale getLocale() { final Locale ret; if (this.attrValues.get(Person.AttrName.LOCALE) != null) { final String localeStr = this.attrValues.get(Person.AttrName.LOCALE); final String[] countries = localeStr.split("_"); if (countries.length == 2) { ret = new Locale(countries[0], countries[1]); } else if (countries.length == 3) { ret = new Locale(countries[0], countries[1], countries[2]); } else { ret = new Locale(localeStr); } } else { ret = Locale.ENGLISH; } return ret; }
[ "public", "Locale", "getLocale", "(", ")", "{", "final", "Locale", "ret", ";", "if", "(", "this", ".", "attrValues", ".", "get", "(", "Person", ".", "AttrName", ".", "LOCALE", ")", "!=", "null", ")", "{", "final", "String", "localeStr", "=", "this", ".", "attrValues", ".", "get", "(", "Person", ".", "AttrName", ".", "LOCALE", ")", ";", "final", "String", "[", "]", "countries", "=", "localeStr", ".", "split", "(", "\"_\"", ")", ";", "if", "(", "countries", ".", "length", "==", "2", ")", "{", "ret", "=", "new", "Locale", "(", "countries", "[", "0", "]", ",", "countries", "[", "1", "]", ")", ";", "}", "else", "if", "(", "countries", ".", "length", "==", "3", ")", "{", "ret", "=", "new", "Locale", "(", "countries", "[", "0", "]", ",", "countries", "[", "1", "]", ",", "countries", "[", "2", "]", ")", ";", "}", "else", "{", "ret", "=", "new", "Locale", "(", "localeStr", ")", ";", "}", "}", "else", "{", "ret", "=", "Locale", ".", "ENGLISH", ";", "}", "return", "ret", ";", "}" ]
Method to get the Locale of this Person. Default is the "English" Locale. @return Locale of this Person
[ "Method", "to", "get", "the", "Locale", "of", "this", "Person", ".", "Default", "is", "the", "English", "Locale", "." ]
train
https://github.com/eFaps/eFaps-Kernel/blob/04b96548f518c2386a93f5ec2b9349f9b9063859/src/main/java/org/efaps/admin/user/Person.java#L504-L521
Azure/azure-sdk-for-java
batch/data-plane/src/main/java/com/microsoft/azure/batch/FileOperations.java
FileOperations.getFileFromTask
public void getFileFromTask(String jobId, String taskId, String fileName, OutputStream outputStream) throws BatchErrorException, IOException { """ Downloads the specified file from the specified task's directory on its compute node. @param jobId The ID of the job containing the task. @param taskId The ID of the task. @param fileName The name of the file to download. @param outputStream A stream into which the file contents will be written. @throws BatchErrorException Exception thrown when an error response is received from the Batch service. @throws IOException Exception thrown when there is an error in serialization/deserialization of data sent to/received from the Batch service. """ getFileFromTask(jobId, taskId, fileName, null, outputStream); }
java
public void getFileFromTask(String jobId, String taskId, String fileName, OutputStream outputStream) throws BatchErrorException, IOException { getFileFromTask(jobId, taskId, fileName, null, outputStream); }
[ "public", "void", "getFileFromTask", "(", "String", "jobId", ",", "String", "taskId", ",", "String", "fileName", ",", "OutputStream", "outputStream", ")", "throws", "BatchErrorException", ",", "IOException", "{", "getFileFromTask", "(", "jobId", ",", "taskId", ",", "fileName", ",", "null", ",", "outputStream", ")", ";", "}" ]
Downloads the specified file from the specified task's directory on its compute node. @param jobId The ID of the job containing the task. @param taskId The ID of the task. @param fileName The name of the file to download. @param outputStream A stream into which the file contents will be written. @throws BatchErrorException Exception thrown when an error response is received from the Batch service. @throws IOException Exception thrown when there is an error in serialization/deserialization of data sent to/received from the Batch service.
[ "Downloads", "the", "specified", "file", "from", "the", "specified", "task", "s", "directory", "on", "its", "compute", "node", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/FileOperations.java#L264-L266
opendatatrentino/smatch-webapi-client
src/main/java/it/unitn/disi/smatch/webapi/client/WebApiClient.java
WebApiClient.getInstance
public static WebApiClient getInstance(Locale locale, String host, int port) { """ Returns instance of web API client for given locale and connection properties. @param locale language. @param host Sweb web API server host. @param port Sweb web API server port. @return instance of web API client for given locale and connection properties. """ if (null == webApiClient) { webApiClient = new WebApiClient(locale, host, "" + port); } return webApiClient; }
java
public static WebApiClient getInstance(Locale locale, String host, int port) { if (null == webApiClient) { webApiClient = new WebApiClient(locale, host, "" + port); } return webApiClient; }
[ "public", "static", "WebApiClient", "getInstance", "(", "Locale", "locale", ",", "String", "host", ",", "int", "port", ")", "{", "if", "(", "null", "==", "webApiClient", ")", "{", "webApiClient", "=", "new", "WebApiClient", "(", "locale", ",", "host", ",", "\"\"", "+", "port", ")", ";", "}", "return", "webApiClient", ";", "}" ]
Returns instance of web API client for given locale and connection properties. @param locale language. @param host Sweb web API server host. @param port Sweb web API server port. @return instance of web API client for given locale and connection properties.
[ "Returns", "instance", "of", "web", "API", "client", "for", "given", "locale", "and", "connection", "properties", "." ]
train
https://github.com/opendatatrentino/smatch-webapi-client/blob/d74fc41ab5bdc29afafd11c9001ac25dff20f965/src/main/java/it/unitn/disi/smatch/webapi/client/WebApiClient.java#L127-L132
j-a-w-r/jawr-main-repo
jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/CheckSumUtils.java
CheckSumUtils.getMD5Checksum
public static String getMD5Checksum(InputStream is) throws IOException { """ Returns the MD5 Checksum of the input stream @param is the input stream @return the Checksum of the input stream @throws IOException if an IO exception occurs """ byte[] digest = null; try { MessageDigest md = MessageDigest.getInstance(JawrConstant.MD5_ALGORITHM); InputStream digestIs = new DigestInputStream(is, md); // read stream to EOF as normal... while (digestIs.read() != -1) { } digest = md.digest(); } catch (NoSuchAlgorithmException e) { throw new BundlingProcessException("MD5 algorithm needs to be installed", e); } return new BigInteger(1, digest).toString(16); }
java
public static String getMD5Checksum(InputStream is) throws IOException { byte[] digest = null; try { MessageDigest md = MessageDigest.getInstance(JawrConstant.MD5_ALGORITHM); InputStream digestIs = new DigestInputStream(is, md); // read stream to EOF as normal... while (digestIs.read() != -1) { } digest = md.digest(); } catch (NoSuchAlgorithmException e) { throw new BundlingProcessException("MD5 algorithm needs to be installed", e); } return new BigInteger(1, digest).toString(16); }
[ "public", "static", "String", "getMD5Checksum", "(", "InputStream", "is", ")", "throws", "IOException", "{", "byte", "[", "]", "digest", "=", "null", ";", "try", "{", "MessageDigest", "md", "=", "MessageDigest", ".", "getInstance", "(", "JawrConstant", ".", "MD5_ALGORITHM", ")", ";", "InputStream", "digestIs", "=", "new", "DigestInputStream", "(", "is", ",", "md", ")", ";", "// read stream to EOF as normal...", "while", "(", "digestIs", ".", "read", "(", ")", "!=", "-", "1", ")", "{", "}", "digest", "=", "md", ".", "digest", "(", ")", ";", "}", "catch", "(", "NoSuchAlgorithmException", "e", ")", "{", "throw", "new", "BundlingProcessException", "(", "\"MD5 algorithm needs to be installed\"", ",", "e", ")", ";", "}", "return", "new", "BigInteger", "(", "1", ",", "digest", ")", ".", "toString", "(", "16", ")", ";", "}" ]
Returns the MD5 Checksum of the input stream @param is the input stream @return the Checksum of the input stream @throws IOException if an IO exception occurs
[ "Returns", "the", "MD5", "Checksum", "of", "the", "input", "stream" ]
train
https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/CheckSumUtils.java#L220-L236
facebookarchive/hadoop-20
src/contrib/highavailability/src/java/org/apache/hadoop/hdfs/server/namenode/bookkeeper/zk/ZkUtil.java
ZkUtil.keeperException
public static void keeperException(String msg, KeeperException e) throws IOException { """ Like {@link #interruptedException(String, InterruptedException)} but handles KeeperException and will not interrupt the thread. """ LOG.error(msg, e); throw new IOException(msg, e); }
java
public static void keeperException(String msg, KeeperException e) throws IOException { LOG.error(msg, e); throw new IOException(msg, e); }
[ "public", "static", "void", "keeperException", "(", "String", "msg", ",", "KeeperException", "e", ")", "throws", "IOException", "{", "LOG", ".", "error", "(", "msg", ",", "e", ")", ";", "throw", "new", "IOException", "(", "msg", ",", "e", ")", ";", "}" ]
Like {@link #interruptedException(String, InterruptedException)} but handles KeeperException and will not interrupt the thread.
[ "Like", "{" ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/highavailability/src/java/org/apache/hadoop/hdfs/server/namenode/bookkeeper/zk/ZkUtil.java#L91-L95
mkolisnyk/cucumber-reports
cucumber-runner/src/main/java/com/github/mkolisnyk/cucumber/assertions/LazyAssert.java
LazyAssert.assertThat
public static <T> void assertThat(T actual, Matcher<? super T> matcher) { """ Asserts that <code>actual</code> satisfies the condition specified by <code>matcher</code>. If not, an {@link LazyAssertionError} is thrown with information about the matcher and failing value. Example: <pre> assertThat(0, is(1)); // fails: // failure message: // expected: is &lt;1&gt; // got value: &lt;0&gt; assertThat(0, is(not(1))) // passes </pre> <code>org.hamcrest.Matcher</code> does not currently document the meaning of its type parameter <code>T</code>. This method assumes that a matcher typed as <code>Matcher&lt;T&gt;</code> can be meaningfully applied only to values that could be assigned to a variable of type <code>T</code>. @param <T> the static type accepted by the matcher (this can flag obvious compile-time problems such as {@code assertThat(1, is("a"))} @param actual the computed value being compared @param matcher an expression, built of {@link Matcher}s, specifying allowed values @see org.hamcrest.CoreMatchers @see org.hamcrest.MatcherAssert """ assertThat("", actual, matcher); }
java
public static <T> void assertThat(T actual, Matcher<? super T> matcher) { assertThat("", actual, matcher); }
[ "public", "static", "<", "T", ">", "void", "assertThat", "(", "T", "actual", ",", "Matcher", "<", "?", "super", "T", ">", "matcher", ")", "{", "assertThat", "(", "\"\"", ",", "actual", ",", "matcher", ")", ";", "}" ]
Asserts that <code>actual</code> satisfies the condition specified by <code>matcher</code>. If not, an {@link LazyAssertionError} is thrown with information about the matcher and failing value. Example: <pre> assertThat(0, is(1)); // fails: // failure message: // expected: is &lt;1&gt; // got value: &lt;0&gt; assertThat(0, is(not(1))) // passes </pre> <code>org.hamcrest.Matcher</code> does not currently document the meaning of its type parameter <code>T</code>. This method assumes that a matcher typed as <code>Matcher&lt;T&gt;</code> can be meaningfully applied only to values that could be assigned to a variable of type <code>T</code>. @param <T> the static type accepted by the matcher (this can flag obvious compile-time problems such as {@code assertThat(1, is("a"))} @param actual the computed value being compared @param matcher an expression, built of {@link Matcher}s, specifying allowed values @see org.hamcrest.CoreMatchers @see org.hamcrest.MatcherAssert
[ "Asserts", "that", "<code", ">", "actual<", "/", "code", ">", "satisfies", "the", "condition", "specified", "by", "<code", ">", "matcher<", "/", "code", ">", ".", "If", "not", "an", "{", "@link", "LazyAssertionError", "}", "is", "thrown", "with", "information", "about", "the", "matcher", "and", "failing", "value", ".", "Example", ":" ]
train
https://github.com/mkolisnyk/cucumber-reports/blob/9c9a32f15f0bf1eb1d3d181a11bae9c5eec84a8e/cucumber-runner/src/main/java/com/github/mkolisnyk/cucumber/assertions/LazyAssert.java#L922-L924
alkacon/opencms-core
src-gwt/org/opencms/ade/sitemap/client/CmsSitemapView.java
CmsSitemapView.setElementVisible
protected void setElementVisible(Widget widget, boolean visible) { """ Shows or hides the element for a widget.<p> @param widget the widget to show or hide @param visible true if the widget should be shown """ if (visible) { widget.getElement().getStyle().clearDisplay(); } else { widget.getElement().getStyle().setDisplay(Display.NONE); } }
java
protected void setElementVisible(Widget widget, boolean visible) { if (visible) { widget.getElement().getStyle().clearDisplay(); } else { widget.getElement().getStyle().setDisplay(Display.NONE); } }
[ "protected", "void", "setElementVisible", "(", "Widget", "widget", ",", "boolean", "visible", ")", "{", "if", "(", "visible", ")", "{", "widget", ".", "getElement", "(", ")", ".", "getStyle", "(", ")", ".", "clearDisplay", "(", ")", ";", "}", "else", "{", "widget", ".", "getElement", "(", ")", ".", "getStyle", "(", ")", ".", "setDisplay", "(", "Display", ".", "NONE", ")", ";", "}", "}" ]
Shows or hides the element for a widget.<p> @param widget the widget to show or hide @param visible true if the widget should be shown
[ "Shows", "or", "hides", "the", "element", "for", "a", "widget", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/sitemap/client/CmsSitemapView.java#L1431-L1439
centic9/commons-dost
src/main/java/org/dstadler/commons/zip/ZipUtils.java
ZipUtils.replaceInZip
public static void replaceInZip(File zip, String file, String data, String encoding) throws IOException { """ Replaces the specified file in the provided ZIP file with the provided content. @param zip The zip-file to process @param file The file to look for @param data The string-data to replace @param encoding The encoding that should be used when writing the string data to the file @throws IOException Thrown if files can not be read or any other error occurs while handling the Zip-files """ // open the output side File zipOutFile = File.createTempFile("ZipReplace", ".zip"); try { FileOutputStream fos = new FileOutputStream(zipOutFile); try (ZipOutputStream zos = new ZipOutputStream(fos)) { // open the input side try (ZipFile zipFile = new ZipFile(zip)) { boolean found = false; // walk all entries and copy them into the new file Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); try { if (entry.getName().equals(file)) { zos.putNextEntry(new ZipEntry(entry.getName())); IOUtils.write(data, zos, encoding); found = true; } else { zos.putNextEntry(entry); IOUtils.copy(zipFile.getInputStream(entry), zos); } } finally { zos.closeEntry(); } } if(!found) { zos.putNextEntry(new ZipEntry(file)); try { IOUtils.write(data, zos, "UTF-8"); } finally { zos.closeEntry(); } } } } // copy over the data FileUtils.copyFile(zipOutFile, zip); } finally { if(!zipOutFile.delete()) { //noinspection ThrowFromFinallyBlock throw new IOException("Error deleting file: " + zipOutFile); } } }
java
public static void replaceInZip(File zip, String file, String data, String encoding) throws IOException { // open the output side File zipOutFile = File.createTempFile("ZipReplace", ".zip"); try { FileOutputStream fos = new FileOutputStream(zipOutFile); try (ZipOutputStream zos = new ZipOutputStream(fos)) { // open the input side try (ZipFile zipFile = new ZipFile(zip)) { boolean found = false; // walk all entries and copy them into the new file Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); try { if (entry.getName().equals(file)) { zos.putNextEntry(new ZipEntry(entry.getName())); IOUtils.write(data, zos, encoding); found = true; } else { zos.putNextEntry(entry); IOUtils.copy(zipFile.getInputStream(entry), zos); } } finally { zos.closeEntry(); } } if(!found) { zos.putNextEntry(new ZipEntry(file)); try { IOUtils.write(data, zos, "UTF-8"); } finally { zos.closeEntry(); } } } } // copy over the data FileUtils.copyFile(zipOutFile, zip); } finally { if(!zipOutFile.delete()) { //noinspection ThrowFromFinallyBlock throw new IOException("Error deleting file: " + zipOutFile); } } }
[ "public", "static", "void", "replaceInZip", "(", "File", "zip", ",", "String", "file", ",", "String", "data", ",", "String", "encoding", ")", "throws", "IOException", "{", "// open the output side", "File", "zipOutFile", "=", "File", ".", "createTempFile", "(", "\"ZipReplace\"", ",", "\".zip\"", ")", ";", "try", "{", "FileOutputStream", "fos", "=", "new", "FileOutputStream", "(", "zipOutFile", ")", ";", "try", "(", "ZipOutputStream", "zos", "=", "new", "ZipOutputStream", "(", "fos", ")", ")", "{", "// open the input side", "try", "(", "ZipFile", "zipFile", "=", "new", "ZipFile", "(", "zip", ")", ")", "{", "boolean", "found", "=", "false", ";", "// walk all entries and copy them into the new file", "Enumeration", "<", "?", "extends", "ZipEntry", ">", "entries", "=", "zipFile", ".", "entries", "(", ")", ";", "while", "(", "entries", ".", "hasMoreElements", "(", ")", ")", "{", "ZipEntry", "entry", "=", "entries", ".", "nextElement", "(", ")", ";", "try", "{", "if", "(", "entry", ".", "getName", "(", ")", ".", "equals", "(", "file", ")", ")", "{", "zos", ".", "putNextEntry", "(", "new", "ZipEntry", "(", "entry", ".", "getName", "(", ")", ")", ")", ";", "IOUtils", ".", "write", "(", "data", ",", "zos", ",", "encoding", ")", ";", "found", "=", "true", ";", "}", "else", "{", "zos", ".", "putNextEntry", "(", "entry", ")", ";", "IOUtils", ".", "copy", "(", "zipFile", ".", "getInputStream", "(", "entry", ")", ",", "zos", ")", ";", "}", "}", "finally", "{", "zos", ".", "closeEntry", "(", ")", ";", "}", "}", "if", "(", "!", "found", ")", "{", "zos", ".", "putNextEntry", "(", "new", "ZipEntry", "(", "file", ")", ")", ";", "try", "{", "IOUtils", ".", "write", "(", "data", ",", "zos", ",", "\"UTF-8\"", ")", ";", "}", "finally", "{", "zos", ".", "closeEntry", "(", ")", ";", "}", "}", "}", "}", "// copy over the data", "FileUtils", ".", "copyFile", "(", "zipOutFile", ",", "zip", ")", ";", "}", "finally", "{", "if", "(", "!", "zipOutFile", ".", "delete", "(", ")", ")", "{", "//noinspection ThrowFromFinallyBlock", "throw", "new", "IOException", "(", "\"Error deleting file: \"", "+", "zipOutFile", ")", ";", "}", "}", "}" ]
Replaces the specified file in the provided ZIP file with the provided content. @param zip The zip-file to process @param file The file to look for @param data The string-data to replace @param encoding The encoding that should be used when writing the string data to the file @throws IOException Thrown if files can not be read or any other error occurs while handling the Zip-files
[ "Replaces", "the", "specified", "file", "in", "the", "provided", "ZIP", "file", "with", "the", "provided", "content", "." ]
train
https://github.com/centic9/commons-dost/blob/f6fa4e3e0b943ff103f918824319d8abf33d0e0f/src/main/java/org/dstadler/commons/zip/ZipUtils.java#L461-L509
ow2-chameleon/fuchsia
bases/knx/calimero/src/main/java/tuwien/auto/calimero/dptxlator/DPTXlatorDateTime.java
DPTXlatorDateTime.setDate
public final void setDate(int year, int month, int day) { """ Sets year, month and day of month information of the first date/time item. <p> This method does not reset other item data or discard other translation items. @param year year value, 1900 &lt;= year &lt;= 2155 @param month month value, 1 &lt;= month &lt;= 12 @param day day value, 1 &lt;= day &lt;= 31 """ set(data, 0, YEAR, year); set(data, 0, MONTH, month); set(data, 0, DAY, day); }
java
public final void setDate(int year, int month, int day) { set(data, 0, YEAR, year); set(data, 0, MONTH, month); set(data, 0, DAY, day); }
[ "public", "final", "void", "setDate", "(", "int", "year", ",", "int", "month", ",", "int", "day", ")", "{", "set", "(", "data", ",", "0", ",", "YEAR", ",", "year", ")", ";", "set", "(", "data", ",", "0", ",", "MONTH", ",", "month", ")", ";", "set", "(", "data", ",", "0", ",", "DAY", ",", "day", ")", ";", "}" ]
Sets year, month and day of month information of the first date/time item. <p> This method does not reset other item data or discard other translation items. @param year year value, 1900 &lt;= year &lt;= 2155 @param month month value, 1 &lt;= month &lt;= 12 @param day day value, 1 &lt;= day &lt;= 31
[ "Sets", "year", "month", "and", "day", "of", "month", "information", "of", "the", "first", "date", "/", "time", "item", ".", "<p", ">", "This", "method", "does", "not", "reset", "other", "item", "data", "or", "discard", "other", "translation", "items", "." ]
train
https://github.com/ow2-chameleon/fuchsia/blob/4e9318eadbdeb945e529789f573b45386e619bed/bases/knx/calimero/src/main/java/tuwien/auto/calimero/dptxlator/DPTXlatorDateTime.java#L300-L305
Carbonado/Carbonado
src/main/java/com/amazon/carbonado/raw/KeyDecoder.java
KeyDecoder.decodeDoubleDesc
public static double decodeDoubleDesc(byte[] src, int srcOffset) throws CorruptEncodingException { """ Decodes a double from exactly 8 bytes, as encoded for descending order. @param src source of encoded bytes @param srcOffset offset into source array @return double value """ long bits = DataDecoder.decodeDoubleBits(src, srcOffset); if (bits >= 0) { bits ^= 0x7fffffffffffffffL; } return Double.longBitsToDouble(bits); }
java
public static double decodeDoubleDesc(byte[] src, int srcOffset) throws CorruptEncodingException { long bits = DataDecoder.decodeDoubleBits(src, srcOffset); if (bits >= 0) { bits ^= 0x7fffffffffffffffL; } return Double.longBitsToDouble(bits); }
[ "public", "static", "double", "decodeDoubleDesc", "(", "byte", "[", "]", "src", ",", "int", "srcOffset", ")", "throws", "CorruptEncodingException", "{", "long", "bits", "=", "DataDecoder", ".", "decodeDoubleBits", "(", "src", ",", "srcOffset", ")", ";", "if", "(", "bits", ">=", "0", ")", "{", "bits", "^=", "0x7fffffffffffffff", "", "L", ";", "}", "return", "Double", ".", "longBitsToDouble", "(", "bits", ")", ";", "}" ]
Decodes a double from exactly 8 bytes, as encoded for descending order. @param src source of encoded bytes @param srcOffset offset into source array @return double value
[ "Decodes", "a", "double", "from", "exactly", "8", "bytes", "as", "encoded", "for", "descending", "order", "." ]
train
https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/raw/KeyDecoder.java#L310-L318
google/closure-compiler
src/com/google/javascript/rhino/jstype/UnionType.java
UnionType.checkUnionEquivalenceHelper
boolean checkUnionEquivalenceHelper(UnionType that, EquivalenceMethod eqMethod, EqCache eqCache) { """ Two union types are equal if, after flattening nested union types, they have the same number of alternates and all alternates are equal. """ List<JSType> thatAlternates = that.getAlternates(); if (eqMethod == EquivalenceMethod.IDENTITY && alternates.size() != thatAlternates.size()) { return false; } for (int i = 0; i < thatAlternates.size(); i++) { JSType thatAlternate = thatAlternates.get(i); if (!hasAlternate(thatAlternate, eqMethod, eqCache)) { return false; } } return true; }
java
boolean checkUnionEquivalenceHelper(UnionType that, EquivalenceMethod eqMethod, EqCache eqCache) { List<JSType> thatAlternates = that.getAlternates(); if (eqMethod == EquivalenceMethod.IDENTITY && alternates.size() != thatAlternates.size()) { return false; } for (int i = 0; i < thatAlternates.size(); i++) { JSType thatAlternate = thatAlternates.get(i); if (!hasAlternate(thatAlternate, eqMethod, eqCache)) { return false; } } return true; }
[ "boolean", "checkUnionEquivalenceHelper", "(", "UnionType", "that", ",", "EquivalenceMethod", "eqMethod", ",", "EqCache", "eqCache", ")", "{", "List", "<", "JSType", ">", "thatAlternates", "=", "that", ".", "getAlternates", "(", ")", ";", "if", "(", "eqMethod", "==", "EquivalenceMethod", ".", "IDENTITY", "&&", "alternates", ".", "size", "(", ")", "!=", "thatAlternates", ".", "size", "(", ")", ")", "{", "return", "false", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "thatAlternates", ".", "size", "(", ")", ";", "i", "++", ")", "{", "JSType", "thatAlternate", "=", "thatAlternates", ".", "get", "(", "i", ")", ";", "if", "(", "!", "hasAlternate", "(", "thatAlternate", ",", "eqMethod", ",", "eqCache", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Two union types are equal if, after flattening nested union types, they have the same number of alternates and all alternates are equal.
[ "Two", "union", "types", "are", "equal", "if", "after", "flattening", "nested", "union", "types", "they", "have", "the", "same", "number", "of", "alternates", "and", "all", "alternates", "are", "equal", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/UnionType.java#L339-L351
Whiley/WhileyCompiler
src/main/java/wyc/io/WhileyFileParser.java
WhileyFileParser.parseRangeExpression
private Expr parseRangeExpression(EnclosingScope scope, boolean terminated) { """ Parse a range expression, which has the form: <pre> RangeExpr ::= Expr ".." Expr </pre> @param scope The enclosing scope for this statement, which determines the set of visible (i.e. declared) variables and also the current indentation level. @param terminated This indicates that the expression is known to be terminated (or not). An expression that's known to be terminated is one which is guaranteed to be followed by something. This is important because it means that we can ignore any newline characters encountered in parsing this expression, and that we'll never overrun the end of the expression (i.e. because there's guaranteed to be something which terminates this expression). A classic situation where terminated is true is when parsing an expression surrounded in braces. In such case, we know the right-brace will always terminate this expression. @return """ int start = index; Expr lhs = parseAdditiveExpression(scope, true); match(DotDot); Expr rhs = parseAdditiveExpression(scope, true); Expr range = new Expr.ArrayRange(Type.Void, lhs, rhs); return annotateSourceLocation(range, start); }
java
private Expr parseRangeExpression(EnclosingScope scope, boolean terminated) { int start = index; Expr lhs = parseAdditiveExpression(scope, true); match(DotDot); Expr rhs = parseAdditiveExpression(scope, true); Expr range = new Expr.ArrayRange(Type.Void, lhs, rhs); return annotateSourceLocation(range, start); }
[ "private", "Expr", "parseRangeExpression", "(", "EnclosingScope", "scope", ",", "boolean", "terminated", ")", "{", "int", "start", "=", "index", ";", "Expr", "lhs", "=", "parseAdditiveExpression", "(", "scope", ",", "true", ")", ";", "match", "(", "DotDot", ")", ";", "Expr", "rhs", "=", "parseAdditiveExpression", "(", "scope", ",", "true", ")", ";", "Expr", "range", "=", "new", "Expr", ".", "ArrayRange", "(", "Type", ".", "Void", ",", "lhs", ",", "rhs", ")", ";", "return", "annotateSourceLocation", "(", "range", ",", "start", ")", ";", "}" ]
Parse a range expression, which has the form: <pre> RangeExpr ::= Expr ".." Expr </pre> @param scope The enclosing scope for this statement, which determines the set of visible (i.e. declared) variables and also the current indentation level. @param terminated This indicates that the expression is known to be terminated (or not). An expression that's known to be terminated is one which is guaranteed to be followed by something. This is important because it means that we can ignore any newline characters encountered in parsing this expression, and that we'll never overrun the end of the expression (i.e. because there's guaranteed to be something which terminates this expression). A classic situation where terminated is true is when parsing an expression surrounded in braces. In such case, we know the right-brace will always terminate this expression. @return
[ "Parse", "a", "range", "expression", "which", "has", "the", "form", ":" ]
train
https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyc/io/WhileyFileParser.java#L2000-L2007
Azure/azure-sdk-for-java
logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/WorkflowsInner.java
WorkflowsInner.getByResourceGroupAsync
public Observable<WorkflowInner> getByResourceGroupAsync(String resourceGroupName, String workflowName) { """ Gets a workflow. @param resourceGroupName The resource group name. @param workflowName The workflow name. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the WorkflowInner object """ return getByResourceGroupWithServiceResponseAsync(resourceGroupName, workflowName).map(new Func1<ServiceResponse<WorkflowInner>, WorkflowInner>() { @Override public WorkflowInner call(ServiceResponse<WorkflowInner> response) { return response.body(); } }); }
java
public Observable<WorkflowInner> getByResourceGroupAsync(String resourceGroupName, String workflowName) { return getByResourceGroupWithServiceResponseAsync(resourceGroupName, workflowName).map(new Func1<ServiceResponse<WorkflowInner>, WorkflowInner>() { @Override public WorkflowInner call(ServiceResponse<WorkflowInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "WorkflowInner", ">", "getByResourceGroupAsync", "(", "String", "resourceGroupName", ",", "String", "workflowName", ")", "{", "return", "getByResourceGroupWithServiceResponseAsync", "(", "resourceGroupName", ",", "workflowName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "WorkflowInner", ">", ",", "WorkflowInner", ">", "(", ")", "{", "@", "Override", "public", "WorkflowInner", "call", "(", "ServiceResponse", "<", "WorkflowInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Gets a workflow. @param resourceGroupName The resource group name. @param workflowName The workflow name. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the WorkflowInner object
[ "Gets", "a", "workflow", "." ]
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/WorkflowsInner.java#L632-L639
googleads/googleads-java-lib
modules/ads_lib/src/main/java/com/google/api/ads/common/lib/utils/CsvFiles.java
CsvFiles.getCsvDataMapArray
public static Map<String, String[]> getCsvDataMapArray(String fileName, boolean headerPresent) throws IOException { """ Returns a {@code Map<String, String[]>} mapping of the first column to an array of the rest of the columns. @param fileName the CSV file to load @param headerPresent {@code true} if the fist line is the header @return a {@code Map<String, String[]>} mapping of the first column to an array of the rest of the columns @throws IllegalArgumentException if there is fewer than 2 columns in the CSV @throws IOException if there was an exception reading the file """ final Map<String, String[]> result = Maps.newHashMap(); new CsvReader(fileName, headerPresent) .processReader( (header, line, lineNumber) -> result.put( line[0], Arrays.asList(line) .subList(1, line.length) .toArray(new String[line.length - 1]))); return result; }
java
public static Map<String, String[]> getCsvDataMapArray(String fileName, boolean headerPresent) throws IOException { final Map<String, String[]> result = Maps.newHashMap(); new CsvReader(fileName, headerPresent) .processReader( (header, line, lineNumber) -> result.put( line[0], Arrays.asList(line) .subList(1, line.length) .toArray(new String[line.length - 1]))); return result; }
[ "public", "static", "Map", "<", "String", ",", "String", "[", "]", ">", "getCsvDataMapArray", "(", "String", "fileName", ",", "boolean", "headerPresent", ")", "throws", "IOException", "{", "final", "Map", "<", "String", ",", "String", "[", "]", ">", "result", "=", "Maps", ".", "newHashMap", "(", ")", ";", "new", "CsvReader", "(", "fileName", ",", "headerPresent", ")", ".", "processReader", "(", "(", "header", ",", "line", ",", "lineNumber", ")", "->", "result", ".", "put", "(", "line", "[", "0", "]", ",", "Arrays", ".", "asList", "(", "line", ")", ".", "subList", "(", "1", ",", "line", ".", "length", ")", ".", "toArray", "(", "new", "String", "[", "line", ".", "length", "-", "1", "]", ")", ")", ")", ";", "return", "result", ";", "}" ]
Returns a {@code Map<String, String[]>} mapping of the first column to an array of the rest of the columns. @param fileName the CSV file to load @param headerPresent {@code true} if the fist line is the header @return a {@code Map<String, String[]>} mapping of the first column to an array of the rest of the columns @throws IllegalArgumentException if there is fewer than 2 columns in the CSV @throws IOException if there was an exception reading the file
[ "Returns", "a", "{", "@code", "Map<String", "String", "[]", ">", "}", "mapping", "of", "the", "first", "column", "to", "an", "array", "of", "the", "rest", "of", "the", "columns", "." ]
train
https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/modules/ads_lib/src/main/java/com/google/api/ads/common/lib/utils/CsvFiles.java#L96-L108
carewebframework/carewebframework-core
org.carewebframework.shell/src/main/java/org/carewebframework/shell/layout/LayoutService.java
LayoutService.renameLayout
@Override public void renameLayout(LayoutIdentifier layout, String newName) { """ Rename a layout. @param layout The original layout identifier. @param newName The new layout name. """ String text = getLayoutContent(layout); saveLayout(new LayoutIdentifier(newName, layout.shared), text); deleteLayout(layout); }
java
@Override public void renameLayout(LayoutIdentifier layout, String newName) { String text = getLayoutContent(layout); saveLayout(new LayoutIdentifier(newName, layout.shared), text); deleteLayout(layout); }
[ "@", "Override", "public", "void", "renameLayout", "(", "LayoutIdentifier", "layout", ",", "String", "newName", ")", "{", "String", "text", "=", "getLayoutContent", "(", "layout", ")", ";", "saveLayout", "(", "new", "LayoutIdentifier", "(", "newName", ",", "layout", ".", "shared", ")", ",", "text", ")", ";", "deleteLayout", "(", "layout", ")", ";", "}" ]
Rename a layout. @param layout The original layout identifier. @param newName The new layout name.
[ "Rename", "a", "layout", "." ]
train
https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.shell/src/main/java/org/carewebframework/shell/layout/LayoutService.java#L90-L95
stephanenicolas/toothpick
toothpick-runtime/src/main/java/toothpick/ScopeImpl.java
ScopeImpl.getUnBoundProvider
private <T> InternalProviderImpl<? extends T> getUnBoundProvider(Class<T> clazz, String bindingName) { """ Obtains the provider of the class {@code clazz} and name {@code bindingName}, if any. The returned provider will belong to the pool of unbound providers. It can be {@code null} if there is no such provider. @param clazz the class for which to obtain the unbound provider. @param bindingName the name, possibly {@code null}, for which to obtain the unbound provider. @param <T> the type of {@code clazz}. @return the unbound provider for class {@code clazz} and {@code bindingName}. Returns {@code null} is there is no such unbound provider. """ return getInternalProvider(clazz, bindingName, false); }
java
private <T> InternalProviderImpl<? extends T> getUnBoundProvider(Class<T> clazz, String bindingName) { return getInternalProvider(clazz, bindingName, false); }
[ "private", "<", "T", ">", "InternalProviderImpl", "<", "?", "extends", "T", ">", "getUnBoundProvider", "(", "Class", "<", "T", ">", "clazz", ",", "String", "bindingName", ")", "{", "return", "getInternalProvider", "(", "clazz", ",", "bindingName", ",", "false", ")", ";", "}" ]
Obtains the provider of the class {@code clazz} and name {@code bindingName}, if any. The returned provider will belong to the pool of unbound providers. It can be {@code null} if there is no such provider. @param clazz the class for which to obtain the unbound provider. @param bindingName the name, possibly {@code null}, for which to obtain the unbound provider. @param <T> the type of {@code clazz}. @return the unbound provider for class {@code clazz} and {@code bindingName}. Returns {@code null} is there is no such unbound provider.
[ "Obtains", "the", "provider", "of", "the", "class", "{", "@code", "clazz", "}", "and", "name", "{", "@code", "bindingName", "}", "if", "any", ".", "The", "returned", "provider", "will", "belong", "to", "the", "pool", "of", "unbound", "providers", ".", "It", "can", "be", "{", "@code", "null", "}", "if", "there", "is", "no", "such", "provider", "." ]
train
https://github.com/stephanenicolas/toothpick/blob/54476ca9a5fa48809c15a46e43e38db9ed7e1a75/toothpick-runtime/src/main/java/toothpick/ScopeImpl.java#L376-L378
apache/incubator-gobblin
gobblin-utility/src/main/java/org/apache/gobblin/util/EmailUtils.java
EmailUtils.sendJobCompletionEmail
public static void sendJobCompletionEmail(String jobId, String message, String state, State jobState) throws EmailException { """ Send a job completion notification email. @param jobId job name @param message email message @param state job state @param jobState a {@link State} object carrying job configuration properties @throws EmailException if there is anything wrong sending the email """ sendEmail(jobState, String.format("Gobblin notification: job %s has completed with state %s", jobId, state), message); }
java
public static void sendJobCompletionEmail(String jobId, String message, String state, State jobState) throws EmailException { sendEmail(jobState, String.format("Gobblin notification: job %s has completed with state %s", jobId, state), message); }
[ "public", "static", "void", "sendJobCompletionEmail", "(", "String", "jobId", ",", "String", "message", ",", "String", "state", ",", "State", "jobState", ")", "throws", "EmailException", "{", "sendEmail", "(", "jobState", ",", "String", ".", "format", "(", "\"Gobblin notification: job %s has completed with state %s\"", ",", "jobId", ",", "state", ")", ",", "message", ")", ";", "}" ]
Send a job completion notification email. @param jobId job name @param message email message @param state job state @param jobState a {@link State} object carrying job configuration properties @throws EmailException if there is anything wrong sending the email
[ "Send", "a", "job", "completion", "notification", "email", "." ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/EmailUtils.java#L93-L97
liferay/com-liferay-commerce
commerce-currency-service/src/main/java/com/liferay/commerce/currency/service/persistence/impl/CommerceCurrencyPersistenceImpl.java
CommerceCurrencyPersistenceImpl.findByGroupId
@Override public List<CommerceCurrency> findByGroupId(long groupId) { """ Returns all the commerce currencies where groupId = &#63;. @param groupId the group ID @return the matching commerce currencies """ return findByGroupId(groupId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); }
java
@Override public List<CommerceCurrency> findByGroupId(long groupId) { return findByGroupId(groupId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); }
[ "@", "Override", "public", "List", "<", "CommerceCurrency", ">", "findByGroupId", "(", "long", "groupId", ")", "{", "return", "findByGroupId", "(", "groupId", ",", "QueryUtil", ".", "ALL_POS", ",", "QueryUtil", ".", "ALL_POS", ",", "null", ")", ";", "}" ]
Returns all the commerce currencies where groupId = &#63;. @param groupId the group ID @return the matching commerce currencies
[ "Returns", "all", "the", "commerce", "currencies", "where", "groupId", "=", "&#63", ";", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-currency-service/src/main/java/com/liferay/commerce/currency/service/persistence/impl/CommerceCurrencyPersistenceImpl.java#L1514-L1517
spotify/ssh-agent-proxy
src/main/java/com/spotify/sshagentproxy/AgentOutput.java
AgentOutput.signRequest
void signRequest(final RSAPublicKey rsaPublicKey, final byte[] data) throws IOException { """ Send a SSH2_AGENTC_SIGN_REQUEST message to ssh-agent. @param rsaPublicKey The {@link RSAPublicKey} that tells ssh-agent which private key to use to sign the data. @param data The data in bytes to be signed. """ // TODO (dxia) Support more than just Rsa keys final String keyType = Rsa.RSA_LABEL; final byte[] publicExponent = rsaPublicKey.getPublicExponent().toByteArray(); final byte[] modulus = rsaPublicKey.getModulus().toByteArray(); // Four bytes indicating length of string denoting key type // Four bytes indicating length of public exponent // Four bytes indicating length of modulus final int publicKeyLength = 4 + keyType.length() + 4 + publicExponent.length + 4 + modulus.length; // The message is made of: // Four bytes indicating length in bytes of rest of message // One byte indicating SSH2_AGENTC_SIGN_REQUEST // Four bytes denoting length of public key // Bytes representing the public key // Four bytes for length of data // Bytes representing data to be signed // Four bytes of flags final ByteBuffer buff = ByteBuffer.allocate( INT_BYTES + 1 + INT_BYTES + publicKeyLength + INT_BYTES + data.length + 4); // 13 = // One byte indicating SSH2_AGENTC_SIGN_REQUEST // Four bytes denoting length of public key // Four bytes for length of data // Four bytes of flags buff.putInt(publicKeyLength + data.length + 13); buff.put((byte) SSH2_AGENTC_SIGN_REQUEST); // Add the public key buff.putInt(publicKeyLength); buff.putInt(keyType.length()); for (final byte b : keyType.getBytes()) { buff.put(b); } buff.putInt(publicExponent.length); buff.put(publicExponent); buff.putInt(modulus.length); buff.put(modulus); // Add the data to be signed buff.putInt(data.length); buff.put(data); // Add empty flags buff.put(new byte[] {0, 0, 0, 0}); out.write(buff.array()); out.flush(); log.debug("Sent SSH2_AGENTC_SIGN_REQUEST message to ssh-agent."); }
java
void signRequest(final RSAPublicKey rsaPublicKey, final byte[] data) throws IOException { // TODO (dxia) Support more than just Rsa keys final String keyType = Rsa.RSA_LABEL; final byte[] publicExponent = rsaPublicKey.getPublicExponent().toByteArray(); final byte[] modulus = rsaPublicKey.getModulus().toByteArray(); // Four bytes indicating length of string denoting key type // Four bytes indicating length of public exponent // Four bytes indicating length of modulus final int publicKeyLength = 4 + keyType.length() + 4 + publicExponent.length + 4 + modulus.length; // The message is made of: // Four bytes indicating length in bytes of rest of message // One byte indicating SSH2_AGENTC_SIGN_REQUEST // Four bytes denoting length of public key // Bytes representing the public key // Four bytes for length of data // Bytes representing data to be signed // Four bytes of flags final ByteBuffer buff = ByteBuffer.allocate( INT_BYTES + 1 + INT_BYTES + publicKeyLength + INT_BYTES + data.length + 4); // 13 = // One byte indicating SSH2_AGENTC_SIGN_REQUEST // Four bytes denoting length of public key // Four bytes for length of data // Four bytes of flags buff.putInt(publicKeyLength + data.length + 13); buff.put((byte) SSH2_AGENTC_SIGN_REQUEST); // Add the public key buff.putInt(publicKeyLength); buff.putInt(keyType.length()); for (final byte b : keyType.getBytes()) { buff.put(b); } buff.putInt(publicExponent.length); buff.put(publicExponent); buff.putInt(modulus.length); buff.put(modulus); // Add the data to be signed buff.putInt(data.length); buff.put(data); // Add empty flags buff.put(new byte[] {0, 0, 0, 0}); out.write(buff.array()); out.flush(); log.debug("Sent SSH2_AGENTC_SIGN_REQUEST message to ssh-agent."); }
[ "void", "signRequest", "(", "final", "RSAPublicKey", "rsaPublicKey", ",", "final", "byte", "[", "]", "data", ")", "throws", "IOException", "{", "// TODO (dxia) Support more than just Rsa keys", "final", "String", "keyType", "=", "Rsa", ".", "RSA_LABEL", ";", "final", "byte", "[", "]", "publicExponent", "=", "rsaPublicKey", ".", "getPublicExponent", "(", ")", ".", "toByteArray", "(", ")", ";", "final", "byte", "[", "]", "modulus", "=", "rsaPublicKey", ".", "getModulus", "(", ")", ".", "toByteArray", "(", ")", ";", "// Four bytes indicating length of string denoting key type", "// Four bytes indicating length of public exponent", "// Four bytes indicating length of modulus", "final", "int", "publicKeyLength", "=", "4", "+", "keyType", ".", "length", "(", ")", "+", "4", "+", "publicExponent", ".", "length", "+", "4", "+", "modulus", ".", "length", ";", "// The message is made of:", "// Four bytes indicating length in bytes of rest of message", "// One byte indicating SSH2_AGENTC_SIGN_REQUEST", "// Four bytes denoting length of public key", "// Bytes representing the public key", "// Four bytes for length of data", "// Bytes representing data to be signed", "// Four bytes of flags", "final", "ByteBuffer", "buff", "=", "ByteBuffer", ".", "allocate", "(", "INT_BYTES", "+", "1", "+", "INT_BYTES", "+", "publicKeyLength", "+", "INT_BYTES", "+", "data", ".", "length", "+", "4", ")", ";", "// 13 =", "// One byte indicating SSH2_AGENTC_SIGN_REQUEST", "// Four bytes denoting length of public key", "// Four bytes for length of data", "// Four bytes of flags", "buff", ".", "putInt", "(", "publicKeyLength", "+", "data", ".", "length", "+", "13", ")", ";", "buff", ".", "put", "(", "(", "byte", ")", "SSH2_AGENTC_SIGN_REQUEST", ")", ";", "// Add the public key", "buff", ".", "putInt", "(", "publicKeyLength", ")", ";", "buff", ".", "putInt", "(", "keyType", ".", "length", "(", ")", ")", ";", "for", "(", "final", "byte", "b", ":", "keyType", ".", "getBytes", "(", ")", ")", "{", "buff", ".", "put", "(", "b", ")", ";", "}", "buff", ".", "putInt", "(", "publicExponent", ".", "length", ")", ";", "buff", ".", "put", "(", "publicExponent", ")", ";", "buff", ".", "putInt", "(", "modulus", ".", "length", ")", ";", "buff", ".", "put", "(", "modulus", ")", ";", "// Add the data to be signed", "buff", ".", "putInt", "(", "data", ".", "length", ")", ";", "buff", ".", "put", "(", "data", ")", ";", "// Add empty flags", "buff", ".", "put", "(", "new", "byte", "[", "]", "{", "0", ",", "0", ",", "0", ",", "0", "}", ")", ";", "out", ".", "write", "(", "buff", ".", "array", "(", ")", ")", ";", "out", ".", "flush", "(", ")", ";", "log", ".", "debug", "(", "\"Sent SSH2_AGENTC_SIGN_REQUEST message to ssh-agent.\"", ")", ";", "}" ]
Send a SSH2_AGENTC_SIGN_REQUEST message to ssh-agent. @param rsaPublicKey The {@link RSAPublicKey} that tells ssh-agent which private key to use to sign the data. @param data The data in bytes to be signed.
[ "Send", "a", "SSH2_AGENTC_SIGN_REQUEST", "message", "to", "ssh", "-", "agent", "." ]
train
https://github.com/spotify/ssh-agent-proxy/blob/b678792750c0157bd5ed3fb6a18895ff95effbc4/src/main/java/com/spotify/sshagentproxy/AgentOutput.java#L113-L167
google/auto
value/src/main/java/com/google/auto/value/processor/AutoAnnotationProcessor.java
AutoAnnotationProcessor.reportError
private void reportError(Element e, String msg, Object... msgParams) { """ Issue a compilation error. This method does not throw an exception, since we want to continue processing and perhaps report other errors. """ String formattedMessage = String.format(msg, msgParams); processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, formattedMessage, e); }
java
private void reportError(Element e, String msg, Object... msgParams) { String formattedMessage = String.format(msg, msgParams); processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, formattedMessage, e); }
[ "private", "void", "reportError", "(", "Element", "e", ",", "String", "msg", ",", "Object", "...", "msgParams", ")", "{", "String", "formattedMessage", "=", "String", ".", "format", "(", "msg", ",", "msgParams", ")", ";", "processingEnv", ".", "getMessager", "(", ")", ".", "printMessage", "(", "Diagnostic", ".", "Kind", ".", "ERROR", ",", "formattedMessage", ",", "e", ")", ";", "}" ]
Issue a compilation error. This method does not throw an exception, since we want to continue processing and perhaps report other errors.
[ "Issue", "a", "compilation", "error", ".", "This", "method", "does", "not", "throw", "an", "exception", "since", "we", "want", "to", "continue", "processing", "and", "perhaps", "report", "other", "errors", "." ]
train
https://github.com/google/auto/blob/4158a5fa71f1ef763e683b627f4d29bc04cfde9d/value/src/main/java/com/google/auto/value/processor/AutoAnnotationProcessor.java#L85-L88
googleapis/google-cloud-java
google-cloud-clients/google-cloud-dataproc/src/main/java/com/google/cloud/dataproc/v1/JobControllerClient.java
JobControllerClient.listJobs
public final ListJobsPagedResponse listJobs(String projectId, String region) { """ Lists regions/{region}/jobs in a project. <p>Sample code: <pre><code> try (JobControllerClient jobControllerClient = JobControllerClient.create()) { String projectId = ""; String region = ""; for (Job element : jobControllerClient.listJobs(projectId, region).iterateAll()) { // doThingsWith(element); } } </code></pre> @param projectId Required. The ID of the Google Cloud Platform project that the job belongs to. @param region Required. The Cloud Dataproc region in which to handle the request. @throws com.google.api.gax.rpc.ApiException if the remote call fails """ ListJobsRequest request = ListJobsRequest.newBuilder().setProjectId(projectId).setRegion(region).build(); return listJobs(request); }
java
public final ListJobsPagedResponse listJobs(String projectId, String region) { ListJobsRequest request = ListJobsRequest.newBuilder().setProjectId(projectId).setRegion(region).build(); return listJobs(request); }
[ "public", "final", "ListJobsPagedResponse", "listJobs", "(", "String", "projectId", ",", "String", "region", ")", "{", "ListJobsRequest", "request", "=", "ListJobsRequest", ".", "newBuilder", "(", ")", ".", "setProjectId", "(", "projectId", ")", ".", "setRegion", "(", "region", ")", ".", "build", "(", ")", ";", "return", "listJobs", "(", "request", ")", ";", "}" ]
Lists regions/{region}/jobs in a project. <p>Sample code: <pre><code> try (JobControllerClient jobControllerClient = JobControllerClient.create()) { String projectId = ""; String region = ""; for (Job element : jobControllerClient.listJobs(projectId, region).iterateAll()) { // doThingsWith(element); } } </code></pre> @param projectId Required. The ID of the Google Cloud Platform project that the job belongs to. @param region Required. The Cloud Dataproc region in which to handle the request. @throws com.google.api.gax.rpc.ApiException if the remote call fails
[ "Lists", "regions", "/", "{", "region", "}", "/", "jobs", "in", "a", "project", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-dataproc/src/main/java/com/google/cloud/dataproc/v1/JobControllerClient.java#L343-L347
wisdom-framework/wisdom
core/wisdom-maven-plugin/src/main/java/org/wisdom/maven/utils/DependencyCopy.java
DependencyCopy.getTransitiveDependencies
private static Set<Artifact> getTransitiveDependencies(AbstractWisdomMojo mojo, DependencyGraphBuilder graph, ArtifactFilter filter) { """ Collects the transitive dependencies of the current projects. @param mojo the mojo @param graph the dependency graph builder @return the set of resolved transitive dependencies. """ Set<Artifact> artifacts; artifacts = new LinkedHashSet<>(); try { Set<Artifact> transitives = new LinkedHashSet<>(); DependencyNode node = graph.buildDependencyGraph(mojo.project, filter); node.accept(new ArtifactVisitor(mojo, transitives)); mojo.getLog().debug(transitives.size() + " transitive dependencies have been collected : " + transitives); // Unfortunately, the retrieved artifacts are not resolved, we need to find their 'surrogates' in the // resolved list. Set<Artifact> resolved = mojo.project.getArtifacts(); for (Artifact a : transitives) { Artifact r = getArtifact(a, resolved); if (r == null) { mojo.getLog().warn("Cannot find resolved artifact for " + a); } else { artifacts.add(r); } } } catch (DependencyGraphBuilderException e) { mojo.getLog().error("Cannot traverse the project's dependencies to collect transitive dependencies, " + "ignoring transitive"); mojo.getLog().debug("Here is the thrown exception having disabled the transitive dependency collection", e); artifacts = mojo.project.getDependencyArtifacts(); } return artifacts; }
java
private static Set<Artifact> getTransitiveDependencies(AbstractWisdomMojo mojo, DependencyGraphBuilder graph, ArtifactFilter filter) { Set<Artifact> artifacts; artifacts = new LinkedHashSet<>(); try { Set<Artifact> transitives = new LinkedHashSet<>(); DependencyNode node = graph.buildDependencyGraph(mojo.project, filter); node.accept(new ArtifactVisitor(mojo, transitives)); mojo.getLog().debug(transitives.size() + " transitive dependencies have been collected : " + transitives); // Unfortunately, the retrieved artifacts are not resolved, we need to find their 'surrogates' in the // resolved list. Set<Artifact> resolved = mojo.project.getArtifacts(); for (Artifact a : transitives) { Artifact r = getArtifact(a, resolved); if (r == null) { mojo.getLog().warn("Cannot find resolved artifact for " + a); } else { artifacts.add(r); } } } catch (DependencyGraphBuilderException e) { mojo.getLog().error("Cannot traverse the project's dependencies to collect transitive dependencies, " + "ignoring transitive"); mojo.getLog().debug("Here is the thrown exception having disabled the transitive dependency collection", e); artifacts = mojo.project.getDependencyArtifacts(); } return artifacts; }
[ "private", "static", "Set", "<", "Artifact", ">", "getTransitiveDependencies", "(", "AbstractWisdomMojo", "mojo", ",", "DependencyGraphBuilder", "graph", ",", "ArtifactFilter", "filter", ")", "{", "Set", "<", "Artifact", ">", "artifacts", ";", "artifacts", "=", "new", "LinkedHashSet", "<>", "(", ")", ";", "try", "{", "Set", "<", "Artifact", ">", "transitives", "=", "new", "LinkedHashSet", "<>", "(", ")", ";", "DependencyNode", "node", "=", "graph", ".", "buildDependencyGraph", "(", "mojo", ".", "project", ",", "filter", ")", ";", "node", ".", "accept", "(", "new", "ArtifactVisitor", "(", "mojo", ",", "transitives", ")", ")", ";", "mojo", ".", "getLog", "(", ")", ".", "debug", "(", "transitives", ".", "size", "(", ")", "+", "\" transitive dependencies have been collected : \"", "+", "transitives", ")", ";", "// Unfortunately, the retrieved artifacts are not resolved, we need to find their 'surrogates' in the", "// resolved list.", "Set", "<", "Artifact", ">", "resolved", "=", "mojo", ".", "project", ".", "getArtifacts", "(", ")", ";", "for", "(", "Artifact", "a", ":", "transitives", ")", "{", "Artifact", "r", "=", "getArtifact", "(", "a", ",", "resolved", ")", ";", "if", "(", "r", "==", "null", ")", "{", "mojo", ".", "getLog", "(", ")", ".", "warn", "(", "\"Cannot find resolved artifact for \"", "+", "a", ")", ";", "}", "else", "{", "artifacts", ".", "add", "(", "r", ")", ";", "}", "}", "}", "catch", "(", "DependencyGraphBuilderException", "e", ")", "{", "mojo", ".", "getLog", "(", ")", ".", "error", "(", "\"Cannot traverse the project's dependencies to collect transitive dependencies, \"", "+", "\"ignoring transitive\"", ")", ";", "mojo", ".", "getLog", "(", ")", ".", "debug", "(", "\"Here is the thrown exception having disabled the transitive dependency collection\"", ",", "e", ")", ";", "artifacts", "=", "mojo", ".", "project", ".", "getDependencyArtifacts", "(", ")", ";", "}", "return", "artifacts", ";", "}" ]
Collects the transitive dependencies of the current projects. @param mojo the mojo @param graph the dependency graph builder @return the set of resolved transitive dependencies.
[ "Collects", "the", "transitive", "dependencies", "of", "the", "current", "projects", "." ]
train
https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/core/wisdom-maven-plugin/src/main/java/org/wisdom/maven/utils/DependencyCopy.java#L214-L243
exoplatform/jcr
exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/impl/AbstractBackupJob.java
AbstractBackupJob.notifyError
protected void notifyError(String message, Throwable error) { """ Notify all listeners about an error @param error - Throwable instance """ synchronized (listeners) { Thread notifier = new ErrorNotifyThread(listeners.toArray(new BackupJobListener[listeners.size()]), this, message, error); notifier.start(); } }
java
protected void notifyError(String message, Throwable error) { synchronized (listeners) { Thread notifier = new ErrorNotifyThread(listeners.toArray(new BackupJobListener[listeners.size()]), this, message, error); notifier.start(); } }
[ "protected", "void", "notifyError", "(", "String", "message", ",", "Throwable", "error", ")", "{", "synchronized", "(", "listeners", ")", "{", "Thread", "notifier", "=", "new", "ErrorNotifyThread", "(", "listeners", ".", "toArray", "(", "new", "BackupJobListener", "[", "listeners", ".", "size", "(", ")", "]", ")", ",", "this", ",", "message", ",", "error", ")", ";", "notifier", ".", "start", "(", ")", ";", "}", "}" ]
Notify all listeners about an error @param error - Throwable instance
[ "Notify", "all", "listeners", "about", "an", "error" ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/impl/AbstractBackupJob.java#L178-L186
gilberto-torrezan/viacep
src/main/java/com/github/gilbertotorrezan/viacep/gwt/ViaCEPGWTClient.java
ViaCEPGWTClient.getEnderecos
public void getEnderecos(String uf, String localidade, String logradouro, final MethodCallback<List<ViaCEPEndereco>> callback) { """ Executa a consulta de endereços a partir da UF, localidade e logradouro @param uf Unidade Federativa. Precisa ter 2 caracteres. @param localidade Localidade (p.e. município). Precisa ter ao menos 3 caracteres. @param logradouro Logradouro (p.e. rua, avenida, estrada). Precisa ter ao menos 3 caracteres. @param callback O retorno da chamada ao webservice. Erros de validação de campos e de conexão são tratados no callback. """ if (uf == null || uf.length() != 2){ callback.onFailure(null, new IllegalArgumentException("UF inválida - deve conter 2 caracteres: " + uf)); return; } if (localidade == null || localidade.length() < 3){ callback.onFailure(null, new IllegalArgumentException("Localidade inválida - deve conter pelo menos 3 caracteres: " + localidade)); return; } if (logradouro == null || logradouro.length() < 3){ callback.onFailure(null, new IllegalArgumentException("Logradouro inválido - deve conter pelo menos 3 caracteres: " + logradouro)); return; } ViaCEPGWTService service = getService(); service.getEnderecos(uf, localidade, logradouro, callback); }
java
public void getEnderecos(String uf, String localidade, String logradouro, final MethodCallback<List<ViaCEPEndereco>> callback){ if (uf == null || uf.length() != 2){ callback.onFailure(null, new IllegalArgumentException("UF inválida - deve conter 2 caracteres: " + uf)); return; } if (localidade == null || localidade.length() < 3){ callback.onFailure(null, new IllegalArgumentException("Localidade inválida - deve conter pelo menos 3 caracteres: " + localidade)); return; } if (logradouro == null || logradouro.length() < 3){ callback.onFailure(null, new IllegalArgumentException("Logradouro inválido - deve conter pelo menos 3 caracteres: " + logradouro)); return; } ViaCEPGWTService service = getService(); service.getEnderecos(uf, localidade, logradouro, callback); }
[ "public", "void", "getEnderecos", "(", "String", "uf", ",", "String", "localidade", ",", "String", "logradouro", ",", "final", "MethodCallback", "<", "List", "<", "ViaCEPEndereco", ">", ">", "callback", ")", "{", "if", "(", "uf", "==", "null", "||", "uf", ".", "length", "(", ")", "!=", "2", ")", "{", "callback", ".", "onFailure", "(", "null", ",", "new", "IllegalArgumentException", "(", "\"UF inválida - deve conter 2 caracteres: \" ", " ", "f)", ")", ";", "", "return", ";", "}", "if", "(", "localidade", "==", "null", "||", "localidade", ".", "length", "(", ")", "<", "3", ")", "{", "callback", ".", "onFailure", "(", "null", ",", "new", "IllegalArgumentException", "(", "\"Localidade inválida - deve conter pelo menos 3 caracteres: \" ", " ", "ocalidade)", ")", ";", "", "return", ";", "}", "if", "(", "logradouro", "==", "null", "||", "logradouro", ".", "length", "(", ")", "<", "3", ")", "{", "callback", ".", "onFailure", "(", "null", ",", "new", "IllegalArgumentException", "(", "\"Logradouro inválido - deve conter pelo menos 3 caracteres: \" ", " ", "ogradouro)", ")", ";", "", "return", ";", "}", "ViaCEPGWTService", "service", "=", "getService", "(", ")", ";", "service", ".", "getEnderecos", "(", "uf", ",", "localidade", ",", "logradouro", ",", "callback", ")", ";", "}" ]
Executa a consulta de endereços a partir da UF, localidade e logradouro @param uf Unidade Federativa. Precisa ter 2 caracteres. @param localidade Localidade (p.e. município). Precisa ter ao menos 3 caracteres. @param logradouro Logradouro (p.e. rua, avenida, estrada). Precisa ter ao menos 3 caracteres. @param callback O retorno da chamada ao webservice. Erros de validação de campos e de conexão são tratados no callback.
[ "Executa", "a", "consulta", "de", "endereços", "a", "partir", "da", "UF", "localidade", "e", "logradouro" ]
train
https://github.com/gilberto-torrezan/viacep/blob/96f203f72accb970e20a14792f0ea0b1b6553e3f/src/main/java/com/github/gilbertotorrezan/viacep/gwt/ViaCEPGWTClient.java#L116-L132
datumbox/datumbox-framework
datumbox-framework-common/src/main/java/com/datumbox/framework/common/ConfigurableFactory.java
ConfigurableFactory.getConfiguration
public static <C extends Configurable> C getConfiguration(Class<C> klass) { """ Initializes the Configuration Object based on the configuration file. @param <C> @param klass @return """ String defaultPropertyFile = "datumbox." + klass.getSimpleName().toLowerCase(Locale.ENGLISH) + DEFAULT_POSTFIX + ".properties"; Properties properties = new Properties(); ClassLoader cl = klass.getClassLoader(); //Load default properties from jar try (InputStream in = cl.getResourceAsStream(defaultPropertyFile)) { properties.load(in); } catch(IOException ex) { throw new UncheckedIOException(ex); } //Look for user defined properties String propertyFile = defaultPropertyFile.replaceFirst(DEFAULT_POSTFIX, ""); if(cl.getResource(propertyFile)!=null) { //Override the default if they exist try (InputStream in = cl.getResourceAsStream(propertyFile)) { properties.load(in); } catch(IOException ex) { throw new UncheckedIOException(ex); } logger.trace("Loading properties file {}: {}", propertyFile, properties); } else { logger.warn("Using default properties file {}: {}", defaultPropertyFile, properties); } return getConfiguration(klass, properties); }
java
public static <C extends Configurable> C getConfiguration(Class<C> klass) { String defaultPropertyFile = "datumbox." + klass.getSimpleName().toLowerCase(Locale.ENGLISH) + DEFAULT_POSTFIX + ".properties"; Properties properties = new Properties(); ClassLoader cl = klass.getClassLoader(); //Load default properties from jar try (InputStream in = cl.getResourceAsStream(defaultPropertyFile)) { properties.load(in); } catch(IOException ex) { throw new UncheckedIOException(ex); } //Look for user defined properties String propertyFile = defaultPropertyFile.replaceFirst(DEFAULT_POSTFIX, ""); if(cl.getResource(propertyFile)!=null) { //Override the default if they exist try (InputStream in = cl.getResourceAsStream(propertyFile)) { properties.load(in); } catch(IOException ex) { throw new UncheckedIOException(ex); } logger.trace("Loading properties file {}: {}", propertyFile, properties); } else { logger.warn("Using default properties file {}: {}", defaultPropertyFile, properties); } return getConfiguration(klass, properties); }
[ "public", "static", "<", "C", "extends", "Configurable", ">", "C", "getConfiguration", "(", "Class", "<", "C", ">", "klass", ")", "{", "String", "defaultPropertyFile", "=", "\"datumbox.\"", "+", "klass", ".", "getSimpleName", "(", ")", ".", "toLowerCase", "(", "Locale", ".", "ENGLISH", ")", "+", "DEFAULT_POSTFIX", "+", "\".properties\"", ";", "Properties", "properties", "=", "new", "Properties", "(", ")", ";", "ClassLoader", "cl", "=", "klass", ".", "getClassLoader", "(", ")", ";", "//Load default properties from jar", "try", "(", "InputStream", "in", "=", "cl", ".", "getResourceAsStream", "(", "defaultPropertyFile", ")", ")", "{", "properties", ".", "load", "(", "in", ")", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "throw", "new", "UncheckedIOException", "(", "ex", ")", ";", "}", "//Look for user defined properties", "String", "propertyFile", "=", "defaultPropertyFile", ".", "replaceFirst", "(", "DEFAULT_POSTFIX", ",", "\"\"", ")", ";", "if", "(", "cl", ".", "getResource", "(", "propertyFile", ")", "!=", "null", ")", "{", "//Override the default if they exist", "try", "(", "InputStream", "in", "=", "cl", ".", "getResourceAsStream", "(", "propertyFile", ")", ")", "{", "properties", ".", "load", "(", "in", ")", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "throw", "new", "UncheckedIOException", "(", "ex", ")", ";", "}", "logger", ".", "trace", "(", "\"Loading properties file {}: {}\"", ",", "propertyFile", ",", "properties", ")", ";", "}", "else", "{", "logger", ".", "warn", "(", "\"Using default properties file {}: {}\"", ",", "defaultPropertyFile", ",", "properties", ")", ";", "}", "return", "getConfiguration", "(", "klass", ",", "properties", ")", ";", "}" ]
Initializes the Configuration Object based on the configuration file. @param <C> @param klass @return
[ "Initializes", "the", "Configuration", "Object", "based", "on", "the", "configuration", "file", "." ]
train
https://github.com/datumbox/datumbox-framework/blob/909dff0476e80834f05ecdde0624dd2390e9b0ca/datumbox-framework-common/src/main/java/com/datumbox/framework/common/ConfigurableFactory.java#L48-L80
JodaOrg/joda-money
src/main/java/org/joda/money/CurrencyUnit.java
CurrencyUnit.registerCurrency
public static synchronized CurrencyUnit registerCurrency( String currencyCode, int numericCurrencyCode, int decimalPlaces, boolean force) { """ Registers a currency allowing it to be used, allowing replacement. <p> This class only permits known currencies to be returned. To achieve this, all currencies have to be registered in advance. <p> Since this method is public, it is possible to add currencies in application code. It is recommended to do this only at startup, however it is safe to do so later as the internal implementation is thread-safe. <p> This method uses a flag to determine whether the registered currency must be new, or can replace an existing currency. <p> The currency code must be three upper-case ASCII letters, based on ISO-4217. The numeric code must be from 0 to 999, or -1 if not applicable. @param currencyCode the three-letter upper-case currency code, not null @param numericCurrencyCode the numeric currency code, from 0 to 999, -1 if none @param decimalPlaces the number of decimal places that the currency normally has, from 0 to 30 (normally 0, 2 or 3), or -1 for a pseudo-currency use of ISO-3166 is recommended, not null @param force true to register forcefully, replacing any existing matching currency, false to validate that there is no existing matching currency @return the new instance, never null @throws IllegalArgumentException if the code is already registered and {@code force} is false; or if the specified data is invalid """ List<String> countryCodes = Collections.emptyList(); return registerCurrency(currencyCode, numericCurrencyCode, decimalPlaces, countryCodes, force); }
java
public static synchronized CurrencyUnit registerCurrency( String currencyCode, int numericCurrencyCode, int decimalPlaces, boolean force) { List<String> countryCodes = Collections.emptyList(); return registerCurrency(currencyCode, numericCurrencyCode, decimalPlaces, countryCodes, force); }
[ "public", "static", "synchronized", "CurrencyUnit", "registerCurrency", "(", "String", "currencyCode", ",", "int", "numericCurrencyCode", ",", "int", "decimalPlaces", ",", "boolean", "force", ")", "{", "List", "<", "String", ">", "countryCodes", "=", "Collections", ".", "emptyList", "(", ")", ";", "return", "registerCurrency", "(", "currencyCode", ",", "numericCurrencyCode", ",", "decimalPlaces", ",", "countryCodes", ",", "force", ")", ";", "}" ]
Registers a currency allowing it to be used, allowing replacement. <p> This class only permits known currencies to be returned. To achieve this, all currencies have to be registered in advance. <p> Since this method is public, it is possible to add currencies in application code. It is recommended to do this only at startup, however it is safe to do so later as the internal implementation is thread-safe. <p> This method uses a flag to determine whether the registered currency must be new, or can replace an existing currency. <p> The currency code must be three upper-case ASCII letters, based on ISO-4217. The numeric code must be from 0 to 999, or -1 if not applicable. @param currencyCode the three-letter upper-case currency code, not null @param numericCurrencyCode the numeric currency code, from 0 to 999, -1 if none @param decimalPlaces the number of decimal places that the currency normally has, from 0 to 30 (normally 0, 2 or 3), or -1 for a pseudo-currency use of ISO-3166 is recommended, not null @param force true to register forcefully, replacing any existing matching currency, false to validate that there is no existing matching currency @return the new instance, never null @throws IllegalArgumentException if the code is already registered and {@code force} is false; or if the specified data is invalid
[ "Registers", "a", "currency", "allowing", "it", "to", "be", "used", "allowing", "replacement", ".", "<p", ">", "This", "class", "only", "permits", "known", "currencies", "to", "be", "returned", ".", "To", "achieve", "this", "all", "currencies", "have", "to", "be", "registered", "in", "advance", ".", "<p", ">", "Since", "this", "method", "is", "public", "it", "is", "possible", "to", "add", "currencies", "in", "application", "code", ".", "It", "is", "recommended", "to", "do", "this", "only", "at", "startup", "however", "it", "is", "safe", "to", "do", "so", "later", "as", "the", "internal", "implementation", "is", "thread", "-", "safe", ".", "<p", ">", "This", "method", "uses", "a", "flag", "to", "determine", "whether", "the", "registered", "currency", "must", "be", "new", "or", "can", "replace", "an", "existing", "currency", ".", "<p", ">", "The", "currency", "code", "must", "be", "three", "upper", "-", "case", "ASCII", "letters", "based", "on", "ISO", "-", "4217", ".", "The", "numeric", "code", "must", "be", "from", "0", "to", "999", "or", "-", "1", "if", "not", "applicable", "." ]
train
https://github.com/JodaOrg/joda-money/blob/e1f2de75aa36610a695358696c8a88a18ca66cde/src/main/java/org/joda/money/CurrencyUnit.java#L265-L273
Azure/azure-sdk-for-java
containerregistry/resource-manager/v2018_09_01/src/main/java/com/microsoft/azure/management/containerregistry/v2018_09_01/implementation/RunsInner.java
RunsInner.updateAsync
public Observable<RunInner> updateAsync(String resourceGroupName, String registryName, String runId) { """ Patch the run properties. @param resourceGroupName The name of the resource group to which the container registry belongs. @param registryName The name of the container registry. @param runId The run ID. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request """ return updateWithServiceResponseAsync(resourceGroupName, registryName, runId).map(new Func1<ServiceResponse<RunInner>, RunInner>() { @Override public RunInner call(ServiceResponse<RunInner> response) { return response.body(); } }); }
java
public Observable<RunInner> updateAsync(String resourceGroupName, String registryName, String runId) { return updateWithServiceResponseAsync(resourceGroupName, registryName, runId).map(new Func1<ServiceResponse<RunInner>, RunInner>() { @Override public RunInner call(ServiceResponse<RunInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "RunInner", ">", "updateAsync", "(", "String", "resourceGroupName", ",", "String", "registryName", ",", "String", "runId", ")", "{", "return", "updateWithServiceResponseAsync", "(", "resourceGroupName", ",", "registryName", ",", "runId", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "RunInner", ">", ",", "RunInner", ">", "(", ")", "{", "@", "Override", "public", "RunInner", "call", "(", "ServiceResponse", "<", "RunInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Patch the run properties. @param resourceGroupName The name of the resource group to which the container registry belongs. @param registryName The name of the container registry. @param runId The run ID. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Patch", "the", "run", "properties", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/containerregistry/resource-manager/v2018_09_01/src/main/java/com/microsoft/azure/management/containerregistry/v2018_09_01/implementation/RunsInner.java#L474-L481
paypal/SeLion
client/src/main/java/com/paypal/selion/internal/reports/runtimereport/JsonRuntimeReporterHelper.java
JsonRuntimeReporterHelper.generateHTMLReport
private void generateHTMLReport(BufferedWriter writer, BufferedReader templateReader, String jsonReport) throws IOException { """ Writing JSON content to HTML file @param writer @param templateReader @param jsonReport @throws IOException """ logger.entering(new Object[] { writer, templateReader, jsonReport }); String readLine = null; while ((readLine = templateReader.readLine()) != null) { if (readLine.trim().equals("${reports}")) { writer.write(jsonReport); writer.newLine(); } else { writer.write(readLine); writer.newLine(); } } logger.exiting(); }
java
private void generateHTMLReport(BufferedWriter writer, BufferedReader templateReader, String jsonReport) throws IOException { logger.entering(new Object[] { writer, templateReader, jsonReport }); String readLine = null; while ((readLine = templateReader.readLine()) != null) { if (readLine.trim().equals("${reports}")) { writer.write(jsonReport); writer.newLine(); } else { writer.write(readLine); writer.newLine(); } } logger.exiting(); }
[ "private", "void", "generateHTMLReport", "(", "BufferedWriter", "writer", ",", "BufferedReader", "templateReader", ",", "String", "jsonReport", ")", "throws", "IOException", "{", "logger", ".", "entering", "(", "new", "Object", "[", "]", "{", "writer", ",", "templateReader", ",", "jsonReport", "}", ")", ";", "String", "readLine", "=", "null", ";", "while", "(", "(", "readLine", "=", "templateReader", ".", "readLine", "(", ")", ")", "!=", "null", ")", "{", "if", "(", "readLine", ".", "trim", "(", ")", ".", "equals", "(", "\"${reports}\"", ")", ")", "{", "writer", ".", "write", "(", "jsonReport", ")", ";", "writer", ".", "newLine", "(", ")", ";", "}", "else", "{", "writer", ".", "write", "(", "readLine", ")", ";", "writer", ".", "newLine", "(", ")", ";", "}", "}", "logger", ".", "exiting", "(", ")", ";", "}" ]
Writing JSON content to HTML file @param writer @param templateReader @param jsonReport @throws IOException
[ "Writing", "JSON", "content", "to", "HTML", "file" ]
train
https://github.com/paypal/SeLion/blob/694d12d0df76db48d0360b16192770c6a4fbdfd2/client/src/main/java/com/paypal/selion/internal/reports/runtimereport/JsonRuntimeReporterHelper.java#L349-L365
alibaba/jstorm
jstorm-core/src/main/java/backtype/storm/topology/TopologyBuilder.java
TopologyBuilder.setBolt
public BoltDeclarer setBolt(String id, IBasicBolt bolt, Number parallelism_hint) throws IllegalArgumentException { """ Define a new bolt in this topology. This defines a basic bolt, which is a simpler to use but more restricted kind of bolt. Basic bolts are intended for non-aggregation processing and automate the anchoring/acking process to achieve proper reliability in the topology. @param id the id of this component. This id is referenced by other components that want to consume this bolt's outputs. @param bolt the basic bolt @param parallelism_hint the number of tasks that should be assigned to execute this bolt. Each task will run on a thread in a process somewhere around the cluster. @return use the returned object to declare the inputs to this component @throws IllegalArgumentException if {@code parallelism_hint} is not positive """ return setBolt(id, new BasicBoltExecutor(bolt), parallelism_hint); }
java
public BoltDeclarer setBolt(String id, IBasicBolt bolt, Number parallelism_hint) throws IllegalArgumentException { return setBolt(id, new BasicBoltExecutor(bolt), parallelism_hint); }
[ "public", "BoltDeclarer", "setBolt", "(", "String", "id", ",", "IBasicBolt", "bolt", ",", "Number", "parallelism_hint", ")", "throws", "IllegalArgumentException", "{", "return", "setBolt", "(", "id", ",", "new", "BasicBoltExecutor", "(", "bolt", ")", ",", "parallelism_hint", ")", ";", "}" ]
Define a new bolt in this topology. This defines a basic bolt, which is a simpler to use but more restricted kind of bolt. Basic bolts are intended for non-aggregation processing and automate the anchoring/acking process to achieve proper reliability in the topology. @param id the id of this component. This id is referenced by other components that want to consume this bolt's outputs. @param bolt the basic bolt @param parallelism_hint the number of tasks that should be assigned to execute this bolt. Each task will run on a thread in a process somewhere around the cluster. @return use the returned object to declare the inputs to this component @throws IllegalArgumentException if {@code parallelism_hint} is not positive
[ "Define", "a", "new", "bolt", "in", "this", "topology", ".", "This", "defines", "a", "basic", "bolt", "which", "is", "a", "simpler", "to", "use", "but", "more", "restricted", "kind", "of", "bolt", ".", "Basic", "bolts", "are", "intended", "for", "non", "-", "aggregation", "processing", "and", "automate", "the", "anchoring", "/", "acking", "process", "to", "achieve", "proper", "reliability", "in", "the", "topology", "." ]
train
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/topology/TopologyBuilder.java#L220-L222
threerings/narya
core/src/main/java/com/threerings/presents/dobj/DObject.java
DObject.postMessage
public void postMessage (Transport transport, String name, Object... args) { """ Posts a message event on this distributed object. @param transport a hint as to the type of transport desired for the message. """ postEvent(new MessageEvent(_oid, name, args).setTransport(transport)); }
java
public void postMessage (Transport transport, String name, Object... args) { postEvent(new MessageEvent(_oid, name, args).setTransport(transport)); }
[ "public", "void", "postMessage", "(", "Transport", "transport", ",", "String", "name", ",", "Object", "...", "args", ")", "{", "postEvent", "(", "new", "MessageEvent", "(", "_oid", ",", "name", ",", "args", ")", ".", "setTransport", "(", "transport", ")", ")", ";", "}" ]
Posts a message event on this distributed object. @param transport a hint as to the type of transport desired for the message.
[ "Posts", "a", "message", "event", "on", "this", "distributed", "object", "." ]
train
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/dobj/DObject.java#L510-L513
looly/hutool
hutool-core/src/main/java/cn/hutool/core/io/FileUtil.java
FileUtil.copyFilesFromDir
public static File copyFilesFromDir(File src, File dest, boolean isOverride) throws IORuntimeException { """ 复制文件或目录<br> 情况如下: <pre> 1、src和dest都为目录,则讲src下所有文件(包括子目录)拷贝到dest下 2、src和dest都为文件,直接复制,名字为dest 3、src为文件,dest为目录,将src拷贝到dest目录下 </pre> @param src 源文件 @param dest 目标文件或目录,目标不存在会自动创建(目录、文件都创建) @param isOverride 是否覆盖目标文件 @return 目标目录或文件 @throws IORuntimeException IO异常 @since 4.1.5 """ return FileCopier.create(src, dest).setCopyContentIfDir(true).setOnlyCopyFile(true).setOverride(isOverride).copy(); }
java
public static File copyFilesFromDir(File src, File dest, boolean isOverride) throws IORuntimeException { return FileCopier.create(src, dest).setCopyContentIfDir(true).setOnlyCopyFile(true).setOverride(isOverride).copy(); }
[ "public", "static", "File", "copyFilesFromDir", "(", "File", "src", ",", "File", "dest", ",", "boolean", "isOverride", ")", "throws", "IORuntimeException", "{", "return", "FileCopier", ".", "create", "(", "src", ",", "dest", ")", ".", "setCopyContentIfDir", "(", "true", ")", ".", "setOnlyCopyFile", "(", "true", ")", ".", "setOverride", "(", "isOverride", ")", ".", "copy", "(", ")", ";", "}" ]
复制文件或目录<br> 情况如下: <pre> 1、src和dest都为目录,则讲src下所有文件(包括子目录)拷贝到dest下 2、src和dest都为文件,直接复制,名字为dest 3、src为文件,dest为目录,将src拷贝到dest目录下 </pre> @param src 源文件 @param dest 目标文件或目录,目标不存在会自动创建(目录、文件都创建) @param isOverride 是否覆盖目标文件 @return 目标目录或文件 @throws IORuntimeException IO异常 @since 4.1.5
[ "复制文件或目录<br", ">", "情况如下:" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/io/FileUtil.java#L1044-L1046
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/mfp/jmf/impl/JSchema.java
JSchema.getCaseIndex
public int getCaseIndex(int accessor, String name) { """ Resolve a case name to a case index @param accessor the accessor of a JSVariant in the schema in whose scope the case name is to be resolved @param name the case name to be resolved @return the case index associated with the name or -1 if either the accessor does not refer to a JSVariant in this schema or the name doesn't name one of its cases """ JMFFieldDef field = getFieldDef(accessor); if (!(field instanceof JSVariant)) return -1; JMFType target = findVariantChildByName((JSVariant)field, name); if (target != null) return getEffectiveSiblingPosition(target); else return -1; }
java
public int getCaseIndex(int accessor, String name) { JMFFieldDef field = getFieldDef(accessor); if (!(field instanceof JSVariant)) return -1; JMFType target = findVariantChildByName((JSVariant)field, name); if (target != null) return getEffectiveSiblingPosition(target); else return -1; }
[ "public", "int", "getCaseIndex", "(", "int", "accessor", ",", "String", "name", ")", "{", "JMFFieldDef", "field", "=", "getFieldDef", "(", "accessor", ")", ";", "if", "(", "!", "(", "field", "instanceof", "JSVariant", ")", ")", "return", "-", "1", ";", "JMFType", "target", "=", "findVariantChildByName", "(", "(", "JSVariant", ")", "field", ",", "name", ")", ";", "if", "(", "target", "!=", "null", ")", "return", "getEffectiveSiblingPosition", "(", "target", ")", ";", "else", "return", "-", "1", ";", "}" ]
Resolve a case name to a case index @param accessor the accessor of a JSVariant in the schema in whose scope the case name is to be resolved @param name the case name to be resolved @return the case index associated with the name or -1 if either the accessor does not refer to a JSVariant in this schema or the name doesn't name one of its cases
[ "Resolve", "a", "case", "name", "to", "a", "case", "index" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/mfp/jmf/impl/JSchema.java#L444-L453