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
listlengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
listlengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
spotbugs/spotbugs
spotbugs/src/main/java/edu/umd/cs/findbugs/xml/MetaCharacterMap.java
MetaCharacterMap.addMeta
public void addMeta(char meta, String replacement) { """ Add a metacharacter and its replacement. @param meta the metacharacter @param replacement the String to replace the metacharacter with """ metaCharacterSet.set(meta); replacementMap.put(new String(new char[] { meta }), replacement); }
java
public void addMeta(char meta, String replacement) { metaCharacterSet.set(meta); replacementMap.put(new String(new char[] { meta }), replacement); }
[ "public", "void", "addMeta", "(", "char", "meta", ",", "String", "replacement", ")", "{", "metaCharacterSet", ".", "set", "(", "meta", ")", ";", "replacementMap", ".", "put", "(", "new", "String", "(", "new", "char", "[", "]", "{", "meta", "}", ")", ...
Add a metacharacter and its replacement. @param meta the metacharacter @param replacement the String to replace the metacharacter with
[ "Add", "a", "metacharacter", "and", "its", "replacement", "." ]
train
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/xml/MetaCharacterMap.java#L53-L56
cloudant/sync-android
cloudant-sync-datastore-core/src/main/java/com/cloudant/sync/internal/documentstore/AttachmentManager.java
AttachmentManager.fileFromKey
public static File fileFromKey(SQLDatabase db, byte[] key, String attachmentsDir, boolean allowCreateName) throws AttachmentException { """ Lookup or create a on disk File representation of blob, in {@code db} using {@code key}. Existing attachments will have an entry in db, so the method just looks this up and returns the File object for the path. For new attachments, the {@code key} doesn't already have an associated filename, one is generated and inserted into the database before returning a File object for blob associated with {@code key}. @param db database to use. @param key key to lookup filename for. @param attachmentsDir Root directory for attachment blobs. @param allowCreateName if the is no existing mapping, whether one should be created and returned. If false, and no existing mapping, AttachmentException is thrown. @return File object for blob associated with {@code key}. @throws AttachmentException if a mapping doesn't exist and {@code allowCreateName} is false or if the name generation process fails. """ String keyString = keyToString(key); String filename = null; db.beginTransaction(); Cursor c = null; try { c = db.rawQuery(SQL_FILENAME_LOOKUP_QUERY, new String[]{ keyString }); if (c.moveToFirst()) { filename = c.getString(0); logger.finest(String.format("Found filename %s for key %s", filename, keyString)); } else if (allowCreateName) { filename = generateFilenameForKey(db, keyString); logger.finest(String.format("Added filename %s for key %s", filename, keyString)); } db.setTransactionSuccessful(); } catch (SQLException e) { logger.log(Level.WARNING, "Couldn't read key,filename mapping database", e); filename = null; } finally { DatabaseUtils.closeCursorQuietly(c); db.endTransaction(); } if (filename != null) { return new File(attachmentsDir, filename); } else { // generateFilenameForKey throws an exception if we couldn't generate, this // means we couldn't get one from the database. throw new AttachmentException("Couldn't retrieve filename for attachment"); } }
java
public static File fileFromKey(SQLDatabase db, byte[] key, String attachmentsDir, boolean allowCreateName) throws AttachmentException { String keyString = keyToString(key); String filename = null; db.beginTransaction(); Cursor c = null; try { c = db.rawQuery(SQL_FILENAME_LOOKUP_QUERY, new String[]{ keyString }); if (c.moveToFirst()) { filename = c.getString(0); logger.finest(String.format("Found filename %s for key %s", filename, keyString)); } else if (allowCreateName) { filename = generateFilenameForKey(db, keyString); logger.finest(String.format("Added filename %s for key %s", filename, keyString)); } db.setTransactionSuccessful(); } catch (SQLException e) { logger.log(Level.WARNING, "Couldn't read key,filename mapping database", e); filename = null; } finally { DatabaseUtils.closeCursorQuietly(c); db.endTransaction(); } if (filename != null) { return new File(attachmentsDir, filename); } else { // generateFilenameForKey throws an exception if we couldn't generate, this // means we couldn't get one from the database. throw new AttachmentException("Couldn't retrieve filename for attachment"); } }
[ "public", "static", "File", "fileFromKey", "(", "SQLDatabase", "db", ",", "byte", "[", "]", "key", ",", "String", "attachmentsDir", ",", "boolean", "allowCreateName", ")", "throws", "AttachmentException", "{", "String", "keyString", "=", "keyToString", "(", "key...
Lookup or create a on disk File representation of blob, in {@code db} using {@code key}. Existing attachments will have an entry in db, so the method just looks this up and returns the File object for the path. For new attachments, the {@code key} doesn't already have an associated filename, one is generated and inserted into the database before returning a File object for blob associated with {@code key}. @param db database to use. @param key key to lookup filename for. @param attachmentsDir Root directory for attachment blobs. @param allowCreateName if the is no existing mapping, whether one should be created and returned. If false, and no existing mapping, AttachmentException is thrown. @return File object for blob associated with {@code key}. @throws AttachmentException if a mapping doesn't exist and {@code allowCreateName} is false or if the name generation process fails.
[ "Lookup", "or", "create", "a", "on", "disk", "File", "representation", "of", "blob", "in", "{", "@code", "db", "}", "using", "{", "@code", "key", "}", "." ]
train
https://github.com/cloudant/sync-android/blob/5f1416ed1bd9ab05d7a4b8736480c8ae68bd7383/cloudant-sync-datastore-core/src/main/java/com/cloudant/sync/internal/documentstore/AttachmentManager.java#L497-L531
jdereg/java-util
src/main/java/com/cedarsoftware/util/MapUtilities.java
MapUtilities.get
public static <T> T get(Map map, String key, T def) { """ Retrieves a value from a map by key @param map Map to retrieve item from @param key the key whose associated value is to be returned @param def value to return if item was not found. @return Returns a string value that was found at the location key. If the item is null then the def value is sent back. If the item is not the expected type, an exception is thrown. @exception ClassCastException if the item found is not a the expected type. """ Object val = map.get(key); return val == null ? def : (T)val; }
java
public static <T> T get(Map map, String key, T def) { Object val = map.get(key); return val == null ? def : (T)val; }
[ "public", "static", "<", "T", ">", "T", "get", "(", "Map", "map", ",", "String", "key", ",", "T", "def", ")", "{", "Object", "val", "=", "map", ".", "get", "(", "key", ")", ";", "return", "val", "==", "null", "?", "def", ":", "(", "T", ")", ...
Retrieves a value from a map by key @param map Map to retrieve item from @param key the key whose associated value is to be returned @param def value to return if item was not found. @return Returns a string value that was found at the location key. If the item is null then the def value is sent back. If the item is not the expected type, an exception is thrown. @exception ClassCastException if the item found is not a the expected type.
[ "Retrieves", "a", "value", "from", "a", "map", "by", "key" ]
train
https://github.com/jdereg/java-util/blob/a2dce61aed16d6454ee575174dda1ba6bff0015c/src/main/java/com/cedarsoftware/util/MapUtilities.java#L47-L50
OpenLiberty/open-liberty
dev/com.ibm.ws.jmx.connector.server.rest/src/com/ibm/ws/jmx/connector/server/rest/helpers/MBeanRoutedNotificationHelper.java
MBeanRoutedNotificationHelper.postRoutedNotificationListenerRegistrationEvent
private void postRoutedNotificationListenerRegistrationEvent(String operation, NotificationTargetInformation nti) { """ Post an event to EventAdmin, instructing the Target-Client Manager to register or unregister a listener for a given target. """ Map<String, Object> props = createListenerRegistrationEvent(operation, nti); safePostEvent(new Event(REGISTER_JMX_NOTIFICATION_LISTENER_TOPIC, props)); }
java
private void postRoutedNotificationListenerRegistrationEvent(String operation, NotificationTargetInformation nti) { Map<String, Object> props = createListenerRegistrationEvent(operation, nti); safePostEvent(new Event(REGISTER_JMX_NOTIFICATION_LISTENER_TOPIC, props)); }
[ "private", "void", "postRoutedNotificationListenerRegistrationEvent", "(", "String", "operation", ",", "NotificationTargetInformation", "nti", ")", "{", "Map", "<", "String", ",", "Object", ">", "props", "=", "createListenerRegistrationEvent", "(", "operation", ",", "nt...
Post an event to EventAdmin, instructing the Target-Client Manager to register or unregister a listener for a given target.
[ "Post", "an", "event", "to", "EventAdmin", "instructing", "the", "Target", "-", "Client", "Manager", "to", "register", "or", "unregister", "a", "listener", "for", "a", "given", "target", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jmx.connector.server.rest/src/com/ibm/ws/jmx/connector/server/rest/helpers/MBeanRoutedNotificationHelper.java#L231-L234
exoplatform/jcr
exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/NamespaceDataPersister.java
NamespaceDataPersister.addNamespaces
public void addNamespaces(Map<String, String> namespaceMap) throws RepositoryException { """ Add new namespace. @param namespaceMap @throws RepositoryException Repository error """ if (!started) { log.warn("Unable save namespaces in to the storage. Storage not initialized"); return; } PlainChangesLog changesLog = new PlainChangesLogImpl(); for (Map.Entry<String, String> entry : namespaceMap.entrySet()) { String prefix = entry.getKey(); String uri = entry.getValue(); if (prefix != null) { if (log.isDebugEnabled()) log.debug("Namespace " + uri + ":" + prefix); internallAdd(changesLog, prefix, uri); } } dataManager.save(new TransactionChangesLog(changesLog)); }
java
public void addNamespaces(Map<String, String> namespaceMap) throws RepositoryException { if (!started) { log.warn("Unable save namespaces in to the storage. Storage not initialized"); return; } PlainChangesLog changesLog = new PlainChangesLogImpl(); for (Map.Entry<String, String> entry : namespaceMap.entrySet()) { String prefix = entry.getKey(); String uri = entry.getValue(); if (prefix != null) { if (log.isDebugEnabled()) log.debug("Namespace " + uri + ":" + prefix); internallAdd(changesLog, prefix, uri); } } dataManager.save(new TransactionChangesLog(changesLog)); }
[ "public", "void", "addNamespaces", "(", "Map", "<", "String", ",", "String", ">", "namespaceMap", ")", "throws", "RepositoryException", "{", "if", "(", "!", "started", ")", "{", "log", ".", "warn", "(", "\"Unable save namespaces in to the storage. Storage not initia...
Add new namespace. @param namespaceMap @throws RepositoryException Repository error
[ "Add", "new", "namespace", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/NamespaceDataPersister.java#L137-L160
goldmansachs/reladomo
reladomo/src/main/java/com/gs/fw/common/mithra/MithraManager.java
MithraManager.loadMithraCache
public void loadMithraCache(List<MithraObjectPortal> portals, int threads) throws MithraBusinessException { """ This method will load the cache of the object already initialized. A Collection is used to keep track of the objects to load. @param portals list of portals to load caches for @param threads number of parallel threads to load @throws MithraBusinessException if something goes wrong during the load """ this.configManager.loadMithraCache(portals, threads); }
java
public void loadMithraCache(List<MithraObjectPortal> portals, int threads) throws MithraBusinessException { this.configManager.loadMithraCache(portals, threads); }
[ "public", "void", "loadMithraCache", "(", "List", "<", "MithraObjectPortal", ">", "portals", ",", "int", "threads", ")", "throws", "MithraBusinessException", "{", "this", ".", "configManager", ".", "loadMithraCache", "(", "portals", ",", "threads", ")", ";", "}"...
This method will load the cache of the object already initialized. A Collection is used to keep track of the objects to load. @param portals list of portals to load caches for @param threads number of parallel threads to load @throws MithraBusinessException if something goes wrong during the load
[ "This", "method", "will", "load", "the", "cache", "of", "the", "object", "already", "initialized", ".", "A", "Collection", "is", "used", "to", "keep", "track", "of", "the", "objects", "to", "load", "." ]
train
https://github.com/goldmansachs/reladomo/blob/e9a069452eece7a6ef9551caf81a69d3d9a3d990/reladomo/src/main/java/com/gs/fw/common/mithra/MithraManager.java#L735-L738
UrielCh/ovh-java-sdk
ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java
ApiOvhOrder.license_virtuozzo_new_duration_POST
public OvhOrder license_virtuozzo_new_duration_POST(String duration, OvhOrderableVirtuozzoContainerNumberEnum containerNumber, String ip, OvhLicenseTypeEnum serviceType, OvhOrderableVirtuozzoVersionEnum version) throws IOException { """ Create order REST: POST /order/license/virtuozzo/new/{duration} @param version [required] This license version @param ip [required] Ip on which this license would be installed @param containerNumber [required] How much container is this license able to manage ... @param serviceType [required] # DEPRECATED # The kind of service on which this license will be used # Will not be used, keeped only for compatibility # @param duration [required] Duration """ String qPath = "/order/license/virtuozzo/new/{duration}"; StringBuilder sb = path(qPath, duration); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "containerNumber", containerNumber); addBody(o, "ip", ip); addBody(o, "serviceType", serviceType); addBody(o, "version", version); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhOrder.class); }
java
public OvhOrder license_virtuozzo_new_duration_POST(String duration, OvhOrderableVirtuozzoContainerNumberEnum containerNumber, String ip, OvhLicenseTypeEnum serviceType, OvhOrderableVirtuozzoVersionEnum version) throws IOException { String qPath = "/order/license/virtuozzo/new/{duration}"; StringBuilder sb = path(qPath, duration); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "containerNumber", containerNumber); addBody(o, "ip", ip); addBody(o, "serviceType", serviceType); addBody(o, "version", version); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhOrder.class); }
[ "public", "OvhOrder", "license_virtuozzo_new_duration_POST", "(", "String", "duration", ",", "OvhOrderableVirtuozzoContainerNumberEnum", "containerNumber", ",", "String", "ip", ",", "OvhLicenseTypeEnum", "serviceType", ",", "OvhOrderableVirtuozzoVersionEnum", "version", ")", "t...
Create order REST: POST /order/license/virtuozzo/new/{duration} @param version [required] This license version @param ip [required] Ip on which this license would be installed @param containerNumber [required] How much container is this license able to manage ... @param serviceType [required] # DEPRECATED # The kind of service on which this license will be used # Will not be used, keeped only for compatibility # @param duration [required] Duration
[ "Create", "order" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java#L1138-L1148
OpenLiberty/open-liberty
dev/com.ibm.ws.logging.osgi/src/com/ibm/ws/logging/internal/osgi/WsTraceRouterImpl.java
WsTraceRouterImpl.routeToAll
protected boolean routeToAll(RoutedMessage routedTrace, Set<String> logHandlerIds) { """ Route the trace to all LogHandlers in the set. @return true if the set contained DEFAULT, which means the msg should be logged normally as well. false otherwise. """ for (String logHandlerId : logHandlerIds) { routeTo(routedTrace, logHandlerId); } return true; //for now return true. Later we might have a config/flag to check whether to log normally or not. }
java
protected boolean routeToAll(RoutedMessage routedTrace, Set<String> logHandlerIds) { for (String logHandlerId : logHandlerIds) { routeTo(routedTrace, logHandlerId); } return true; //for now return true. Later we might have a config/flag to check whether to log normally or not. }
[ "protected", "boolean", "routeToAll", "(", "RoutedMessage", "routedTrace", ",", "Set", "<", "String", ">", "logHandlerIds", ")", "{", "for", "(", "String", "logHandlerId", ":", "logHandlerIds", ")", "{", "routeTo", "(", "routedTrace", ",", "logHandlerId", ")", ...
Route the trace to all LogHandlers in the set. @return true if the set contained DEFAULT, which means the msg should be logged normally as well. false otherwise.
[ "Route", "the", "trace", "to", "all", "LogHandlers", "in", "the", "set", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.logging.osgi/src/com/ibm/ws/logging/internal/osgi/WsTraceRouterImpl.java#L136-L143
mijecu25/dsa
src/main/java/com/mijecu25/dsa/algorithms/search/logarithmic/BinarySearch.java
BinarySearch.searchDescending
public static int searchDescending(float[] floatArray, float value) { """ Search for the value in the reverse sorted float array and return the index. @param floatArray array that we are searching in. @param value value that is being searched in the array. @return the index where the value is found in the array, else -1. """ int start = 0; int end = floatArray.length - 1; int middle = 0; while(start <= end) { middle = (start + end) >> 1; if(value == floatArray[middle]) { return middle; } if(value > floatArray[middle]) { end = middle - 1 ; } else { start = middle + 1; } } return -1; }
java
public static int searchDescending(float[] floatArray, float value) { int start = 0; int end = floatArray.length - 1; int middle = 0; while(start <= end) { middle = (start + end) >> 1; if(value == floatArray[middle]) { return middle; } if(value > floatArray[middle]) { end = middle - 1 ; } else { start = middle + 1; } } return -1; }
[ "public", "static", "int", "searchDescending", "(", "float", "[", "]", "floatArray", ",", "float", "value", ")", "{", "int", "start", "=", "0", ";", "int", "end", "=", "floatArray", ".", "length", "-", "1", ";", "int", "middle", "=", "0", ";", "while...
Search for the value in the reverse sorted float array and return the index. @param floatArray array that we are searching in. @param value value that is being searched in the array. @return the index where the value is found in the array, else -1.
[ "Search", "for", "the", "value", "in", "the", "reverse", "sorted", "float", "array", "and", "return", "the", "index", "." ]
train
https://github.com/mijecu25/dsa/blob/a22971b746833e78a3939ae4de65e8f6bf2e3fd4/src/main/java/com/mijecu25/dsa/algorithms/search/logarithmic/BinarySearch.java#L569-L591
tvesalainen/util
util/src/main/java/org/vesalainen/math/CircleFitter.java
CircleFitter.initialCenter
public static double initialCenter(DenseMatrix64F points, DenseMatrix64F center) { """ Calculates an initial estimate for tempCenter. @param points @param center @return """ assert points.numCols == 2; assert center.numCols == 1; assert center.numRows == 2; center.zero(); int count = 0; int len1 = points.numRows; int len2 = len1-1; int len3 = len2-1; for (int i=0;i<len3;i++) { for (int j=i+1;j<len2;j++) { for (int k=j+1;k<len1;k++) { if (center(points, i, j, k, center)) { count++; } } } } if (count > 0) { divide(center, count); DenseMatrix64F di = new DenseMatrix64F(points.numRows, 1); computeDi(center, points, di); return elementSum(di) / (double)points.numRows; } else { return Double.NaN; } }
java
public static double initialCenter(DenseMatrix64F points, DenseMatrix64F center) { assert points.numCols == 2; assert center.numCols == 1; assert center.numRows == 2; center.zero(); int count = 0; int len1 = points.numRows; int len2 = len1-1; int len3 = len2-1; for (int i=0;i<len3;i++) { for (int j=i+1;j<len2;j++) { for (int k=j+1;k<len1;k++) { if (center(points, i, j, k, center)) { count++; } } } } if (count > 0) { divide(center, count); DenseMatrix64F di = new DenseMatrix64F(points.numRows, 1); computeDi(center, points, di); return elementSum(di) / (double)points.numRows; } else { return Double.NaN; } }
[ "public", "static", "double", "initialCenter", "(", "DenseMatrix64F", "points", ",", "DenseMatrix64F", "center", ")", "{", "assert", "points", ".", "numCols", "==", "2", ";", "assert", "center", ".", "numCols", "==", "1", ";", "assert", "center", ".", "numRo...
Calculates an initial estimate for tempCenter. @param points @param center @return
[ "Calculates", "an", "initial", "estimate", "for", "tempCenter", "." ]
train
https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/math/CircleFitter.java#L225-L259
sagiegurari/fax4j
src/main/java/org/fax4j/util/SpiUtil.java
SpiUtil.urlDecode
public static String urlDecode(String text) { """ This function URL decodes the given text. @param text The text to decode @return The decoded text """ String urlEncodedString=text; if(text!=null) { try { urlEncodedString=URLDecoder.decode(text,SpiUtil.UTF_8_ENCODING_NAME); } catch(UnsupportedEncodingException exception) { throw new FaxException("Error while URL decoding text.",exception); } } return urlEncodedString; }
java
public static String urlDecode(String text) { String urlEncodedString=text; if(text!=null) { try { urlEncodedString=URLDecoder.decode(text,SpiUtil.UTF_8_ENCODING_NAME); } catch(UnsupportedEncodingException exception) { throw new FaxException("Error while URL decoding text.",exception); } } return urlEncodedString; }
[ "public", "static", "String", "urlDecode", "(", "String", "text", ")", "{", "String", "urlEncodedString", "=", "text", ";", "if", "(", "text", "!=", "null", ")", "{", "try", "{", "urlEncodedString", "=", "URLDecoder", ".", "decode", "(", "text", ",", "Sp...
This function URL decodes the given text. @param text The text to decode @return The decoded text
[ "This", "function", "URL", "decodes", "the", "given", "text", "." ]
train
https://github.com/sagiegurari/fax4j/blob/42fa51acabe7bf279e27ab3dd1cf76146b27955f/src/main/java/org/fax4j/util/SpiUtil.java#L235-L251
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/nullness/NullnessFixes.java
NullnessFixes.makeFix
static SuggestedFix makeFix(VisitorState state, Tree declaration) { """ Make the {@link SuggestedFix} to add the {@code Nullable} annotation. """ SuggestedFix.Builder builder = SuggestedFix.builder(); String qualifiedName = getQualifiedName(state, builder); return builder.prefixWith(declaration, "@" + qualifiedName + " ").build(); }
java
static SuggestedFix makeFix(VisitorState state, Tree declaration) { SuggestedFix.Builder builder = SuggestedFix.builder(); String qualifiedName = getQualifiedName(state, builder); return builder.prefixWith(declaration, "@" + qualifiedName + " ").build(); }
[ "static", "SuggestedFix", "makeFix", "(", "VisitorState", "state", ",", "Tree", "declaration", ")", "{", "SuggestedFix", ".", "Builder", "builder", "=", "SuggestedFix", ".", "builder", "(", ")", ";", "String", "qualifiedName", "=", "getQualifiedName", "(", "stat...
Make the {@link SuggestedFix} to add the {@code Nullable} annotation.
[ "Make", "the", "{" ]
train
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/nullness/NullnessFixes.java#L36-L40
kuali/ojb-1.0.4
src/java/org/apache/ojb/broker/query/Criteria.java
Criteria.addIn
public void addIn(Object attribute, Query subQuery) { """ IN Criteria with SubQuery @param attribute The field name to be used @param subQuery The subQuery """ // PAW // addSelectionCriteria(ValueCriteria.buildInCriteria(attribute, subQuery, getAlias())); addSelectionCriteria(ValueCriteria.buildInCriteria(attribute, subQuery, getUserAlias(attribute))); }
java
public void addIn(Object attribute, Query subQuery) { // PAW // addSelectionCriteria(ValueCriteria.buildInCriteria(attribute, subQuery, getAlias())); addSelectionCriteria(ValueCriteria.buildInCriteria(attribute, subQuery, getUserAlias(attribute))); }
[ "public", "void", "addIn", "(", "Object", "attribute", ",", "Query", "subQuery", ")", "{", "// PAW\r", "// addSelectionCriteria(ValueCriteria.buildInCriteria(attribute, subQuery, getAlias()));\r", "addSelectionCriteria", "(", "ValueCriteria", ".", "buildInCriteria", "(", "attri...
IN Criteria with SubQuery @param attribute The field name to be used @param subQuery The subQuery
[ "IN", "Criteria", "with", "SubQuery" ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/query/Criteria.java#L841-L846
jmapper-framework/jmapper-core
JMapper Framework/src/main/java/com/googlecode/jmapper/cache/JMapperCache.java
JMapperCache.getRelationalMapper
public static <T> IRelationalJMapper<T> getRelationalMapper(final Class<T> configuredClass, JMapperAPI jmapperAPI) { """ Returns an instance of JMapper from cache if exists, in alternative a new instance. <br>Takes in input the configured Class and the configuration in API format. @param configuredClass configured class @param jmapperAPI the configuration @param <T> Mapped class type @return the mapper instance """ return getRelationalMapper(configuredClass, jmapperAPI.toXStream().toString()); }
java
public static <T> IRelationalJMapper<T> getRelationalMapper(final Class<T> configuredClass, JMapperAPI jmapperAPI){ return getRelationalMapper(configuredClass, jmapperAPI.toXStream().toString()); }
[ "public", "static", "<", "T", ">", "IRelationalJMapper", "<", "T", ">", "getRelationalMapper", "(", "final", "Class", "<", "T", ">", "configuredClass", ",", "JMapperAPI", "jmapperAPI", ")", "{", "return", "getRelationalMapper", "(", "configuredClass", ",", "jmap...
Returns an instance of JMapper from cache if exists, in alternative a new instance. <br>Takes in input the configured Class and the configuration in API format. @param configuredClass configured class @param jmapperAPI the configuration @param <T> Mapped class type @return the mapper instance
[ "Returns", "an", "instance", "of", "JMapper", "from", "cache", "if", "exists", "in", "alternative", "a", "new", "instance", ".", "<br", ">", "Takes", "in", "input", "the", "configured", "Class", "and", "the", "configuration", "in", "API", "format", "." ]
train
https://github.com/jmapper-framework/jmapper-core/blob/b48fd3527f35055b8b4a30f53a51136f183acc90/JMapper Framework/src/main/java/com/googlecode/jmapper/cache/JMapperCache.java#L166-L168
JOML-CI/JOML
src/org/joml/Matrix4f.java
Matrix4f.rotationTowards
public Matrix4f rotationTowards(Vector3fc dir, Vector3fc up) { """ Set this matrix to a model transformation for a right-handed coordinate system, that aligns the local <code>-z</code> axis with <code>dir</code>. <p> In order to apply the rotation transformation to a previous existing transformation, use {@link #rotateTowards(float, float, float, float, float, float) rotateTowards}. <p> This method is equivalent to calling: <code>setLookAt(new Vector3f(), new Vector3f(dir).negate(), up).invertAffine()</code> @see #rotationTowards(Vector3fc, Vector3fc) @see #rotateTowards(float, float, float, float, float, float) @param dir the direction to orient the local -z axis towards @param up the up vector @return this """ return rotationTowards(dir.x(), dir.y(), dir.z(), up.x(), up.y(), up.z()); }
java
public Matrix4f rotationTowards(Vector3fc dir, Vector3fc up) { return rotationTowards(dir.x(), dir.y(), dir.z(), up.x(), up.y(), up.z()); }
[ "public", "Matrix4f", "rotationTowards", "(", "Vector3fc", "dir", ",", "Vector3fc", "up", ")", "{", "return", "rotationTowards", "(", "dir", ".", "x", "(", ")", ",", "dir", ".", "y", "(", ")", ",", "dir", ".", "z", "(", ")", ",", "up", ".", "x", ...
Set this matrix to a model transformation for a right-handed coordinate system, that aligns the local <code>-z</code> axis with <code>dir</code>. <p> In order to apply the rotation transformation to a previous existing transformation, use {@link #rotateTowards(float, float, float, float, float, float) rotateTowards}. <p> This method is equivalent to calling: <code>setLookAt(new Vector3f(), new Vector3f(dir).negate(), up).invertAffine()</code> @see #rotationTowards(Vector3fc, Vector3fc) @see #rotateTowards(float, float, float, float, float, float) @param dir the direction to orient the local -z axis towards @param up the up vector @return this
[ "Set", "this", "matrix", "to", "a", "model", "transformation", "for", "a", "right", "-", "handed", "coordinate", "system", "that", "aligns", "the", "local", "<code", ">", "-", "z<", "/", "code", ">", "axis", "with", "<code", ">", "dir<", "/", "code", "...
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4f.java#L14306-L14308
facebookarchive/hadoop-20
src/core/org/apache/hadoop/io/nativeio/NativeIO.java
NativeIO.ioprioSetIfPossible
public static void ioprioSetIfPossible(int classOfService, int data) throws IOException { """ Call ioprio_set(class, data) for this thread. @throws NativeIOException if there is an error with the syscall """ if (nativeLoaded && ioprioPossible) { if (classOfService == IOPRIO_CLASS_NONE) { // ioprio is disabled. return; } try { ioprio_set(classOfService, data); } catch (UnsupportedOperationException uoe) { LOG.warn("ioprioSetIfPossible() failed", uoe); ioprioPossible = false; } catch (UnsatisfiedLinkError ule) { LOG.warn("ioprioSetIfPossible() failed", ule); ioprioPossible = false; } catch (NativeIOException nie) { LOG.warn("ioprioSetIfPossible() failed", nie); throw nie; } } }
java
public static void ioprioSetIfPossible(int classOfService, int data) throws IOException { if (nativeLoaded && ioprioPossible) { if (classOfService == IOPRIO_CLASS_NONE) { // ioprio is disabled. return; } try { ioprio_set(classOfService, data); } catch (UnsupportedOperationException uoe) { LOG.warn("ioprioSetIfPossible() failed", uoe); ioprioPossible = false; } catch (UnsatisfiedLinkError ule) { LOG.warn("ioprioSetIfPossible() failed", ule); ioprioPossible = false; } catch (NativeIOException nie) { LOG.warn("ioprioSetIfPossible() failed", nie); throw nie; } } }
[ "public", "static", "void", "ioprioSetIfPossible", "(", "int", "classOfService", ",", "int", "data", ")", "throws", "IOException", "{", "if", "(", "nativeLoaded", "&&", "ioprioPossible", ")", "{", "if", "(", "classOfService", "==", "IOPRIO_CLASS_NONE", ")", "{",...
Call ioprio_set(class, data) for this thread. @throws NativeIOException if there is an error with the syscall
[ "Call", "ioprio_set", "(", "class", "data", ")", "for", "this", "thread", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/io/nativeio/NativeIO.java#L289-L309
joniles/mpxj
src/main/java/net/sf/mpxj/common/DateHelper.java
DateHelper.setTime
public static void setTime(Calendar cal, Date time) { """ Given a date represented by a Calendar instance, set the time component of the date based on the hours and minutes of the time supplied by the Date instance. @param cal Calendar instance representing the date @param time Date instance representing the time of day """ if (time != null) { Calendar startCalendar = popCalendar(time); cal.set(Calendar.HOUR_OF_DAY, startCalendar.get(Calendar.HOUR_OF_DAY)); cal.set(Calendar.MINUTE, startCalendar.get(Calendar.MINUTE)); cal.set(Calendar.SECOND, startCalendar.get(Calendar.SECOND)); pushCalendar(startCalendar); } }
java
public static void setTime(Calendar cal, Date time) { if (time != null) { Calendar startCalendar = popCalendar(time); cal.set(Calendar.HOUR_OF_DAY, startCalendar.get(Calendar.HOUR_OF_DAY)); cal.set(Calendar.MINUTE, startCalendar.get(Calendar.MINUTE)); cal.set(Calendar.SECOND, startCalendar.get(Calendar.SECOND)); pushCalendar(startCalendar); } }
[ "public", "static", "void", "setTime", "(", "Calendar", "cal", ",", "Date", "time", ")", "{", "if", "(", "time", "!=", "null", ")", "{", "Calendar", "startCalendar", "=", "popCalendar", "(", "time", ")", ";", "cal", ".", "set", "(", "Calendar", ".", ...
Given a date represented by a Calendar instance, set the time component of the date based on the hours and minutes of the time supplied by the Date instance. @param cal Calendar instance representing the date @param time Date instance representing the time of day
[ "Given", "a", "date", "represented", "by", "a", "Calendar", "instance", "set", "the", "time", "component", "of", "the", "date", "based", "on", "the", "hours", "and", "minutes", "of", "the", "time", "supplied", "by", "the", "Date", "instance", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/common/DateHelper.java#L337-L347
LGoodDatePicker/LGoodDatePicker
Project/src/main/java/com/github/lgooddatepicker/demo/FullDemo.java
FullDemo.getConstraints
private static GridBagConstraints getConstraints(int gridx, int gridy, int gridwidth) { """ getConstraints, This returns a grid bag constraints object that can be used for placing a component appropriately into a grid bag layout. """ GridBagConstraints gc = new GridBagConstraints(); gc.fill = GridBagConstraints.NONE; gc.anchor = GridBagConstraints.WEST; gc.gridx = gridx; gc.gridy = gridy; gc.gridwidth = gridwidth; return gc; }
java
private static GridBagConstraints getConstraints(int gridx, int gridy, int gridwidth) { GridBagConstraints gc = new GridBagConstraints(); gc.fill = GridBagConstraints.NONE; gc.anchor = GridBagConstraints.WEST; gc.gridx = gridx; gc.gridy = gridy; gc.gridwidth = gridwidth; return gc; }
[ "private", "static", "GridBagConstraints", "getConstraints", "(", "int", "gridx", ",", "int", "gridy", ",", "int", "gridwidth", ")", "{", "GridBagConstraints", "gc", "=", "new", "GridBagConstraints", "(", ")", ";", "gc", ".", "fill", "=", "GridBagConstraints", ...
getConstraints, This returns a grid bag constraints object that can be used for placing a component appropriately into a grid bag layout.
[ "getConstraints", "This", "returns", "a", "grid", "bag", "constraints", "object", "that", "can", "be", "used", "for", "placing", "a", "component", "appropriately", "into", "a", "grid", "bag", "layout", "." ]
train
https://github.com/LGoodDatePicker/LGoodDatePicker/blob/c7df05a5fe382e1e08a6237e9391d8dc5fd48692/Project/src/main/java/com/github/lgooddatepicker/demo/FullDemo.java#L671-L679
apache/incubator-gobblin
gobblin-service/src/main/java/org/apache/gobblin/service/modules/core/GitFlowGraphMonitor.java
GitFlowGraphMonitor.loadEdgeFileWithOverrides
private Config loadEdgeFileWithOverrides(Path filePath) throws IOException { """ Load the edge file. @param filePath path of the edge file relative to the repository root @return the configuration object @throws IOException """ Config edgeConfig = this.pullFileLoader.loadPullFile(filePath, emptyConfig, false); return getEdgeConfigWithOverrides(edgeConfig, filePath); }
java
private Config loadEdgeFileWithOverrides(Path filePath) throws IOException { Config edgeConfig = this.pullFileLoader.loadPullFile(filePath, emptyConfig, false); return getEdgeConfigWithOverrides(edgeConfig, filePath); }
[ "private", "Config", "loadEdgeFileWithOverrides", "(", "Path", "filePath", ")", "throws", "IOException", "{", "Config", "edgeConfig", "=", "this", ".", "pullFileLoader", ".", "loadPullFile", "(", "filePath", ",", "emptyConfig", ",", "false", ")", ";", "return", ...
Load the edge file. @param filePath path of the edge file relative to the repository root @return the configuration object @throws IOException
[ "Load", "the", "edge", "file", "." ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-service/src/main/java/org/apache/gobblin/service/modules/core/GitFlowGraphMonitor.java#L370-L373
m-m-m/util
pojopath/src/main/java/net/sf/mmm/util/pojo/path/base/AbstractPojoPathNavigator.java
AbstractPojoPathNavigator.getFromMap
@SuppressWarnings( { """ This method {@link Map#get(Object) gets} the single {@link CachingPojoPath#getSegment() segment} of the given {@code currentPath} from the {@link Map} given by {@code parentPojo}. If the result is {@code null} and {@link PojoPathState#getMode() mode} is {@link PojoPathMode#CREATE_IF_NULL} it creates and {@link Map#put(Object, Object) attaches} the missing object. @param currentPath is the current {@link CachingPojoPath} to evaluate. @param context is the {@link PojoPathContext context} for this operation. @param state is the {@link #createState(Object, String, PojoPathMode, PojoPathContext) state} of this operation. @param parentPojo is the parent object to work on. @return the result of the evaluation. It might be {@code null} according to the {@link PojoPathState#getMode() mode}. """ "unchecked", "rawtypes" }) protected Object getFromMap(CachingPojoPath currentPath, PojoPathContext context, PojoPathState state, Map parentPojo) { // determine pojo type GenericType pojoType = currentPath.parent.pojoType; GenericType componentType = pojoType.getComponentType(); if (componentType.getRetrievalClass() == Object.class) { currentPath.pojoClass = Object.class; } else { currentPath.pojoType = componentType; currentPath.pojoClass = componentType.getAssignmentClass(); } Object result = null; if (!state.isGetType()) { result = parentPojo.get(currentPath.getSegment()); if ((result == null) && (state.mode == PojoPathMode.CREATE_IF_NULL)) { result = create(currentPath, context, state, currentPath.pojoClass); parentPojo.put(currentPath.getSegment(), result); } } return result; }
java
@SuppressWarnings({ "unchecked", "rawtypes" }) protected Object getFromMap(CachingPojoPath currentPath, PojoPathContext context, PojoPathState state, Map parentPojo) { // determine pojo type GenericType pojoType = currentPath.parent.pojoType; GenericType componentType = pojoType.getComponentType(); if (componentType.getRetrievalClass() == Object.class) { currentPath.pojoClass = Object.class; } else { currentPath.pojoType = componentType; currentPath.pojoClass = componentType.getAssignmentClass(); } Object result = null; if (!state.isGetType()) { result = parentPojo.get(currentPath.getSegment()); if ((result == null) && (state.mode == PojoPathMode.CREATE_IF_NULL)) { result = create(currentPath, context, state, currentPath.pojoClass); parentPojo.put(currentPath.getSegment(), result); } } return result; }
[ "@", "SuppressWarnings", "(", "{", "\"unchecked\"", ",", "\"rawtypes\"", "}", ")", "protected", "Object", "getFromMap", "(", "CachingPojoPath", "currentPath", ",", "PojoPathContext", "context", ",", "PojoPathState", "state", ",", "Map", "parentPojo", ")", "{", "//...
This method {@link Map#get(Object) gets} the single {@link CachingPojoPath#getSegment() segment} of the given {@code currentPath} from the {@link Map} given by {@code parentPojo}. If the result is {@code null} and {@link PojoPathState#getMode() mode} is {@link PojoPathMode#CREATE_IF_NULL} it creates and {@link Map#put(Object, Object) attaches} the missing object. @param currentPath is the current {@link CachingPojoPath} to evaluate. @param context is the {@link PojoPathContext context} for this operation. @param state is the {@link #createState(Object, String, PojoPathMode, PojoPathContext) state} of this operation. @param parentPojo is the parent object to work on. @return the result of the evaluation. It might be {@code null} according to the {@link PojoPathState#getMode() mode}.
[ "This", "method", "{", "@link", "Map#get", "(", "Object", ")", "gets", "}", "the", "single", "{", "@link", "CachingPojoPath#getSegment", "()", "segment", "}", "of", "the", "given", "{", "@code", "currentPath", "}", "from", "the", "{", "@link", "Map", "}", ...
train
https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/pojopath/src/main/java/net/sf/mmm/util/pojo/path/base/AbstractPojoPathNavigator.java#L495-L516
apache/spark
sql/core/src/main/java/org/apache/spark/sql/execution/datasources/parquet/VectorizedColumnReader.java
VectorizedColumnReader.readBooleanBatch
private void readBooleanBatch(int rowId, int num, WritableColumnVector column) throws IOException { """ For all the read*Batch functions, reads `num` values from this columnReader into column. It is guaranteed that num is smaller than the number of values left in the current page. """ if (column.dataType() != DataTypes.BooleanType) { throw constructConvertNotSupportedException(descriptor, column); } defColumn.readBooleans( num, column, rowId, maxDefLevel, (VectorizedValuesReader) dataColumn); }
java
private void readBooleanBatch(int rowId, int num, WritableColumnVector column) throws IOException { if (column.dataType() != DataTypes.BooleanType) { throw constructConvertNotSupportedException(descriptor, column); } defColumn.readBooleans( num, column, rowId, maxDefLevel, (VectorizedValuesReader) dataColumn); }
[ "private", "void", "readBooleanBatch", "(", "int", "rowId", ",", "int", "num", ",", "WritableColumnVector", "column", ")", "throws", "IOException", "{", "if", "(", "column", ".", "dataType", "(", ")", "!=", "DataTypes", ".", "BooleanType", ")", "{", "throw",...
For all the read*Batch functions, reads `num` values from this columnReader into column. It is guaranteed that num is smaller than the number of values left in the current page.
[ "For", "all", "the", "read", "*", "Batch", "functions", "reads", "num", "values", "from", "this", "columnReader", "into", "column", ".", "It", "is", "guaranteed", "that", "num", "is", "smaller", "than", "the", "number", "of", "values", "left", "in", "the",...
train
https://github.com/apache/spark/blob/25ee0474f47d9c30d6f553a7892d9549f91071cf/sql/core/src/main/java/org/apache/spark/sql/execution/datasources/parquet/VectorizedColumnReader.java#L397-L404
mockito/mockito
src/main/java/org/mockito/internal/util/reflection/Fields.java
Fields.declaredFieldsOf
public static InstanceFields declaredFieldsOf(Object instance) { """ Instance fields declared in the class of the given instance. @param instance Instance from which declared fields will be retrieved. @return InstanceFields of this object instance. """ List<InstanceField> instanceFields = new ArrayList<InstanceField>(); instanceFields.addAll(instanceFieldsIn(instance, instance.getClass().getDeclaredFields())); return new InstanceFields(instance, instanceFields); }
java
public static InstanceFields declaredFieldsOf(Object instance) { List<InstanceField> instanceFields = new ArrayList<InstanceField>(); instanceFields.addAll(instanceFieldsIn(instance, instance.getClass().getDeclaredFields())); return new InstanceFields(instance, instanceFields); }
[ "public", "static", "InstanceFields", "declaredFieldsOf", "(", "Object", "instance", ")", "{", "List", "<", "InstanceField", ">", "instanceFields", "=", "new", "ArrayList", "<", "InstanceField", ">", "(", ")", ";", "instanceFields", ".", "addAll", "(", "instance...
Instance fields declared in the class of the given instance. @param instance Instance from which declared fields will be retrieved. @return InstanceFields of this object instance.
[ "Instance", "fields", "declared", "in", "the", "class", "of", "the", "given", "instance", "." ]
train
https://github.com/mockito/mockito/blob/c5e2b80af76e3192cae7c9550b70c4d1ab312034/src/main/java/org/mockito/internal/util/reflection/Fields.java#L43-L47
docusign/docusign-java-client
src/main/java/com/docusign/esign/api/CloudStorageApi.java
CloudStorageApi.listFolders
public ExternalFolder listFolders(String accountId, String userId, String serviceId) throws ApiException { """ Retrieves a list of all the items in a specified folder from the specified cloud storage provider. Retrieves a list of all the items in a specified folder from the specified cloud storage provider. @param accountId The external account number (int) or account ID Guid. (required) @param userId The user ID of the user being accessed. Generally this is the user ID of the authenticated user, but if the authenticated user is an Admin on the account, this may be another user the Admin user is accessing. (required) @param serviceId The ID of the service to access. Valid values are the service name (\&quot;Box\&quot;) or the numerical serviceId (\&quot;4136\&quot;). (required) @return ExternalFolder """ return listFolders(accountId, userId, serviceId, null); }
java
public ExternalFolder listFolders(String accountId, String userId, String serviceId) throws ApiException { return listFolders(accountId, userId, serviceId, null); }
[ "public", "ExternalFolder", "listFolders", "(", "String", "accountId", ",", "String", "userId", ",", "String", "serviceId", ")", "throws", "ApiException", "{", "return", "listFolders", "(", "accountId", ",", "userId", ",", "serviceId", ",", "null", ")", ";", "...
Retrieves a list of all the items in a specified folder from the specified cloud storage provider. Retrieves a list of all the items in a specified folder from the specified cloud storage provider. @param accountId The external account number (int) or account ID Guid. (required) @param userId The user ID of the user being accessed. Generally this is the user ID of the authenticated user, but if the authenticated user is an Admin on the account, this may be another user the Admin user is accessing. (required) @param serviceId The ID of the service to access. Valid values are the service name (\&quot;Box\&quot;) or the numerical serviceId (\&quot;4136\&quot;). (required) @return ExternalFolder
[ "Retrieves", "a", "list", "of", "all", "the", "items", "in", "a", "specified", "folder", "from", "the", "specified", "cloud", "storage", "provider", ".", "Retrieves", "a", "list", "of", "all", "the", "items", "in", "a", "specified", "folder", "from", "the"...
train
https://github.com/docusign/docusign-java-client/blob/17ae82ace0f023e98edf813be832950568212e34/src/main/java/com/docusign/esign/api/CloudStorageApi.java#L522-L524
kmi/iserve
iserve-elda/src/main/java/uk/ac/open/kmi/iserve/elda/EldaRouterRestletSupport.java
EldaRouterRestletSupport.expiresAtAsRFC1123
public static String expiresAtAsRFC1123(long expiresAt) { """ expiresAt (date/time in milliseconds) as an RFC1123 date/time string suitable for use in an HTTP header. """ Calendar c = Calendar.getInstance(); c.setTimeInMillis(expiresAt); SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.UK); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); String result = dateFormat.format(c.getTime()); // System.err.println( ">> expires (RFC): " + result ); // long delta = expiresAt - System.currentTimeMillis(); // System.err.println( ">> expires in " + (delta/1000) + "s" ); return result; }
java
public static String expiresAtAsRFC1123(long expiresAt) { Calendar c = Calendar.getInstance(); c.setTimeInMillis(expiresAt); SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.UK); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); String result = dateFormat.format(c.getTime()); // System.err.println( ">> expires (RFC): " + result ); // long delta = expiresAt - System.currentTimeMillis(); // System.err.println( ">> expires in " + (delta/1000) + "s" ); return result; }
[ "public", "static", "String", "expiresAtAsRFC1123", "(", "long", "expiresAt", ")", "{", "Calendar", "c", "=", "Calendar", ".", "getInstance", "(", ")", ";", "c", ".", "setTimeInMillis", "(", "expiresAt", ")", ";", "SimpleDateFormat", "dateFormat", "=", "new", ...
expiresAt (date/time in milliseconds) as an RFC1123 date/time string suitable for use in an HTTP header.
[ "expiresAt", "(", "date", "/", "time", "in", "milliseconds", ")", "as", "an", "RFC1123", "date", "/", "time", "string", "suitable", "for", "use", "in", "an", "HTTP", "header", "." ]
train
https://github.com/kmi/iserve/blob/13e7016e64c1d5a539b838c6debf1a5cc4aefcb7/iserve-elda/src/main/java/uk/ac/open/kmi/iserve/elda/EldaRouterRestletSupport.java#L217-L229
looly/hutool
hutool-captcha/src/main/java/cn/hutool/captcha/ShearCaptcha.java
ShearCaptcha.shearY
private void shearY(Graphics g, int w1, int h1, Color color) { """ X坐标扭曲 @param g {@link Graphics} @param w1 w1 @param h1 h1 @param color 颜色 """ int period = RandomUtil.randomInt(40) + 10; // 50; boolean borderGap = true; int frames = 20; int phase = 7; for (int i = 0; i < w1; i++) { double d = (double) (period >> 1) * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames); g.copyArea(i, 0, 1, h1, 0, (int) d); if (borderGap) { g.setColor(color); g.drawLine(i, (int) d, i, 0); g.drawLine(i, (int) d + h1, i, h1); } } }
java
private void shearY(Graphics g, int w1, int h1, Color color) { int period = RandomUtil.randomInt(40) + 10; // 50; boolean borderGap = true; int frames = 20; int phase = 7; for (int i = 0; i < w1; i++) { double d = (double) (period >> 1) * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames); g.copyArea(i, 0, 1, h1, 0, (int) d); if (borderGap) { g.setColor(color); g.drawLine(i, (int) d, i, 0); g.drawLine(i, (int) d + h1, i, h1); } } }
[ "private", "void", "shearY", "(", "Graphics", "g", ",", "int", "w1", ",", "int", "h1", ",", "Color", "color", ")", "{", "int", "period", "=", "RandomUtil", ".", "randomInt", "(", "40", ")", "+", "10", ";", "// 50;\r", "boolean", "borderGap", "=", "tr...
X坐标扭曲 @param g {@link Graphics} @param w1 w1 @param h1 h1 @param color 颜色
[ "X坐标扭曲" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-captcha/src/main/java/cn/hutool/captcha/ShearCaptcha.java#L150-L168
google/error-prone-javac
src/jdk.compiler/share/classes/com/sun/tools/javac/util/Options.java
Options.isLintSet
public boolean isLintSet(String s) { """ Check if the value for a lint option has been explicitly set, either with -Xlint:opt or if all lint options have enabled and this one not disabled with -Xlint:-opt. """ // return true if either the specific option is enabled, or // they are all enabled without the specific one being // disabled return isSet(XLINT_CUSTOM, s) || (isSet(XLINT) || isSet(XLINT_CUSTOM, "all")) && isUnset(XLINT_CUSTOM, "-" + s); }
java
public boolean isLintSet(String s) { // return true if either the specific option is enabled, or // they are all enabled without the specific one being // disabled return isSet(XLINT_CUSTOM, s) || (isSet(XLINT) || isSet(XLINT_CUSTOM, "all")) && isUnset(XLINT_CUSTOM, "-" + s); }
[ "public", "boolean", "isLintSet", "(", "String", "s", ")", "{", "// return true if either the specific option is enabled, or", "// they are all enabled without the specific one being", "// disabled", "return", "isSet", "(", "XLINT_CUSTOM", ",", "s", ")", "||", "(", "isSet", ...
Check if the value for a lint option has been explicitly set, either with -Xlint:opt or if all lint options have enabled and this one not disabled with -Xlint:-opt.
[ "Check", "if", "the", "value", "for", "a", "lint", "option", "has", "been", "explicitly", "set", "either", "with", "-", "Xlint", ":", "opt", "or", "if", "all", "lint", "options", "have", "enabled", "and", "this", "one", "not", "disabled", "with", "-", ...
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/util/Options.java#L118-L125
landawn/AbacusUtil
src/com/landawn/abacus/util/MongoDB.java
MongoDB.registerIdProeprty
public static void registerIdProeprty(final Class<?> cls, final String idPropertyName) { """ The object id ("_id") property will be read from/write to the specified property @param cls @param idPropertyName """ if (ClassUtil.getPropGetMethod(cls, idPropertyName) == null || ClassUtil.getPropSetMethod(cls, idPropertyName) == null) { throw new IllegalArgumentException("The specified class: " + ClassUtil.getCanonicalClassName(cls) + " doesn't have getter or setter method for the specified id propery: " + idPropertyName); } final Method setMethod = ClassUtil.getPropSetMethod(cls, idPropertyName); final Class<?> parameterType = setMethod.getParameterTypes()[0]; if (!(String.class.isAssignableFrom(parameterType) || ObjectId.class.isAssignableFrom(parameterType))) { throw new IllegalArgumentException( "The parameter type of the specified id setter method must be 'String' or 'ObjectId': " + setMethod.toGenericString()); } classIdSetMethodPool.put(cls, setMethod); }
java
public static void registerIdProeprty(final Class<?> cls, final String idPropertyName) { if (ClassUtil.getPropGetMethod(cls, idPropertyName) == null || ClassUtil.getPropSetMethod(cls, idPropertyName) == null) { throw new IllegalArgumentException("The specified class: " + ClassUtil.getCanonicalClassName(cls) + " doesn't have getter or setter method for the specified id propery: " + idPropertyName); } final Method setMethod = ClassUtil.getPropSetMethod(cls, idPropertyName); final Class<?> parameterType = setMethod.getParameterTypes()[0]; if (!(String.class.isAssignableFrom(parameterType) || ObjectId.class.isAssignableFrom(parameterType))) { throw new IllegalArgumentException( "The parameter type of the specified id setter method must be 'String' or 'ObjectId': " + setMethod.toGenericString()); } classIdSetMethodPool.put(cls, setMethod); }
[ "public", "static", "void", "registerIdProeprty", "(", "final", "Class", "<", "?", ">", "cls", ",", "final", "String", "idPropertyName", ")", "{", "if", "(", "ClassUtil", ".", "getPropGetMethod", "(", "cls", ",", "idPropertyName", ")", "==", "null", "||", ...
The object id ("_id") property will be read from/write to the specified property @param cls @param idPropertyName
[ "The", "object", "id", "(", "_id", ")", "property", "will", "be", "read", "from", "/", "write", "to", "the", "specified", "property" ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/MongoDB.java#L165-L180
google/error-prone-javac
src/jdk.compiler/share/classes/com/sun/source/util/SimpleDocTreeVisitor.java
SimpleDocTreeVisitor.visitReference
@Override public R visitReference(ReferenceTree node, P p) { """ {@inheritDoc} This implementation calls {@code defaultAction}. @param node {@inheritDoc} @param p {@inheritDoc} @return the result of {@code defaultAction} """ return defaultAction(node, p); }
java
@Override public R visitReference(ReferenceTree node, P p) { return defaultAction(node, p); }
[ "@", "Override", "public", "R", "visitReference", "(", "ReferenceTree", "node", ",", "P", "p", ")", "{", "return", "defaultAction", "(", "node", ",", "p", ")", ";", "}" ]
{@inheritDoc} This implementation calls {@code defaultAction}. @param node {@inheritDoc} @param p {@inheritDoc} @return the result of {@code defaultAction}
[ "{", "@inheritDoc", "}", "This", "implementation", "calls", "{", "@code", "defaultAction", "}", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/source/util/SimpleDocTreeVisitor.java#L309-L312
cojen/Cojen
src/main/java/org/cojen/util/BeanPropertyAccessor.java
BeanPropertyAccessor.forClass
public static <B> BeanPropertyAccessor<B> forClass(Class<B> clazz) { """ Returns a new or cached BeanPropertyAccessor for the given class. """ return forClass(clazz, PropertySet.ALL); }
java
public static <B> BeanPropertyAccessor<B> forClass(Class<B> clazz) { return forClass(clazz, PropertySet.ALL); }
[ "public", "static", "<", "B", ">", "BeanPropertyAccessor", "<", "B", ">", "forClass", "(", "Class", "<", "B", ">", "clazz", ")", "{", "return", "forClass", "(", "clazz", ",", "PropertySet", ".", "ALL", ")", ";", "}" ]
Returns a new or cached BeanPropertyAccessor for the given class.
[ "Returns", "a", "new", "or", "cached", "BeanPropertyAccessor", "for", "the", "given", "class", "." ]
train
https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/util/BeanPropertyAccessor.java#L79-L81
aws/aws-sdk-java
aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/model/transform/XmlResponsesSaxParser.java
XmlResponsesSaxParser.decodeIfSpecified
private static String decodeIfSpecified(String value, boolean decode) { """ Perform a url decode on the given value if specified. Return value by default; """ return decode ? SdkHttpUtils.urlDecode(value) : value; }
java
private static String decodeIfSpecified(String value, boolean decode) { return decode ? SdkHttpUtils.urlDecode(value) : value; }
[ "private", "static", "String", "decodeIfSpecified", "(", "String", "value", ",", "boolean", "decode", ")", "{", "return", "decode", "?", "SdkHttpUtils", ".", "urlDecode", "(", "value", ")", ":", "value", ";", "}" ]
Perform a url decode on the given value if specified. Return value by default;
[ "Perform", "a", "url", "decode", "on", "the", "given", "value", "if", "specified", ".", "Return", "value", "by", "default", ";" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/model/transform/XmlResponsesSaxParser.java#L306-L308
ahome-it/lienzo-core
src/main/java/com/ait/lienzo/client/core/shape/Scene.java
Scene.setPixelSize
public final Scene setPixelSize(final int wide, final int high) { """ Sets this scene's size (width and height) in pixels. @param wide @param high @return this Scene """ m_wide = wide; m_high = high; getElement().getStyle().setWidth(wide, Unit.PX); getElement().getStyle().setHeight(high, Unit.PX); final NFastArrayList<Layer> layers = getChildNodes(); if (null != layers) { final int size = layers.size(); for (int i = 0; i < size; i++) { final Layer layer = layers.get(i); if (null != layer) { layer.setPixelSize(wide, high); } } } return this; }
java
public final Scene setPixelSize(final int wide, final int high) { m_wide = wide; m_high = high; getElement().getStyle().setWidth(wide, Unit.PX); getElement().getStyle().setHeight(high, Unit.PX); final NFastArrayList<Layer> layers = getChildNodes(); if (null != layers) { final int size = layers.size(); for (int i = 0; i < size; i++) { final Layer layer = layers.get(i); if (null != layer) { layer.setPixelSize(wide, high); } } } return this; }
[ "public", "final", "Scene", "setPixelSize", "(", "final", "int", "wide", ",", "final", "int", "high", ")", "{", "m_wide", "=", "wide", ";", "m_high", "=", "high", ";", "getElement", "(", ")", ".", "getStyle", "(", ")", ".", "setWidth", "(", "wide", "...
Sets this scene's size (width and height) in pixels. @param wide @param high @return this Scene
[ "Sets", "this", "scene", "s", "size", "(", "width", "and", "height", ")", "in", "pixels", "." ]
train
https://github.com/ahome-it/lienzo-core/blob/8e03723700dec366f77064d12fb8676d8cd6be99/src/main/java/com/ait/lienzo/client/core/shape/Scene.java#L160-L187
Azure/azure-sdk-for-java
network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/NetworkInterfacesInner.java
NetworkInterfacesInner.beginListEffectiveNetworkSecurityGroupsAsync
public Observable<EffectiveNetworkSecurityGroupListResultInner> beginListEffectiveNetworkSecurityGroupsAsync(String resourceGroupName, String networkInterfaceName) { """ Gets all network security groups applied to a network interface. @param resourceGroupName The name of the resource group. @param networkInterfaceName The name of the network interface. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the EffectiveNetworkSecurityGroupListResultInner object """ return beginListEffectiveNetworkSecurityGroupsWithServiceResponseAsync(resourceGroupName, networkInterfaceName).map(new Func1<ServiceResponse<EffectiveNetworkSecurityGroupListResultInner>, EffectiveNetworkSecurityGroupListResultInner>() { @Override public EffectiveNetworkSecurityGroupListResultInner call(ServiceResponse<EffectiveNetworkSecurityGroupListResultInner> response) { return response.body(); } }); }
java
public Observable<EffectiveNetworkSecurityGroupListResultInner> beginListEffectiveNetworkSecurityGroupsAsync(String resourceGroupName, String networkInterfaceName) { return beginListEffectiveNetworkSecurityGroupsWithServiceResponseAsync(resourceGroupName, networkInterfaceName).map(new Func1<ServiceResponse<EffectiveNetworkSecurityGroupListResultInner>, EffectiveNetworkSecurityGroupListResultInner>() { @Override public EffectiveNetworkSecurityGroupListResultInner call(ServiceResponse<EffectiveNetworkSecurityGroupListResultInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "EffectiveNetworkSecurityGroupListResultInner", ">", "beginListEffectiveNetworkSecurityGroupsAsync", "(", "String", "resourceGroupName", ",", "String", "networkInterfaceName", ")", "{", "return", "beginListEffectiveNetworkSecurityGroupsWithServiceResponseAs...
Gets all network security groups applied to a network interface. @param resourceGroupName The name of the resource group. @param networkInterfaceName The name of the network interface. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the EffectiveNetworkSecurityGroupListResultInner object
[ "Gets", "all", "network", "security", "groups", "applied", "to", "a", "network", "interface", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/NetworkInterfacesInner.java#L1436-L1443
pgjdbc/pgjdbc
pgjdbc/src/main/java/org/postgresql/util/ByteConverter.java
ByteConverter.int2
public static void int2(byte[] target, int idx, int value) { """ Encodes a int value to the byte array. @param target The byte array to encode to. @param idx The starting index in the byte array. @param value The value to encode. """ target[idx + 0] = (byte) (value >>> 8); target[idx + 1] = (byte) value; }
java
public static void int2(byte[] target, int idx, int value) { target[idx + 0] = (byte) (value >>> 8); target[idx + 1] = (byte) value; }
[ "public", "static", "void", "int2", "(", "byte", "[", "]", "target", ",", "int", "idx", ",", "int", "value", ")", "{", "target", "[", "idx", "+", "0", "]", "=", "(", "byte", ")", "(", "value", ">>>", "8", ")", ";", "target", "[", "idx", "+", ...
Encodes a int value to the byte array. @param target The byte array to encode to. @param idx The starting index in the byte array. @param value The value to encode.
[ "Encodes", "a", "int", "value", "to", "the", "byte", "array", "." ]
train
https://github.com/pgjdbc/pgjdbc/blob/95ba7b261e39754674c5817695ae5ebf9a341fae/pgjdbc/src/main/java/org/postgresql/util/ByteConverter.java#L138-L141
pwall567/jsonutil
src/main/java/net/pwall/json/JSON.java
JSON.parseArray
public static JSONArray parseArray(InputStream is, Charset charSet) throws IOException { """ Parse a sequence of characters from an {@link InputStream} as a JSON array, specifying the character set. @param is the {@link InputStream} @param charSet the character set @return the JSON array @throws JSONException if the stream does not contain a valid JSON value @throws IOException on any I/O errors @throws ClassCastException if the value is not an array """ return (JSONArray)parse(is, charSet); }
java
public static JSONArray parseArray(InputStream is, Charset charSet) throws IOException { return (JSONArray)parse(is, charSet); }
[ "public", "static", "JSONArray", "parseArray", "(", "InputStream", "is", ",", "Charset", "charSet", ")", "throws", "IOException", "{", "return", "(", "JSONArray", ")", "parse", "(", "is", ",", "charSet", ")", ";", "}" ]
Parse a sequence of characters from an {@link InputStream} as a JSON array, specifying the character set. @param is the {@link InputStream} @param charSet the character set @return the JSON array @throws JSONException if the stream does not contain a valid JSON value @throws IOException on any I/O errors @throws ClassCastException if the value is not an array
[ "Parse", "a", "sequence", "of", "characters", "from", "an", "{", "@link", "InputStream", "}", "as", "a", "JSON", "array", "specifying", "the", "character", "set", "." ]
train
https://github.com/pwall567/jsonutil/blob/dd5960b9b0bcc9acfe6c52b884fffd9ee5f422fe/src/main/java/net/pwall/json/JSON.java#L377-L379
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/collection/impl/queue/QueueContainer.java
QueueContainer.txnOfferBackupReserve
public void txnOfferBackupReserve(long itemId, String transactionId) { """ Reserves an ID for a future queue item and associates it with the given {@code transactionId}. The item is not yet visible in the queue, it is just reserved for future insertion. @param transactionId the ID of the transaction offering this item @param itemId the ID of the item being reserved """ TxQueueItem o = txnOfferReserveInternal(itemId, transactionId); if (o != null) { logger.severe("txnOfferBackupReserve operation-> Item exists already at txMap for itemId: " + itemId); } }
java
public void txnOfferBackupReserve(long itemId, String transactionId) { TxQueueItem o = txnOfferReserveInternal(itemId, transactionId); if (o != null) { logger.severe("txnOfferBackupReserve operation-> Item exists already at txMap for itemId: " + itemId); } }
[ "public", "void", "txnOfferBackupReserve", "(", "long", "itemId", ",", "String", "transactionId", ")", "{", "TxQueueItem", "o", "=", "txnOfferReserveInternal", "(", "itemId", ",", "transactionId", ")", ";", "if", "(", "o", "!=", "null", ")", "{", "logger", "...
Reserves an ID for a future queue item and associates it with the given {@code transactionId}. The item is not yet visible in the queue, it is just reserved for future insertion. @param transactionId the ID of the transaction offering this item @param itemId the ID of the item being reserved
[ "Reserves", "an", "ID", "for", "a", "future", "queue", "item", "and", "associates", "it", "with", "the", "given", "{", "@code", "transactionId", "}", ".", "The", "item", "is", "not", "yet", "visible", "in", "the", "queue", "it", "is", "just", "reserved",...
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/collection/impl/queue/QueueContainer.java#L319-L324
GCRC/nunaliit
nunaliit2-multimedia/src/main/java/ca/carleton/gcrc/olkit/multimedia/apachePDFBox/imageio/ImageIOUtil.java
ImageIOUtil.writeImage
public static boolean writeImage(BufferedImage image, String filename, int dpi, float quality) throws IOException { """ Writes a buffered image to a file using the given image format. See {@link #writeImage(BufferedImage image, String formatName, OutputStream output, int dpi, float quality)} for more details. @param image the image to be written @param filename used to construct the filename for the individual image. Its suffix will be used as the image format. @param dpi the resolution in dpi (dots per inch) to be used in metadata @param quality quality to be used when compressing the image (0 &lt; quality &lt; 1.0f) @return true if the image file was produced, false if there was an error. @throws IOException if an I/O error occurs """ File file = new File(filename); FileOutputStream output = new FileOutputStream(file); try { String formatName = filename.substring(filename.lastIndexOf('.') + 1); return writeImage(image, formatName, output, dpi, quality); } finally { output.close(); } }
java
public static boolean writeImage(BufferedImage image, String filename, int dpi, float quality) throws IOException { File file = new File(filename); FileOutputStream output = new FileOutputStream(file); try { String formatName = filename.substring(filename.lastIndexOf('.') + 1); return writeImage(image, formatName, output, dpi, quality); } finally { output.close(); } }
[ "public", "static", "boolean", "writeImage", "(", "BufferedImage", "image", ",", "String", "filename", ",", "int", "dpi", ",", "float", "quality", ")", "throws", "IOException", "{", "File", "file", "=", "new", "File", "(", "filename", ")", ";", "FileOutputSt...
Writes a buffered image to a file using the given image format. See {@link #writeImage(BufferedImage image, String formatName, OutputStream output, int dpi, float quality)} for more details. @param image the image to be written @param filename used to construct the filename for the individual image. Its suffix will be used as the image format. @param dpi the resolution in dpi (dots per inch) to be used in metadata @param quality quality to be used when compressing the image (0 &lt; quality &lt; 1.0f) @return true if the image file was produced, false if there was an error. @throws IOException if an I/O error occurs
[ "Writes", "a", "buffered", "image", "to", "a", "file", "using", "the", "given", "image", "format", ".", "See", "{", "@link", "#writeImage", "(", "BufferedImage", "image", "String", "formatName", "OutputStream", "output", "int", "dpi", "float", "quality", ")", ...
train
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-multimedia/src/main/java/ca/carleton/gcrc/olkit/multimedia/apachePDFBox/imageio/ImageIOUtil.java#L81-L95
j-a-w-r/jawr-main-repo
jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/factory/BundlesHandlerFactory.java
BundlesHandlerFactory.buildDirMappedResourceBundle
private JoinableResourceBundle buildDirMappedResourceBundle(String bundleId, String pathMapping) { """ Build a bundle based on a mapping returned by the ResourceBundleDirMapperFactory. @param bundleId the bundle Id @param pathMapping the path mapping @return a bundle based on a mapping returned by the ResourceBundleDirMapperFactory """ List<String> path = Collections.singletonList(pathMapping); JoinableResourceBundle newBundle = new JoinableResourceBundleImpl(bundleId, generateBundleNameFromBundleId(bundleId), null, fileExtension, new InclusionPattern(), path, resourceReaderHandler, jawrConfig.getGeneratorRegistry()); return newBundle; }
java
private JoinableResourceBundle buildDirMappedResourceBundle(String bundleId, String pathMapping) { List<String> path = Collections.singletonList(pathMapping); JoinableResourceBundle newBundle = new JoinableResourceBundleImpl(bundleId, generateBundleNameFromBundleId(bundleId), null, fileExtension, new InclusionPattern(), path, resourceReaderHandler, jawrConfig.getGeneratorRegistry()); return newBundle; }
[ "private", "JoinableResourceBundle", "buildDirMappedResourceBundle", "(", "String", "bundleId", ",", "String", "pathMapping", ")", "{", "List", "<", "String", ">", "path", "=", "Collections", ".", "singletonList", "(", "pathMapping", ")", ";", "JoinableResourceBundle"...
Build a bundle based on a mapping returned by the ResourceBundleDirMapperFactory. @param bundleId the bundle Id @param pathMapping the path mapping @return a bundle based on a mapping returned by the ResourceBundleDirMapperFactory
[ "Build", "a", "bundle", "based", "on", "a", "mapping", "returned", "by", "the", "ResourceBundleDirMapperFactory", "." ]
train
https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/factory/BundlesHandlerFactory.java#L747-L753
facebookarchive/hadoop-20
src/contrib/streaming/src/java/org/apache/hadoop/streaming/UTF8ByteArrayUtils.java
UTF8ByteArrayUtils.findNthByte
@Deprecated public static int findNthByte(byte [] utf, int start, int length, byte b, int n) { """ Find the nth occurrence of the given byte b in a UTF-8 encoded string @param utf a byte array containing a UTF-8 encoded string @param start starting offset @param length the length of byte array @param b the byte to find @param n the desired occurrence of the given byte @return position that nth occurrence of the given byte if exists; otherwise -1 @deprecated use {@link org.apache.hadoop.util.UTF8ByteArrayUtils#findNthByte(byte[], int, int, byte, int)} """ return org.apache.hadoop.util.UTF8ByteArrayUtils.findNthByte(utf, start, length, b, n); }
java
@Deprecated public static int findNthByte(byte [] utf, int start, int length, byte b, int n) { return org.apache.hadoop.util.UTF8ByteArrayUtils.findNthByte(utf, start, length, b, n); }
[ "@", "Deprecated", "public", "static", "int", "findNthByte", "(", "byte", "[", "]", "utf", ",", "int", "start", ",", "int", "length", ",", "byte", "b", ",", "int", "n", ")", "{", "return", "org", ".", "apache", ".", "hadoop", ".", "util", ".", "UTF...
Find the nth occurrence of the given byte b in a UTF-8 encoded string @param utf a byte array containing a UTF-8 encoded string @param start starting offset @param length the length of byte array @param b the byte to find @param n the desired occurrence of the given byte @return position that nth occurrence of the given byte if exists; otherwise -1 @deprecated use {@link org.apache.hadoop.util.UTF8ByteArrayUtils#findNthByte(byte[], int, int, byte, int)}
[ "Find", "the", "nth", "occurrence", "of", "the", "given", "byte", "b", "in", "a", "UTF", "-", "8", "encoded", "string" ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/streaming/src/java/org/apache/hadoop/streaming/UTF8ByteArrayUtils.java#L90-L94
jbundle/jbundle
base/base/src/main/java/org/jbundle/base/field/DoubleField.java
DoubleField.setValue
public int setValue(double value, boolean bDisplayOption, int iMoveMode) { """ /* Set the Value of this field as a double. @param value The value of this field. @param iDisplayOption If true, display the new field. @param iMoveMove The move mode. @return An error code (NORMAL_RETURN for success). """ // Set this field's value double dRoundAt = Math.pow(10, m_ibScale); Double tempdouble = new Double(Math.floor(value * dRoundAt + 0.5) / dRoundAt); int errorCode = this.setData(tempdouble, bDisplayOption, iMoveMode); return errorCode; }
java
public int setValue(double value, boolean bDisplayOption, int iMoveMode) { // Set this field's value double dRoundAt = Math.pow(10, m_ibScale); Double tempdouble = new Double(Math.floor(value * dRoundAt + 0.5) / dRoundAt); int errorCode = this.setData(tempdouble, bDisplayOption, iMoveMode); return errorCode; }
[ "public", "int", "setValue", "(", "double", "value", ",", "boolean", "bDisplayOption", ",", "int", "iMoveMode", ")", "{", "// Set this field's value", "double", "dRoundAt", "=", "Math", ".", "pow", "(", "10", ",", "m_ibScale", ")", ";", "Double", "tempdouble",...
/* Set the Value of this field as a double. @param value The value of this field. @param iDisplayOption If true, display the new field. @param iMoveMove The move mode. @return An error code (NORMAL_RETURN for success).
[ "/", "*", "Set", "the", "Value", "of", "this", "field", "as", "a", "double", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/field/DoubleField.java#L192-L198
groundupworks/wings
wings-facebook/src/main/java/com/groundupworks/wings/facebook/FacebookEndpoint.java
FacebookEndpoint.startOpenSessionRequest
private void startOpenSessionRequest(final Activity activity, final Fragment fragment) { """ Opens a new session with read permissions. @param activity the {@link Activity}. @param fragment the {@link Fragment}. May be null. """ // State transition. mLinkRequestState = STATE_OPEN_SESSION_REQUEST; // Construct status callback. Session.StatusCallback statusCallback = new Session.StatusCallback() { @Override public void call(Session session, SessionState state, Exception exception) { if (mLinkRequestState == STATE_OPEN_SESSION_REQUEST && state.isOpened()) { // Request publish permissions. if (!startPublishPermissionsRequest(activity, fragment)) { handleLinkError(); } } } }; // Construct new session. Session session = new Session(activity); Session.setActiveSession(session); // Construct read permissions to request for. List<String> readPermissions = new LinkedList<String>(); readPermissions.add(PERMISSION_PUBLIC_PROFILE); readPermissions.add(PERMISSION_USER_PHOTOS); // Construct open request. OpenRequest openRequest; if (fragment == null) { openRequest = new OpenRequest(activity); } else { openRequest = new OpenRequest(fragment); } // Allow SSO login only because the web login does not allow PERMISSION_USER_PHOTOS to be bundled with the // first openForRead() call. openRequest.setLoginBehavior(SessionLoginBehavior.SSO_ONLY); openRequest.setPermissions(readPermissions); openRequest.setDefaultAudience(SessionDefaultAudience.EVERYONE); openRequest.setCallback(statusCallback); // Execute open request. session.openForRead(openRequest); }
java
private void startOpenSessionRequest(final Activity activity, final Fragment fragment) { // State transition. mLinkRequestState = STATE_OPEN_SESSION_REQUEST; // Construct status callback. Session.StatusCallback statusCallback = new Session.StatusCallback() { @Override public void call(Session session, SessionState state, Exception exception) { if (mLinkRequestState == STATE_OPEN_SESSION_REQUEST && state.isOpened()) { // Request publish permissions. if (!startPublishPermissionsRequest(activity, fragment)) { handleLinkError(); } } } }; // Construct new session. Session session = new Session(activity); Session.setActiveSession(session); // Construct read permissions to request for. List<String> readPermissions = new LinkedList<String>(); readPermissions.add(PERMISSION_PUBLIC_PROFILE); readPermissions.add(PERMISSION_USER_PHOTOS); // Construct open request. OpenRequest openRequest; if (fragment == null) { openRequest = new OpenRequest(activity); } else { openRequest = new OpenRequest(fragment); } // Allow SSO login only because the web login does not allow PERMISSION_USER_PHOTOS to be bundled with the // first openForRead() call. openRequest.setLoginBehavior(SessionLoginBehavior.SSO_ONLY); openRequest.setPermissions(readPermissions); openRequest.setDefaultAudience(SessionDefaultAudience.EVERYONE); openRequest.setCallback(statusCallback); // Execute open request. session.openForRead(openRequest); }
[ "private", "void", "startOpenSessionRequest", "(", "final", "Activity", "activity", ",", "final", "Fragment", "fragment", ")", "{", "// State transition.", "mLinkRequestState", "=", "STATE_OPEN_SESSION_REQUEST", ";", "// Construct status callback.", "Session", ".", "StatusC...
Opens a new session with read permissions. @param activity the {@link Activity}. @param fragment the {@link Fragment}. May be null.
[ "Opens", "a", "new", "session", "with", "read", "permissions", "." ]
train
https://github.com/groundupworks/wings/blob/03d2827c30ef55f2db4e23f7500e016c7771fa39/wings-facebook/src/main/java/com/groundupworks/wings/facebook/FacebookEndpoint.java#L309-L352
jbake-org/jbake
jbake-core/src/main/java/org/jbake/app/Crawler.java
Crawler.createUri
private String createUri(String uri) { """ commons-codec's URLCodec could be used when we add that dependency. """ try { return FileUtil.URI_SEPARATOR_CHAR + FilenameUtils.getPath(uri) + URLEncoder.encode(FilenameUtils.getBaseName(uri), StandardCharsets.UTF_8.name()) + config.getOutputExtension(); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Missing UTF-8 encoding??", e); // Won't happen unless JDK is broken. } }
java
private String createUri(String uri) { try { return FileUtil.URI_SEPARATOR_CHAR + FilenameUtils.getPath(uri) + URLEncoder.encode(FilenameUtils.getBaseName(uri), StandardCharsets.UTF_8.name()) + config.getOutputExtension(); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Missing UTF-8 encoding??", e); // Won't happen unless JDK is broken. } }
[ "private", "String", "createUri", "(", "String", "uri", ")", "{", "try", "{", "return", "FileUtil", ".", "URI_SEPARATOR_CHAR", "+", "FilenameUtils", ".", "getPath", "(", "uri", ")", "+", "URLEncoder", ".", "encode", "(", "FilenameUtils", ".", "getBaseName", ...
commons-codec's URLCodec could be used when we add that dependency.
[ "commons", "-", "codec", "s", "URLCodec", "could", "be", "used", "when", "we", "add", "that", "dependency", "." ]
train
https://github.com/jbake-org/jbake/blob/beb9042a54bf0eb168821d524c88b9ea0bee88dc/jbake-core/src/main/java/org/jbake/app/Crawler.java#L153-L162
JavaMoney/jsr354-ri
moneta-core/src/main/java/org/javamoney/moneta/format/MonetaryAmountDecimalFormatBuilder.java
MonetaryAmountDecimalFormatBuilder.build
public MonetaryAmountFormat build() { """ Creates the {@link MonetaryAmountFormat} If @{link Locale} didn't set the default value is {@link Locale#getDefault()} If @{link MonetaryAmountProducer} didn't set the default value is {@link MoneyProducer} If @{link CurrencyUnit} didn't set the default value is a currency from {@link Locale} @return {@link MonetaryAmountFormat} """ if (Objects.isNull(locale)) { locale = Locale.getDefault(); } if (Objects.isNull(decimalFormat)) { decimalFormat = (DecimalFormat) NumberFormat.getCurrencyInstance(locale); } if (Objects.isNull(currencyUnit)) { currencyUnit = Monetary.getCurrency(locale); } if (Objects.isNull(producer)) { producer = new MoneyProducer(); } decimalFormat.setCurrency(Currency.getInstance(currencyUnit.getCurrencyCode())); return new MonetaryAmountDecimalFormat(decimalFormat, producer, currencyUnit); }
java
public MonetaryAmountFormat build() { if (Objects.isNull(locale)) { locale = Locale.getDefault(); } if (Objects.isNull(decimalFormat)) { decimalFormat = (DecimalFormat) NumberFormat.getCurrencyInstance(locale); } if (Objects.isNull(currencyUnit)) { currencyUnit = Monetary.getCurrency(locale); } if (Objects.isNull(producer)) { producer = new MoneyProducer(); } decimalFormat.setCurrency(Currency.getInstance(currencyUnit.getCurrencyCode())); return new MonetaryAmountDecimalFormat(decimalFormat, producer, currencyUnit); }
[ "public", "MonetaryAmountFormat", "build", "(", ")", "{", "if", "(", "Objects", ".", "isNull", "(", "locale", ")", ")", "{", "locale", "=", "Locale", ".", "getDefault", "(", ")", ";", "}", "if", "(", "Objects", ".", "isNull", "(", "decimalFormat", ")",...
Creates the {@link MonetaryAmountFormat} If @{link Locale} didn't set the default value is {@link Locale#getDefault()} If @{link MonetaryAmountProducer} didn't set the default value is {@link MoneyProducer} If @{link CurrencyUnit} didn't set the default value is a currency from {@link Locale} @return {@link MonetaryAmountFormat}
[ "Creates", "the", "{" ]
train
https://github.com/JavaMoney/jsr354-ri/blob/cf8ff2bbaf9b115acc05eb9b0c76c8397c308284/moneta-core/src/main/java/org/javamoney/moneta/format/MonetaryAmountDecimalFormatBuilder.java#L129-L144
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/transactional/TransactionTopologyBuilder.java
TransactionTopologyBuilder.setBoltWithAck
public BoltDeclarer setBoltWithAck(String id, IRichBolt bolt, Number parallelismHint) { """ Build bolt to provide the compatibility with Storm's ack mechanism @param id bolt Id @param bolt @return """ return setBolt(id, new AckTransactionBolt(bolt), parallelismHint); }
java
public BoltDeclarer setBoltWithAck(String id, IRichBolt bolt, Number parallelismHint) { return setBolt(id, new AckTransactionBolt(bolt), parallelismHint); }
[ "public", "BoltDeclarer", "setBoltWithAck", "(", "String", "id", ",", "IRichBolt", "bolt", ",", "Number", "parallelismHint", ")", "{", "return", "setBolt", "(", "id", ",", "new", "AckTransactionBolt", "(", "bolt", ")", ",", "parallelismHint", ")", ";", "}" ]
Build bolt to provide the compatibility with Storm's ack mechanism @param id bolt Id @param bolt @return
[ "Build", "bolt", "to", "provide", "the", "compatibility", "with", "Storm", "s", "ack", "mechanism" ]
train
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/transactional/TransactionTopologyBuilder.java#L181-L183
apache/spark
core/src/main/java/org/apache/spark/shuffle/sort/ShuffleInMemorySorter.java
ShuffleInMemorySorter.insertRecord
public void insertRecord(long recordPointer, int partitionId) { """ Inserts a record to be sorted. @param recordPointer a pointer to the record, encoded by the task memory manager. Due to certain pointer compression techniques used by the sorter, the sort can only operate on pointers that point to locations in the first {@link PackedRecordPointer#MAXIMUM_PAGE_SIZE_BYTES} bytes of a data page. @param partitionId the partition id, which must be less than or equal to {@link PackedRecordPointer#MAXIMUM_PARTITION_ID}. """ if (!hasSpaceForAnotherRecord()) { throw new IllegalStateException("There is no space for new record"); } array.set(pos, PackedRecordPointer.packPointer(recordPointer, partitionId)); pos++; }
java
public void insertRecord(long recordPointer, int partitionId) { if (!hasSpaceForAnotherRecord()) { throw new IllegalStateException("There is no space for new record"); } array.set(pos, PackedRecordPointer.packPointer(recordPointer, partitionId)); pos++; }
[ "public", "void", "insertRecord", "(", "long", "recordPointer", ",", "int", "partitionId", ")", "{", "if", "(", "!", "hasSpaceForAnotherRecord", "(", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"There is no space for new record\"", ")", ";", "}"...
Inserts a record to be sorted. @param recordPointer a pointer to the record, encoded by the task memory manager. Due to certain pointer compression techniques used by the sorter, the sort can only operate on pointers that point to locations in the first {@link PackedRecordPointer#MAXIMUM_PAGE_SIZE_BYTES} bytes of a data page. @param partitionId the partition id, which must be less than or equal to {@link PackedRecordPointer#MAXIMUM_PARTITION_ID}.
[ "Inserts", "a", "record", "to", "be", "sorted", "." ]
train
https://github.com/apache/spark/blob/25ee0474f47d9c30d6f553a7892d9549f91071cf/core/src/main/java/org/apache/spark/shuffle/sort/ShuffleInMemorySorter.java#L146-L152
OpenTSDB/opentsdb
src/uid/UniqueId.java
UniqueId.hbaseGet
private Deferred<byte[]> hbaseGet(final byte[] key, final byte[] family) { """ Returns the cell of the specified row key, using family:kind. """ final GetRequest get = new GetRequest(table, key); get.family(family).qualifier(kind); class GetCB implements Callback<byte[], ArrayList<KeyValue>> { public byte[] call(final ArrayList<KeyValue> row) { if (row == null || row.isEmpty()) { return null; } return row.get(0).value(); } } return client.get(get).addCallback(new GetCB()); }
java
private Deferred<byte[]> hbaseGet(final byte[] key, final byte[] family) { final GetRequest get = new GetRequest(table, key); get.family(family).qualifier(kind); class GetCB implements Callback<byte[], ArrayList<KeyValue>> { public byte[] call(final ArrayList<KeyValue> row) { if (row == null || row.isEmpty()) { return null; } return row.get(0).value(); } } return client.get(get).addCallback(new GetCB()); }
[ "private", "Deferred", "<", "byte", "[", "]", ">", "hbaseGet", "(", "final", "byte", "[", "]", "key", ",", "final", "byte", "[", "]", "family", ")", "{", "final", "GetRequest", "get", "=", "new", "GetRequest", "(", "table", ",", "key", ")", ";", "g...
Returns the cell of the specified row key, using family:kind.
[ "Returns", "the", "cell", "of", "the", "specified", "row", "key", "using", "family", ":", "kind", "." ]
train
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/uid/UniqueId.java#L1338-L1350
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/mfp/jmf/impl/JSField.java
JSField.copyValue
public Object copyValue(Object val, int indirect) throws JMFSchemaViolationException { """ Create a copy of the value of this JSField's type @param val the value to be copied @param indirect the list indirection that applies to the object or -1 if the JSField's maximum list indirection (based on the number of JSRepeated nodes that dominate it in the schema) is to be used: this, of course, includes the possibility that it isn't a list at all. @return a copy of val. This can be the original if the type for this field is immutable. """ if (indirect == 0) return copy(val, 0); else return coder.copy(val, indirect - 1); }
java
public Object copyValue(Object val, int indirect) throws JMFSchemaViolationException { if (indirect == 0) return copy(val, 0); else return coder.copy(val, indirect - 1); }
[ "public", "Object", "copyValue", "(", "Object", "val", ",", "int", "indirect", ")", "throws", "JMFSchemaViolationException", "{", "if", "(", "indirect", "==", "0", ")", "return", "copy", "(", "val", ",", "0", ")", ";", "else", "return", "coder", ".", "co...
Create a copy of the value of this JSField's type @param val the value to be copied @param indirect the list indirection that applies to the object or -1 if the JSField's maximum list indirection (based on the number of JSRepeated nodes that dominate it in the schema) is to be used: this, of course, includes the possibility that it isn't a list at all. @return a copy of val. This can be the original if the type for this field is immutable.
[ "Create", "a", "copy", "of", "the", "value", "of", "this", "JSField", "s", "type" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/mfp/jmf/impl/JSField.java#L239-L245
querydsl/querydsl
querydsl-sql/src/main/java/com/querydsl/sql/ProjectableSQLQuery.java
ProjectableSQLQuery.addJoinFlag
@Override public Q addJoinFlag(String flag) { """ Add the given String literal as a join flag to the last added join with the position BEFORE_TARGET @param flag join flag @return the current object """ return addJoinFlag(flag, JoinFlag.Position.BEFORE_TARGET); }
java
@Override public Q addJoinFlag(String flag) { return addJoinFlag(flag, JoinFlag.Position.BEFORE_TARGET); }
[ "@", "Override", "public", "Q", "addJoinFlag", "(", "String", "flag", ")", "{", "return", "addJoinFlag", "(", "flag", ",", "JoinFlag", ".", "Position", ".", "BEFORE_TARGET", ")", ";", "}" ]
Add the given String literal as a join flag to the last added join with the position BEFORE_TARGET @param flag join flag @return the current object
[ "Add", "the", "given", "String", "literal", "as", "a", "join", "flag", "to", "the", "last", "added", "join", "with", "the", "position", "BEFORE_TARGET" ]
train
https://github.com/querydsl/querydsl/blob/2bf234caf78549813a1e0f44d9c30ecc5ef734e3/querydsl-sql/src/main/java/com/querydsl/sql/ProjectableSQLQuery.java#L83-L86
jOOQ/jOOL
jOOL-java-8/src/main/java/org/jooq/lambda/Unchecked.java
Unchecked.toLongFunction
public static <T> ToLongFunction<T> toLongFunction(CheckedToLongFunction<T> function) { """ Wrap a {@link CheckedToLongFunction} in a {@link ToLongFunction}. <p> Example: <code><pre> map.computeIfAbsent("key", Unchecked.toLongFunction(k -> { if (k.length() > 10) throw new Exception("Only short strings allowed"); return 42L; })); </pre></code> """ return toLongFunction(function, THROWABLE_TO_RUNTIME_EXCEPTION); }
java
public static <T> ToLongFunction<T> toLongFunction(CheckedToLongFunction<T> function) { return toLongFunction(function, THROWABLE_TO_RUNTIME_EXCEPTION); }
[ "public", "static", "<", "T", ">", "ToLongFunction", "<", "T", ">", "toLongFunction", "(", "CheckedToLongFunction", "<", "T", ">", "function", ")", "{", "return", "toLongFunction", "(", "function", ",", "THROWABLE_TO_RUNTIME_EXCEPTION", ")", ";", "}" ]
Wrap a {@link CheckedToLongFunction} in a {@link ToLongFunction}. <p> Example: <code><pre> map.computeIfAbsent("key", Unchecked.toLongFunction(k -> { if (k.length() > 10) throw new Exception("Only short strings allowed"); return 42L; })); </pre></code>
[ "Wrap", "a", "{", "@link", "CheckedToLongFunction", "}", "in", "a", "{", "@link", "ToLongFunction", "}", ".", "<p", ">", "Example", ":", "<code", ">", "<pre", ">", "map", ".", "computeIfAbsent", "(", "key", "Unchecked", ".", "toLongFunction", "(", "k", "...
train
https://github.com/jOOQ/jOOL/blob/889d87c85ca57bafd4eddd78e0f7ae2804d2ee86/jOOL-java-8/src/main/java/org/jooq/lambda/Unchecked.java#L949-L951
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/resolution/DependencyExplorer.java
DependencyExplorer.locateHighestAccessibleSource
private GinjectorBindings locateHighestAccessibleSource(Key<?> key, GinjectorBindings origin) { """ Find the highest binding in the Ginjector tree that could be used to supply the given key. <p>This takes care not to use a higher parent binding if the parent only has the binding because its exposed from this Ginjector. This leads to problems because the resolution algorithm won't actually create the binding here if it can just use a parents binding. @param key The binding to search for @return the highest ginjector that contains the key or {@code null} if none contain it """ // If we don't already have a binding, and the key is "pinned", it means that this injector // is supposed to contain a binding, but it needs to have one created implicitly. We return // null so that we attempt to create the implicit binding. if (!origin.isBound(key) && origin.isPinned(key)) { return null; } GinjectorBindings source = null; for (GinjectorBindings iter = origin; iter != null; iter = iter.getParent()) { // If the key is already explicitly bound, or has a pin indicating that it // will be explicitly bound once it gets visited (we visit children before // parents) then we can access the binding from the given location. if (iter.isBound(key) || iter.isPinned(key)) { source = iter; } } return source; }
java
private GinjectorBindings locateHighestAccessibleSource(Key<?> key, GinjectorBindings origin) { // If we don't already have a binding, and the key is "pinned", it means that this injector // is supposed to contain a binding, but it needs to have one created implicitly. We return // null so that we attempt to create the implicit binding. if (!origin.isBound(key) && origin.isPinned(key)) { return null; } GinjectorBindings source = null; for (GinjectorBindings iter = origin; iter != null; iter = iter.getParent()) { // If the key is already explicitly bound, or has a pin indicating that it // will be explicitly bound once it gets visited (we visit children before // parents) then we can access the binding from the given location. if (iter.isBound(key) || iter.isPinned(key)) { source = iter; } } return source; }
[ "private", "GinjectorBindings", "locateHighestAccessibleSource", "(", "Key", "<", "?", ">", "key", ",", "GinjectorBindings", "origin", ")", "{", "// If we don't already have a binding, and the key is \"pinned\", it means that this injector", "// is supposed to contain a binding, but it...
Find the highest binding in the Ginjector tree that could be used to supply the given key. <p>This takes care not to use a higher parent binding if the parent only has the binding because its exposed from this Ginjector. This leads to problems because the resolution algorithm won't actually create the binding here if it can just use a parents binding. @param key The binding to search for @return the highest ginjector that contains the key or {@code null} if none contain it
[ "Find", "the", "highest", "binding", "in", "the", "Ginjector", "tree", "that", "could", "be", "used", "to", "supply", "the", "given", "key", "." ]
train
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/resolution/DependencyExplorer.java#L139-L157
elki-project/elki
elki-persistent/src/main/java/de/lmu/ifi/dbs/elki/persistent/OnDiskArray.java
OnDiskArray.mixMagic
public static final int mixMagic(int magic1, int magic2) { """ Mix two magic numbers into one, to obtain a combined magic. Note: mixMagic(a,b) != mixMagic(b,a) usually. @param magic1 Magic number to mix. @param magic2 Magic number to mix. @return Mixed magic number. """ final long prime = 2654435761L; long result = 1; result = prime * result + magic1; result = prime * result + magic2; return (int) result; }
java
public static final int mixMagic(int magic1, int magic2) { final long prime = 2654435761L; long result = 1; result = prime * result + magic1; result = prime * result + magic2; return (int) result; }
[ "public", "static", "final", "int", "mixMagic", "(", "int", "magic1", ",", "int", "magic2", ")", "{", "final", "long", "prime", "=", "2654435761L", ";", "long", "result", "=", "1", ";", "result", "=", "prime", "*", "result", "+", "magic1", ";", "result...
Mix two magic numbers into one, to obtain a combined magic. Note: mixMagic(a,b) != mixMagic(b,a) usually. @param magic1 Magic number to mix. @param magic2 Magic number to mix. @return Mixed magic number.
[ "Mix", "two", "magic", "numbers", "into", "one", "to", "obtain", "a", "combined", "magic", ".", "Note", ":", "mixMagic", "(", "a", "b", ")", "!", "=", "mixMagic", "(", "b", "a", ")", "usually", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-persistent/src/main/java/de/lmu/ifi/dbs/elki/persistent/OnDiskArray.java#L299-L305
casmi/casmi
src/main/java/casmi/graphics/element/Lines.java
Lines.vertex
public void vertex(double x, double y) { """ Adds the point to Lines. @param x The x-coordinate of a new added point. @param y The y-coordinate of a new added point. """ MODE = LINES; this.x.add(x); this.y.add(y); colors.add(this.strokeColor); calcG(); }
java
public void vertex(double x, double y) { MODE = LINES; this.x.add(x); this.y.add(y); colors.add(this.strokeColor); calcG(); }
[ "public", "void", "vertex", "(", "double", "x", ",", "double", "y", ")", "{", "MODE", "=", "LINES", ";", "this", ".", "x", ".", "add", "(", "x", ")", ";", "this", ".", "y", ".", "add", "(", "y", ")", ";", "colors", ".", "add", "(", "this", ...
Adds the point to Lines. @param x The x-coordinate of a new added point. @param y The y-coordinate of a new added point.
[ "Adds", "the", "point", "to", "Lines", "." ]
train
https://github.com/casmi/casmi/blob/90f6514a9cbce0685186e7a92beb69e22a3b11c4/src/main/java/casmi/graphics/element/Lines.java#L78-L84
census-instrumentation/opencensus-java
api/src/main/java/io/opencensus/trace/SpanId.java
SpanId.fromLowerBase16
public static SpanId fromLowerBase16(CharSequence src) { """ Returns a {@code SpanId} built from a lowercase base16 representation. @param src the lowercase base16 representation. @return a {@code SpanId} built from a lowercase base16 representation. @throws NullPointerException if {@code src} is null. @throws IllegalArgumentException if {@code src.length} is not {@code 2 * SpanId.SIZE} OR if the {@code str} has invalid characters. @since 0.11 """ Utils.checkNotNull(src, "src"); // TODO: Remove this extra condition. Utils.checkArgument( src.length() == BASE16_SIZE, "Invalid size: expected %s, got %s", BASE16_SIZE, src.length()); return fromLowerBase16(src, 0); }
java
public static SpanId fromLowerBase16(CharSequence src) { Utils.checkNotNull(src, "src"); // TODO: Remove this extra condition. Utils.checkArgument( src.length() == BASE16_SIZE, "Invalid size: expected %s, got %s", BASE16_SIZE, src.length()); return fromLowerBase16(src, 0); }
[ "public", "static", "SpanId", "fromLowerBase16", "(", "CharSequence", "src", ")", "{", "Utils", ".", "checkNotNull", "(", "src", ",", "\"src\"", ")", ";", "// TODO: Remove this extra condition.", "Utils", ".", "checkArgument", "(", "src", ".", "length", "(", ")"...
Returns a {@code SpanId} built from a lowercase base16 representation. @param src the lowercase base16 representation. @return a {@code SpanId} built from a lowercase base16 representation. @throws NullPointerException if {@code src} is null. @throws IllegalArgumentException if {@code src.length} is not {@code 2 * SpanId.SIZE} OR if the {@code str} has invalid characters. @since 0.11
[ "Returns", "a", "{", "@code", "SpanId", "}", "built", "from", "a", "lowercase", "base16", "representation", "." ]
train
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/api/src/main/java/io/opencensus/trace/SpanId.java#L100-L109
eclipse/hawkbit
hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/HawkbitCommonUtil.java
HawkbitCommonUtil.getPollStatusToolTip
public static String getPollStatusToolTip(final PollStatus pollStatus, final VaadinMessageSource i18N) { """ Get tool tip for Poll status. @param pollStatus @param i18N @return PollStatusToolTip """ if (pollStatus != null && pollStatus.getLastPollDate() != null && pollStatus.isOverdue()) { final TimeZone tz = SPDateTimeUtil.getBrowserTimeZone(); return i18N.getMessage(UIMessageIdProvider.TOOLTIP_OVERDUE, SPDateTimeUtil.getDurationFormattedString( pollStatus.getOverdueDate().atZone(SPDateTimeUtil.getTimeZoneId(tz)).toInstant().toEpochMilli(), pollStatus.getCurrentDate().atZone(SPDateTimeUtil.getTimeZoneId(tz)).toInstant().toEpochMilli(), i18N)); } return null; }
java
public static String getPollStatusToolTip(final PollStatus pollStatus, final VaadinMessageSource i18N) { if (pollStatus != null && pollStatus.getLastPollDate() != null && pollStatus.isOverdue()) { final TimeZone tz = SPDateTimeUtil.getBrowserTimeZone(); return i18N.getMessage(UIMessageIdProvider.TOOLTIP_OVERDUE, SPDateTimeUtil.getDurationFormattedString( pollStatus.getOverdueDate().atZone(SPDateTimeUtil.getTimeZoneId(tz)).toInstant().toEpochMilli(), pollStatus.getCurrentDate().atZone(SPDateTimeUtil.getTimeZoneId(tz)).toInstant().toEpochMilli(), i18N)); } return null; }
[ "public", "static", "String", "getPollStatusToolTip", "(", "final", "PollStatus", "pollStatus", ",", "final", "VaadinMessageSource", "i18N", ")", "{", "if", "(", "pollStatus", "!=", "null", "&&", "pollStatus", ".", "getLastPollDate", "(", ")", "!=", "null", "&&"...
Get tool tip for Poll status. @param pollStatus @param i18N @return PollStatusToolTip
[ "Get", "tool", "tip", "for", "Poll", "status", "." ]
train
https://github.com/eclipse/hawkbit/blob/9884452ad42f3b4827461606d8a9215c8625a7fe/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/HawkbitCommonUtil.java#L165-L174
gallandarakhneorg/afc
core/inputoutput/src/main/java/org/arakhne/afc/inputoutput/xml/XMLUtil.java
XMLUtil.readXMLFragment
public static DocumentFragment readXMLFragment(String file) throws IOException, SAXException, ParserConfigurationException { """ Read an XML fragment from an XML file. The XML file is well-formed. It means that the fragment will contains a single element: the root element within the input file. @param file is the file to read @return the fragment from the {@code file}. @throws IOException if the stream cannot be read. @throws SAXException if the stream does not contains valid XML data. @throws ParserConfigurationException if the parser cannot be configured. """ return readXMLFragment(file, false); }
java
public static DocumentFragment readXMLFragment(String file) throws IOException, SAXException, ParserConfigurationException { return readXMLFragment(file, false); }
[ "public", "static", "DocumentFragment", "readXMLFragment", "(", "String", "file", ")", "throws", "IOException", ",", "SAXException", ",", "ParserConfigurationException", "{", "return", "readXMLFragment", "(", "file", ",", "false", ")", ";", "}" ]
Read an XML fragment from an XML file. The XML file is well-formed. It means that the fragment will contains a single element: the root element within the input file. @param file is the file to read @return the fragment from the {@code file}. @throws IOException if the stream cannot be read. @throws SAXException if the stream does not contains valid XML data. @throws ParserConfigurationException if the parser cannot be configured.
[ "Read", "an", "XML", "fragment", "from", "an", "XML", "file", ".", "The", "XML", "file", "is", "well", "-", "formed", ".", "It", "means", "that", "the", "fragment", "will", "contains", "a", "single", "element", ":", "the", "root", "element", "within", ...
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/inputoutput/src/main/java/org/arakhne/afc/inputoutput/xml/XMLUtil.java#L2101-L2103
fcrepo4/fcrepo4
fcrepo-kernel-modeshape/src/main/java/org/fcrepo/kernel/modeshape/services/NodeServiceImpl.java
NodeServiceImpl.copyObject
@Override public void copyObject(final FedoraSession session, final String source, final String destination) { """ Copy an existing object from the source path to the destination path @param session a JCR session @param source the source path @param destination the destination path """ final Session jcrSession = getJcrSession(session); try { jcrSession.getWorkspace().copy(source, destination); touchLdpMembershipResource(getJcrNode(find(session, destination))); } catch (final RepositoryException e) { throw new RepositoryRuntimeException(e); } }
java
@Override public void copyObject(final FedoraSession session, final String source, final String destination) { final Session jcrSession = getJcrSession(session); try { jcrSession.getWorkspace().copy(source, destination); touchLdpMembershipResource(getJcrNode(find(session, destination))); } catch (final RepositoryException e) { throw new RepositoryRuntimeException(e); } }
[ "@", "Override", "public", "void", "copyObject", "(", "final", "FedoraSession", "session", ",", "final", "String", "source", ",", "final", "String", "destination", ")", "{", "final", "Session", "jcrSession", "=", "getJcrSession", "(", "session", ")", ";", "try...
Copy an existing object from the source path to the destination path @param session a JCR session @param source the source path @param destination the destination path
[ "Copy", "an", "existing", "object", "from", "the", "source", "path", "to", "the", "destination", "path" ]
train
https://github.com/fcrepo4/fcrepo4/blob/7489ad5bc8fb44e2442c93eceb7d97ac54553ab6/fcrepo-kernel-modeshape/src/main/java/org/fcrepo/kernel/modeshape/services/NodeServiceImpl.java#L92-L101
yidongnan/grpc-spring-boot-starter
grpc-client-spring-boot-autoconfigure/src/main/java/net/devh/boot/grpc/client/security/CallCredentialsHelper.java
CallCredentialsHelper.basicAuth
public static CallCredentials basicAuth(final String username, final String password) { """ Creates a new call credential with the given username and password for basic auth. <p> <b>Note:</b> This method uses experimental grpc-java-API features. </p> @param username The username to use. @param password The password to use. @return The newly created basic auth credentials. """ final Metadata extraHeaders = new Metadata(); extraHeaders.put(AUTHORIZATION_HEADER, encodeBasicAuth(username, password)); return new StaticSecurityHeaderCallCredentials(extraHeaders); }
java
public static CallCredentials basicAuth(final String username, final String password) { final Metadata extraHeaders = new Metadata(); extraHeaders.put(AUTHORIZATION_HEADER, encodeBasicAuth(username, password)); return new StaticSecurityHeaderCallCredentials(extraHeaders); }
[ "public", "static", "CallCredentials", "basicAuth", "(", "final", "String", "username", ",", "final", "String", "password", ")", "{", "final", "Metadata", "extraHeaders", "=", "new", "Metadata", "(", ")", ";", "extraHeaders", ".", "put", "(", "AUTHORIZATION_HEAD...
Creates a new call credential with the given username and password for basic auth. <p> <b>Note:</b> This method uses experimental grpc-java-API features. </p> @param username The username to use. @param password The password to use. @return The newly created basic auth credentials.
[ "Creates", "a", "new", "call", "credential", "with", "the", "given", "username", "and", "password", "for", "basic", "auth", "." ]
train
https://github.com/yidongnan/grpc-spring-boot-starter/blob/07f8853cfafc9707584f2371aff012e590217b85/grpc-client-spring-boot-autoconfigure/src/main/java/net/devh/boot/grpc/client/security/CallCredentialsHelper.java#L187-L191
xcesco/kripton
kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/AbstractSelectCodeGenerator.java
AbstractSelectCodeGenerator.checkUnusedParameters
public static void checkUnusedParameters(SQLiteModelMethod method, Set<String> usedMethodParameters, TypeName excludedClasses) { """ Check if there are unused method parameters. In this case an exception was throws. @param method the method @param usedMethodParameters the used method parameters @param excludedClasses the excluded classes """ int paramsCount = method.getParameters().size(); int usedCount = usedMethodParameters.size(); if (paramsCount > usedCount) { StringBuilder sb = new StringBuilder(); String separator = ""; for (Pair<String, TypeName> item : method.getParameters()) { if (excludedClasses != null && item.value1.equals(excludedClasses)) { usedCount++; } else { if (!usedMethodParameters.contains(item.value0)) { sb.append(separator + "'" + item.value0 + "'"); separator = ", "; } } } if (paramsCount > usedCount) { throw (new InvalidMethodSignException(method, "unused parameter(s) " + sb.toString())); } } }
java
public static void checkUnusedParameters(SQLiteModelMethod method, Set<String> usedMethodParameters, TypeName excludedClasses) { int paramsCount = method.getParameters().size(); int usedCount = usedMethodParameters.size(); if (paramsCount > usedCount) { StringBuilder sb = new StringBuilder(); String separator = ""; for (Pair<String, TypeName> item : method.getParameters()) { if (excludedClasses != null && item.value1.equals(excludedClasses)) { usedCount++; } else { if (!usedMethodParameters.contains(item.value0)) { sb.append(separator + "'" + item.value0 + "'"); separator = ", "; } } } if (paramsCount > usedCount) { throw (new InvalidMethodSignException(method, "unused parameter(s) " + sb.toString())); } } }
[ "public", "static", "void", "checkUnusedParameters", "(", "SQLiteModelMethod", "method", ",", "Set", "<", "String", ">", "usedMethodParameters", ",", "TypeName", "excludedClasses", ")", "{", "int", "paramsCount", "=", "method", ".", "getParameters", "(", ")", ".",...
Check if there are unused method parameters. In this case an exception was throws. @param method the method @param usedMethodParameters the used method parameters @param excludedClasses the excluded classes
[ "Check", "if", "there", "are", "unused", "method", "parameters", ".", "In", "this", "case", "an", "exception", "was", "throws", "." ]
train
https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/AbstractSelectCodeGenerator.java#L789-L811
Stratio/stratio-cassandra
src/java/org/apache/cassandra/db/Memtable.java
Memtable.put
long put(DecoratedKey key, ColumnFamily cf, SecondaryIndexManager.Updater indexer, OpOrder.Group opGroup) { """ Should only be called by ColumnFamilyStore.apply via Keyspace.apply, which supplies the appropriate OpOrdering. replayPosition should only be null if this is a secondary index, in which case it is *expected* to be null """ AtomicBTreeColumns previous = rows.get(key); if (previous == null) { AtomicBTreeColumns empty = cf.cloneMeShallow(AtomicBTreeColumns.factory, false); final DecoratedKey cloneKey = allocator.clone(key, opGroup); // We'll add the columns later. This avoids wasting works if we get beaten in the putIfAbsent previous = rows.putIfAbsent(cloneKey, empty); if (previous == null) { previous = empty; // allocate the row overhead after the fact; this saves over allocating and having to free after, but // means we can overshoot our declared limit. int overhead = (int) (cfs.partitioner.getHeapSizeOf(key.getToken()) + ROW_OVERHEAD_HEAP_SIZE); allocator.onHeap().allocate(overhead, opGroup); } else { allocator.reclaimer().reclaimImmediately(cloneKey); } } final Pair<Long, Long> pair = previous.addAllWithSizeDelta(cf, allocator, opGroup, indexer); liveDataSize.addAndGet(pair.left); currentOperations.addAndGet(cf.getColumnCount() + (cf.isMarkedForDelete() ? 1 : 0) + cf.deletionInfo().rangeCount()); return pair.right; }
java
long put(DecoratedKey key, ColumnFamily cf, SecondaryIndexManager.Updater indexer, OpOrder.Group opGroup) { AtomicBTreeColumns previous = rows.get(key); if (previous == null) { AtomicBTreeColumns empty = cf.cloneMeShallow(AtomicBTreeColumns.factory, false); final DecoratedKey cloneKey = allocator.clone(key, opGroup); // We'll add the columns later. This avoids wasting works if we get beaten in the putIfAbsent previous = rows.putIfAbsent(cloneKey, empty); if (previous == null) { previous = empty; // allocate the row overhead after the fact; this saves over allocating and having to free after, but // means we can overshoot our declared limit. int overhead = (int) (cfs.partitioner.getHeapSizeOf(key.getToken()) + ROW_OVERHEAD_HEAP_SIZE); allocator.onHeap().allocate(overhead, opGroup); } else { allocator.reclaimer().reclaimImmediately(cloneKey); } } final Pair<Long, Long> pair = previous.addAllWithSizeDelta(cf, allocator, opGroup, indexer); liveDataSize.addAndGet(pair.left); currentOperations.addAndGet(cf.getColumnCount() + (cf.isMarkedForDelete() ? 1 : 0) + cf.deletionInfo().rangeCount()); return pair.right; }
[ "long", "put", "(", "DecoratedKey", "key", ",", "ColumnFamily", "cf", ",", "SecondaryIndexManager", ".", "Updater", "indexer", ",", "OpOrder", ".", "Group", "opGroup", ")", "{", "AtomicBTreeColumns", "previous", "=", "rows", ".", "get", "(", "key", ")", ";",...
Should only be called by ColumnFamilyStore.apply via Keyspace.apply, which supplies the appropriate OpOrdering. replayPosition should only be null if this is a secondary index, in which case it is *expected* to be null
[ "Should", "only", "be", "called", "by", "ColumnFamilyStore", ".", "apply", "via", "Keyspace", ".", "apply", "which", "supplies", "the", "appropriate", "OpOrdering", "." ]
train
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/Memtable.java#L184-L212
TheHortonMachine/hortonmachine
gears/src/main/java/oms3/ngmf/util/IOCase.java
IOCase.checkStartsWith
public boolean checkStartsWith(String str, String start) { """ Checks if one string starts with another using the case-sensitivity rule. <p> This method mimics {@link String#startsWith(String)} but takes case-sensitivity into account. @param str the string to check, not null @param start the start to compare against, not null @return true if equal using the case rules @throws NullPointerException if either string is null """ return str.regionMatches(!sensitive, 0, start, 0, start.length()); }
java
public boolean checkStartsWith(String str, String start) { return str.regionMatches(!sensitive, 0, start, 0, start.length()); }
[ "public", "boolean", "checkStartsWith", "(", "String", "str", ",", "String", "start", ")", "{", "return", "str", ".", "regionMatches", "(", "!", "sensitive", ",", "0", ",", "start", ",", "0", ",", "start", ".", "length", "(", ")", ")", ";", "}" ]
Checks if one string starts with another using the case-sensitivity rule. <p> This method mimics {@link String#startsWith(String)} but takes case-sensitivity into account. @param str the string to check, not null @param start the start to compare against, not null @return true if equal using the case rules @throws NullPointerException if either string is null
[ "Checks", "if", "one", "string", "starts", "with", "another", "using", "the", "case", "-", "sensitivity", "rule", ".", "<p", ">", "This", "method", "mimics", "{", "@link", "String#startsWith", "(", "String", ")", "}", "but", "takes", "case", "-", "sensitiv...
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/oms3/ngmf/util/IOCase.java#L178-L180
Samsung/GearVRf
GVRf/Extensions/script/src/main/java/org/gearvrf/script/javascript/ExternalScriptable.java
ExternalScriptable.has
public synchronized boolean has(String name, Scriptable start) { """ Returns true if the named property is defined. @param name the name of the property @param start the object in which the lookup began @return true if and only if the property was found in the object """ if (isEmpty(name)) { return indexedProps.containsKey(name); } else { synchronized (context) { return context.getAttributesScope(name) != -1; } } }
java
public synchronized boolean has(String name, Scriptable start) { if (isEmpty(name)) { return indexedProps.containsKey(name); } else { synchronized (context) { return context.getAttributesScope(name) != -1; } } }
[ "public", "synchronized", "boolean", "has", "(", "String", "name", ",", "Scriptable", "start", ")", "{", "if", "(", "isEmpty", "(", "name", ")", ")", "{", "return", "indexedProps", ".", "containsKey", "(", "name", ")", ";", "}", "else", "{", "synchronize...
Returns true if the named property is defined. @param name the name of the property @param start the object in which the lookup began @return true if and only if the property was found in the object
[ "Returns", "true", "if", "the", "named", "property", "is", "defined", "." ]
train
https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Extensions/script/src/main/java/org/gearvrf/script/javascript/ExternalScriptable.java#L144-L152
Azure/azure-sdk-for-java
datalakeanalytics/resource-manager/v2016_11_01/src/main/java/com/microsoft/azure/management/datalakeanalytics/v2016_11_01/implementation/AccountsInner.java
AccountsInner.checkNameAvailabilityAsync
public Observable<NameAvailabilityInformationInner> checkNameAvailabilityAsync(String location, CheckNameAvailabilityParameters parameters) { """ Checks whether the specified account name is available or taken. @param location The resource location without whitespace. @param parameters Parameters supplied to check the Data Lake Analytics account name availability. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the NameAvailabilityInformationInner object """ return checkNameAvailabilityWithServiceResponseAsync(location, parameters).map(new Func1<ServiceResponse<NameAvailabilityInformationInner>, NameAvailabilityInformationInner>() { @Override public NameAvailabilityInformationInner call(ServiceResponse<NameAvailabilityInformationInner> response) { return response.body(); } }); }
java
public Observable<NameAvailabilityInformationInner> checkNameAvailabilityAsync(String location, CheckNameAvailabilityParameters parameters) { return checkNameAvailabilityWithServiceResponseAsync(location, parameters).map(new Func1<ServiceResponse<NameAvailabilityInformationInner>, NameAvailabilityInformationInner>() { @Override public NameAvailabilityInformationInner call(ServiceResponse<NameAvailabilityInformationInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "NameAvailabilityInformationInner", ">", "checkNameAvailabilityAsync", "(", "String", "location", ",", "CheckNameAvailabilityParameters", "parameters", ")", "{", "return", "checkNameAvailabilityWithServiceResponseAsync", "(", "location", ",", "param...
Checks whether the specified account name is available or taken. @param location The resource location without whitespace. @param parameters Parameters supplied to check the Data Lake Analytics account name availability. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the NameAvailabilityInformationInner object
[ "Checks", "whether", "the", "specified", "account", "name", "is", "available", "or", "taken", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/datalakeanalytics/resource-manager/v2016_11_01/src/main/java/com/microsoft/azure/management/datalakeanalytics/v2016_11_01/implementation/AccountsInner.java#L1388-L1395
box/box-java-sdk
src/main/java/com/box/sdk/BoxUser.java
BoxUser.createEnterpriseUser
public static BoxUser.Info createEnterpriseUser(BoxAPIConnection api, String login, String name) { """ Provisions a new user in an enterprise. @param api the API connection to be used by the created user. @param login the email address the user will use to login. @param name the name of the user. @return the created user's info. """ return createEnterpriseUser(api, login, name, null); }
java
public static BoxUser.Info createEnterpriseUser(BoxAPIConnection api, String login, String name) { return createEnterpriseUser(api, login, name, null); }
[ "public", "static", "BoxUser", ".", "Info", "createEnterpriseUser", "(", "BoxAPIConnection", "api", ",", "String", "login", ",", "String", "name", ")", "{", "return", "createEnterpriseUser", "(", "api", ",", "login", ",", "name", ",", "null", ")", ";", "}" ]
Provisions a new user in an enterprise. @param api the API connection to be used by the created user. @param login the email address the user will use to login. @param name the name of the user. @return the created user's info.
[ "Provisions", "a", "new", "user", "in", "an", "enterprise", "." ]
train
https://github.com/box/box-java-sdk/blob/35b4ba69417f9d6a002c19dfaab57527750ef349/src/main/java/com/box/sdk/BoxUser.java#L108-L110
taimos/RESTUtils
src/main/java/de/taimos/restutils/RESTAssert.java
RESTAssert.assertPattern
public static void assertPattern(String string, String pattern, final StatusType status) { """ assert that string matches the given pattern @param string the string to check @param status the status code to throw @throws WebApplicationException with given status code """ RESTAssert.assertNotNull(string); RESTAssert.assertNotNull(pattern); RESTAssert.assertTrue(string.matches(pattern), status); }
java
public static void assertPattern(String string, String pattern, final StatusType status) { RESTAssert.assertNotNull(string); RESTAssert.assertNotNull(pattern); RESTAssert.assertTrue(string.matches(pattern), status); }
[ "public", "static", "void", "assertPattern", "(", "String", "string", ",", "String", "pattern", ",", "final", "StatusType", "status", ")", "{", "RESTAssert", ".", "assertNotNull", "(", "string", ")", ";", "RESTAssert", ".", "assertNotNull", "(", "pattern", ")"...
assert that string matches the given pattern @param string the string to check @param status the status code to throw @throws WebApplicationException with given status code
[ "assert", "that", "string", "matches", "the", "given", "pattern" ]
train
https://github.com/taimos/RESTUtils/blob/bdb1bf9a2eb13ede0eec6f071c10cb2698313501/src/main/java/de/taimos/restutils/RESTAssert.java#L300-L304
OpenLiberty/open-liberty
dev/com.ibm.ws.security.client/src/com/ibm/ws/security/client/internal/jaas/JAASClientConfigurationImpl.java
JAASClientConfigurationImpl.createAppConfigurationEntry
public AppConfigurationEntry createAppConfigurationEntry(JAASLoginModuleConfig loginModule, String loginContextEntryName) { """ Create an AppConfigurationEntry object for the given JAAS login module @param loginModule the JAAS login module @param loginContextEntryName the JAAS login context entry name referencing the login module @return the AppConfigurationEntry object @throws IllegalArgumentException if loginModuleName is null, if LoginModuleName has a length of 0, if controlFlag is not either REQUIRED, REQUISITE, SUFFICIENT or OPTIONAL, or if options is null. """ String loginModuleClassName = loginModule.getClassName(); LoginModuleControlFlag controlFlag = loginModule.getControlFlag(); Map<String, Object> options = new HashMap<String, Object>(); options.putAll(loginModule.getOptions()); if (JaasLoginConfigConstants.APPLICATION_WSLOGIN.equals(loginContextEntryName)) { options.put(WAS_IGNORE_CLIENT_CONTAINER_DD, true); } else { options.put(WAS_IGNORE_CLIENT_CONTAINER_DD, false); } if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "loginModuleClassName: " + loginModuleClassName + " options: " + options.toString() + " controlFlag: " + controlFlag.toString()); } AppConfigurationEntry loginModuleEntry = new AppConfigurationEntry(loginModuleClassName, controlFlag, options); return loginModuleEntry; }
java
public AppConfigurationEntry createAppConfigurationEntry(JAASLoginModuleConfig loginModule, String loginContextEntryName) { String loginModuleClassName = loginModule.getClassName(); LoginModuleControlFlag controlFlag = loginModule.getControlFlag(); Map<String, Object> options = new HashMap<String, Object>(); options.putAll(loginModule.getOptions()); if (JaasLoginConfigConstants.APPLICATION_WSLOGIN.equals(loginContextEntryName)) { options.put(WAS_IGNORE_CLIENT_CONTAINER_DD, true); } else { options.put(WAS_IGNORE_CLIENT_CONTAINER_DD, false); } if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "loginModuleClassName: " + loginModuleClassName + " options: " + options.toString() + " controlFlag: " + controlFlag.toString()); } AppConfigurationEntry loginModuleEntry = new AppConfigurationEntry(loginModuleClassName, controlFlag, options); return loginModuleEntry; }
[ "public", "AppConfigurationEntry", "createAppConfigurationEntry", "(", "JAASLoginModuleConfig", "loginModule", ",", "String", "loginContextEntryName", ")", "{", "String", "loginModuleClassName", "=", "loginModule", ".", "getClassName", "(", ")", ";", "LoginModuleControlFlag",...
Create an AppConfigurationEntry object for the given JAAS login module @param loginModule the JAAS login module @param loginContextEntryName the JAAS login context entry name referencing the login module @return the AppConfigurationEntry object @throws IllegalArgumentException if loginModuleName is null, if LoginModuleName has a length of 0, if controlFlag is not either REQUIRED, REQUISITE, SUFFICIENT or OPTIONAL, or if options is null.
[ "Create", "an", "AppConfigurationEntry", "object", "for", "the", "given", "JAAS", "login", "module" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.client/src/com/ibm/ws/security/client/internal/jaas/JAASClientConfigurationImpl.java#L122-L139
Netflix/conductor
client/src/main/java/com/netflix/conductor/client/http/ClientBase.java
ClientBase.downloadFromExternalStorage
@SuppressWarnings("unchecked") protected Map<String, Object> downloadFromExternalStorage(ExternalPayloadStorage.PayloadType payloadType, String path) { """ Uses the {@link PayloadStorage} for downloading large payloads to be used by the client. Gets the uri of the payload fom the server and then downloads from this location. @param payloadType the {@link com.netflix.conductor.common.utils.ExternalPayloadStorage.PayloadType} to be downloaded @param path the relative of the payload in external storage @return the payload object that is stored in external storage """ Preconditions.checkArgument(StringUtils.isNotBlank(path), "uri cannot be blank"); ExternalStorageLocation externalStorageLocation = payloadStorage.getLocation(ExternalPayloadStorage.Operation.READ, payloadType, path); try (InputStream inputStream = payloadStorage.download(externalStorageLocation.getUri())) { return objectMapper.readValue(inputStream, Map.class); } catch (IOException e) { String errorMsg = String.format("Unable to download payload from external storage location: %s", path); logger.error(errorMsg, e); throw new ConductorClientException(errorMsg, e); } }
java
@SuppressWarnings("unchecked") protected Map<String, Object> downloadFromExternalStorage(ExternalPayloadStorage.PayloadType payloadType, String path) { Preconditions.checkArgument(StringUtils.isNotBlank(path), "uri cannot be blank"); ExternalStorageLocation externalStorageLocation = payloadStorage.getLocation(ExternalPayloadStorage.Operation.READ, payloadType, path); try (InputStream inputStream = payloadStorage.download(externalStorageLocation.getUri())) { return objectMapper.readValue(inputStream, Map.class); } catch (IOException e) { String errorMsg = String.format("Unable to download payload from external storage location: %s", path); logger.error(errorMsg, e); throw new ConductorClientException(errorMsg, e); } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "protected", "Map", "<", "String", ",", "Object", ">", "downloadFromExternalStorage", "(", "ExternalPayloadStorage", ".", "PayloadType", "payloadType", ",", "String", "path", ")", "{", "Preconditions", ".", "checkA...
Uses the {@link PayloadStorage} for downloading large payloads to be used by the client. Gets the uri of the payload fom the server and then downloads from this location. @param payloadType the {@link com.netflix.conductor.common.utils.ExternalPayloadStorage.PayloadType} to be downloaded @param path the relative of the payload in external storage @return the payload object that is stored in external storage
[ "Uses", "the", "{", "@link", "PayloadStorage", "}", "for", "downloading", "large", "payloads", "to", "be", "used", "by", "the", "client", ".", "Gets", "the", "uri", "of", "the", "payload", "fom", "the", "server", "and", "then", "downloads", "from", "this",...
train
https://github.com/Netflix/conductor/blob/78fae0ed9ddea22891f9eebb96a2ec0b2783dca0/client/src/main/java/com/netflix/conductor/client/http/ClientBase.java#L219-L230
GeoLatte/geolatte-common
src/main/java/org/geolatte/common/dataformats/json/jackson/GeometrySerializer.java
GeometrySerializer.writeCrs
protected void writeCrs(JsonGenerator jgen, Geometry shape) throws IOException { """ Writes out the crs information in the GeoJSON string @param jgen the jsongenerator used for the geojson construction @param shape the geometry for which the contents is to be retrieved @throws java.io.IOException If the underlying jsongenerator fails writing the contents """ /* "crs": { "type": "name", "properties": { "name": "EPSG:xxxx" } } */ if (shape.getSRID() > 0) { jgen.writeFieldName("crs"); jgen.writeStartObject(); jgen.writeStringField("type", "name"); jgen.writeFieldName("properties"); jgen.writeStartObject(); jgen.writeStringField("name", "EPSG:" + shape.getSRID()); jgen.writeEndObject(); jgen.writeEndObject(); } }
java
protected void writeCrs(JsonGenerator jgen, Geometry shape) throws IOException { /* "crs": { "type": "name", "properties": { "name": "EPSG:xxxx" } } */ if (shape.getSRID() > 0) { jgen.writeFieldName("crs"); jgen.writeStartObject(); jgen.writeStringField("type", "name"); jgen.writeFieldName("properties"); jgen.writeStartObject(); jgen.writeStringField("name", "EPSG:" + shape.getSRID()); jgen.writeEndObject(); jgen.writeEndObject(); } }
[ "protected", "void", "writeCrs", "(", "JsonGenerator", "jgen", ",", "Geometry", "shape", ")", "throws", "IOException", "{", "/*\n \"crs\": {\n \"type\": \"name\",\n \"properties\": {\n \"name\": \"EPSG:xxxx\"\n }\n }...
Writes out the crs information in the GeoJSON string @param jgen the jsongenerator used for the geojson construction @param shape the geometry for which the contents is to be retrieved @throws java.io.IOException If the underlying jsongenerator fails writing the contents
[ "Writes", "out", "the", "crs", "information", "in", "the", "GeoJSON", "string" ]
train
https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/dataformats/json/jackson/GeometrySerializer.java#L125-L145
undertow-io/undertow
core/src/main/java/io/undertow/server/HttpServerExchange.java
HttpServerExchange.upgradeChannel
public HttpServerExchange upgradeChannel(String productName, final HttpUpgradeListener listener) { """ Upgrade the channel to a raw socket. This method set the response code to 101, and then marks both the request and response as terminated, which means that once the current request is completed the raw channel can be obtained from {@link io.undertow.server.protocol.http.HttpServerConnection#getChannel()} @param productName the product name to report to the client @throws IllegalStateException if a response or upgrade was already sent, or if the request body is already being read """ if (!connection.isUpgradeSupported()) { throw UndertowMessages.MESSAGES.upgradeNotSupported(); } UndertowLogger.REQUEST_LOGGER.debugf("Upgrading request %s", this); connection.setUpgradeListener(listener); setStatusCode(StatusCodes.SWITCHING_PROTOCOLS); final HeaderMap headers = getResponseHeaders(); headers.put(Headers.UPGRADE, productName); headers.put(Headers.CONNECTION, Headers.UPGRADE_STRING); return this; }
java
public HttpServerExchange upgradeChannel(String productName, final HttpUpgradeListener listener) { if (!connection.isUpgradeSupported()) { throw UndertowMessages.MESSAGES.upgradeNotSupported(); } UndertowLogger.REQUEST_LOGGER.debugf("Upgrading request %s", this); connection.setUpgradeListener(listener); setStatusCode(StatusCodes.SWITCHING_PROTOCOLS); final HeaderMap headers = getResponseHeaders(); headers.put(Headers.UPGRADE, productName); headers.put(Headers.CONNECTION, Headers.UPGRADE_STRING); return this; }
[ "public", "HttpServerExchange", "upgradeChannel", "(", "String", "productName", ",", "final", "HttpUpgradeListener", "listener", ")", "{", "if", "(", "!", "connection", ".", "isUpgradeSupported", "(", ")", ")", "{", "throw", "UndertowMessages", ".", "MESSAGES", "....
Upgrade the channel to a raw socket. This method set the response code to 101, and then marks both the request and response as terminated, which means that once the current request is completed the raw channel can be obtained from {@link io.undertow.server.protocol.http.HttpServerConnection#getChannel()} @param productName the product name to report to the client @throws IllegalStateException if a response or upgrade was already sent, or if the request body is already being read
[ "Upgrade", "the", "channel", "to", "a", "raw", "socket", ".", "This", "method", "set", "the", "response", "code", "to", "101", "and", "then", "marks", "both", "the", "request", "and", "response", "as", "terminated", "which", "means", "that", "once", "the",...
train
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/HttpServerExchange.java#L912-L923
facebookarchive/hadoop-20
src/contrib/corona/src/java/org/apache/hadoop/corona/TFactoryBasedThreadPoolServer.java
TFactoryBasedThreadPoolServer.createNewServer
public static TFactoryBasedThreadPoolServer createNewServer( TProcessor processor, ServerSocket serverSocket, int socketTimeOut) throws IOException { """ This is a helper method which creates a TFactoryBased..Server object using the processor, ServerSocket object and socket timeout limit. This is useful when we change the mechanism of server object creation. As a result, we don't have to change code in multiple places. @param processor @param serverSocket @param socketTimeOut @return A TFactoryBasedThreadPoolServer object @throws IOException """ TServerSocket socket = new TServerSocket(serverSocket, socketTimeOut); TFactoryBasedThreadPoolServer.Args args = new TFactoryBasedThreadPoolServer.Args(socket); args.stopTimeoutVal = 0; args.processor(processor); args.transportFactory(new TFramedTransport.Factory()); args.protocolFactory(new TBinaryProtocol.Factory(true, true)); return new TFactoryBasedThreadPoolServer( args, new TFactoryBasedThreadPoolServer.DaemonThreadFactory()); }
java
public static TFactoryBasedThreadPoolServer createNewServer( TProcessor processor, ServerSocket serverSocket, int socketTimeOut) throws IOException { TServerSocket socket = new TServerSocket(serverSocket, socketTimeOut); TFactoryBasedThreadPoolServer.Args args = new TFactoryBasedThreadPoolServer.Args(socket); args.stopTimeoutVal = 0; args.processor(processor); args.transportFactory(new TFramedTransport.Factory()); args.protocolFactory(new TBinaryProtocol.Factory(true, true)); return new TFactoryBasedThreadPoolServer( args, new TFactoryBasedThreadPoolServer.DaemonThreadFactory()); }
[ "public", "static", "TFactoryBasedThreadPoolServer", "createNewServer", "(", "TProcessor", "processor", ",", "ServerSocket", "serverSocket", ",", "int", "socketTimeOut", ")", "throws", "IOException", "{", "TServerSocket", "socket", "=", "new", "TServerSocket", "(", "ser...
This is a helper method which creates a TFactoryBased..Server object using the processor, ServerSocket object and socket timeout limit. This is useful when we change the mechanism of server object creation. As a result, we don't have to change code in multiple places. @param processor @param serverSocket @param socketTimeOut @return A TFactoryBasedThreadPoolServer object @throws IOException
[ "This", "is", "a", "helper", "method", "which", "creates", "a", "TFactoryBased", "..", "Server", "object", "using", "the", "processor", "ServerSocket", "object", "and", "socket", "timeout", "limit", ".", "This", "is", "useful", "when", "we", "change", "the", ...
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/corona/src/java/org/apache/hadoop/corona/TFactoryBasedThreadPoolServer.java#L49-L62
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/math/CombinationGeneratorFlexible.java
CombinationGeneratorFlexible.iterateAllCombinations
public void iterateAllCombinations (@Nonnull final ICommonsList <DATATYPE> aElements, @Nonnull final Consumer <? super ICommonsList <DATATYPE>> aCallback) { """ Iterate all combination, no matter they are unique or not. @param aElements List of elements. @param aCallback Callback to invoke """ ValueEnforcer.notNull (aElements, "Elements"); ValueEnforcer.notNull (aCallback, "Callback"); for (int nSlotCount = m_bAllowEmpty ? 0 : 1; nSlotCount <= m_nSlotCount; nSlotCount++) { if (aElements.isEmpty ()) { aCallback.accept (new CommonsArrayList <> ()); } else { // Add all permutations for the current slot count for (final ICommonsList <DATATYPE> aPermutation : new CombinationGenerator <> (aElements, nSlotCount)) aCallback.accept (aPermutation); } } }
java
public void iterateAllCombinations (@Nonnull final ICommonsList <DATATYPE> aElements, @Nonnull final Consumer <? super ICommonsList <DATATYPE>> aCallback) { ValueEnforcer.notNull (aElements, "Elements"); ValueEnforcer.notNull (aCallback, "Callback"); for (int nSlotCount = m_bAllowEmpty ? 0 : 1; nSlotCount <= m_nSlotCount; nSlotCount++) { if (aElements.isEmpty ()) { aCallback.accept (new CommonsArrayList <> ()); } else { // Add all permutations for the current slot count for (final ICommonsList <DATATYPE> aPermutation : new CombinationGenerator <> (aElements, nSlotCount)) aCallback.accept (aPermutation); } } }
[ "public", "void", "iterateAllCombinations", "(", "@", "Nonnull", "final", "ICommonsList", "<", "DATATYPE", ">", "aElements", ",", "@", "Nonnull", "final", "Consumer", "<", "?", "super", "ICommonsList", "<", "DATATYPE", ">", ">", "aCallback", ")", "{", "ValueEn...
Iterate all combination, no matter they are unique or not. @param aElements List of elements. @param aCallback Callback to invoke
[ "Iterate", "all", "combination", "no", "matter", "they", "are", "unique", "or", "not", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/math/CombinationGeneratorFlexible.java#L73-L92
Javacord/Javacord
javacord-api/src/main/java/org/javacord/api/entity/message/MessageBuilder.java
MessageBuilder.addAttachment
public MessageBuilder addAttachment(BufferedImage image, String fileName) { """ Adds an attachment to the message. @param image The image to add as an attachment. @param fileName The file name of the image. @return The current instance in order to chain call methods. """ delegate.addAttachment(image, fileName); return this; }
java
public MessageBuilder addAttachment(BufferedImage image, String fileName) { delegate.addAttachment(image, fileName); return this; }
[ "public", "MessageBuilder", "addAttachment", "(", "BufferedImage", "image", ",", "String", "fileName", ")", "{", "delegate", ".", "addAttachment", "(", "image", ",", "fileName", ")", ";", "return", "this", ";", "}" ]
Adds an attachment to the message. @param image The image to add as an attachment. @param fileName The file name of the image. @return The current instance in order to chain call methods.
[ "Adds", "an", "attachment", "to", "the", "message", "." ]
train
https://github.com/Javacord/Javacord/blob/915aad084dc5e863284267529d0dccd625fc6886/javacord-api/src/main/java/org/javacord/api/entity/message/MessageBuilder.java#L295-L298
knightliao/disconf
disconf-web/src/main/java/com/baidu/unbiz/common/genericdao/dao/GenericDao.java
GenericDao.find
public List<ENTITY> find(String column, Object value) { """ 获取查询结果 @param column 条件字段 @param value 条件字段的值。支持集合对象,支持数组,会按照in 操作来组装条件 @return """ return find(Operators.match(column, value)); }
java
public List<ENTITY> find(String column, Object value) { return find(Operators.match(column, value)); }
[ "public", "List", "<", "ENTITY", ">", "find", "(", "String", "column", ",", "Object", "value", ")", "{", "return", "find", "(", "Operators", ".", "match", "(", "column", ",", "value", ")", ")", ";", "}" ]
获取查询结果 @param column 条件字段 @param value 条件字段的值。支持集合对象,支持数组,会按照in 操作来组装条件 @return
[ "获取查询结果" ]
train
https://github.com/knightliao/disconf/blob/d413cbce9334fe38a5a24982ce4db3a6ed8e98ea/disconf-web/src/main/java/com/baidu/unbiz/common/genericdao/dao/GenericDao.java#L278-L280
iig-uni-freiburg/SEWOL
ext/org/deckfour/xes/extension/std/XOrganizationalExtension.java
XOrganizationalExtension.assignResource
public void assignResource(XEvent event, String resource) { """ Assigns the resource attribute value for a given event. @param event Event to be modified. @param resource Resource string to be assigned. """ if (resource != null && resource.trim().length() > 0) { XAttributeLiteral attr = (XAttributeLiteral) ATTR_RESOURCE.clone(); attr.setValue(resource.trim()); event.getAttributes().put(KEY_RESOURCE, attr); } }
java
public void assignResource(XEvent event, String resource) { if (resource != null && resource.trim().length() > 0) { XAttributeLiteral attr = (XAttributeLiteral) ATTR_RESOURCE.clone(); attr.setValue(resource.trim()); event.getAttributes().put(KEY_RESOURCE, attr); } }
[ "public", "void", "assignResource", "(", "XEvent", "event", ",", "String", "resource", ")", "{", "if", "(", "resource", "!=", "null", "&&", "resource", ".", "trim", "(", ")", ".", "length", "(", ")", ">", "0", ")", "{", "XAttributeLiteral", "attr", "="...
Assigns the resource attribute value for a given event. @param event Event to be modified. @param resource Resource string to be assigned.
[ "Assigns", "the", "resource", "attribute", "value", "for", "a", "given", "event", "." ]
train
https://github.com/iig-uni-freiburg/SEWOL/blob/e791cb07a6e62ecf837d760d58a25f32fbf6bbca/ext/org/deckfour/xes/extension/std/XOrganizationalExtension.java#L195-L201
comapi/comapi-sdk-android
COMAPI/foundation/src/main/java/com/comapi/internal/network/InternalService.java
InternalService.addParticipants
public void addParticipants(@NonNull final String conversationId, @NonNull final List<Participant> participants, @Nullable Callback<ComapiResult<Void>> callback) { """ Returns observable to add a list of participants to a conversation. @param conversationId ID of a conversation to update. @param participants New conversation participants details. @param callback Callback to deliver new session instance. """ adapter.adapt(addParticipants(conversationId, participants), callback); }
java
public void addParticipants(@NonNull final String conversationId, @NonNull final List<Participant> participants, @Nullable Callback<ComapiResult<Void>> callback) { adapter.adapt(addParticipants(conversationId, participants), callback); }
[ "public", "void", "addParticipants", "(", "@", "NonNull", "final", "String", "conversationId", ",", "@", "NonNull", "final", "List", "<", "Participant", ">", "participants", ",", "@", "Nullable", "Callback", "<", "ComapiResult", "<", "Void", ">", ">", "callbac...
Returns observable to add a list of participants to a conversation. @param conversationId ID of a conversation to update. @param participants New conversation participants details. @param callback Callback to deliver new session instance.
[ "Returns", "observable", "to", "add", "a", "list", "of", "participants", "to", "a", "conversation", "." ]
train
https://github.com/comapi/comapi-sdk-android/blob/53140a58d5a62afe196047ccc5120bfe090ef211/COMAPI/foundation/src/main/java/com/comapi/internal/network/InternalService.java#L686-L688
ical4j/ical4j
src/main/java/net/fortuna/ical4j/validate/PropertyValidator.java
PropertyValidator.assertNone
public void assertNone(final String propertyName, final PropertyList properties) throws ValidationException { """ Ensure a property doesn't occur in the specified list. @param propertyName the name of a property @param properties a list of properties @throws ValidationException thrown when the specified property is found in the list of properties """ if (properties.getProperty(propertyName) != null) { throw new ValidationException(ASSERT_NONE_MESSAGE, new Object[] {propertyName}); } }
java
public void assertNone(final String propertyName, final PropertyList properties) throws ValidationException { if (properties.getProperty(propertyName) != null) { throw new ValidationException(ASSERT_NONE_MESSAGE, new Object[] {propertyName}); } }
[ "public", "void", "assertNone", "(", "final", "String", "propertyName", ",", "final", "PropertyList", "properties", ")", "throws", "ValidationException", "{", "if", "(", "properties", ".", "getProperty", "(", "propertyName", ")", "!=", "null", ")", "{", "throw",...
Ensure a property doesn't occur in the specified list. @param propertyName the name of a property @param properties a list of properties @throws ValidationException thrown when the specified property is found in the list of properties
[ "Ensure", "a", "property", "doesn", "t", "occur", "in", "the", "specified", "list", "." ]
train
https://github.com/ical4j/ical4j/blob/7ac4bd1ce2bb2e0a2906fb69a56fbd2d9d974156/src/main/java/net/fortuna/ical4j/validate/PropertyValidator.java#L122-L126
SahaginOrg/sahagin-java
src/main/java/org/sahagin/runlib/runresultsgen/RunResultsGenerateHookSetter.java
RunResultsGenerateHookSetter.beforeHookInsertLine
private int beforeHookInsertLine(TestMethod method, int codeLineIndex) { """ Returns -1 if beforeHook for the codeLineIndex should not be inserted """ if (!isLineLastStament(method, codeLineIndex)) { // don't insert the beforeHook since afterHook does not inserted to this line return -1; } // so that not to insert the hook to the middle of the line, // search the line top statement and insert hook to the statement line for (int i = codeLineIndex; i > 0; i--) { CodeLine thisLine = method.getCodeBody().get(i); CodeLine prevLine = method.getCodeBody().get(i - 1); assert prevLine.getEndLine() <= thisLine.getEndLine(); if (prevLine.getEndLine() != thisLine.getStartLine()) { return thisLine.getStartLine(); } } return method.getCodeBody().get(0).getStartLine(); }
java
private int beforeHookInsertLine(TestMethod method, int codeLineIndex) { if (!isLineLastStament(method, codeLineIndex)) { // don't insert the beforeHook since afterHook does not inserted to this line return -1; } // so that not to insert the hook to the middle of the line, // search the line top statement and insert hook to the statement line for (int i = codeLineIndex; i > 0; i--) { CodeLine thisLine = method.getCodeBody().get(i); CodeLine prevLine = method.getCodeBody().get(i - 1); assert prevLine.getEndLine() <= thisLine.getEndLine(); if (prevLine.getEndLine() != thisLine.getStartLine()) { return thisLine.getStartLine(); } } return method.getCodeBody().get(0).getStartLine(); }
[ "private", "int", "beforeHookInsertLine", "(", "TestMethod", "method", ",", "int", "codeLineIndex", ")", "{", "if", "(", "!", "isLineLastStament", "(", "method", ",", "codeLineIndex", ")", ")", "{", "// don't insert the beforeHook since afterHook does not inserted to this...
Returns -1 if beforeHook for the codeLineIndex should not be inserted
[ "Returns", "-", "1", "if", "beforeHook", "for", "the", "codeLineIndex", "should", "not", "be", "inserted" ]
train
https://github.com/SahaginOrg/sahagin-java/blob/7ace428adebe3466ceb5826bc9681f8e3d52be68/src/main/java/org/sahagin/runlib/runresultsgen/RunResultsGenerateHookSetter.java#L128-L145
OpenLiberty/open-liberty
dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ws/ejbcontainer/jitdeploy/EJBWrapper.java
EJBWrapper.addAfterDeliveryMethod
private static void addAfterDeliveryMethod(ClassWriter cw, String implClassName) { """ Adds a definition for an afterDelivery() wrapper method that invokes MessageEndpointBase.afterDelivery(). It is only needed for no-method Interface MDB's. Otherwise, MessageEndpointBase.afterDelivery() is inherited. @param cw ASM ClassWriter to add the method to. @param implClassName name of the wrapper class being generated. """ if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, INDENT + "adding method : afterDelivery ()V"); // ----------------------------------------------------------------------- // public void afterDelivery() throws ResourceException // { // ----------------------------------------------------------------------- final String desc = "()V"; MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "afterDelivery", desc, null, new String[] { "javax/resource/ResourceException" }); GeneratorAdapter mg = new GeneratorAdapter(mv, ACC_PUBLIC, "afterDelivery", desc); mg.visitCode(); // ----------------------------------------------------------------------- // this.ivMessageEndpointBase.afterDelivery(); // ----------------------------------------------------------------------- mg.loadThis(); mg.visitFieldInsn(GETFIELD, implClassName, MESSAGE_ENDPOINT_BASE_FIELD, MESSAGE_ENDPOINT_BASE_FIELD_TYPE); mg.visitMethodInsn(INVOKEVIRTUAL, MESSAGE_ENDPOINT_BASE_STRING, "afterDelivery", desc); mg.returnValue(); // ----------------------------------------------------------------------- // } // ----------------------------------------------------------------------- mg.endMethod(); mg.visitEnd(); }
java
private static void addAfterDeliveryMethod(ClassWriter cw, String implClassName) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, INDENT + "adding method : afterDelivery ()V"); // ----------------------------------------------------------------------- // public void afterDelivery() throws ResourceException // { // ----------------------------------------------------------------------- final String desc = "()V"; MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "afterDelivery", desc, null, new String[] { "javax/resource/ResourceException" }); GeneratorAdapter mg = new GeneratorAdapter(mv, ACC_PUBLIC, "afterDelivery", desc); mg.visitCode(); // ----------------------------------------------------------------------- // this.ivMessageEndpointBase.afterDelivery(); // ----------------------------------------------------------------------- mg.loadThis(); mg.visitFieldInsn(GETFIELD, implClassName, MESSAGE_ENDPOINT_BASE_FIELD, MESSAGE_ENDPOINT_BASE_FIELD_TYPE); mg.visitMethodInsn(INVOKEVIRTUAL, MESSAGE_ENDPOINT_BASE_STRING, "afterDelivery", desc); mg.returnValue(); // ----------------------------------------------------------------------- // } // ----------------------------------------------------------------------- mg.endMethod(); mg.visitEnd(); }
[ "private", "static", "void", "addAfterDeliveryMethod", "(", "ClassWriter", "cw", ",", "String", "implClassName", ")", "{", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isDebugEnabled", "(", ")", ")", "Tr", ".", "debug", ...
Adds a definition for an afterDelivery() wrapper method that invokes MessageEndpointBase.afterDelivery(). It is only needed for no-method Interface MDB's. Otherwise, MessageEndpointBase.afterDelivery() is inherited. @param cw ASM ClassWriter to add the method to. @param implClassName name of the wrapper class being generated.
[ "Adds", "a", "definition", "for", "an", "afterDelivery", "()", "wrapper", "method", "that", "invokes", "MessageEndpointBase", ".", "afterDelivery", "()", ".", "It", "is", "only", "needed", "for", "no", "-", "method", "Interface", "MDB", "s", ".", "Otherwise", ...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ws/ejbcontainer/jitdeploy/EJBWrapper.java#L811-L842
btc-ag/redg
redg-runtime/src/main/java/com/btc/redg/runtime/jdbc/RedGDatabaseUtil.java
RedGDatabaseUtil.distinctByKey
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) { """ Taken from http://stackoverflow.com/a/27872852 @param keyExtractor The key extractor function @param <T> the generic type @return a predicate for filtering """ final Map<Object, Boolean> seen = new ConcurrentHashMap<>(); return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null; }
java
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) { final Map<Object, Boolean> seen = new ConcurrentHashMap<>(); return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null; }
[ "public", "static", "<", "T", ">", "Predicate", "<", "T", ">", "distinctByKey", "(", "Function", "<", "?", "super", "T", ",", "?", ">", "keyExtractor", ")", "{", "final", "Map", "<", "Object", ",", "Boolean", ">", "seen", "=", "new", "ConcurrentHashMap...
Taken from http://stackoverflow.com/a/27872852 @param keyExtractor The key extractor function @param <T> the generic type @return a predicate for filtering
[ "Taken", "from", "http", ":", "//", "stackoverflow", ".", "com", "/", "a", "/", "27872852" ]
train
https://github.com/btc-ag/redg/blob/416a68639d002512cabfebff09afd2e1909e27df/redg-runtime/src/main/java/com/btc/redg/runtime/jdbc/RedGDatabaseUtil.java#L147-L150
jwtk/jjwt
impl/src/main/java/io/jsonwebtoken/impl/crypto/RsaProvider.java
RsaProvider.generateKeyPair
protected static KeyPair generateKeyPair(String jcaAlgorithmName, int keySizeInBits, SecureRandom random) { """ Generates a new secure-random key pair of the specified size using the specified SecureRandom according to the specified {@code jcaAlgorithmName}. @param jcaAlgorithmName the name of the JCA algorithm to use for key pair generation, for example, {@code RSA}. @param keySizeInBits the key size in bits (<em>NOT bytes</em>) @param random the SecureRandom generator to use during key generation. @return a new secure-randomly generated key pair of the specified size using the specified SecureRandom according to the specified {@code jcaAlgorithmName}. @see #generateKeyPair() @see #generateKeyPair(int) @see #generateKeyPair(int, SecureRandom) @since 0.5 """ KeyPairGenerator keyGenerator; try { keyGenerator = KeyPairGenerator.getInstance(jcaAlgorithmName); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("Unable to obtain an RSA KeyPairGenerator: " + e.getMessage(), e); } keyGenerator.initialize(keySizeInBits, random); return keyGenerator.genKeyPair(); }
java
protected static KeyPair generateKeyPair(String jcaAlgorithmName, int keySizeInBits, SecureRandom random) { KeyPairGenerator keyGenerator; try { keyGenerator = KeyPairGenerator.getInstance(jcaAlgorithmName); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("Unable to obtain an RSA KeyPairGenerator: " + e.getMessage(), e); } keyGenerator.initialize(keySizeInBits, random); return keyGenerator.genKeyPair(); }
[ "protected", "static", "KeyPair", "generateKeyPair", "(", "String", "jcaAlgorithmName", ",", "int", "keySizeInBits", ",", "SecureRandom", "random", ")", "{", "KeyPairGenerator", "keyGenerator", ";", "try", "{", "keyGenerator", "=", "KeyPairGenerator", ".", "getInstanc...
Generates a new secure-random key pair of the specified size using the specified SecureRandom according to the specified {@code jcaAlgorithmName}. @param jcaAlgorithmName the name of the JCA algorithm to use for key pair generation, for example, {@code RSA}. @param keySizeInBits the key size in bits (<em>NOT bytes</em>) @param random the SecureRandom generator to use during key generation. @return a new secure-randomly generated key pair of the specified size using the specified SecureRandom according to the specified {@code jcaAlgorithmName}. @see #generateKeyPair() @see #generateKeyPair(int) @see #generateKeyPair(int, SecureRandom) @since 0.5
[ "Generates", "a", "new", "secure", "-", "random", "key", "pair", "of", "the", "specified", "size", "using", "the", "specified", "SecureRandom", "according", "to", "the", "specified", "{", "@code", "jcaAlgorithmName", "}", "." ]
train
https://github.com/jwtk/jjwt/blob/86b6096946752cffcfbc9b0a5503f1ea195cc140/impl/src/main/java/io/jsonwebtoken/impl/crypto/RsaProvider.java#L183-L194
brianm/gressil
src/main/java/org/skife/gressil/Daemon.java
Daemon.checkStatus
public DaemonStatus checkStatus() { """ 0 program is running or service is OK 1 program is dead and /var/run pid file exists 2 program is dead and /var/lock lock file exists 3 program is not running 4 program or service status is unknown 5-99 reserved for future LSB use 100-149 reserved for distribution use 150-199 reserved for application use 200-254 reserved """ if (this.pidfile == null) { throw new IllegalStateException("No pidfile specified, cannot check status!"); } if (!pidfile.exists()) { return DaemonStatus.STATUS_NOT_RUNNING; } final int pid; try { byte[] content = Files.readAllBytes(pidfile.toPath()); String s = new String(content, StandardCharsets.UTF_8).trim(); pid = Integer.parseInt(s); } catch (Exception e) { System.err.println(e.getMessage()); return DaemonStatus.STATUS_UNKNOWN; } int rs = posix.kill(pid, 0); if (rs == 0) { return DaemonStatus.STATUS_RUNNING; } else { return DaemonStatus.STATUS_DEAD; } }
java
public DaemonStatus checkStatus() { if (this.pidfile == null) { throw new IllegalStateException("No pidfile specified, cannot check status!"); } if (!pidfile.exists()) { return DaemonStatus.STATUS_NOT_RUNNING; } final int pid; try { byte[] content = Files.readAllBytes(pidfile.toPath()); String s = new String(content, StandardCharsets.UTF_8).trim(); pid = Integer.parseInt(s); } catch (Exception e) { System.err.println(e.getMessage()); return DaemonStatus.STATUS_UNKNOWN; } int rs = posix.kill(pid, 0); if (rs == 0) { return DaemonStatus.STATUS_RUNNING; } else { return DaemonStatus.STATUS_DEAD; } }
[ "public", "DaemonStatus", "checkStatus", "(", ")", "{", "if", "(", "this", ".", "pidfile", "==", "null", ")", "{", "throw", "new", "IllegalStateException", "(", "\"No pidfile specified, cannot check status!\"", ")", ";", "}", "if", "(", "!", "pidfile", ".", "e...
0 program is running or service is OK 1 program is dead and /var/run pid file exists 2 program is dead and /var/lock lock file exists 3 program is not running 4 program or service status is unknown 5-99 reserved for future LSB use 100-149 reserved for distribution use 150-199 reserved for application use 200-254 reserved
[ "0", "program", "is", "running", "or", "service", "is", "OK", "1", "program", "is", "dead", "and", "/", "var", "/", "run", "pid", "file", "exists", "2", "program", "is", "dead", "and", "/", "var", "/", "lock", "lock", "file", "exists", "3", "program"...
train
https://github.com/brianm/gressil/blob/8530929f1f8a3807b76f2cc93dc80c3997aa6b21/src/main/java/org/skife/gressil/Daemon.java#L242-L273
Baidu-AIP/java-sdk
src/main/java/com/baidu/aip/face/AipFace.java
AipFace.faceDelete
public JSONObject faceDelete(String userId, String groupId, String faceToken, HashMap<String, String> options) { """ 人脸删除接口 @param userId - 用户id(由数字、字母、下划线组成),长度限制128B @param groupId - 用户组id(由数字、字母、下划线组成),长度限制128B @param faceToken - 需要删除的人脸图片token,(由数字、字母、下划线组成)长度限制64B @param options - 可选参数对象,key: value都为string类型 options - options列表: @return JSONObject """ AipRequest request = new AipRequest(); preOperation(request); request.addBody("user_id", userId); request.addBody("group_id", groupId); request.addBody("face_token", faceToken); if (options != null) { request.addBody(options); } request.setUri(FaceConsts.FACE_DELETE); request.setBodyFormat(EBodyFormat.RAW_JSON); postOperation(request); return requestServer(request); }
java
public JSONObject faceDelete(String userId, String groupId, String faceToken, HashMap<String, String> options) { AipRequest request = new AipRequest(); preOperation(request); request.addBody("user_id", userId); request.addBody("group_id", groupId); request.addBody("face_token", faceToken); if (options != null) { request.addBody(options); } request.setUri(FaceConsts.FACE_DELETE); request.setBodyFormat(EBodyFormat.RAW_JSON); postOperation(request); return requestServer(request); }
[ "public", "JSONObject", "faceDelete", "(", "String", "userId", ",", "String", "groupId", ",", "String", "faceToken", ",", "HashMap", "<", "String", ",", "String", ">", "options", ")", "{", "AipRequest", "request", "=", "new", "AipRequest", "(", ")", ";", "...
人脸删除接口 @param userId - 用户id(由数字、字母、下划线组成),长度限制128B @param groupId - 用户组id(由数字、字母、下划线组成),长度限制128B @param faceToken - 需要删除的人脸图片token,(由数字、字母、下划线组成)长度限制64B @param options - 可选参数对象,key: value都为string类型 options - options列表: @return JSONObject
[ "人脸删除接口" ]
train
https://github.com/Baidu-AIP/java-sdk/blob/16bb8b7bb8f9bbcb7c8af62d0a67a1e79eecad90/src/main/java/com/baidu/aip/face/AipFace.java#L173-L189
zxing/zxing
core/src/main/java/com/google/zxing/oned/UPCEANReader.java
UPCEANReader.decodeDigit
static int decodeDigit(BitArray row, int[] counters, int rowOffset, int[][] patterns) throws NotFoundException { """ Attempts to decode a single UPC/EAN-encoded digit. @param row row of black/white values to decode @param counters the counts of runs of observed black/white/black/... values @param rowOffset horizontal offset to start decoding from @param patterns the set of patterns to use to decode -- sometimes different encodings for the digits 0-9 are used, and this indicates the encodings for 0 to 9 that should be used @return horizontal offset of first pixel beyond the decoded digit @throws NotFoundException if digit cannot be decoded """ recordPattern(row, rowOffset, counters); float bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept int bestMatch = -1; int max = patterns.length; for (int i = 0; i < max; i++) { int[] pattern = patterns[i]; float variance = patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE); if (variance < bestVariance) { bestVariance = variance; bestMatch = i; } } if (bestMatch >= 0) { return bestMatch; } else { throw NotFoundException.getNotFoundInstance(); } }
java
static int decodeDigit(BitArray row, int[] counters, int rowOffset, int[][] patterns) throws NotFoundException { recordPattern(row, rowOffset, counters); float bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept int bestMatch = -1; int max = patterns.length; for (int i = 0; i < max; i++) { int[] pattern = patterns[i]; float variance = patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE); if (variance < bestVariance) { bestVariance = variance; bestMatch = i; } } if (bestMatch >= 0) { return bestMatch; } else { throw NotFoundException.getNotFoundInstance(); } }
[ "static", "int", "decodeDigit", "(", "BitArray", "row", ",", "int", "[", "]", "counters", ",", "int", "rowOffset", ",", "int", "[", "]", "[", "]", "patterns", ")", "throws", "NotFoundException", "{", "recordPattern", "(", "row", ",", "rowOffset", ",", "c...
Attempts to decode a single UPC/EAN-encoded digit. @param row row of black/white values to decode @param counters the counts of runs of observed black/white/black/... values @param rowOffset horizontal offset to start decoding from @param patterns the set of patterns to use to decode -- sometimes different encodings for the digits 0-9 are used, and this indicates the encodings for 0 to 9 that should be used @return horizontal offset of first pixel beyond the decoded digit @throws NotFoundException if digit cannot be decoded
[ "Attempts", "to", "decode", "a", "single", "UPC", "/", "EAN", "-", "encoded", "digit", "." ]
train
https://github.com/zxing/zxing/blob/653ac2a3beb11481eff82e7d5f2bab8a745f7fac/core/src/main/java/com/google/zxing/oned/UPCEANReader.java#L361-L380
feedzai/pdb
src/main/java/com/feedzai/commons/sql/abstraction/engine/AbstractDatabaseEngine.java
AbstractDatabaseEngine.addBatch
@Override public synchronized void addBatch(final String name, final EntityEntry entry) throws DatabaseEngineException { """ Add an entry to the batch. @param name The entity name. @param entry The entry to persist. @throws DatabaseEngineException If something goes wrong while persisting data. """ try { final MappedEntity me = entities.get(name); if (me == null) { throw new DatabaseEngineException(String.format("Unknown entity '%s'", name)); } PreparedStatement ps = me.getInsert(); entityToPreparedStatement(me.getEntity(), ps, entry, true); ps.addBatch(); } catch (final Exception ex) { throw new DatabaseEngineException("Error adding to batch", ex); } }
java
@Override public synchronized void addBatch(final String name, final EntityEntry entry) throws DatabaseEngineException { try { final MappedEntity me = entities.get(name); if (me == null) { throw new DatabaseEngineException(String.format("Unknown entity '%s'", name)); } PreparedStatement ps = me.getInsert(); entityToPreparedStatement(me.getEntity(), ps, entry, true); ps.addBatch(); } catch (final Exception ex) { throw new DatabaseEngineException("Error adding to batch", ex); } }
[ "@", "Override", "public", "synchronized", "void", "addBatch", "(", "final", "String", "name", ",", "final", "EntityEntry", "entry", ")", "throws", "DatabaseEngineException", "{", "try", "{", "final", "MappedEntity", "me", "=", "entities", ".", "get", "(", "na...
Add an entry to the batch. @param name The entity name. @param entry The entry to persist. @throws DatabaseEngineException If something goes wrong while persisting data.
[ "Add", "an", "entry", "to", "the", "batch", "." ]
train
https://github.com/feedzai/pdb/blob/fe07ca08417e0ddcd620a36aa1fdbca7f338be98/src/main/java/com/feedzai/commons/sql/abstraction/engine/AbstractDatabaseEngine.java#L1026-L1045
jsonld-java/jsonld-java
core/src/main/java/com/github/jsonldjava/core/JsonLdProcessor.java
JsonLdProcessor.fromRDF
public static Object fromRDF(Object dataset, JsonLdOptions options) throws JsonLdError { """ Converts an RDF dataset to JSON-LD. @param dataset a serialized string of RDF in a format specified by the format option or an RDF dataset to convert. @param options the options to use: [format] the format if input is not an array: 'application/nquads' for N-Quads (default). [useRdfType] true to use rdf:type, false to use @type (default: false). [useNativeTypes] true to convert XSD types into native types (boolean, integer, double), false not to (default: true). @return A JSON-LD object. @throws JsonLdError If there is an error converting the dataset to JSON-LD. """ // handle non specified serializer case RDFParser parser = null; if (options.format == null && dataset instanceof String) { // attempt to parse the input as nquads options.format = JsonLdConsts.APPLICATION_NQUADS; } if (rdfParsers.containsKey(options.format)) { parser = rdfParsers.get(options.format); } else { throw new JsonLdError(JsonLdError.Error.UNKNOWN_FORMAT, options.format); } // convert from RDF return fromRDF(dataset, options, parser); }
java
public static Object fromRDF(Object dataset, JsonLdOptions options) throws JsonLdError { // handle non specified serializer case RDFParser parser = null; if (options.format == null && dataset instanceof String) { // attempt to parse the input as nquads options.format = JsonLdConsts.APPLICATION_NQUADS; } if (rdfParsers.containsKey(options.format)) { parser = rdfParsers.get(options.format); } else { throw new JsonLdError(JsonLdError.Error.UNKNOWN_FORMAT, options.format); } // convert from RDF return fromRDF(dataset, options, parser); }
[ "public", "static", "Object", "fromRDF", "(", "Object", "dataset", ",", "JsonLdOptions", "options", ")", "throws", "JsonLdError", "{", "// handle non specified serializer case", "RDFParser", "parser", "=", "null", ";", "if", "(", "options", ".", "format", "==", "n...
Converts an RDF dataset to JSON-LD. @param dataset a serialized string of RDF in a format specified by the format option or an RDF dataset to convert. @param options the options to use: [format] the format if input is not an array: 'application/nquads' for N-Quads (default). [useRdfType] true to use rdf:type, false to use @type (default: false). [useNativeTypes] true to convert XSD types into native types (boolean, integer, double), false not to (default: true). @return A JSON-LD object. @throws JsonLdError If there is an error converting the dataset to JSON-LD.
[ "Converts", "an", "RDF", "dataset", "to", "JSON", "-", "LD", "." ]
train
https://github.com/jsonld-java/jsonld-java/blob/efeef6ee96029a0011649633457035fa6be42da1/core/src/main/java/com/github/jsonldjava/core/JsonLdProcessor.java#L384-L402
moparisthebest/beehive
beehive-netui-compiler/src/main/java/org/apache/beehive/netui/compiler/CompilerUtils.java
CompilerUtils.assertAnnotationValue
private static AnnotationValue assertAnnotationValue( Declaration element, String annotationName, String valueName, boolean defaultIsNull ) { """ If the given annotation exists, assert that the given member is not null</code>, and return it; otherwise, if the given annotation does not exist, return null</code>. """ AnnotationInstance ann = getAnnotation( element, annotationName ); if ( ann == null ) { return null; } else { return getAnnotationValue( ann, valueName, defaultIsNull ); } }
java
private static AnnotationValue assertAnnotationValue( Declaration element, String annotationName, String valueName, boolean defaultIsNull ) { AnnotationInstance ann = getAnnotation( element, annotationName ); if ( ann == null ) { return null; } else { return getAnnotationValue( ann, valueName, defaultIsNull ); } }
[ "private", "static", "AnnotationValue", "assertAnnotationValue", "(", "Declaration", "element", ",", "String", "annotationName", ",", "String", "valueName", ",", "boolean", "defaultIsNull", ")", "{", "AnnotationInstance", "ann", "=", "getAnnotation", "(", "element", "...
If the given annotation exists, assert that the given member is not null</code>, and return it; otherwise, if the given annotation does not exist, return null</code>.
[ "If", "the", "given", "annotation", "exists", "assert", "that", "the", "given", "member", "is", "not", "null<", "/", "code", ">", "and", "return", "it", ";", "otherwise", "if", "the", "given", "annotation", "does", "not", "exist", "return", "null<", "/", ...
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-compiler/src/main/java/org/apache/beehive/netui/compiler/CompilerUtils.java#L104-L117
UrielCh/ovh-java-sdk
ovh-java-sdk-freefax/src/main/java/net/minidev/ovh/api/ApiOvhFreefax.java
ApiOvhFreefax.serviceName_voicemail_changeRouting_POST
public void serviceName_voicemail_changeRouting_POST(String serviceName, OvhVoicefaxRoutingEnum routing) throws IOException { """ Disable/Enable voicemail. Available only if the line has fax capabilities REST: POST /freefax/{serviceName}/voicemail/changeRouting @param routing [required] Activate or Desactivate voicemail on the line @param serviceName [required] Freefax number """ String qPath = "/freefax/{serviceName}/voicemail/changeRouting"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "routing", routing); exec(qPath, "POST", sb.toString(), o); }
java
public void serviceName_voicemail_changeRouting_POST(String serviceName, OvhVoicefaxRoutingEnum routing) throws IOException { String qPath = "/freefax/{serviceName}/voicemail/changeRouting"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "routing", routing); exec(qPath, "POST", sb.toString(), o); }
[ "public", "void", "serviceName_voicemail_changeRouting_POST", "(", "String", "serviceName", ",", "OvhVoicefaxRoutingEnum", "routing", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/freefax/{serviceName}/voicemail/changeRouting\"", ";", "StringBuilder", "sb", "...
Disable/Enable voicemail. Available only if the line has fax capabilities REST: POST /freefax/{serviceName}/voicemail/changeRouting @param routing [required] Activate or Desactivate voicemail on the line @param serviceName [required] Freefax number
[ "Disable", "/", "Enable", "voicemail", ".", "Available", "only", "if", "the", "line", "has", "fax", "capabilities" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-freefax/src/main/java/net/minidev/ovh/api/ApiOvhFreefax.java#L126-L132
OpenLiberty/open-liberty
dev/com.ibm.ws.container.service.compat/src/com/ibm/ws/util/ThreadPool.java
ThreadPool.addThread
@Deprecated protected void addThread(Runnable command) { """ Create and start a thread to handle a new command. Call only when holding lock. @deprecated This will be private in a future release. """ Worker worker; if (_isDecoratedZOS) // 331761A worker = new DecoratedZOSWorker(command, threadid++); // 331761A else // 331761A worker = new Worker(command, threadid++); // LIDB1855-58 // D527355.3 - If the current thread is an application thread, then the // creation of a new thread will copy the application class loader as the // context class loader. If the new thread is long-lived in this pool, the // application class loader will be leaked. if (contextClassLoader != null && THREAD_CONTEXT_ACCESSOR.getContextClassLoader(worker) != contextClassLoader) { THREAD_CONTEXT_ACCESSOR.setContextClassLoader(worker, contextClassLoader); } Thread.interrupted(); // PK27301 threads_.put(worker, worker); ++poolSize_; ++activeThreads; // PK77809 Tell the buffer that we have created a new thread waiting for // work if (command == null) { requestBuffer.incrementWaitingThreads(); } // must fire before it is started fireThreadCreated(poolSize_); try { worker.start(); } catch (OutOfMemoryError error) { // 394200 - If an OutOfMemoryError is thrown because too many threads // have already been created, undo everything we've done. // Alex Ffdc.log(error, this, ThreadPool.class.getName(), "626"); // // D477704.2 threads_.remove(worker); --poolSize_; --activeThreads; fireThreadDestroyed(poolSize_); throw error; } }
java
@Deprecated protected void addThread(Runnable command) { Worker worker; if (_isDecoratedZOS) // 331761A worker = new DecoratedZOSWorker(command, threadid++); // 331761A else // 331761A worker = new Worker(command, threadid++); // LIDB1855-58 // D527355.3 - If the current thread is an application thread, then the // creation of a new thread will copy the application class loader as the // context class loader. If the new thread is long-lived in this pool, the // application class loader will be leaked. if (contextClassLoader != null && THREAD_CONTEXT_ACCESSOR.getContextClassLoader(worker) != contextClassLoader) { THREAD_CONTEXT_ACCESSOR.setContextClassLoader(worker, contextClassLoader); } Thread.interrupted(); // PK27301 threads_.put(worker, worker); ++poolSize_; ++activeThreads; // PK77809 Tell the buffer that we have created a new thread waiting for // work if (command == null) { requestBuffer.incrementWaitingThreads(); } // must fire before it is started fireThreadCreated(poolSize_); try { worker.start(); } catch (OutOfMemoryError error) { // 394200 - If an OutOfMemoryError is thrown because too many threads // have already been created, undo everything we've done. // Alex Ffdc.log(error, this, ThreadPool.class.getName(), "626"); // // D477704.2 threads_.remove(worker); --poolSize_; --activeThreads; fireThreadDestroyed(poolSize_); throw error; } }
[ "@", "Deprecated", "protected", "void", "addThread", "(", "Runnable", "command", ")", "{", "Worker", "worker", ";", "if", "(", "_isDecoratedZOS", ")", "// 331761A", "worker", "=", "new", "DecoratedZOSWorker", "(", "command", ",", "threadid", "++", ")", ";", ...
Create and start a thread to handle a new command. Call only when holding lock. @deprecated This will be private in a future release.
[ "Create", "and", "start", "a", "thread", "to", "handle", "a", "new", "command", ".", "Call", "only", "when", "holding", "lock", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.container.service.compat/src/com/ibm/ws/util/ThreadPool.java#L633-L676
vdmeer/asciitable
src/main/java/de/vandermeer/asciitable/AsciiTable.java
AsciiTable.setPaddingTopBottom
public AsciiTable setPaddingTopBottom(int paddingTop, int paddingBottom) { """ Sets top and bottom padding for all cells in the table (only if both values are not smaller than 0). @param paddingTop new top padding, ignored if smaller than 0 @param paddingBottom new bottom padding, ignored if smaller than 0 @return this to allow chaining """ for(AT_Row row : this.rows){ if(row.getType()==TableRowType.CONTENT){ row.setPaddingTopBottom(paddingTop, paddingBottom); } } return this; }
java
public AsciiTable setPaddingTopBottom(int paddingTop, int paddingBottom){ for(AT_Row row : this.rows){ if(row.getType()==TableRowType.CONTENT){ row.setPaddingTopBottom(paddingTop, paddingBottom); } } return this; }
[ "public", "AsciiTable", "setPaddingTopBottom", "(", "int", "paddingTop", ",", "int", "paddingBottom", ")", "{", "for", "(", "AT_Row", "row", ":", "this", ".", "rows", ")", "{", "if", "(", "row", ".", "getType", "(", ")", "==", "TableRowType", ".", "CONTE...
Sets top and bottom padding for all cells in the table (only if both values are not smaller than 0). @param paddingTop new top padding, ignored if smaller than 0 @param paddingBottom new bottom padding, ignored if smaller than 0 @return this to allow chaining
[ "Sets", "top", "and", "bottom", "padding", "for", "all", "cells", "in", "the", "table", "(", "only", "if", "both", "values", "are", "not", "smaller", "than", "0", ")", "." ]
train
https://github.com/vdmeer/asciitable/blob/b6a73710271c89f9c749603be856ba84a969ed5f/src/main/java/de/vandermeer/asciitable/AsciiTable.java#L400-L407
kite-sdk/kite
kite-data/kite-data-core/src/main/java/org/kitesdk/data/spi/DataModelUtil.java
DataModelUtil.getReaderSchema
public static <E> Schema getReaderSchema(Class<E> type, Schema schema) { """ Get the reader schema based on the given type and writer schema. @param <E> The entity type @param type The Java class of the entity type @param schema The {@link Schema} for the entity @return The reader schema based on the given type and writer schema """ Schema readerSchema = schema; GenericData dataModel = getDataModelForType(type); if (dataModel instanceof SpecificData) { readerSchema = ((SpecificData)dataModel).getSchema(type); } return readerSchema; }
java
public static <E> Schema getReaderSchema(Class<E> type, Schema schema) { Schema readerSchema = schema; GenericData dataModel = getDataModelForType(type); if (dataModel instanceof SpecificData) { readerSchema = ((SpecificData)dataModel).getSchema(type); } return readerSchema; }
[ "public", "static", "<", "E", ">", "Schema", "getReaderSchema", "(", "Class", "<", "E", ">", "type", ",", "Schema", "schema", ")", "{", "Schema", "readerSchema", "=", "schema", ";", "GenericData", "dataModel", "=", "getDataModelForType", "(", "type", ")", ...
Get the reader schema based on the given type and writer schema. @param <E> The entity type @param type The Java class of the entity type @param schema The {@link Schema} for the entity @return The reader schema based on the given type and writer schema
[ "Get", "the", "reader", "schema", "based", "on", "the", "given", "type", "and", "writer", "schema", "." ]
train
https://github.com/kite-sdk/kite/blob/72bfb4b1a881af85808cd7f14bc3e15160a1e811/kite-data/kite-data-core/src/main/java/org/kitesdk/data/spi/DataModelUtil.java#L173-L182
thymeleaf/thymeleaf
src/main/java/org/thymeleaf/expression/Uris.java
Uris.unescapeFragmentId
public String unescapeFragmentId(final String text, final String encoding) { """ <p> Perform am URI fragment identifier <strong>unescape</strong> operation on a {@code String} input. </p> <p> This method simply calls the equivalent method in the {@code UriEscape} class from the <a href="http://www.unbescape.org">Unbescape</a> library. </p> <p> This method will unescape every percent-encoded ({@code %HH}) sequences present in input, even for those characters that do not need to be percent-encoded in this context (unreserved characters can be percent-encoded even if/when this is not required, though it is not generally considered a good practice). </p> <p> This method will use specified {@code encoding} in order to determine the characters specified in the percent-encoded byte sequences. </p> <p> This method is <strong>thread-safe</strong>. </p> @param text the {@code String} to be unescaped. @param encoding the encoding to be used for unescaping. @return The unescaped result {@code String}. As a memory-performance improvement, will return the exact same object as the {@code text} input argument if no unescaping modifications were required (and no additional {@code String} objects will be created during processing). Will return {@code null} if {@code text} is {@code null}. """ return UriEscape.unescapeUriFragmentId(text, encoding); }
java
public String unescapeFragmentId(final String text, final String encoding) { return UriEscape.unescapeUriFragmentId(text, encoding); }
[ "public", "String", "unescapeFragmentId", "(", "final", "String", "text", ",", "final", "String", "encoding", ")", "{", "return", "UriEscape", ".", "unescapeUriFragmentId", "(", "text", ",", "encoding", ")", ";", "}" ]
<p> Perform am URI fragment identifier <strong>unescape</strong> operation on a {@code String} input. </p> <p> This method simply calls the equivalent method in the {@code UriEscape} class from the <a href="http://www.unbescape.org">Unbescape</a> library. </p> <p> This method will unescape every percent-encoded ({@code %HH}) sequences present in input, even for those characters that do not need to be percent-encoded in this context (unreserved characters can be percent-encoded even if/when this is not required, though it is not generally considered a good practice). </p> <p> This method will use specified {@code encoding} in order to determine the characters specified in the percent-encoded byte sequences. </p> <p> This method is <strong>thread-safe</strong>. </p> @param text the {@code String} to be unescaped. @param encoding the encoding to be used for unescaping. @return The unescaped result {@code String}. As a memory-performance improvement, will return the exact same object as the {@code text} input argument if no unescaping modifications were required (and no additional {@code String} objects will be created during processing). Will return {@code null} if {@code text} is {@code null}.
[ "<p", ">", "Perform", "am", "URI", "fragment", "identifier", "<strong", ">", "unescape<", "/", "strong", ">", "operation", "on", "a", "{", "@code", "String", "}", "input", ".", "<", "/", "p", ">", "<p", ">", "This", "method", "simply", "calls", "the", ...
train
https://github.com/thymeleaf/thymeleaf/blob/2b0e6d6d7571fbe638904b5fd222fc9e77188879/src/main/java/org/thymeleaf/expression/Uris.java#L477-L479
Azure/azure-sdk-for-java
labservices/resource-manager/v2018_10_15/src/main/java/com/microsoft/azure/management/labservices/v2018_10_15/implementation/GalleryImagesInner.java
GalleryImagesInner.listAsync
public Observable<Page<GalleryImageInner>> listAsync(final String resourceGroupName, final String labAccountName) { """ List gallery images in a given lab account. @param resourceGroupName The name of the resource group. @param labAccountName The name of the lab Account. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;GalleryImageInner&gt; object """ return listWithServiceResponseAsync(resourceGroupName, labAccountName) .map(new Func1<ServiceResponse<Page<GalleryImageInner>>, Page<GalleryImageInner>>() { @Override public Page<GalleryImageInner> call(ServiceResponse<Page<GalleryImageInner>> response) { return response.body(); } }); }
java
public Observable<Page<GalleryImageInner>> listAsync(final String resourceGroupName, final String labAccountName) { return listWithServiceResponseAsync(resourceGroupName, labAccountName) .map(new Func1<ServiceResponse<Page<GalleryImageInner>>, Page<GalleryImageInner>>() { @Override public Page<GalleryImageInner> call(ServiceResponse<Page<GalleryImageInner>> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Page", "<", "GalleryImageInner", ">", ">", "listAsync", "(", "final", "String", "resourceGroupName", ",", "final", "String", "labAccountName", ")", "{", "return", "listWithServiceResponseAsync", "(", "resourceGroupName", ",", "labAccountN...
List gallery images in a given lab account. @param resourceGroupName The name of the resource group. @param labAccountName The name of the lab Account. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;GalleryImageInner&gt; object
[ "List", "gallery", "images", "in", "a", "given", "lab", "account", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/labservices/resource-manager/v2018_10_15/src/main/java/com/microsoft/azure/management/labservices/v2018_10_15/implementation/GalleryImagesInner.java#L141-L149
Netflix/servo
servo-core/src/main/java/com/netflix/servo/monitor/Monitors.java
Monitors.newTimer
public static Timer newTimer(String name, TaggingContext context) { """ Create a new timer with a name and context. The returned timer will maintain separate sub-monitors for each distinct set of tags returned from the context on an update operation. """ return newTimer(name, TimeUnit.MILLISECONDS, context); }
java
public static Timer newTimer(String name, TaggingContext context) { return newTimer(name, TimeUnit.MILLISECONDS, context); }
[ "public", "static", "Timer", "newTimer", "(", "String", "name", ",", "TaggingContext", "context", ")", "{", "return", "newTimer", "(", "name", ",", "TimeUnit", ".", "MILLISECONDS", ",", "context", ")", ";", "}" ]
Create a new timer with a name and context. The returned timer will maintain separate sub-monitors for each distinct set of tags returned from the context on an update operation.
[ "Create", "a", "new", "timer", "with", "a", "name", "and", "context", ".", "The", "returned", "timer", "will", "maintain", "separate", "sub", "-", "monitors", "for", "each", "distinct", "set", "of", "tags", "returned", "from", "the", "context", "on", "an",...
train
https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/monitor/Monitors.java#L90-L92
contentful/contentful-management.java
src/main/java/com/contentful/java/cma/model/CMAEntry.java
CMAEntry.getField
@SuppressWarnings("unchecked") public <T> T getField(String key, String locale) { """ Return a specific localized field. @param key the key of the field @param locale the locale of the key @param <T> the type of the return value @return the value requested or null, if something (fields, key, locale) was not found. """ if (fields == null) { return null; } LinkedHashMap<String, Object> field = fields.get(key); if (field == null) { return null; } else { return (T) field.get(locale); } }
java
@SuppressWarnings("unchecked") public <T> T getField(String key, String locale) { if (fields == null) { return null; } LinkedHashMap<String, Object> field = fields.get(key); if (field == null) { return null; } else { return (T) field.get(locale); } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "<", "T", ">", "T", "getField", "(", "String", "key", ",", "String", "locale", ")", "{", "if", "(", "fields", "==", "null", ")", "{", "return", "null", ";", "}", "LinkedHashMap", "<", "Strin...
Return a specific localized field. @param key the key of the field @param locale the locale of the key @param <T> the type of the return value @return the value requested or null, if something (fields, key, locale) was not found.
[ "Return", "a", "specific", "localized", "field", "." ]
train
https://github.com/contentful/contentful-management.java/blob/ca310fb9ea9577fcff0ca57949ab7c2315fa2534/src/main/java/com/contentful/java/cma/model/CMAEntry.java#L122-L134
openengsb/openengsb
api/ekb/src/main/java/org/openengsb/core/ekb/api/transformation/TransformationDescription.java
TransformationDescription.instantiateField
public void instantiateField(String targetField, String targetType, String targetTypeInit, String... sourceFields) { """ Adds an instantiate step to the transformation description. An object defined through the given target type will be created. For the instantiation the targetTypeInit method will be used. If this parameter is null, the constructor of the targetType will be used with the object type of the source object as parameter. """ TransformationStep step = new TransformationStep(); step.setSourceFields(sourceFields); step.setTargetField(targetField); step.setOperationParameter(TransformationConstants.INSTANTIATE_TARGETTYPE_PARAM, targetType); if (targetTypeInit != null) { step.setOperationParameter(TransformationConstants.INSTANTIATE_INITMETHOD_PARAM, targetTypeInit); } step.setOperationName("instantiate"); steps.add(step); }
java
public void instantiateField(String targetField, String targetType, String targetTypeInit, String... sourceFields) { TransformationStep step = new TransformationStep(); step.setSourceFields(sourceFields); step.setTargetField(targetField); step.setOperationParameter(TransformationConstants.INSTANTIATE_TARGETTYPE_PARAM, targetType); if (targetTypeInit != null) { step.setOperationParameter(TransformationConstants.INSTANTIATE_INITMETHOD_PARAM, targetTypeInit); } step.setOperationName("instantiate"); steps.add(step); }
[ "public", "void", "instantiateField", "(", "String", "targetField", ",", "String", "targetType", ",", "String", "targetTypeInit", ",", "String", "...", "sourceFields", ")", "{", "TransformationStep", "step", "=", "new", "TransformationStep", "(", ")", ";", "step",...
Adds an instantiate step to the transformation description. An object defined through the given target type will be created. For the instantiation the targetTypeInit method will be used. If this parameter is null, the constructor of the targetType will be used with the object type of the source object as parameter.
[ "Adds", "an", "instantiate", "step", "to", "the", "transformation", "description", ".", "An", "object", "defined", "through", "the", "given", "target", "type", "will", "be", "created", ".", "For", "the", "instantiation", "the", "targetTypeInit", "method", "will"...
train
https://github.com/openengsb/openengsb/blob/d39058000707f617cd405629f9bc7f17da7b414a/api/ekb/src/main/java/org/openengsb/core/ekb/api/transformation/TransformationDescription.java#L275-L285
Unicon/cas-addons
src/main/java/net/unicon/cas/addons/authentication/strong/oath/totp/TOTP.java
TOTP.hmacSha
private static byte[] hmacSha(String crypto, byte[] keyBytes, byte[] text) { """ This method uses the JCE to provide the crypto algorithm. HMAC computes a Hashed Message Authentication Code with the crypto hash algorithm as a parameter. @param crypto : the crypto algorithm (HmacSHA1, HmacSHA256, HmacSHA512) @param keyBytes : the bytes to use for the HMAC key @param text : the message or text to be authenticated """ try { Mac hmac; hmac = Mac.getInstance(crypto); SecretKeySpec macKey = new SecretKeySpec(keyBytes, "RAW"); hmac.init(macKey); return hmac.doFinal(text); } catch (GeneralSecurityException gse) { throw new UndeclaredThrowableException(gse); } }
java
private static byte[] hmacSha(String crypto, byte[] keyBytes, byte[] text) { try { Mac hmac; hmac = Mac.getInstance(crypto); SecretKeySpec macKey = new SecretKeySpec(keyBytes, "RAW"); hmac.init(macKey); return hmac.doFinal(text); } catch (GeneralSecurityException gse) { throw new UndeclaredThrowableException(gse); } }
[ "private", "static", "byte", "[", "]", "hmacSha", "(", "String", "crypto", ",", "byte", "[", "]", "keyBytes", ",", "byte", "[", "]", "text", ")", "{", "try", "{", "Mac", "hmac", ";", "hmac", "=", "Mac", ".", "getInstance", "(", "crypto", ")", ";", ...
This method uses the JCE to provide the crypto algorithm. HMAC computes a Hashed Message Authentication Code with the crypto hash algorithm as a parameter. @param crypto : the crypto algorithm (HmacSHA1, HmacSHA256, HmacSHA512) @param keyBytes : the bytes to use for the HMAC key @param text : the message or text to be authenticated
[ "This", "method", "uses", "the", "JCE", "to", "provide", "the", "crypto", "algorithm", ".", "HMAC", "computes", "a", "Hashed", "Message", "Authentication", "Code", "with", "the", "crypto", "hash", "algorithm", "as", "a", "parameter", "." ]
train
https://github.com/Unicon/cas-addons/blob/9af2d4896e02d30622acec638539bfc41f45e480/src/main/java/net/unicon/cas/addons/authentication/strong/oath/totp/TOTP.java#L35-L45
pravega/pravega
segmentstore/storage/impl/src/main/java/io/pravega/segmentstore/storage/impl/bookkeeper/BookKeeperLog.java
BookKeeperLog.initialize
@Override public void initialize(Duration timeout) throws DurableDataLogException { """ Open-Fences this BookKeeper log using the following protocol: 1. Read Log Metadata from ZooKeeper. 2. Fence at least the last 2 ledgers in the Ledger List. 3. Create a new Ledger. 3.1 If any of the steps so far fails, the process is interrupted at the point of failure, and no cleanup is attempted. 4. Update Log Metadata using compare-and-set (this update contains the new ledger and new epoch). 4.1 If CAS fails on metadata update, the newly created Ledger is deleted (this means we were fenced out by some other instance) and no other update is performed. @param timeout Timeout for the operation. @throws DataLogWriterNotPrimaryException If we were fenced-out during this process. @throws DataLogNotAvailableException If BookKeeper or ZooKeeper are not available. @throws DataLogDisabledException If the BookKeeperLog is disabled. No fencing is attempted in this case. @throws DataLogInitializationException If a general initialization error occurred. @throws DurableDataLogException If another type of exception occurred. """ List<Long> ledgersToDelete; LogMetadata newMetadata; synchronized (this.lock) { Preconditions.checkState(this.writeLedger == null, "BookKeeperLog is already initialized."); assert this.logMetadata == null : "writeLedger == null but logMetadata != null"; // Get metadata about the current state of the log, if any. LogMetadata oldMetadata = loadMetadata(); if (oldMetadata != null) { if (!oldMetadata.isEnabled()) { throw new DataLogDisabledException("BookKeeperLog is disabled. Cannot initialize."); } // Fence out ledgers. val emptyLedgerIds = Ledgers.fenceOut(oldMetadata.getLedgers(), this.bookKeeper, this.config, this.traceObjectId); // Update Metadata to reflect those newly found empty ledgers. oldMetadata = oldMetadata.updateLedgerStatus(emptyLedgerIds); } // Create new ledger. LedgerHandle newLedger = Ledgers.create(this.bookKeeper, this.config); log.info("{}: Created Ledger {}.", this.traceObjectId, newLedger.getId()); // Update Metadata with new Ledger and persist to ZooKeeper. newMetadata = updateMetadata(oldMetadata, newLedger, true); LedgerMetadata ledgerMetadata = newMetadata.getLedger(newLedger.getId()); assert ledgerMetadata != null : "cannot find newly added ledger metadata"; this.writeLedger = new WriteLedger(newLedger, ledgerMetadata); this.logMetadata = newMetadata; ledgersToDelete = getLedgerIdsToDelete(oldMetadata, newMetadata); } // Delete the orphaned ledgers from BookKeeper. ledgersToDelete.forEach(id -> { try { Ledgers.delete(id, this.bookKeeper); log.info("{}: Deleted orphan empty ledger {}.", this.traceObjectId, id); } catch (DurableDataLogException ex) { // A failure here has no effect on the initialization of BookKeeperLog. In this case, the (empty) Ledger // will remain in BookKeeper until manually deleted by a cleanup tool. log.warn("{}: Unable to delete orphan empty ledger {}.", this.traceObjectId, id, ex); } }); log.info("{}: Initialized (Epoch = {}, UpdateVersion = {}).", this.traceObjectId, newMetadata.getEpoch(), newMetadata.getUpdateVersion()); }
java
@Override public void initialize(Duration timeout) throws DurableDataLogException { List<Long> ledgersToDelete; LogMetadata newMetadata; synchronized (this.lock) { Preconditions.checkState(this.writeLedger == null, "BookKeeperLog is already initialized."); assert this.logMetadata == null : "writeLedger == null but logMetadata != null"; // Get metadata about the current state of the log, if any. LogMetadata oldMetadata = loadMetadata(); if (oldMetadata != null) { if (!oldMetadata.isEnabled()) { throw new DataLogDisabledException("BookKeeperLog is disabled. Cannot initialize."); } // Fence out ledgers. val emptyLedgerIds = Ledgers.fenceOut(oldMetadata.getLedgers(), this.bookKeeper, this.config, this.traceObjectId); // Update Metadata to reflect those newly found empty ledgers. oldMetadata = oldMetadata.updateLedgerStatus(emptyLedgerIds); } // Create new ledger. LedgerHandle newLedger = Ledgers.create(this.bookKeeper, this.config); log.info("{}: Created Ledger {}.", this.traceObjectId, newLedger.getId()); // Update Metadata with new Ledger and persist to ZooKeeper. newMetadata = updateMetadata(oldMetadata, newLedger, true); LedgerMetadata ledgerMetadata = newMetadata.getLedger(newLedger.getId()); assert ledgerMetadata != null : "cannot find newly added ledger metadata"; this.writeLedger = new WriteLedger(newLedger, ledgerMetadata); this.logMetadata = newMetadata; ledgersToDelete = getLedgerIdsToDelete(oldMetadata, newMetadata); } // Delete the orphaned ledgers from BookKeeper. ledgersToDelete.forEach(id -> { try { Ledgers.delete(id, this.bookKeeper); log.info("{}: Deleted orphan empty ledger {}.", this.traceObjectId, id); } catch (DurableDataLogException ex) { // A failure here has no effect on the initialization of BookKeeperLog. In this case, the (empty) Ledger // will remain in BookKeeper until manually deleted by a cleanup tool. log.warn("{}: Unable to delete orphan empty ledger {}.", this.traceObjectId, id, ex); } }); log.info("{}: Initialized (Epoch = {}, UpdateVersion = {}).", this.traceObjectId, newMetadata.getEpoch(), newMetadata.getUpdateVersion()); }
[ "@", "Override", "public", "void", "initialize", "(", "Duration", "timeout", ")", "throws", "DurableDataLogException", "{", "List", "<", "Long", ">", "ledgersToDelete", ";", "LogMetadata", "newMetadata", ";", "synchronized", "(", "this", ".", "lock", ")", "{", ...
Open-Fences this BookKeeper log using the following protocol: 1. Read Log Metadata from ZooKeeper. 2. Fence at least the last 2 ledgers in the Ledger List. 3. Create a new Ledger. 3.1 If any of the steps so far fails, the process is interrupted at the point of failure, and no cleanup is attempted. 4. Update Log Metadata using compare-and-set (this update contains the new ledger and new epoch). 4.1 If CAS fails on metadata update, the newly created Ledger is deleted (this means we were fenced out by some other instance) and no other update is performed. @param timeout Timeout for the operation. @throws DataLogWriterNotPrimaryException If we were fenced-out during this process. @throws DataLogNotAvailableException If BookKeeper or ZooKeeper are not available. @throws DataLogDisabledException If the BookKeeperLog is disabled. No fencing is attempted in this case. @throws DataLogInitializationException If a general initialization error occurred. @throws DurableDataLogException If another type of exception occurred.
[ "Open", "-", "Fences", "this", "BookKeeper", "log", "using", "the", "following", "protocol", ":", "1", ".", "Read", "Log", "Metadata", "from", "ZooKeeper", ".", "2", ".", "Fence", "at", "least", "the", "last", "2", "ledgers", "in", "the", "Ledger", "List...
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/storage/impl/src/main/java/io/pravega/segmentstore/storage/impl/bookkeeper/BookKeeperLog.java#L205-L253
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/lang/Long.java
Long.remainderUnsigned
public static long remainderUnsigned(long dividend, long divisor) { """ Returns the unsigned remainder from dividing the first argument by the second where each argument and the result is interpreted as an unsigned value. @param dividend the value to be divided @param divisor the value doing the dividing @return the unsigned remainder of the first argument divided by the second argument @see #divideUnsigned @since 1.8 """ if (dividend > 0 && divisor > 0) { // signed comparisons return dividend % divisor; } else { if (compareUnsigned(dividend, divisor) < 0) // Avoid explicit check for 0 divisor return dividend; else return toUnsignedBigInteger(dividend). remainder(toUnsignedBigInteger(divisor)).longValue(); } }
java
public static long remainderUnsigned(long dividend, long divisor) { if (dividend > 0 && divisor > 0) { // signed comparisons return dividend % divisor; } else { if (compareUnsigned(dividend, divisor) < 0) // Avoid explicit check for 0 divisor return dividend; else return toUnsignedBigInteger(dividend). remainder(toUnsignedBigInteger(divisor)).longValue(); } }
[ "public", "static", "long", "remainderUnsigned", "(", "long", "dividend", ",", "long", "divisor", ")", "{", "if", "(", "dividend", ">", "0", "&&", "divisor", ">", "0", ")", "{", "// signed comparisons", "return", "dividend", "%", "divisor", ";", "}", "else...
Returns the unsigned remainder from dividing the first argument by the second where each argument and the result is interpreted as an unsigned value. @param dividend the value to be divided @param divisor the value doing the dividing @return the unsigned remainder of the first argument divided by the second argument @see #divideUnsigned @since 1.8
[ "Returns", "the", "unsigned", "remainder", "from", "dividing", "the", "first", "argument", "by", "the", "second", "where", "each", "argument", "and", "the", "result", "is", "interpreted", "as", "an", "unsigned", "value", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/lang/Long.java#L1171-L1181
Azure/azure-sdk-for-java
datalakeanalytics/resource-manager/v2016_11_01/src/main/java/com/microsoft/azure/management/datalakeanalytics/v2016_11_01/implementation/StorageAccountsInner.java
StorageAccountsInner.listStorageContainersWithServiceResponseAsync
public Observable<ServiceResponse<Page<StorageContainerInner>>> listStorageContainersWithServiceResponseAsync(final String resourceGroupName, final String accountName, final String storageAccountName) { """ Lists the Azure Storage containers, if any, associated with the specified Data Lake Analytics and Azure Storage account combination. The response includes a link to the next page of results, if any. @param resourceGroupName The name of the Azure resource group. @param accountName The name of the Data Lake Analytics account. @param storageAccountName The name of the Azure storage account from which to list blob containers. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;StorageContainerInner&gt; object """ return listStorageContainersSinglePageAsync(resourceGroupName, accountName, storageAccountName) .concatMap(new Func1<ServiceResponse<Page<StorageContainerInner>>, Observable<ServiceResponse<Page<StorageContainerInner>>>>() { @Override public Observable<ServiceResponse<Page<StorageContainerInner>>> call(ServiceResponse<Page<StorageContainerInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listStorageContainersNextWithServiceResponseAsync(nextPageLink)); } }); }
java
public Observable<ServiceResponse<Page<StorageContainerInner>>> listStorageContainersWithServiceResponseAsync(final String resourceGroupName, final String accountName, final String storageAccountName) { return listStorageContainersSinglePageAsync(resourceGroupName, accountName, storageAccountName) .concatMap(new Func1<ServiceResponse<Page<StorageContainerInner>>, Observable<ServiceResponse<Page<StorageContainerInner>>>>() { @Override public Observable<ServiceResponse<Page<StorageContainerInner>>> call(ServiceResponse<Page<StorageContainerInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listStorageContainersNextWithServiceResponseAsync(nextPageLink)); } }); }
[ "public", "Observable", "<", "ServiceResponse", "<", "Page", "<", "StorageContainerInner", ">", ">", ">", "listStorageContainersWithServiceResponseAsync", "(", "final", "String", "resourceGroupName", ",", "final", "String", "accountName", ",", "final", "String", "storag...
Lists the Azure Storage containers, if any, associated with the specified Data Lake Analytics and Azure Storage account combination. The response includes a link to the next page of results, if any. @param resourceGroupName The name of the Azure resource group. @param accountName The name of the Data Lake Analytics account. @param storageAccountName The name of the Azure storage account from which to list blob containers. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;StorageContainerInner&gt; object
[ "Lists", "the", "Azure", "Storage", "containers", "if", "any", "associated", "with", "the", "specified", "Data", "Lake", "Analytics", "and", "Azure", "Storage", "account", "combination", ".", "The", "response", "includes", "a", "link", "to", "the", "next", "pa...
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/datalakeanalytics/resource-manager/v2016_11_01/src/main/java/com/microsoft/azure/management/datalakeanalytics/v2016_11_01/implementation/StorageAccountsInner.java#L928-L940
gosu-lang/gosu-lang
gosu-core-api/src/main/java/gw/util/GosuStringUtil.java
GosuStringUtil.indexOfAny
public static int indexOfAny(String str, String[] searchStrs) { """ <p>Find the first index of any of a set of potential substrings.</p> <p>A <code>null</code> String will return <code>-1</code>. A <code>null</code> or zero length search array will return <code>-1</code>. A <code>null</code> search array entry will be ignored, but a search array containing "" will return <code>0</code> if <code>str</code> is not null. This method uses {@link String#indexOf(String)}.</p> <pre> GosuStringUtil.indexOfAny(null, *) = -1 GosuStringUtil.indexOfAny(*, null) = -1 GosuStringUtil.indexOfAny(*, []) = -1 GosuStringUtil.indexOfAny("zzabyycdxx", ["ab","cd"]) = 2 GosuStringUtil.indexOfAny("zzabyycdxx", ["cd","ab"]) = 2 GosuStringUtil.indexOfAny("zzabyycdxx", ["mn","op"]) = -1 GosuStringUtil.indexOfAny("zzabyycdxx", ["zab","aby"]) = 1 GosuStringUtil.indexOfAny("zzabyycdxx", [""]) = 0 GosuStringUtil.indexOfAny("", [""]) = 0 GosuStringUtil.indexOfAny("", ["a"]) = -1 </pre> @param str the String to check, may be null @param searchStrs the Strings to search for, may be null @return the first index of any of the searchStrs in str, -1 if no match """ if ((str == null) || (searchStrs == null)) { return -1; } int sz = searchStrs.length; // String's can't have a MAX_VALUEth index. int ret = Integer.MAX_VALUE; int tmp = 0; for (int i = 0; i < sz; i++) { String search = searchStrs[i]; if (search == null) { continue; } tmp = str.indexOf(search); if (tmp == -1) { continue; } if (tmp < ret) { ret = tmp; } } return (ret == Integer.MAX_VALUE) ? -1 : ret; }
java
public static int indexOfAny(String str, String[] searchStrs) { if ((str == null) || (searchStrs == null)) { return -1; } int sz = searchStrs.length; // String's can't have a MAX_VALUEth index. int ret = Integer.MAX_VALUE; int tmp = 0; for (int i = 0; i < sz; i++) { String search = searchStrs[i]; if (search == null) { continue; } tmp = str.indexOf(search); if (tmp == -1) { continue; } if (tmp < ret) { ret = tmp; } } return (ret == Integer.MAX_VALUE) ? -1 : ret; }
[ "public", "static", "int", "indexOfAny", "(", "String", "str", ",", "String", "[", "]", "searchStrs", ")", "{", "if", "(", "(", "str", "==", "null", ")", "||", "(", "searchStrs", "==", "null", ")", ")", "{", "return", "-", "1", ";", "}", "int", "...
<p>Find the first index of any of a set of potential substrings.</p> <p>A <code>null</code> String will return <code>-1</code>. A <code>null</code> or zero length search array will return <code>-1</code>. A <code>null</code> search array entry will be ignored, but a search array containing "" will return <code>0</code> if <code>str</code> is not null. This method uses {@link String#indexOf(String)}.</p> <pre> GosuStringUtil.indexOfAny(null, *) = -1 GosuStringUtil.indexOfAny(*, null) = -1 GosuStringUtil.indexOfAny(*, []) = -1 GosuStringUtil.indexOfAny("zzabyycdxx", ["ab","cd"]) = 2 GosuStringUtil.indexOfAny("zzabyycdxx", ["cd","ab"]) = 2 GosuStringUtil.indexOfAny("zzabyycdxx", ["mn","op"]) = -1 GosuStringUtil.indexOfAny("zzabyycdxx", ["zab","aby"]) = 1 GosuStringUtil.indexOfAny("zzabyycdxx", [""]) = 0 GosuStringUtil.indexOfAny("", [""]) = 0 GosuStringUtil.indexOfAny("", ["a"]) = -1 </pre> @param str the String to check, may be null @param searchStrs the Strings to search for, may be null @return the first index of any of the searchStrs in str, -1 if no match
[ "<p", ">", "Find", "the", "first", "index", "of", "any", "of", "a", "set", "of", "potential", "substrings", ".", "<", "/", "p", ">" ]
train
https://github.com/gosu-lang/gosu-lang/blob/d6e9261b137ce66fef3726cabe7826d4a1f946b7/gosu-core-api/src/main/java/gw/util/GosuStringUtil.java#L1423-L1449
dustin/java-memcached-client
src/main/java/net/spy/memcached/MemcachedClient.java
MemcachedClient.asyncGet
@Override public <T> GetFuture<T> asyncGet(final String key, final Transcoder<T> tc) { """ Get the given key asynchronously. @param <T> @param key the key to fetch @param tc the transcoder to serialize and unserialize value @return a future that will hold the return value of the fetch @throws IllegalStateException in the rare circumstance where queue is too full to accept any more requests """ final CountDownLatch latch = new CountDownLatch(1); final GetFuture<T> rv = new GetFuture<T>(latch, operationTimeout, key, executorService); Operation op = opFact.get(key, new GetOperation.Callback() { private Future<T> val; @Override public void receivedStatus(OperationStatus status) { rv.set(val, status); } @Override public void gotData(String k, int flags, byte[] data) { assert key.equals(k) : "Wrong key returned"; val = tcService.decode(tc, new CachedData(flags, data, tc.getMaxSize())); } @Override public void complete() { latch.countDown(); rv.signalComplete(); } }); rv.setOperation(op); mconn.enqueueOperation(key, op); return rv; }
java
@Override public <T> GetFuture<T> asyncGet(final String key, final Transcoder<T> tc) { final CountDownLatch latch = new CountDownLatch(1); final GetFuture<T> rv = new GetFuture<T>(latch, operationTimeout, key, executorService); Operation op = opFact.get(key, new GetOperation.Callback() { private Future<T> val; @Override public void receivedStatus(OperationStatus status) { rv.set(val, status); } @Override public void gotData(String k, int flags, byte[] data) { assert key.equals(k) : "Wrong key returned"; val = tcService.decode(tc, new CachedData(flags, data, tc.getMaxSize())); } @Override public void complete() { latch.countDown(); rv.signalComplete(); } }); rv.setOperation(op); mconn.enqueueOperation(key, op); return rv; }
[ "@", "Override", "public", "<", "T", ">", "GetFuture", "<", "T", ">", "asyncGet", "(", "final", "String", "key", ",", "final", "Transcoder", "<", "T", ">", "tc", ")", "{", "final", "CountDownLatch", "latch", "=", "new", "CountDownLatch", "(", "1", ")",...
Get the given key asynchronously. @param <T> @param key the key to fetch @param tc the transcoder to serialize and unserialize value @return a future that will hold the return value of the fetch @throws IllegalStateException in the rare circumstance where queue is too full to accept any more requests
[ "Get", "the", "given", "key", "asynchronously", "." ]
train
https://github.com/dustin/java-memcached-client/blob/c232307ad8e0c7ccc926e495dd7d5aad2d713318/src/main/java/net/spy/memcached/MemcachedClient.java#L1016-L1046
spotbugs/spotbugs
eclipsePlugin/src/de/tobject/findbugs/properties/ReportConfigurationTab.java
ReportConfigurationTab.createBugCategoriesGroup
private void createBugCategoriesGroup(Composite parent, final IProject project) { """ Build list of bug categories to be enabled or disabled. Populates chkEnableBugCategoryList and bugCategoryList fields. @param parent control checkboxes should be added to @param project the project being configured """ Group checkBoxGroup = new Group(parent, SWT.SHADOW_ETCHED_OUT); checkBoxGroup.setText(getMessage("property.categoriesGroup")); checkBoxGroup.setLayout(new GridLayout(1, true)); checkBoxGroup.setLayoutData(new GridData(SWT.BEGINNING, SWT.TOP, true, true)); List<String> bugCategoryList = new LinkedList<>(DetectorFactoryCollection.instance().getBugCategories()); chkEnableBugCategoryList = new LinkedList<>(); ProjectFilterSettings origFilterSettings = propertyPage.getOriginalUserPreferences().getFilterSettings(); for (String category : bugCategoryList) { Button checkBox = new Button(checkBoxGroup, SWT.CHECK); checkBox.setText(I18N.instance().getBugCategoryDescription(category)); checkBox.setSelection(origFilterSettings.containsCategory(category)); GridData layoutData = new GridData(); layoutData.horizontalIndent = 10; checkBox.setLayoutData(layoutData); // Every time a checkbox is clicked, rebuild the detector factory // table // to show only relevant entries checkBox.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event e) { syncSelectedCategories(); } }); checkBox.setData(category); chkEnableBugCategoryList.add(checkBox); } }
java
private void createBugCategoriesGroup(Composite parent, final IProject project) { Group checkBoxGroup = new Group(parent, SWT.SHADOW_ETCHED_OUT); checkBoxGroup.setText(getMessage("property.categoriesGroup")); checkBoxGroup.setLayout(new GridLayout(1, true)); checkBoxGroup.setLayoutData(new GridData(SWT.BEGINNING, SWT.TOP, true, true)); List<String> bugCategoryList = new LinkedList<>(DetectorFactoryCollection.instance().getBugCategories()); chkEnableBugCategoryList = new LinkedList<>(); ProjectFilterSettings origFilterSettings = propertyPage.getOriginalUserPreferences().getFilterSettings(); for (String category : bugCategoryList) { Button checkBox = new Button(checkBoxGroup, SWT.CHECK); checkBox.setText(I18N.instance().getBugCategoryDescription(category)); checkBox.setSelection(origFilterSettings.containsCategory(category)); GridData layoutData = new GridData(); layoutData.horizontalIndent = 10; checkBox.setLayoutData(layoutData); // Every time a checkbox is clicked, rebuild the detector factory // table // to show only relevant entries checkBox.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event e) { syncSelectedCategories(); } }); checkBox.setData(category); chkEnableBugCategoryList.add(checkBox); } }
[ "private", "void", "createBugCategoriesGroup", "(", "Composite", "parent", ",", "final", "IProject", "project", ")", "{", "Group", "checkBoxGroup", "=", "new", "Group", "(", "parent", ",", "SWT", ".", "SHADOW_ETCHED_OUT", ")", ";", "checkBoxGroup", ".", "setText...
Build list of bug categories to be enabled or disabled. Populates chkEnableBugCategoryList and bugCategoryList fields. @param parent control checkboxes should be added to @param project the project being configured
[ "Build", "list", "of", "bug", "categories", "to", "be", "enabled", "or", "disabled", ".", "Populates", "chkEnableBugCategoryList", "and", "bugCategoryList", "fields", "." ]
train
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/eclipsePlugin/src/de/tobject/findbugs/properties/ReportConfigurationTab.java#L244-L273